output
stringlengths
1
928k
instruction
stringlengths
7
928k
system
stringlengths
0
104k
Parses the sections in the memory and returns a list of them
Can you generate the documentation for the following Python 3 function def _parseSections(self, data, imageDosHeader, imageNtHeaders, parse_header_only=False): sections = [] optional_header_offset = imageDosHeader.header.e_lfanew + 4 + sizeof(IMAGE_FILE_HEADER) offset = optional_header_offset +...
You are a Python code generator, capable of creating scripts from specifications.
def _getSectionForDataDirectoryEntry(self, data_directory_entry, sections): """Returns the section which contains the data of DataDirectory""" for section in sections: if data_directory_entry.VirtualAddress >= section.header.VirtualAddress and \ data_directory_entry.VirtualAddres...
Create a Python 3 function for returning the section which contains the data of the DataDirectory entry.
As a Python code composer, you craft elegant and concise scripts.
Parses the entries of the DataDirectory and returns a list of the content
Here you have a function in Python 3, explain what it does def _parseDataDirectory(self, data, sections, imageNtHeaders): data_directory_data_list = [None for i in range(15)] # parse DataDirectory[Export] export_data_directory = imageNtHeaders.header.OptionalHeader.DataDirectory[ImageDirectoryE...
As a Python code composer, you craft elegant and concise scripts.
def _parseDataDirectoryExport(self, data, dataDirectoryEntry, exportSection): """Parses the EmportDataDirectory and returns an instance of ExportDirectoryData""" if not exportSection: return functions = [] export_directory = IMAGE_EXPORT_DIRECTORY.from_buffer(exportSection.ra...
How would you implement a function in Python 3 that parses the EmportDataDirectory and returns an instance of ExportDirectoryData
As a Python code composer, you craft elegant and concise scripts.
def _parseDataDirectoryImport(self, dataDirectoryEntry, importSection): """Parses the ImportDataDirectory and returns a list of ImportDescriptorData""" if not importSection: return raw_bytes = (c_ubyte * dataDirectoryEntry.Size).from_buffer(importSection.raw, to_offset(dataDirector...
How would you code a function in Python 3 to parse the ImportDataDirectory and returns a list of ImportDescriptorData s.
As a python code expert, you are capable of creating scripts from specifications.
def __parseThunks(self, thunkRVA, importSection): """Parses the thunks and returns a list""" offset = to_offset(thunkRVA, importSection) table_offset = 0 thunks = [] while True: thunk = IMAGE_THUNK_DATA.from_buffer(importSection.raw, offset) offset += size...
Write a Python 3 function for parsing the thunks and returns a list of ThunkData objects
As a Python code analyst, you investigate and solve complex coding mysteries
Parses the data of a thunk and sets the data
Given the following Python 3 function, write the documentation def __parseThunkData(self, thunk,importSection): offset = to_offset(thunk.header.AddressOfData, importSection) if 0xf0000000 & thunk.header.AddressOfData == 0x80000000: thunk.ordinal = thunk.header.AddressOfData & 0x0fffffff ...
As a python code expert, you are capable of creating scripts from specifications.
def get_ptr(data, offset=None, ptr_type=ctypes.c_void_p): """Returns a void pointer to the data""" ptr = ctypes.cast(ctypes.pointer(data), ctypes.c_void_p) if offset: ptr = ctypes.c_void_p(ptr.value + offset) if ptr_type != ctypes.c_void_p: ptr = ctypes.cast(ptr, ptr_type) return ...
Create a Python 3 function for returning a void pointer to the data
As a Python code analyst, you investigate and solve complex coding mysteries
def to_ubyte_array(barray): """Returns a c_ubyte_array filled with the given data of a bytearray or bytes""" bs = (ctypes.c_ubyte * len(barray))() pack_into('%ds' % len(barray), bs, 0, barray) return bs
Implement a function in Python 3 to return a c_ubyte_array filled with the given data of a bytearray or bytes
As a Python code analyst, you investigate and solve complex coding mysteries
def _readFile(self, fileName): """ Returns the bytes of the file. """ with open(fileName, 'rb') as binFile: b = binFile.read() return to_ubyte_array(b)
Can you write a function in Python 3 where it reads the file and returns the bytes of the file.
As a Python code analyst, you investigate and solve complex coding mysteries
def _getSuitableClasses(self, data): """Returns the class which holds the suitable classes for the loaded file""" classes = None if data[EI.CLASS] == ELFCLASS.BITS_32: if data[EI.DATA] == ELFDATA.LSB: classes = LSB_32 elif data[EI.DATA] == ELFDATA.MSB: ...
Implement a Python 3 function for returning the class which holds the suitable classes for the loaded file
As a python code expert, you are capable of creating scripts from specifications.
Returns the elf header
Make a summary of the following Python 3 code def _parseElfHeader(self, data): ehdr = self.__classes.EHDR.from_buffer(data) return EhdrData(header=ehdr)
You are a Python code analyst, evaluating scripts for potential improvements.
Parse the segments from the data.
Can you generate the documentation for the following Python 3 function def _parseSegments(self, data, elfHeader): offset = elfHeader.header.e_phoff segments = [] for i in range(elfHeader.header.e_phnum): phdr = self.__classes.PHDR.from_buffer(data, offset) segment_bytes =...
As a Python code composer, you craft elegant and concise scripts.
Returns a list of sections
Can you generate the documentation for the following Python 3 function def _parseSections(self, data, elfHeader): offset = elfHeader.header.e_shoff shdrs = [] for i in range(elfHeader.header.e_shnum): shdr = self.__classes.SHDR.from_buffer(data, offset) section_bytes = No...
As a Python code analyst, you investigate and solve complex coding mysteries
Sets a list of symbols in each DYNSYM and SYMTAB section
Can you tell what is the following Python 3 function doing def _parseSymbols(self, sections): for section in sections: strtab = sections[section.header.sh_link] if section.header.sh_type in (int(SHT.DYNSYM), int(SHT.SYMTAB)): section.symbols = self.__parseSymbolEntriesFor...
As a Python code composer, you craft elegant and concise scripts.
Parses the relocations and adds those to the section
Explain what the following Python 3 code does def _parseRelocations(self, sections): for section in sections: if section.header.sh_link != SHN.UNDEF and section.header.sh_type in (SHT.REL, SHT.RELA): symbols = sections[section.header.sh_link].symbols relocations = sel...
You are a Python code generator, capable of creating scripts from specifications.
def run_with_snapshots(self, tsnapstart=0., tsnapint=432000.): """Run the model forward, yielding to user code at specified intervals. Parameters ---------- tsnapstart : int The timestep at which to begin yielding. tstapint : int The interval at which to...
Implement a function in Python 3 to run the model forward yielding to user code at specified intervals.
You are a Python code analyst, evaluating scripts for potential improvements.
def vertical_modes(self): """ Calculate standard vertical modes. Simply the eigenvectors of the stretching matrix S """ evals,evecs = np.linalg.eig(-self.S) asort = evals.argsort() # deformation wavenumbers and radii self.kdi2 = evals[asort] self.radii = np...
Write a Python 3 function for calculating the vertical modes of the standard matrix S.
As a Python code translator, you convert algorithms and pseudocode into Python.
Performs a field p into modal amplitudes pn using the basis [ pmodes ]. The inverse transform calculates p from pn.
Can you generate the documentation for the following Python 3 function def modal_projection(self,p,forward=True): if forward: pt = np.linalg.solve(self.pmodes[np.newaxis,np.newaxis],p.T).T else: pt = np.einsum("ik,k...->i...",self.pmodes,p) return pt
As a Python code translator, you convert algorithms and pseudocode into Python.
Set up background state.
Explain what the following Python 3 code does def _initialize_background(self): # background vel. if len(np.shape(self.U)) == 0: self.U = (self.U * np.ones((self.ny))) print(np.shape(self.U)) self.set_U(self.U) # the meridional PV gradients in each layer self....
As a Python code translator, you convert algorithms and pseudocode into Python.
initialize the inversion matrix
Can you tell what is the following Python 3 function doing def _initialize_inversion_matrix(self): # The sqg model is diagonal. The inversion is simply qh = -kappa**2 ph self.a = np.asarray(self.Nb*np.sqrt(self.wv2i))[np.newaxis, np.newaxis, :, :]
As a python code expert, you are capable of creating scripts from specifications.
Set background zonal flow
Can you tell what is the following Python 3 function doing def set_U(self, U): self.Ubg = np.asarray(U)[np.newaxis,...]
As a Python code translator, you convert algorithms and pseudocode into Python.
Advance particles using a function to determine u and v.
Make a summary of the following Python 3 code def step_forward_with_function(self, uv0fun, uv1fun, dt): dx, dy = self._rk4_integrate(self.x, self.y, uv0fun, uv1fun, dt) self.x = self._wrap_x(self.x + dx) self.y = self._wrap_y(self.y + dy)
You are a Python code generator, capable of creating scripts from specifications.
def _rk4_integrate(self, x, y, uv0fun, uv1fun, dt): """Integrates positions x, y using velocity functions uv0fun, uv1fun. Returns dx and dy, the displacements.""" u0, v0 = uv0fun(x, y) k1u = dt*u0 k1v = dt*v0 x11 = self._wrap_x(x + 0.5*k1u) y11 = self._wrap_y(y...
Create a Python 3 function for integrating positions x y using velocity functions uv0fun uv1fun. Returns dx dy the displacements.
As a python code expert, you are capable of creating scripts from specifications.
Utitlity function to compute distance between points.
Here you have a function in Python 3, explain what it does def _distance(self, x0, y0, x1, y1): dx = x1-x0 dy = y1-y0 # roll displacements across the borders if self.pix: dx[ dx > self.Lx/2 ] -= self.Lx dx[ dx < -self.Lx/2 ] += self.Lx if self.piy: ...
You are a Python code architect, reviewing and designing scalable and efficient code
Interpolate gridded scalar C to points x y.
Can you generate the documentation for the following Python 3 function def interpolate_gridded_scalar(self, x, y, c, order=1, pad=1, offset=0): ## no longer necessary because we accept pre-padded arrays # assert c.shape == (self.Ny, self.Nx), 'Shape of c needs to be (Ny,Nx)' # ...
As a python code expert, you are capable of creating scripts from specifications.
def step_forward_with_gridded_uv(self, U0, V0, U1, V1, dt, order=1): """Advance particles using a gridded velocity field. Because of the Runga-Kutta timestepping, we need two velocity fields at different times. Parameters ---------- U0, V0 : array-like ...
How would you implement a function in Python 3 that advances particles using a gridded velocity field.
You are a Python code analyst, evaluating scripts for potential improvements.
def spec_var(model, ph): """Compute variance of ``p`` from Fourier coefficients ``ph``. Parameters ---------- model : pyqg.Model instance The model object from which `ph` originates ph : complex array The field on which to compute the variance Returns ------- var_dens :...
Implement a function in Python 3 to compute the variance of p from Fourier coefficients ph.
As a Python code translator, you convert algorithms and pseudocode into Python.
Compute total spectral sum of the real spectral quantity ph^2
Given the following Python 3 function, write the documentation def spec_sum(ph2): ph2 = 2.*ph2 ph2[...,0] = ph2[...,0]/2. ph2[...,-1] = ph2[...,-1]/2. return ph2.sum(axis=(-1,-2))
You are a Python code analyst, evaluating scripts for potential improvements.
Compute isotropic spectrum phr of ph of model.
Can you tell what is the following Python 3 function doing def calc_ispec(model, ph): if model.kk.max()>model.ll.max(): kmax = model.ll.max() else: kmax = model.kk.max() # create radial wavenumber dkr = np.sqrt(model.dk**2 + model.dl**2) kr = np.arange(dkr/2.,kmax+dkr,dkr) phr...
You are a Python code analyst, evaluating scripts for potential improvements.
Initialize the stretching matrix.
How would you explain what the following Python 3 function does def _initialize_stretching_matrix(self): self.S = np.zeros((self.nz, self.nz)) if (self.nz==2) and (self.rd) and (self.delta): self.del1 = self.delta/(self.delta+1.) self.del2 = (self.delta+1.)**-1 sel...
As a Python code analyst, you investigate and solve complex coding mysteries
Initialize the background state of the current state of the class.
Explain what the following Python 3 code does def _initialize_background(self): self.H = self.Hi.sum() if np.asarray(self.U).ndim == 2: self.Ubg = self.U * np.ones((self.ny)) else: self.Ubg = np.expand_dims(self.U,axis=1) * np.ones((self.ny)) if not (self.nz==2...
As a Python code analyst, you investigate and solve complex coding mysteries
def _calc_eddy_time(self): """ estimate the eddy turn-over time in days """ ens = 0. for j in range(self.nz): ens = .5*self.Hi[j] * self.spec_var(self.wv2*self.ph[j]) return 2.*pi*np.sqrt( self.H / ens.sum() ) / 86400
Write a Python 3 script to estimate the eddy turn - over time in days
You are a Python code architect, reviewing and designing scalable and efficient code
def _initialize_model_diagnostics(self): """ Extra diagnostics for layered model """ self.add_diagnostic('entspec', description='barotropic enstrophy spectrum', function= (lambda self: np.abs((self.Hi[:,np.newaxis,np.newaxis]*self.qh).sum(axis=0))**2/...
Can you write a function in Python 3 where it adds diagnostics for the layered model.
You are a Python code architect, reviewing and designing scalable and efficient code
def _initialize_background(self): """Set up background state (zonal flow and PV gradients).""" # Background zonal flow (m/s): self.H = self.Hi.sum() self.set_U1U2(self.U1, self.U2) self.U = self.U1 - self.U2 # the F parameters self.F1 = self.rd**-2 / (1.+self.de...
How would you implement a function in Python 3 that initializes the background state of the current log - level hierarchy.
You are a Python code architect, reviewing and designing scalable and efficient code
def set_q1q2(self, q1, q2, check=False): """Set upper and lower layer PV anomalies. Parameters ---------- q1 : array-like Upper layer PV anomaly in spatial coordinates. q1 : array-like Lower layer PV anomaly in spatial coordinates. """ se...
Write a Python 3 function that can set the upper and lower layer PV anomalies.
As a Python code analyst, you investigate and solve complex coding mysteries
Set background zonal flow.
Make a summary of the following Python 3 code def set_U1U2(self, U1, U2): if len(np.shape(U1)) == 0: U1 = U1 * np.ones((self.ny)) if len(np.shape(U2)) == 0: U2 = U2 * np.ones((self.ny)) #self.Ubg = np.array([U1,U2])[:,np.newaxis,np.newaxis] self.U1 = U1 self...
As a Python code translator, you convert algorithms and pseudocode into Python.
estimate the eddy turn - over time in days
Can you generate a brief explanation for the following Python 3 code def _calc_eddy_time(self): ens = .5*self.Hi[0] * self.spec_var(self.wv2*self.ph1) + \ .5*self.Hi[1] * self.spec_var(self.wv2*self.ph2) return 2.*pi*np.sqrt( self.H / ens ) / 86400
As a python code expert, you are capable of creating scripts from specifications.
Initialize the diagnostics for the two - layer model.
Can you generate the documentation for the following Python 3 function def _initialize_model_diagnostics(self): self.add_diagnostic('entspec', description='barotropic enstrophy spectrum', function= (lambda self: np.abs(self.del1*self.qh[0] + self.del2*self.qh[1])**...
As a Python code analyst, you investigate and solve complex coding mysteries
initialize the inversion matrix
Explain what the following Python 3 code does def _initialize_inversion_matrix(self): # The bt model is diagonal. The inversion is simply qh = -kappa**2 ph self.a = -(self.wv2i+self.kd2)[np.newaxis, np.newaxis, :, :]
As a python code expert, you are capable of creating scripts from specifications.
def _calc_eddy_time(self): """ estimate the eddy turn-over time in days """ ens = .5*self.H * self.spec_var(self.wv2*self.ph) return 2.*pi*np.sqrt( self.H / ens ) / year
Implement a function in Python 3 to estimate the eddy turn - over time in days
You are a Python code analyst, evaluating scripts for potential improvements.
def calc_uv(self, x, y, prev=False): """Calculate velocity at x and y points due to vortex velocity field. Assumes x and y are vortex positions and are ordered the same as x0 and y0. The ordering is used to neglect to vortex self interaction.""" assert len(x) == self.N assert len...
Write a Python 3 script for calculating velocity at x and y points due to vortex velocity field.
As a Python code translator, you convert algorithms and pseudocode into Python.
Returns two arrays of u v at x y
Here you have a function in Python 3, explain what it does def uv_at_xy(self, x, y, x0, y0, s0): dx, dy = self.distance(x0, y0, x, y) #print 'dx, dy:', dx, dy rr2 = (dx**2 + dy**2)**-1 u = - s0 * dy * r_twopi * rr2 v = s0 * dx * r_twopi * rr2 #print 'u, v', u, v r...
As a Python code analyst, you investigate and solve complex coding mysteries
def reduce(args): """ >>> reduce([(2, 4), (4, 9)]) [(2, 4), (4, 9)] >>> reduce([(2, 6), (4, 10)]) [(2, 10)] """ if len(args) < 2: return args args.sort() ret = [args[0]] for next_i, (s, e) in enumerate(args, start=1): if next_i == len(args): ret[-1] = ret[-1]...
Create a Python 3 function for reducing the list of arguments into a single list of the same size.
As a Python code analyst, you investigate and solve complex coding mysteries
Return an interable of elements that overlap other in the tree.
Can you generate a brief explanation for the following Python 3 code def find(self, other): iset = self._iset l = binsearch_left_start(iset, other[0] - self._maxlen, 0, len(iset)) r = binsearch_right_end(iset, other[1], 0, len(iset)) iopts = iset[l:r] iiter = (s for s in iopts if...
As a Python code analyst, you investigate and solve complex coding mysteries
def loaddict(filename=DICTIONARY): """ Load the dictionary from a specific JSON file. """ global zhcdicts if zhcdicts: return if filename == _DEFAULT_DICT: zhcdicts = json.loads(get_module_res(filename).read().decode('utf-8')) else: with open(filename, 'rb') as f: ...
Write a Python 3 script for loading the dictionary from a specific JSON file.
As a Python code analyst, you investigate and solve complex coding mysteries
def getdict(locale): """ Generate or get convertion dict cache for certain locale. Dictionaries are loaded on demand. """ global zhcdicts, dict_zhcn, dict_zhsg, dict_zhtw, dict_zhhk, pfsdict if zhcdicts is None: loaddict(DICTIONARY) if locale == 'zh-cn': if dict_zhcn: ...
Can you write a function in Python 3 where it generates or get convertion dict cache for certain locale.
As a Python code composer, you craft elegant and concise scripts.
Detect text is whether Simplified Chinese or Traditional Chinese.
Make a summary of the following Python 3 code def issimp(s, full=False): if zhcdicts is None: loaddict(DICTIONARY) simp, trad = 0, 0 if full: for ch in s: if ch in zhcdicts['SIMPONLY']: simp += 1 elif ch in zhcdicts['TRADONLY']: trad +=...
You are a Python code analyst, evaluating scripts for potential improvements.
Convert a list of conversion dict to a dict for a certain locale.
Given the following Python 3 function, write the documentation def convtable2dict(convtable, locale, update=None): rdict = update.copy() if update else {} for r in convtable: if ':uni' in r: if locale in r: rdict[r[':uni']] = r[locale] elif locale[:-1] == 'zh-han': ...
You are a Python code analyst, evaluating scripts for potential improvements.
Tokenize s according to corresponding locale dictionary.
Explain what the following Python 3 code does def tokenize(s, locale, update=None): zhdict = getdict(locale) pfset = pfsdict[locale] if update: zhdict = zhdict.copy() zhdict.update(update) newset = set() for word in update: for ch in range(len(word)): ...
As a Python code composer, you craft elegant and concise scripts.
def convert_for_mw(s, locale, update=None): """ Recognizes MediaWiki's human conversion format. Use locale='zh' for no conversion. Reference: (all tests passed) https://zh.wikipedia.org/wiki/Help:高级字词转换语法 https://www.mediawiki.org/wiki/Writing_systems/Syntax >>> print(convert_for_mw('在现代,机...
Implement a function in Python 3 to convert a MediaWiki string to a human - readable format.
As a python code expert, you are capable of creating scripts from specifications.
A generator function for listing keys in a bucket.
Can you tell what is the following Python 3 function doing def bucket_lister(manager, bucket_name, prefix=None, marker=None, limit=None): eof = False while not eof: ret, eof, info = manager.list(bucket_name, prefix=prefix, limit=limit, marker=marker) if ret ...
You are a Python code generator, capable of creating scripts from specifications.
Get a Qiniu configuration variable from environment variable or django setting. py
Make a summary of the following Python 3 code def get_qiniu_config(name, default=None): config = os.environ.get(name, getattr(settings, name, default)) if config is not None: if isinstance(config, six.string_types): return config.strip() else: return config else: ...
As a python code expert, you are capable of creating scripts from specifications.
def register(self, username=""): """Performs /register with type: m.login.application_service Args: username(str): Username to register. """ if not username: username = utils.mxid2localpart(self.identity) content = { "type": "m.login.applicati...
Implement a Python 3 function for performing a register with type m. login. application_service AttributeNames
As a python code expert, you are capable of creating scripts from specifications.
Load a list of filenames from an external text file.
Can you tell what is the following Python 3 function doing def load_from_file(filename): if os.path.isdir(filename): logger.error("Err: File '%s' is a directory", filename) return None if not os.path.isfile(filename): logger.error("Err: File '%s' does not exist", filename) return...
You are a Python code generator, capable of creating scripts from specifications.
def parse_argv(): """ Parse command line arguments. Settings will be stored in the global variables declared above. """ parser = argparse.ArgumentParser(description='Find lyrics for a set of mp3' ' files and embed them as metadata') parser.add_argument('-j', ...
Write a Python 3 script for parsing command line arguments and return a dictionary of configuration variables.
As a Python code analyst, you investigate and solve complex coding mysteries
def decode(slug): """ Returns the uuid.UUID object represented by the given v4 or "nice" slug """ if sys.version_info.major != 2 and isinstance(slug, bytes): slug = slug.decode('ascii') slug = slug + '==' # base64 padding return uuid.UUID(bytes=base64.urlsafe_b64decode(slug))
Write a Python 3 script for decoding a base64 - encoded UUID object.
As a python code expert, you are capable of creating scripts from specifications.
def nice(): """ Returns a randomly generated uuid v4 compliant slug which conforms to a set of "nice" properties, at the cost of some entropy. Currently this means one extra fixed bit (the first bit of the uuid is set to 0) which guarantees the slug will begin with [A-Za-f]. For example such slugs d...
Write a Python 3 script to return a randomly generated uuid v4 compliant slug that conforms to a set of nice properties.
As a Python code composer, you craft elegant and concise scripts.
def filter_against_normal(self, normal_mutations, maf_min=0.2, maf_count_threshold=20, count_min=1): """Filters mutations that are in the given normal""" assert(normal_mutations.chrom == self.chrom) assert(normal_mutations.pos == self.pos) assert(normal_muta...
Create a Python 3 function for filtering mutations that are in the given normal.
You are a Python code analyst, evaluating scripts for potential improvements.
Returns the mutation in oncotator input format. Assumes mutations have vcf style positions.
Can you tell what is the following Python 3 function doing def to_oncotator(self): if self.type == ".": ref = self.ref alt = self.change start = self.pos end = self.pos elif self.type == "-": ref = self.change alt = "-" ...
You are a Python code architect, reviewing and designing scalable and efficient code
def add_handlers(self, room_handler=None, transaction_handler=None, user_handler=None): """Adds routes to Application that use specified handlers.""" # Add all the normal matrix API routes if room_handler: room = resources.Room(room_handler, ...
Write a Python 3 function that can add routes to Application that use specified handlers.
You are a Python code generator, capable of creating scripts from specifications.
def _merge(left, right, path=None, conflict=_Conflict.error): """ Merges values in place from *right* into *left*. :param left: mapping to merge into :param right: mapping to merge from :param path: `list` of keys processed before (used for error reporting only, should only need to be provi...
Can you implement a function in Python 3 that merges values in place from *right* into *left*. :param left: mapping to merge into :param right: mapping to merge from :param path: `list` of keys processed before (used for error reporting only, should only need to be provided by recursive calls) :param conflict: action t...
You are a Python code architect, reviewing and designing scalable and efficient code
simplest monitoring function to be aggregated with sum
Can you tell what is the following Python 3 function doing def log_mon_value(name, value=1, **kwargs): message = '{} => {}'.format(name, value) log_mon.info({'metric_name': name, 'value': value, 'message': message, **kwargs})
As a python code expert, you are capable of creating scripts from specifications.
Use a form to create a new object.
Here you have a function in Python 3, explain what it does def use_form(form_class, request=None, **top_kwargs): def validated_form(request, **kwargs): # import ipdb; ipdb.set_trace() data = request.query_params.dict() if request.method in ['GET'] else request.data if isinstance(data, Query...
You are a Python code analyst, evaluating scripts for potential improvements.
An orbit system of the given moon.
Here you have a function in Python 3, explain what it does def dx_orbit_sys(t, X): '''X = [ m1x, m1y, m2x, m2y, m3x, m3y, m4x, m4y, m1vx, m1vy, m2vx, m2vy, m3vx, m3vy, m4vx, m4vy ] ''' (m1x, m1y, m2x, m2y, m3x, m3y, m4x, m4y, m1vx, m1vy, m2vx, m2v...
As a Python code analyst, you investigate and solve complex coding mysteries
Adds a client to the penalty box.
Here you have a function in Python 3, explain what it does def add(self, client): if client.pool_id in self._client_ids: log.info("%r is already in the penalty box. Ignoring.", client) return release = time.time() + self._min_wait heapq.heappush(self._clients, (release, (...
You are a Python code architect, reviewing and designing scalable and efficient code
Get any clients ready to be used.
Can you tell what is the following Python 3 function doing def get(self): now = time.time() while self._clients and self._clients[0][0] < now: _, (client, last_wait) = heapq.heappop(self._clients) connect_start = time.time() try: client.echo("test") #...
As a Python code analyst, you investigate and solve complex coding mysteries
Validates a given input is of type string.
Can you tell what is the following Python 3 function doing def string(_object): if is_callable(_object): _validator = _object @wraps(_validator) def decorated(value): ensure(isinstance(value, basestring), "not of type string") return _validator(value) return ...
You are a Python code analyst, evaluating scripts for potential improvements.
def boolean(_object): """ Validates a given input is of type boolean. Example usage:: data = {'a' : True} schema = ('a', boolean) You can also use this as a decorator, as a way to check for the input before it even hits a validator you may be writing. .. note:: If the...
Write a Python 3 script for validating a given input is of type boolean.
As a Python code translator, you convert algorithms and pseudocode into Python.
Validates a given input is of type dictionary.
Can you generate a brief explanation for the following Python 3 code def dictionary(_object, *args): error_msg = 'not of type dictionary' if is_callable(_object): _validator = _object @wraps(_validator) def decorated(value): ensure(isinstance(value, dict), error_msg) ...
You are a Python code generator, capable of creating scripts from specifications.
Validates a given input is of type list.
How would you explain what the following Python 3 function does def array(_object): if is_callable(_object): _validator = _object @wraps(_validator) def decorated(value): ensure(isinstance(value, list), "not of type array") return _validator(value) return dec...
As a Python code analyst, you investigate and solve complex coding mysteries
def integer(_object): """ Validates a given input is of type int.. Example usage:: data = {'a' : 21} schema = ('a', integer) You can also use this as a decorator, as a way to check for the input before it even hits a validator you may be writing. .. note:: If the argu...
Write a Python 3 script for validating a given input is of type int..
As a Python code analyst, you investigate and solve complex coding mysteries
def constant(cls, value: Value, dtype: tf.DType = tf.float32) -> 'TensorFluent': '''Returns a constant `value` TensorFluent with given `dtype`. Args: value: The constant value. dtype: The output's data type. Returns: A constant Tensor...
How would you implement a function in Python 3 that returns a constant value TensorFluent with given dtype.
As a Python code translator, you convert algorithms and pseudocode into Python.
Returns a TensorFluent for the Bernoulli sampling op with given mean parameter.
Explain what the following Python 3 code does def Bernoulli(cls, mean: 'TensorFluent', batch_size: Optional[int] = None) -> Tuple[Distribution, 'TensorFluent']: '''Returns a TensorFluent for the Bernoulli sampling op with given mean parameter. Args: mean: The mean parameter ...
You are a Python code analyst, evaluating scripts for potential improvements.
def Uniform(cls, low: 'TensorFluent', high: 'TensorFluent', batch_size: Optional[int] = None) -> Tuple[Distribution, 'TensorFluent']: '''Returns a TensorFluent for the Uniform sampling op with given low and high parameters. Args: low: The low parameter of the Uniform...
Can you create a Python 3 function that returns a TensorFluent for the Uniform sampling op with given low and high parameters.
As a Python code translator, you convert algorithms and pseudocode into Python.
Returns a TensorFluent for the Normal sampling op with given mean and variance.
Here you have a function in Python 3, explain what it does def Normal(cls, mean: 'TensorFluent', variance: 'TensorFluent', batch_size: Optional[int] = None) -> Tuple[Distribution, 'TensorFluent']: '''Returns a TensorFluent for the Normal sampling op with given mean and variance. ...
As a Python code translator, you convert algorithms and pseudocode into Python.
Returns a TensorFluent for the Gamma sampling op with given shape and scale parameters.
Make a summary of the following Python 3 code def Gamma(cls, shape: 'TensorFluent', scale: 'TensorFluent', batch_size: Optional[int] = None) -> Tuple[Distribution, 'TensorFluent']: '''Returns a TensorFluent for the Gamma sampling op with given shape and scale parameters. ...
As a Python code composer, you craft elegant and concise scripts.
def Exponential(cls, mean: 'TensorFluent', batch_size: Optional[int] = None) -> Tuple[Distribution, 'TensorFluent']: '''Returns a TensorFluent for the Exponential sampling op with given mean parameter. Args: mean: The mean parameter of the Exponential distribution. ...
How would you implement a function in Python 3 that returns a TensorFluent for the Exponential sampling op with given mean parameter.
You are a Python code generator, capable of creating scripts from specifications.
Returns a copy of the input fluent with stop_gradient at tensor level.
Can you tell what is the following Python 3 function doing def stop_gradient(cls, x: 'TensorFluent') -> 'TensorFluent': '''Returns a copy of the input fluent with stop_gradient at tensor level. Args: x: The input fluent. Returns: A TensorFluent that stops backpropagatio...
As a Python code composer, you craft elegant and concise scripts.
Returns a copy of the fluent with stop_gradient applied at batch level.
Can you tell what is the following Python 3 function doing def stop_batch_gradient(cls, x: 'TensorFluent', stop_batch: tf.Tensor) -> 'TensorFluent': '''Returns a copy of the inputs fluent with stop_gradient applied at batch level. Args: x: The input fluent. stop_batch: A boolean...
You are a Python code architect, reviewing and designing scalable and efficient code
Returns a TensorFluent for the abs function.
Given the following Python 3 function, write the documentation def abs(cls, x: 'TensorFluent') -> 'TensorFluent': '''Returns a TensorFluent for the abs function. Args: x: The input fluent. Returns: A TensorFluent wrapping the abs function. ''' return cls...
You are a Python code architect, reviewing and designing scalable and efficient code
Returns a TensorFluent for the exp function.
Can you generate a brief explanation for the following Python 3 code def exp(cls, x: 'TensorFluent') -> 'TensorFluent': '''Returns a TensorFluent for the exp function. Args: x: The input fluent. Returns: A TensorFluent wrapping the exp function. ''' retu...
As a python code expert, you are capable of creating scripts from specifications.
def log(cls, x: 'TensorFluent') -> 'TensorFluent': '''Returns a TensorFluent for the log function. Args: x: The input fluent. Returns: A TensorFluent wrapping the log function. ''' return cls._unary_op(x, tf.log, tf.float32)
Implement a Python 3 function for returning a TensorFluent for the log function.
You are a Python code generator, capable of creating scripts from specifications.
def sqrt(cls, x: 'TensorFluent') -> 'TensorFluent': '''Returns a TensorFluent for the sqrt function. Args: x: The input fluent. Returns: A TensorFluent wrapping the sqrt function. ''' return cls._unary_op(x, tf.sqrt, tf.float32)
Can you implement a function in Python 3 that returns a TensorFluent for the sqrt function.
As a Python code composer, you craft elegant and concise scripts.
def cos(cls, x: 'TensorFluent') -> 'TensorFluent': '''Returns a TensorFluent for the cos function. Args: x: The input fluent. Returns: A TensorFluent wrapping the cos function. ''' return cls._unary_op(x, tf.cos, tf.float32)
How would you code a function in Python 3 to return a TensorFluent for the cos function.
You are a Python code architect, reviewing and designing scalable and efficient code
Returns a TensorFluent for the sin function.
Can you tell what is the following Python 3 function doing def sin(cls, x: 'TensorFluent') -> 'TensorFluent': '''Returns a TensorFluent for the sin function. Args: x: The input fluent. Returns: A TensorFluent wrapping the sin function. ''' return cls._un...
As a python code expert, you are capable of creating scripts from specifications.
def tan(cls, x: 'TensorFluent') -> 'TensorFluent': '''Returns a TensorFluent for the tan function. Args: x: The input fluent. Returns: A TensorFluent wrapping the tan function. ''' return cls._unary_op(x, tf.tan, tf.float32)
Write a Python 3 script for returning a TensorFluent for the tan function.
You are a Python code architect, reviewing and designing scalable and efficient code
def acos(cls, x: 'TensorFluent') -> 'TensorFluent': '''Returns a TensorFluent for the arccos function. Args: x: The input fluent. Returns: A TensorFluent wrapping the arccos function. ''' return cls._unary_op(x, tf.acos, tf.float32)
Create a Python 3 function for returning a TensorFluent for the acos function.
You are a Python code architect, reviewing and designing scalable and efficient code
def asin(cls, x: 'TensorFluent') -> 'TensorFluent': '''Returns a TensorFluent for the arcsin function. Args: x: The input fluent. Returns: A TensorFluent wrapping the arcsin function. ''' return cls._unary_op(x, tf.asin, tf.float32)
How would you code a function in Python 3 to return a TensorFluent for the arcsin function.
As a Python code translator, you convert algorithms and pseudocode into Python.
Returns a TensorFluent for the arctan function.
Explain what the following Python 3 code does def atan(cls, x: 'TensorFluent') -> 'TensorFluent': '''Returns a TensorFluent for the arctan function. Args: x: The input fluent. Returns: A TensorFluent wrapping the arctan function. ''' return cls._unary_op...
As a Python code analyst, you investigate and solve complex coding mysteries
Returns a TensorFluent for the round function.
Can you generate a brief explanation for the following Python 3 code def round(cls, x: 'TensorFluent') -> 'TensorFluent': '''Returns a TensorFluent for the round function. Args: x: The input fluent. Returns: A TensorFluent wrapping the round function. ''' ...
As a Python code translator, you convert algorithms and pseudocode into Python.
Returns a TensorFluent for the ceil function.
Make a summary of the following Python 3 code def ceil(cls, x: 'TensorFluent') -> 'TensorFluent': '''Returns a TensorFluent for the ceil function. Args: x: The input fluent. Returns: A TensorFluent wrapping the ceil function. ''' return cls._unary_op(x, ...
You are a Python code architect, reviewing and designing scalable and efficient code
Returns a TensorFluent for the floor function.
Given the following Python 3 function, write the documentation def floor(cls, x: 'TensorFluent') -> 'TensorFluent': '''Returns a TensorFluent for the floor function. Args: x: The input fluent. Returns: A TensorFluent wrapping the floor function. ''' retu...
As a Python code translator, you convert algorithms and pseudocode into Python.
def pow(cls, x: 'TensorFluent', y: 'TensorFluent') -> 'TensorFluent': '''Returns a TensorFluent for the pow function.TensorFluent Args: x: The first operand. y: The second operand. Returns: A TensorFluent wrapping the pow function. ''' return...
Write a Python 3 function that can return a TensorFluent for the pow function.
You are a Python code generator, capable of creating scripts from specifications.
def max(cls, x: 'TensorFluent', y: 'TensorFluent') -> 'TensorFluent': '''Returns a TensorFluent for the maximum function.TensorFluent Args: x: The first operand. y: The second operand. Returns: A TensorFluent wrapping the maximum function. ''' ...
Can you implement a function in Python 3 that returns a TensorFluent for the maximum function.
As a python code expert, you are capable of creating scripts from specifications.
def min(cls, x: 'TensorFluent', y: 'TensorFluent') -> 'TensorFluent': '''Returns a TensorFluent for the minimum function. Args: x: The first operand. y: The second operand. Returns: A TensorFluent wrapping the minimum function. ''' return cls...
How would you code a function in Python 3 to return a TensorFluent for the minimum function.
You are a Python code generator, capable of creating scripts from specifications.
def if_then_else(cls, condition: 'TensorFluent', true_case: 'TensorFluent', false_case: 'TensorFluent') -> 'TensorFluent': '''Returns a TensorFluent for the control op if-then-else. Args: condition: Boolean fluent for the if condition. true_ca...
Create a Python 3 function to return a TensorFluent for the if - then - else control op.
As a Python code analyst, you investigate and solve complex coding mysteries
def _binary_op(cls, x: 'TensorFluent', y: 'TensorFluent', op: Callable[[tf.Tensor, tf.Tensor], tf.Tensor], dtype: tf.DType) -> 'TensorFluent': '''Returns a TensorFluent for the binary `op` applied to fluents `x` and `y`. Args: x: The first ope...
Implement a function in Python 3 to return a TensorFluent for the binary op applied to fluents x and y.
As a Python code translator, you convert algorithms and pseudocode into Python.
Returns a TensorFluent for the unary op applied to fluent x.
Can you generate a brief explanation for the following Python 3 code def _unary_op(cls, x: 'TensorFluent', op: Callable[[tf.Tensor], tf.Tensor], dtype: tf.DType) -> 'TensorFluent': '''Returns a TensorFluent for the unary `op` applied to fluent `x`. Args: ...
As a Python code analyst, you investigate and solve complex coding mysteries
Returns a TensorFluent for the aggregation op applied to fluent x.
Explain what the following Python 3 code does def _aggregation_op(cls, op: Callable[[tf.Tensor, Optional[Sequence[int]]], tf.Tensor], x: 'TensorFluent', vars_list: List[str]) -> 'TensorFluent': '''Returns a TensorFluent for the aggregation `op` applied to fluent `x`. ...
As a Python code analyst, you investigate and solve complex coding mysteries