output
stringlengths
1
928k
instruction
stringlengths
7
928k
system
stringlengths
0
104k
Get the version string through the binary.
How would you explain what the following Python 3 function does def get_bin_version_str(bin_path, version_flag='-v', kw={}): try: prog = _get_exec_binary(bin_path, kw) version_str = version_expr.search( check_output([prog, version_flag], **kw).decode(locale) ).groups()[0] ex...
You are a Python code generator, capable of creating scripts from specifications.
Get the version string through the binary and return a tuple of integers.
How would you explain what the following Python 3 function does def get_bin_version(bin_path, version_flag='-v', kw={}): version_str = get_bin_version_str(bin_path, version_flag, kw) if version_str: return tuple(int(i) for i in version_str.split('.'))
You are a Python code generator, capable of creating scripts from specifications.
Calls node with an inline source.
Explain what the following Python 3 code does def node(self, source, args=(), env={}): return self._exec(self.node_bin, source, args=args, env=env)
You are a Python code analyst, evaluating scripts for potential improvements.
This function generates a manifest json for the Python package name.
Given the following Python 3 function, write the documentation def pkg_manager_view( self, package_names, stream=None, explicit=False, **kw): """ Returns the manifest JSON for the Python package name. Default npm implementation calls for package.json. If this class is initi...
You are a Python code architect, reviewing and designing scalable and efficient code
def pkg_manager_init( self, package_names, overwrite=False, merge=False, callback=None, **kw): """ Note: default implementation calls for npm and package.json, please note that it may not be the case for this instance of Driver. If this class is initiated...
Can you write a function in Python 3 where it notes default implementation calls for npm and package.json, please note that it may not be the case for this instance of Driver. If this class is initiated using standard procedures, this will emulate the functionality of ``npm init`` for the generation of a working ``pack...
As a Python code composer, you craft elegant and concise scripts.
This method installs all dependencies into the current working directory for the specified Python package.
Can you generate a brief explanation for the following Python 3 code def pkg_manager_install( self, package_names=None, production=None, development=None, args=(), env={}, **kw): """ This will install all dependencies into the current working directory for the...
You are a Python code generator, capable of creating scripts from specifications.
Calls the package manager with the arguments.
Can you generate the documentation for the following Python 3 function def run(self, args=(), env={}): # the following will call self._get_exec_binary return self._exec(self.binary, args=args, env=env)
As a python code expert, you are capable of creating scripts from specifications.
Get the executable path for the .
Given the following Python 3 function, write the documentation def _get_exec_binary(binary, kw): binary = which(binary, path=kw.get('env', {}).get('PATH')) if binary is None: raise_os_error(errno.ENOENT) return binary
As a Python code composer, you craft elegant and concise scripts.
def _init_entry_points(self, entry_points): """ Default initialization loop. """ logger.debug( "registering %d entry points for registry '%s'", len(entry_points), self.registry_name, ) for entry_point in entry_points: try: ...
Can you implement a function in Python 3 that initializes the entry points for the specified registry.
You are a Python code generator, capable of creating scripts from specifications.
def store_records_for_package(self, entry_point, records): """ Store the records in a way that permit lookup by package """ # If provided records already exist in the module mapping list, # it likely means that a package declared multiple keys for the # same package name...
Write a Python 3 function for storing the records for the given entry_point in a way that permit lookup by package .
You are a Python code analyst, evaluating scripts for potential improvements.
Register a lone entry_point
Make a summary of the following Python 3 code def register_entry_point(self, entry_point): module = _import_module(entry_point.module_name) self._register_entry_point_module(entry_point, module)
As a Python code translator, you convert algorithms and pseudocode into Python.
def get_record(self, name): """ Get a record by name """ result = {} result.update(self.records.get(name, {})) return result
Write a Python 3 function for getting a record by name
You are a Python code generator, capable of creating scripts from specifications.
def get_records_for_package(self, package_name): """ Get all records identified by package. """ names = self.package_module_map.get(package_name, []) result = {} for name in names: result.update(self.get_record(name)) return result
Can you create a Python 3 function that gets all records identified by package.
You are a Python code architect, reviewing and designing scalable and efficient code
Resolve the parent module registry name.
Given the following Python 3 function, write the documentation def resolve_parent_registry_name(self, registry_name, suffix): if not registry_name.endswith(suffix): raise ValueError( "child module registry name defined with invalid suffix " "('%s' does not end with '...
As a Python code analyst, you investigate and solve complex coding mysteries
def get_record(self, name): """ Get a record for the registered name, which will be a set of matching desired "module names" for the given path. """ return set().union(self.records.get(name, set()))
Can you create a Python 3 function that gets a record for the given name which will be a set of all records matching the desired module names.
You are a Python code generator, capable of creating scripts from specifications.
def get_records_for_package(self, package_name): """ Get all records identified by package. """ result = [] result.extend(self.package_module_map.get(package_name)) return result
Can you write a function in Python 3 where it gets all records identified by package.
You are a Python code analyst, evaluating scripts for potential improvements.
def which(self): """ Figure out which binary this will execute. Returns None if the binary is not found. """ if self.binary is None: return None return which(self.binary, path=self.env_path)
How would you code a function in Python 3 to figure out which binary this will execute.
As a Python code translator, you convert algorithms and pseudocode into Python.
def find_node_modules_basedir(self): """ Find all node_modules directories configured to be accessible through this driver instance. This is typically used for adding the direct instance, and does not traverse the parent directories like what Node.js does. Returns a lis...
Write a Python 3 function for finding all node_modules directories configured to be accessible through this driver instance.
As a Python code composer, you craft elegant and concise scripts.
Return the path to the binary which has node_path and node_modules.
Explain what the following Python 3 code does def which_with_node_modules(self): if self.binary is None: return None # first, log down the pedantic things... if isdir(self.join_cwd(NODE_MODULES)): logger.debug( "'%s' instance will attempt to locate '%s' ...
As a Python code translator, you convert algorithms and pseudocode into Python.
Attempts to locate and set the PATH environment variable for the instance with the node modules defined for this instance.
Explain what the following Python 3 code does def _set_env_path_with_node_modules(self): modcls_name = ':'.join(( self.__class__.__module__, self.__class__.__name__)) if self.binary is None: raise ValueError( "binary undefined for '%s' instance" % modcls_name) ...
As a Python code translator, you convert algorithms and pseudocode into Python.
Executes the given binary using stdin and args with environment variables.
Can you tell what is the following Python 3 function doing def _exec(self, binary, stdin='', args=(), env={}): call_kw = self._gen_call_kws(**env) call_args = [self._get_exec_binary(call_kw)] call_args.extend(args) return fork_exec(call_args, stdin, **call_kw)
As a Python code composer, you craft elegant and concise scripts.
def dump(self, blob, stream): """ Call json.dump with the attributes of this instance as arguments. """ json.dump( blob, stream, indent=self.indent, sort_keys=True, separators=self.separators, )
How would you implement a function in Python 3 that dumps the contents of the object to a file - like object stream.
As a Python code translator, you convert algorithms and pseudocode into Python.
Dump the contents of the object as a JSON string.
Can you generate the documentation for the following Python 3 function def dumps(self, blob): return json.dumps( blob, indent=self.indent, sort_keys=True, separators=self.separators, )
As a Python code analyst, you investigate and solve complex coding mysteries
def join_cwd(self, path=None): """ Join the path with the current working directory. If it is specified for this instance of the object it will be used, otherwise rely on the global value. """ if self.working_dir: logger.debug( "'%s' instance...
Write a Python 3 script to join the current working directory with the current working directory.
You are a Python code analyst, evaluating scripts for potential improvements.
Transform an unicode string into a UTF - 8 equivalent.
Make a summary of the following Python 3 code def _unicode_handler(obj): try: result = obj.isoformat() except AttributeError: raise TypeError("Unserializable object {} of type {}".format(obj, type(obj))) return result
As a Python code composer, you craft elegant and concise scripts.
def encode(self, entity): """ Encodes the data, creating a JSON structure from an instance from the domain model. :param entity: the instance to encode :return: a JSON structure created from the received data """ encoded = self._dict_encoder.encode(entity) ...
Implement a Python 3 function for encoding the data into a JSON structure from an instance from the current domain model.
You are a Python code generator, capable of creating scripts from specifications.
returns a parser for the IPI Base Number field
Given the following Python 3 function, write the documentation def ipi_base_number(name=None): if name is None: name = 'IPI Base Number Field' field = pp.Regex('I-[0-9]{9}-[0-9]') # Name field.setName(name) field_num = basic.numeric(13) field_num.setName(name) field = field | fi...
You are a Python code architect, reviewing and designing scalable and efficient code
A function to create a parser for the IPI Name Number field.
How would you explain what the following Python 3 function does def ipi_name_number(name=None): if name is None: name = 'IPI Name Number Field' field = basic.numeric(11) field.setName(name) return field.setResultsName('ipi_name_n')
As a Python code composer, you craft elegant and concise scripts.
A function to create a parser for the ISWC code field.
Can you generate the documentation for the following Python 3 function def iswc(name=None): if name is None: name = 'ISWC Field' # T followed by 10 numbers field = pp.Regex('T[0-9]{10}') # Name field.setName(name) # White spaces are not removed field.leaveWhitespace() return...
You are a Python code analyst, evaluating scripts for potential improvements.
Returns a grammar for a numeric field storing a percentage field.
Explain what the following Python 3 code does def percentage(columns, maximum=100, name=None): if name is None: name = 'Percentage Field' if columns < 3: message = 'The values can not be lower than 3' raise pp.ParseException(message) field = basic.numeric_float(columns, 3) fi...
As a Python code composer, you craft elegant and concise scripts.
def _assert_is_percentage(value, maximum=100): """ Makes sure the received value is a percentage. Otherwise an exception is thrown. :param value: the value to check """ if value < 0 or value > maximum: message = 'The value on a percentage field should be between 0 and %s' \ ...
Create a Python 3 function for ensuring that the received value is a percentage.
As a Python code translator, you convert algorithms and pseudocode into Python.
def ean_13(name=None): """ Creates the grammar for an EAN 13 code. These are the codes on thirteen digits barcodes. :param name: name for the field :return: grammar for an EAN 13 field """ if name is None: name = 'EAN 13 Field' field = basic.numeric(13) field = field.set...
Can you implement a function in Python 3 that returns the grammar for an EAN 13 code.
As a Python code composer, you craft elegant and concise scripts.
def isrc(name=None): """ Creates the grammar for an ISRC code. ISRC stands for International Standard Recording Code, which is the standard ISO 3901. This stores information identifying a particular recording. :param name: name for the field :return: grammar for an ISRC field """ ...
Write a Python 3 function that can return a grammar for an ISRC code.
As a python code expert, you are capable of creating scripts from specifications.
Returns a grammar for a short ISRC code.
Can you tell what is the following Python 3 function doing def _isrc_long(name=None): config = CWRTables() if name is None: name = 'ISRC Field' country = config.get_data('isrc_country_code') # registrant = basic.alphanum(3) # year = pp.Regex('[0-9]{2}') # work_id = pp.Regex('[0-9]{5}'...
As a Python code analyst, you investigate and solve complex coding mysteries
def visan(name=None): """ Creates the grammar for a V-ISAN code. This is a variation on the ISAN (International Standard Audiovisual Number) :param name: name for the field :return: grammar for an ISRC field """ if name is None: name = 'V-ISAN Field' field = pp.Regex('[0-9]{2...
Write a Python 3 function that can return a grammar for a V - ISAN code.
As a Python code translator, you convert algorithms and pseudocode into Python.
Creates the grammar for an audio visual key code.
Can you generate the documentation for the following Python 3 function def audio_visual_key(name=None): if name is None: name = 'AVI Field' society_code = basic.numeric(3) society_code = society_code.setName('Society Code') \ .setResultsName('society_code') av_number = basic.alphanum(...
You are a Python code generator, capable of creating scripts from specifications.
def date_time(name=None): """ Creates the grammar for a date and time field, which is a combination of the Date (D) and Time or Duration field (T). This field requires first a Date, and then a Time, without any space in between. :param name: name for the field :return: grammar for a Date a...
How would you implement a function in Python 3 that returns a grammar for a date and time field.
As a Python code analyst, you investigate and solve complex coding mysteries
def lookup_int(values, name=None): """ Lookup field which transforms the result into an integer. :param values: values allowed :param name: name for the field :return: grammar for the lookup field """ field = basic.lookup(values, name) field.addParseAction(lambda l: int(l[0])) ret...
Can you create a Python 3 function that returns a Lookup field which transforms the result into an integer.
As a Python code composer, you craft elegant and concise scripts.
Extract a specific argument from a specific function name.
Here you have a function in Python 3, explain what it does def extract_function_argument(text, f_name, f_argn, f_argt=asttypes.String): tree = parse(text) return list(filter_function_argument(tree, f_name, f_argn, f_argt))
As a Python code analyst, you investigate and solve complex coding mysteries
Yields only strings within the list of module names that are not defined in the function call.
Make a summary of the following Python 3 code def yield_amd_require_string_arguments( node, pos, reserved_module=reserved_module, wrapped=define_wrapped): """ This yields only strings within the lists provided in the argument list at the specified position from a function call. Original...
As a Python code translator, you convert algorithms and pseudocode into Python.
Yield just a string argument from the given position.
Given the following Python 3 function, write the documentation def yield_string_argument(node, pos): if not isinstance(node.args.items[pos], asttypes.String): return yield to_str(node.args.items[pos])
As a Python code analyst, you investigate and solve complex coding mysteries
Yields all module names from the source tree root.
Here you have a function in Python 3, explain what it does def yield_module_imports(root, checks=string_imports()): if not isinstance(root, asttypes.Node): raise TypeError('provided root must be a node') for child in yield_function(root, deep_filter): for f, condition in checks: if...
As a Python code composer, you craft elegant and concise scripts.
Yield all nodes that provide an import
Make a summary of the following Python 3 code def yield_module_imports_nodes(root, checks=import_nodes()): if not isinstance(root, asttypes.Node): raise TypeError('provided root must be a node') for child in yield_function(root, deep_filter): for f, condition in checks: if conditio...
You are a Python code generator, capable of creating scripts from specifications.
open the index file and return the object
Can you generate a brief explanation for the following Python 3 code def open_fasta_index(self): index = self.fasta_index try: handle = open(index, 'rb') except (IOError, TypeError): sys.stderr.write('index not found, creating it\n') try: self....
As a python code expert, you are capable of creating scripts from specifications.
Get the sequence from the file.
How would you explain what the following Python 3 function does def get_sequence(self, chrom, start, end, strand='+', indexing=(-1, 0)): try: divisor = int(self.sequence_index[chrom][2]) except KeyError: self.open_fasta_index() try: divisor = int(self....
You are a Python code architect, reviewing and designing scalable and efficient code
Given a child module registry attempt to resolve the lineage.
Explain what the following Python 3 code does def resolve_child_module_registries_lineage(registry): children = [registry] while isinstance(registry, BaseChildModuleRegistry): if registry.parent in children: # this should never normally occur under normal usage where # classes h...
As a python code expert, you are capable of creating scripts from specifications.
Add a modification to the list of modifications.
Given the following Python 3 function, write the documentation def addModification(self, aa,position, modMass, modType): #clean up xtandem if not modType: #try to figure out what it is tmass = abs(modMass) smass = str(tmass) prec = len(str(tmass-int(tmass)...
As a Python code composer, you craft elegant and concise scripts.
def resource_filename_mod_dist(module_name, dist): """ Given a module name and a distribution, attempt to resolve the actual path to the module. """ try: return pkg_resources.resource_filename( dist.as_requirement(), join(*module_name.split('.'))) except pkg_resources.Distri...
Write a Python 3 function for attempting to resolve the ArcGIS module name and a distribution.
You are a Python code analyst, evaluating scripts for potential improvements.
def resource_filename_mod_entry_point(module_name, entry_point): """ If a given package declares a namespace and also provide submodules nested at that namespace level, and for whatever reason that module is needed, Python's import mechanism will not have a path associated with that module. However...
Can you implement a function in Python 3 that returns the full path to the resource file for the given module and entry point.
As a Python code translator, you convert algorithms and pseudocode into Python.
def modgen( module, entry_point, modpath='pkg_resources', globber='root', fext=JS_EXT, registry=_utils): """ JavaScript styled module location listing generator. Arguments: module The Python module to start fetching from. entry_point This is the original en...
How would you code a function in Python 3 to generate a JavaScript styled module location listing for the given entry point.
You are a Python code architect, reviewing and designing scalable and efficient code
Provides the raw __path__ of the module.
How would you explain what the following Python 3 function does def modpath_all(module, entry_point): module_paths = getattr(module, '__path__', []) if not module_paths: logger.warning( "module '%s' does not appear to be a namespace module or does not " "export available paths o...
As a python code expert, you are capable of creating scripts from specifications.
def modpath_last(module, entry_point): """ Provides the raw __path__. Incompatible with PEP 302-based import hooks and incompatible with zip_safe packages. Deprecated. Will be removed by calmjs-4.0. """ module_paths = modpath_all(module, entry_point) if len(module_paths) > 1: log...
Can you create a Python 3 function that returns the raw path of the last module in the list.
As a python code expert, you are capable of creating scripts from specifications.
def modpath_pkg_resources(module, entry_point): """ Goes through pkg_resources for compliance with various PEPs. This one accepts a module as argument. """ result = [] try: path = resource_filename_mod_entry_point(module.__name__, entry_point) except ImportError: logger.war...
Implement a Python 3 function for going through pkg_resources for compliance with various PEPs.
As a Python code analyst, you investigate and solve complex coding mysteries
General mapper for the micro registry.
How would you explain what the following Python 3 function does def mapper(module, entry_point, modpath='pkg_resources', globber='root', modname='es6', fext=JS_EXT, registry=_utils): """ General mapper Loads components from the micro registry. """ modname_f = modname if calla...
You are a Python code analyst, evaluating scripts for potential improvements.
Default mapper using python style globber
Can you generate the documentation for the following Python 3 function def mapper_python(module, entry_point, globber='root', fext=JS_EXT): return mapper( module, entry_point=entry_point, modpath='pkg_resources', globber=globber, modname='python', fext=fext)
As a Python code analyst, you investigate and solve complex coding mysteries
def _printable_id_code(self): """ Returns the code in a printable form, filling with zeros if needed. :return: the ID code in a printable form """ code = str(self.id_code) while len(code) < self._code_size: code = '0' + code return code
Create a Python 3 function to return the ID code in a printable form filling with zeros if needed.
As a python code expert, you are capable of creating scripts from specifications.
def _printable_id_code(self): """ Returns the code in a printable form, separating it into groups of three characters using a point between them. :return: the ID code in a printable form """ code = super(ISWCCode, self)._printable_id_code() code1 = code[:3] ...
Write a Python 3 function for returning the code in a printable form separating it into groups of three characters using a point between them.
As a python code expert, you are capable of creating scripts from specifications.
Discard from original file.
Can you generate a brief explanation for the following Python 3 code def discard(self, s): lines = s.splitlines(True) for line in lines: if line[-1] not in '\r\n': if not self.warn: logger.warning( 'partial line discard UNSUPPORTED...
As a Python code analyst, you investigate and solve complex coding mysteries
def write_padding(self, s): """ Write string that are not part of the original file. """ lines = s.splitlines(True) for line in lines: self.stream.write(line) if line[-1] in '\r\n': self._newline() else: # this ...
Create a Python 3 function to write a string that is not part of the original file.
You are a Python code architect, reviewing and designing scalable and efficient code
Same as babel. numbers. format_currency but has a force_frac argument instead of currency_digits.
Make a summary of the following Python 3 code def format_currency(number, currency, format, locale=babel.numbers.LC_NUMERIC, force_frac=None, format_type='standard'): """Same as ``babel.numbers.format_currency``, but has ``force_frac`` argument instead of ``currency_digits``. If the ``f...
As a Python code translator, you convert algorithms and pseudocode into Python.
This example prints the variant character data.
Can you generate the documentation for the following Python 3 function def run(unihan_options={}): print("This example prints variant character data.") c = Cihai() if not c.unihan.is_bootstrapped: # download and install Unihan to db c.unihan.bootstrap(unihan_options) c.unihan.add_plugin( ...
You are a Python code analyst, evaluating scripts for potential improvements.
def reflect_db(self): """ No-op to reflect db info. This is available as a method so the database can be reflected outside initialization (such bootstrapping unihan during CLI usage). """ self.metadata.reflect(views=True, extend_existing=True) self.base = automap...
Implement a function in Python 3 to reflect the database info.
As a Python code translator, you convert algorithms and pseudocode into Python.
Parses a string representation of a single element into a tree of elements.
Make a summary of the following Python 3 code def parse(s, element=Element, atomicstring=lambda s: s): global Element_, AtomicString_ Element_ = element AtomicString_ = atomicstring s, nodes = parse_exprs(s) remove_invisible(nodes) nodes = map(remove_private, nodes) return El('math', El(...
As a python code expert, you are capable of creating scripts from specifications.
Decorator for tracing the parser.
Explain what the following Python 3 code does def trace_parser(p): def nodes_to_string(n): if isinstance(n, list): result = '[ ' for m in map(nodes_to_string, n): result += m result += ' ' result += ']' return result e...
You are a Python code architect, reviewing and designing scalable and efficient code
Removes a symbol from a probability distribution.
Given the following Python 3 function, write the documentation def remove_symbol_from_dist(dist, index): ''' prob is a ndarray representing a probability distribution. index is a number between 0 and and the number of symbols ( len(prob)-1 ) return the probability distribution if the element at 'index' ...
As a Python code composer, you craft elegant and concise scripts.
def change_response(x, prob, index): ''' change every response in x that matches 'index' by randomly sampling from prob ''' #pdb.set_trace() N = (x==index).sum() #x[x==index]=9 x[x==index] = dist.sample(N)
How would you implement a function in Python 3 that changes every response in x that matches index by randomly sampling from prob
You are a Python code generator, capable of creating scripts from specifications.
def toy_example(): """ Make a toy example where x is uniformly distributed with N bits and y follows x but with symbol dependent noise. x=0 -> y=0 x=1 -> y=1 + e x=2 -> y=2 + 2*e ... x=n -> y=n + n*e where by n*e I am saying that the noise grows """ #pdb.set_trace() N=4 ...
How would you code a function in Python 3 to make a toy example where x is uniformly distributed with N bits and y is uniformly distributed with N bits and y follows x and with symbol dependent noise.
You are a Python code architect, reviewing and designing scalable and efficient code
def differentiate_mi(x, y): ''' for each symbol in x, change x such that there are no more of such symbols (replacing by a random distribution with the same proba of all other symbols) and compute mi(new_x, y) ''' #pdb.set_trace() dist = Distribution(discrete.symbols_to_prob(x)) diff = ...
Can you write a function in Python 3 where it computes the mi of the given x and y
As a python code expert, you are capable of creating scripts from specifications.
def sample(self, *args): ''' generate a random number in [0,1) and return the index into self.prob such that self.prob[index] <= random_number but self.prob[index+1] > random_number implementation note: the problem is identical to finding the index into self.cumsum where the ran...
Write a Python 3 function for generating a random number in [ 0 1 ) and return the index into self. prob where the random number is greater than random_number.
As a Python code translator, you convert algorithms and pseudocode into Python.
def default_log_template(self, record): """Return the prefix for the log message. Template for Formatter. :param: record: :py:class:`logging.LogRecord` object. this is passed in from inside the :py:meth:`logging.Formatter.format` record. """ reset = Style.RESET_ALL levelname = [ LEVEL...
Can you implement a function in Python 3 that returns the default log template for the given log record.
You are a Python code analyst, evaluating scripts for potential improvements.
Combine two dictionary - like objects.
How would you explain what the following Python 3 function does def merge_dict(base, additional): if base is None: return additional if additional is None: return base if not ( isinstance(base, collections.Mapping) and isinstance(additional, collections.Mapping) ): ...
You are a Python code generator, capable of creating scripts from specifications.
def expand_config(d, dirs): """ Expand configuration XDG variables, environmental variables, and tildes. Parameters ---------- d : dict config information dirs : appdirs.AppDirs XDG application mapping Notes ----- *Environmentable variables* are expanded via :py:fun...
Write a Python 3 script to expand configuration XDG variables environmental variables and tildes.
You are a Python code generator, capable of creating scripts from specifications.
Download extract and import unihan to database.
How would you explain what the following Python 3 function does def bootstrap_unihan(metadata, options={}): options = merge_dict(UNIHAN_ETL_DEFAULT_OPTIONS.copy(), options) p = unihan.Packager(options) p.download() data = p.export() table = create_unihan_table(UNIHAN_FIELDS, metadata) metadata....
As a Python code analyst, you investigate and solve complex coding mysteries
Return True if cihai is correctly bootstrapped.
Can you generate the documentation for the following Python 3 function def is_bootstrapped(metadata): fields = UNIHAN_FIELDS + DEFAULT_COLUMNS if TABLE_NAME in metadata.tables.keys(): table = metadata.tables[TABLE_NAME] if set(fields) == set(c.name for c in table.columns): return Tr...
You are a Python code architect, reviewing and designing scalable and efficient code
def create_unihan_table(columns, metadata): """Create table and return :class:`sqlalchemy.Table`. Parameters ---------- columns : list columns for table, e.g. ``['kDefinition', 'kCantonese']`` metadata : :class:`sqlalchemy.schema.MetaData` Instance of sqlalchemy metadata Retur...
Can you implement a function in Python 3 that creates a new table with columns and index.
As a Python code composer, you craft elegant and concise scripts.
compute the nem - py address from the public one
Given the following Python 3 function, write the documentation def get_address(pk, main_net=True, prefix=None): if isinstance(pk, str): pk = unhexlify(pk.encode()) assert len(pk) == 32, 'PK is 32bytes {}'.format(len(pk)) k = keccak_256(pk).digest() ripe = RIPEMD160.new(k).digest() if prefix ...
As a Python code analyst, you investigate and solve complex coding mysteries
Return character information from datasets.
How would you explain what the following Python 3 function does def lookup_char(self, char): Unihan = self.sql.base.classes.Unihan return self.sql.session.query(Unihan).filter_by(char=char)
As a Python code translator, you convert algorithms and pseudocode into Python.
def reverse_char(self, hints): """Return QuerySet of objects from SQLAlchemy of results. Parameters ---------- hints: list of str strings to lookup Returns ------- :class:`sqlalchemy.orm.query.Query` : reverse matches """ ...
Implement a function in Python 3 to return QuerySet of objects from SQLAlchemy of results.
As a Python code analyst, you investigate and solve complex coding mysteries
Returns list of characters with information for certain fields.
How would you explain what the following Python 3 function does def with_fields(self, *fields): Unihan = self.sql.base.classes.Unihan query = self.sql.session.query(Unihan) for field in fields: query = query.filter(Column(field).isnot(None)) return query
As a Python code analyst, you investigate and solve complex coding mysteries
Compute and return continuous entropy of a random vector.
Can you tell what is the following Python 3 function doing def entropy(data=None, prob=None, method='nearest-neighbors', bins=None, errorVal=1e-5, units='bits'): ''' given a probability distribution (prob) or an interable of symbols (data) compute and return its continuous entropy. inputs: ------ ...
As a Python code composer, you craft elegant and concise scripts.
compute the mutual information between x and y
Can you tell what is the following Python 3 function doing def mi(x, y, bins_x=None, bins_y=None, bins_xy=None, method='nearest-neighbors', units='bits'): ''' compute and return the mutual information between x and y inputs: ------- x, y: numpy arrays of shape samples x dimension ...
As a Python code composer, you craft elegant and concise scripts.
compute the conditional entropy of two arrays x and y
Explain what the following Python 3 code does def cond_entropy(x, y, bins_y=None, bins_xy=None, method='nearest-neighbors', units='bits'): ''' compute the conditional entropy H(X|Y). method: 'nearest-neighbors', 'gaussian', or 'bin' if 'bin' need to provide bins_y, and bins_xy units...
As a Python code composer, you craft elegant and concise scripts.
def entropy(data=None, prob=None, tol=1e-5): ''' given a probability distribution (prob) or an interable of symbols (data) compute and return its entropy inputs: ------ data: iterable of symbols prob: iterable with probabilities tol: if prob is given, 'e...
Implement a function in Python 3 to compute and return the entropy of a single object
As a Python code analyst, you investigate and solve complex coding mysteries
Returns a dict mapping symbols to probability.
Can you generate the documentation for the following Python 3 function def symbols_to_prob(symbols): ''' Return a dict mapping symbols to probability. input: ----- symbols: iterable of hashable items works well if symbols is a zip of iterables ''' myCounter = C...
You are a Python code generator, capable of creating scripts from specifications.
def combine_symbols(*args): ''' Combine different symbols into a 'super'-symbol args can be an iterable of iterables that support hashing see example for 2D ndarray input usage: 1) combine two symbols, each a number into just one symbol x = numpy.random.randint(0,4,1000) y...
Write a Python 3 script to combine different symbols into a super - symbol.
As a Python code translator, you convert algorithms and pseudocode into Python.
compute and return the mutual information between x and y
How would you explain what the following Python 3 function does def mi(x, y): ''' compute and return the mutual information between x and y inputs: ------- x, y: iterables of hashable items output: ------- mi: float Notes: ------ if you are trying to mix ...
You are a Python code architect, reviewing and designing scalable and efficient code
compute and return the mutual information between x y and z given z
Can you tell what is the following Python 3 function doing def cond_mi(x, y, z): ''' compute and return the mutual information between x and y given z, I(x, y | z) inputs: ------- x, y, z: iterables with discrete symbols output: ------- mi: float implementation notes...
As a Python code translator, you convert algorithms and pseudocode into Python.
Decompose the information between all X and y according to the chain rule and return all the terms in the chain rule.
Make a summary of the following Python 3 code def mi_chain_rule(X, y): ''' Decompose the information between all X and y according to the chain rule and return all the terms in the chain rule. Inputs: ------- X: iterable of iterables. You should be able to compute [mi(x, y) for x in X]...
As a Python code translator, you convert algorithms and pseudocode into Python.
def KL_divergence(P,Q): ''' Compute the KL divergence between distributions P and Q P and Q should be dictionaries linking symbols to probabilities. the keys to P and Q should be the same. ''' assert(P.keys()==Q.keys()) distance = 0 for k in P.keys(): distance += P[k] *...
Write a Python 3 script to compute the KL divergence between distributions P and Q where P and Q should be dictionaries linking symbols to probabilities.
You are a Python code analyst, evaluating scripts for potential improvements.
bin signal x using binsN bins
Can you generate the documentation for the following Python 3 function def bin(x, bins, maxX=None, minX=None): ''' bin signal x using 'binsN' bin. If minX, maxX are None, they default to the full range of the signal. If they are not None, everything above maxX gets assigned to binsN-1 and everything bel...
As a python code expert, you are capable of creating scripts from specifications.
def linkcode_resolve(domain, info): # NOQA: C901 """ Determine the URL corresponding to Python object Notes ----- From https://github.com/numpy/numpy/blob/v1.15.1/doc/source/conf.py, 7c49cfa on Jul 31. License BSD-3. https://github.com/numpy/numpy/blob/v1.15.1/LICENSE.txt """ if domain...
Implement a Python 3 function for determining the URL corresponding to the Python object in the specified domain.
As a Python code translator, you convert algorithms and pseudocode into Python.
Inverse of the curve25519 curve.
Make a summary of the following Python 3 code def inv(z): # Adapted from curve25519_athlon.c in djb's Curve25519. z = qdiv(z) z2 = z * z % PRIME # 2 z9 = pow2(z2, 2) * z % PRIME # 9 z11 = z9 * z2 % PRIME # 11 z2_5_0 = (z11*z11) % PRIME * z9 % PRIME # 31 == 2^5 - 2^0 z2_10_0 = pow2(z2_5_0...
As a python code expert, you are capable of creating scripts from specifications.
Implements scalarmult B more efficiently.
Can you generate the documentation for the following Python 3 function def scalarmult_B(e): # scalarmult(B, l) is the identity e %= L P = IDENT for i in range(253): if e & 1: P = edwards_add(P=P, Q=Bpow[i]) e //= 2 assert e == 0, e return P
You are a Python code architect, reviewing and designing scalable and efficient code
given a value y recover the preimage x
Make a summary of the following Python 3 code def recover(y): p = (y*y - 1) * inverse(D*y*y + 1) x = powmod(p, (PRIME+3) // 8, PRIME) if (x*x - p) % PRIME != 0: i = powmod(2, (PRIME-1) // 4, PRIME) x = (x*i) % PRIME if x % 2 != 0: x = PRIME - x return x
As a Python code translator, you convert algorithms and pseudocode into Python.
Execute rubberband on the input time series y and return the output time series y after rubberband transformation
Can you generate a brief explanation for the following Python 3 code def __rubberband(y, sr, **kwargs): '''Execute rubberband Parameters ---------- y : np.ndarray [shape=(n,) or (n, c)] Audio time series, either single or multichannel sr : int > 0 sampling rate of y **kwargs ...
As a Python code analyst, you investigate and solve complex coding mysteries
def time_stretch(y, sr, rate, rbargs=None): '''Apply a time stretch of `rate` to an audio time series. This uses the `tempo` form for rubberband, so the higher the rate, the faster the playback. Parameters ---------- y : np.ndarray [shape=(n,) or (n, c)] Audio time series, either sing...
Implement a Python 3 function for applying a time stretch of rate to an audio time series.
You are a Python code analyst, evaluating scripts for potential improvements.
Apply a timemap stretch to an audio time series.
Explain what the following Python 3 code does def timemap_stretch(y, sr, time_map, rbargs=None): '''Apply a timemap stretch to an audio time series. A timemap stretch allows non-linear time-stretching by mapping source to target sample frame numbers for fixed time points within the audio data. This us...
You are a Python code generator, capable of creating scripts from specifications.
def pitch_shift(y, sr, n_steps, rbargs=None): '''Apply a pitch shift to an audio time series. Parameters ---------- y : np.ndarray [shape=(n,) or (n, c)] Audio time series, either single or multichannel sr : int > 0 Sampling rate of `y` n_steps : float Shift by `n_step...
Write a Python 3 function that can apply a pitch shift to an audio time series.
You are a Python code generator, capable of creating scripts from specifications.
def kuten_to_gb2312(kuten): """ Convert GB kuten / quwei form (94 zones * 94 points) to GB2312-1980 / ISO-2022-CN hex (internal representation) """ zone, point = int(kuten[:2]), int(kuten[2:]) hi, lo = hexd(zone + 0x20), hexd(point + 0x20) gb2312 = "%s%s" % (hi, lo) assert isinstance(g...
Write a Python 3 function that can convert a kuten string to GB2312 - 1980 hex
You are a Python code analyst, evaluating scripts for potential improvements.
Convert a GB2312 - 1980 hex string to EUC - CN hex string
Here you have a function in Python 3, explain what it does def gb2312_to_euc(gb2312hex): hi, lo = int(gb2312hex[:2], 16), int(gb2312hex[2:], 16) hi, lo = hexd(hi + 0x80), hexd(lo + 0x80) euc = "%s%s" % (hi, lo) assert isinstance(euc, bytes) return euc
As a python code expert, you are capable of creating scripts from specifications.