output
stringlengths
1
928k
instruction
stringlengths
7
928k
system
stringlengths
0
104k
This method returns a TGS ticket for the specified user.
How would you explain what the following Python 3 function does def get_TGS(self, spn_user, override_etype = None): #construct tgs_req logger.debug('Constructing TGS request for user %s' % spn_user.get_formatted_pname()) now = datetime.datetime.utcnow() kdc_req_body = {} kdc_req_body['kdc-options'] = KDCOpti...
As a python code expert, you are capable of creating scripts from specifications.
Minimise the routing table.
Make a summary of the following Python 3 code def minimise(table, target_length, check_for_aliases=True): # If alias checking is required, see if we can cheaply prove that no # aliases exist in the table to skip this costly check. if check_for_aliases: # Aliases cannot exist when all entries share t...
As a Python code analyst, you investigate and solve complex coding mysteries
Determine if an entry may be removed from a routing table and a default route.
Make a summary of the following Python 3 code def _is_defaultable(i, entry, table, check_for_aliases=True): # May only have one source and sink (which may not be None) if (len(entry.sources) == 1 and len(entry.route) == 1 and None not in entry.sources): # Neither the source nor s...
As a Python code composer, you craft elegant and concise scripts.
def routing_tree_to_tables(routes, net_keys): """Convert a set of :py:class:`~rig.place_and_route.routing_tree.RoutingTree` s into a per-chip set of routing tables. .. warning:: A :py:exc:`rig.routing_table.MultisourceRouteError` will be raised if entries with identical keys and masks b...
How would you code a function in Python 3 to convert a set of routing trees into a set of routing tables.
As a python code expert, you are capable of creating scripts from specifications.
def build_routing_table_target_lengths(system_info): """Build a dictionary of target routing table lengths from a :py:class:`~rig.machine_control.machine_controller.SystemInfo` object. Useful in conjunction with :py:func:`~rig.routing_table.minimise_tables`. Returns ------- {(x, y): num, ...} ...
Write a Python 3 function that can build a dictionary of target routing table lengths from a system info object.
You are a Python code architect, reviewing and designing scalable and efficient code
Check that every entry in one table results in the same route when checked against the other table.
Can you generate the documentation for the following Python 3 function def table_is_subset_of(entries_a, entries_b): # Determine which bits we don't need to explicitly test for common_xs = get_common_xs(entries_b) # For every entry in the first table for entry in expand_entries(entries_a, ignore_xs=com...
As a python code expert, you are capable of creating scripts from specifications.
Expand the entries in the routing table into a single tree of entries.
Here you have a function in Python 3, explain what it does def expand_entry(entry, ignore_xs=0x0): # Get all the Xs in the entry that are not ignored xs = (~entry.key & ~entry.mask) & ~ignore_xs # Find the most significant X for bit in (1 << i for i in range(31, -1, -1)): if bit & xs: ...
You are a Python code architect, reviewing and designing scalable and efficient code
Expand the given list of entries into a single set of entries.
Given the following Python 3 function, write the documentation def expand_entries(entries, ignore_xs=None): # Find the common Xs for the entries if ignore_xs is None: ignore_xs = get_common_xs(entries) # Keep a track of keys that we've seen seen_keys = set({}) # Expand each entry in turn ...
You are a Python code analyst, evaluating scripts for potential improvements.
Return a mask of where there are common Xs in all entries.
How would you explain what the following Python 3 function does def get_common_xs(entries): # Determine where there are never 1s in the key and mask key = 0x00000000 mask = 0x00000000 for entry in entries: key |= entry.key mask |= entry.mask # Where there are never 1s in the key or...
As a Python code translator, you convert algorithms and pseudocode into Python.
Test if the ranges covered by a pair of slices overlap.
Can you tell what is the following Python 3 function doing def slices_overlap(slice_a, slice_b): assert slice_a.step is None assert slice_b.step is None return max(slice_a.start, slice_b.start) \ < min(slice_a.stop, slice_b.stop)
As a Python code analyst, you investigate and solve complex coding mysteries
def minimise_xyz(xyz): """Minimise an (x, y, z) coordinate.""" x, y, z = xyz m = max(min(x, y), min(max(x, y), z)) return (x-m, y-m, z-m)
How would you implement a function in Python 3 that minimises an ( x y z ) coordinate.
You are a Python code generator, capable of creating scripts from specifications.
def standard_system_dimensions(num_boards): """Calculate the standard network dimensions (in chips) for a full torus system with the specified number of SpiNN-5 boards. Returns ------- (w, h) Width and height of the network in chips. Standard SpiNNaker systems are constructed as sq...
Write a Python 3 function that can calculate the standard network dimensions for a full torus system.
As a Python code translator, you convert algorithms and pseudocode into Python.
Generate a list of board coordinates with Ethernet connectivity in a SpiNNaker machine.
Given the following Python 3 function, write the documentation def spinn5_eth_coords(width, height, root_x=0, root_y=0): # In oddly-shaped machines where chip (0, 0) does not exist, we must offset # the coordinates returned in accordance with the root chip's location. root_x %= 12 root_x %= 12 # In...
You are a Python code architect, reviewing and designing scalable and efficient code
Returns the coordinates of a chip s local ethernet connected chip on the same board as the supplied chip.
Can you generate the documentation for the following Python 3 function def spinn5_local_eth_coord(x, y, w, h, root_x=0, root_y=0): dx, dy = SPINN5_ETH_OFFSET[(y - root_y) % 12][(x - root_x) % 12] return ((x + int(dx)) % w), ((y + int(dy)) % h)
You are a Python code generator, capable of creating scripts from specifications.
Calculates the coordinates of a chip on its board.
Explain what the following Python 3 code does def spinn5_chip_coord(x, y, root_x=0, root_y=0): dx, dy = SPINN5_ETH_OFFSET[(y - root_y) % 12][(x - root_x) % 12] return (-int(dx), -int(dy))
You are a Python code analyst, evaluating scripts for potential improvements.
def spinn5_fpga_link(x, y, link, root_x=0, root_y=0): """Get the identity of the FPGA link which corresponds with the supplied link. .. note:: This function assumes the system is constructed from SpiNN-5 boards whose FPGAs are loaded with the SpI/O 'spinnaker_fpgas' image. Parameters ...
Write a Python 3 script to return the identity of the FPGA link which corresponds with the supplied link.
As a Python code translator, you convert algorithms and pseudocode into Python.
def _load_resource(self, source_r, abs_path=False): """The CSV package has no reseources, so we just need to resolve the URLs to them. Usually, the CSV package is built from a file system ackage on a publically acessible server. """ r = self.doc.resource(source_r.name) r.url = self...
Create a Python 3 function for loading the CSV package resource from a source resource.
As a Python code translator, you convert algorithms and pseudocode into Python.
Reset the internal state of the thread.
How would you explain what the following Python 3 function does def _reset(self): self._arbiter = None self._workers = None self._working_queue = None self._must_stop = threading.Event()
As a Python code translator, you convert algorithms and pseudocode into Python.
def attach_tasks(self, tasks: Tasks): """Attach a set of tasks. A task cannot be scheduled or executed before it is attached to an Engine. >>> tasks = Tasks() >>> spin.attach_tasks(tasks) """ if tasks._spin is not None and tasks._spin is not self: lo...
Can you implement a function in Python 3 that attaches a set of tasks to an Engine.
You are a Python code architect, reviewing and designing scalable and efficient code
Schedule a job to be executed in the background.
Can you generate the documentation for the following Python 3 function def schedule_at(self, task: Schedulable, at: datetime, *args, **kwargs): task = self._tasks.get(task) job = Job(task.name, task.queue, at, task.max_retries, task_args=args, task_kwargs=kwargs) return self._b...
As a Python code analyst, you investigate and solve complex coding mysteries
def schedule_batch(self, batch: Batch): """Schedule many jobs at once. Scheduling jobs in batches allows to enqueue them fast by avoiding round-trips to the broker. :arg batch: :class:`Batch` instance containing jobs to schedule """ jobs = list() for task, at, a...
Write a Python 3 script for scheduling many jobs at once.
As a Python code analyst, you investigate and solve complex coding mysteries
Start the workers threads.
Make a summary of the following Python 3 code def start_workers(self, number: int=DEFAULT_WORKER_NUMBER, queue=DEFAULT_QUEUE, block=True, stop_when_queue_empty=False): """Start the worker threads. :arg number: number of worker threads to launch :arg q...
You are a Python code generator, capable of creating scripts from specifications.
Stop the workers and wait for them to terminate.
Can you generate a brief explanation for the following Python 3 code def stop_workers(self, _join_arbiter=True): # _join_arbiter is used internally when the arbiter is shutting down # the full engine itself. This is because the arbiter thread cannot # join itself. self._must_stop.set() ...
As a Python code composer, you craft elegant and concise scripts.
Handle trunks from the server.
Can you tell what is the following Python 3 function doing def handle_trunks(self, trunks, event_type): LOG.debug("Trunks event received: %(event_type)s. Trunks: %(trunks)s", {'event_type': event_type, 'trunks': trunks}) if event_type == events.DELETED: # The port trunks ...
As a python code expert, you are capable of creating scripts from specifications.
Handle the subports event.
Make a summary of the following Python 3 code def handle_subports(self, subports, event_type): LOG.debug("Subports event received: %(event_type)s. " "Subports: %(subports)s", {'event_type': event_type, 'subports': subports}) # update the cache. if event_type...
As a Python code composer, you craft elegant and concise scripts.
Sets up VLAN trunk and updates the trunk status.
Can you generate the documentation for the following Python 3 function def _setup_trunk(self, trunk, vlan_id=None): LOG.info('Binding trunk port: %s.', trunk) try: # bind sub_ports to host. self._trunk_rpc.update_subport_bindings(self._context, ...
As a python code expert, you are capable of creating scripts from specifications.
def _get_port_profile_id(self, request): """Get the port profile ID from the request path.""" # Note(alexcoman): The port profile ID can be found as suffix # in request path. port_profile_id = request.path.split("/")[-1].strip() if uuidutils.is_uuid_like(port_profile_id): ...
Write a Python 3 script for getting the port profile ID from the request path.
You are a Python code analyst, evaluating scripts for potential improvements.
Setup the RPC client for the current agent.
Can you tell what is the following Python 3 function doing def _setup_rpc(self): self._state_rpc = agent_rpc.PluginReportStateAPI(topics.REPORTS) report_interval = CONF.AGENT.report_interval if report_interval: heartbeat = loopingcall.FixedIntervalLoopingCall( self._r...
As a python code expert, you are capable of creating scripts from specifications.
Start the neutron - hnv - metadata - proxy agent.
Given the following Python 3 function, write the documentation def _work(self): server = wsgi.Server( name=self._AGENT_BINARY, num_threads=CONF.AGENT.worker_count) server.start( application=_MetadataProxyHandler(), port=CONF.bind_port, host=CON...
You are a Python code analyst, evaluating scripts for potential improvements.
def set_azure_web_info(self, resource_group_name, website_name, credentials, subscription_id, subscription_name, tenant_id, webapp_location): """ Call this method before attempting to setup continuous delivery to setup the azure settings :param resource_group_name: ...
Can you write a function in Python 3 where it sets the Azure web info for the resource group.
As a Python code translator, you convert algorithms and pseudocode into Python.
def set_repository_info(self, repo_url, branch, git_token, private_repo_username, private_repo_password): """ Call this method before attempting to setup continuous delivery to setup the source control settings :param repo_url: URL of the code repo :param branch: repo branch :par...
Can you create a Python 3 function that sets the repository info for the current source control
You are a Python code analyst, evaluating scripts for potential improvements.
def setup_continuous_delivery(self, swap_with_slot, app_type_details, cd_project_url, create_account, vsts_app_auth_token, test, webapp_list): """ Use this method to setup Continuous Delivery of an Azure web site from a source control repository. :param swap_wit...
Can you implement a function in Python 3 that uses this method to setup Continuous Delivery of an Azure web site from a source control repository. :param swap_with_slot: the slot to use for deployment :param app_type_details: the details of app that will be deployed. i.e. app_type = Python, python_framework = Django et...
You are a Python code analyst, evaluating scripts for potential improvements.
List the steps on a longest - dimension first route.
Here you have a function in Python 3, explain what it does def longest_dimension_first(vector, start=(0, 0), width=None, height=None): x, y = start out = [] for dimension, magnitude in sorted(enumerate(vector), key=(lambda x: ...
As a Python code analyst, you investigate and solve complex coding mysteries
def links_between(a, b, machine): """Get the set of working links connecting chips a and b. Parameters ---------- a : (x, y) b : (x, y) machine : :py:class:`~rig.place_and_route.Machine` Returns ------- set([:py:class:`~rig.links.Links`, ...]) """ ax, ay = a bx, by = b ...
Can you write a function in Python 3 where it returns the set of working links between chips a and b.
You are a Python code architect, reviewing and designing scalable and efficient code
def set_s3_profile(profile_name): """Load the credentials for an s3 profile into environmental variables""" import os session = boto3.Session(profile_name=profile_name) os.environ['AWS_ACCESS_KEY_ID'] = session.get_credentials().access_key os.environ['AWS_SECRET_ACCESS_KEY'] = session.get_credenti...
Can you implement a function in Python 3 that loads the credentials for an s3 profile into environmental variables
As a Python code translator, you convert algorithms and pseudocode into Python.
Create a new network and return it
Given the following Python 3 function, write the documentation def create_new_model(reference, duration, dt=0.025, # ms temperature=6.3, # degC default_region=None, parameters = None, cell_for...
You are a Python code analyst, evaluating scripts for potential improvements.
def send(self, *sender, **kwargs): """Emit this signal on behalf of `sender`, passing on kwargs. This is an extension of `Signal.send` that changes one thing: Exceptions raised in calling the receiver are logged but do not fail """ if len(sender) == 0: sender = None ...
How would you implement a function in Python 3 that emits this signal on behalf of sender passing on kwargs.
As a python code expert, you are capable of creating scripts from specifications.
def update_metatab(self, doc, resources): """Add documentation entries for resources""" if not 'Documentation' in doc: doc.new_section("Documentation") ds = doc['Documentation'] if not 'Name' in ds.args: ds.add_arg('Name', prepend=True) # This is the ...
Create a Python 3 function to update the metatab with the resources from the HTML exporter.
You are a Python code generator, capable of creating scripts from specifications.
This is the name of the package we will be creating.
Can you generate a brief explanation for the following Python 3 code def get_package_dir_name(self, nb): package_dir = self.package_dir if not package_dir: package_dir = getcwd() package_name = self.package_name if not package_name: doc = ExtractInlineMetatabD...
As a Python code translator, you convert algorithms and pseudocode into Python.
def get_output_dir(self, nb): """Open a notebook and determine the output directory from the name""" self.package_dir, self.package_name = self.get_package_dir_name(nb) return join(self.package_dir, self.package_name)
Can you create a Python 3 function that opens a notebook and determine the output directory from the name
As a Python code composer, you craft elegant and concise scripts.
def extract_terms(self, nb): """Extract some term values, usually set with tags or metadata""" emt = ExtractMetatabTerms() emt.preprocess(nb, {}) return emt.terms
Write a Python 3 function for extracting some terms from a NB object
As a Python code translator, you convert algorithms and pseudocode into Python.
def from_notebook_node(self, nb, resources=None, **kw): """Create a Metatab package from a notebook node """ nb_copy = copy.deepcopy(nb) # The the package name and directory, either from the inlined Metatab doc, # or from the config try: self.output_dir = self.get_...
How would you implement a function in Python 3 that creates a Metatab package from a notebook node.
You are a Python code generator, capable of creating scripts from specifications.
This method is called by the cell processor to extract attachments and add them to the cell s outputs.
Here you have a function in Python 3, explain what it does def preprocess_cell(self, cell, resources, cell_index): from nbformat.notebooknode import NotebookNode attach_names = [] # Just move the attachment into an output for k, attach in cell.get('attachments', {}).items(): ...
As a python code expert, you are capable of creating scripts from specifications.
A generator which iterates over a set of chips in a hilbert path.
Given the following Python 3 function, write the documentation def hilbert_chip_order(machine): max_dimen = max(machine.width, machine.height) hilbert_levels = int(ceil(log(max_dimen, 2.0))) if max_dimen >= 1 else 0 return hilbert(hilbert_levels)
You are a Python code analyst, evaluating scripts for potential improvements.
Places vertices in breadth - first order along a hilbert - curve path.
Here you have a function in Python 3, explain what it does def place(vertices_resources, nets, machine, constraints, breadth_first=True): return sequential_place(vertices_resources, nets, machine, constraints, (None if not breadth_first else ...
As a Python code composer, you craft elegant and concise scripts.
def minimise_table(table, target_length, methods=(remove_default_entries, ordered_covering)): """Apply different minimisation algorithms to minimise a single routing table. Parameters ---------- table : [:py:class:`~rig.routing_table.RoutingTableEntry`, ...] Routing table...
Can you write a function in Python 3 where it minimises a routing table.
As a Python code translator, you convert algorithms and pseudocode into Python.
def configure_ckan(m): """Load groups and organizations, from a file in Metatab format""" from ckanapi import RemoteCKAN try: doc = MetapackDoc(m.mt_file, cache=m.cache) except (IOError, MetatabError) as e: err("Failed to open metatab '{}': {}".format(m.mt_file, e)) c = RemoteCKAN(...
Implement a Python 3 function for loading groups and organizations from a file in Metatab format
As a python code expert, you are capable of creating scripts from specifications.
def package_load_instructions(inst_distributions): """Load instructions, displayed in the package notes""" per_package_inst = '' for dist in inst_distributions: if dist.type == 'zip': per_package_inst += dedent( """ # Loading the ZIP Package ...
How would you code a function in Python 3 to return the load instructions for the given list of packages.
You are a Python code generator, capable of creating scripts from specifications.
Dump the groups and organizations to a file
Can you tell what is the following Python 3 function doing def dump_ckan(m): doc = MetapackDoc(cache=m.cache) doc.new_section('Groups', 'Title Description Id Image_url'.split()) doc.new_section('Organizations', 'Title Description Id Image_url'.split()) c = RemoteCKAN(m.ckan_url, apikey=m.api_ke...
As a Python code analyst, you investigate and solve complex coding mysteries
Return a new memo with a new metatabfile argument
Can you generate a brief explanation for the following Python 3 code def update_mt_arg(self, metatabfile): o = MetapackCliMemo(self.args) o.set_mt_arg(metatabfile) return o
As a Python code analyst, you investigate and solve complex coding mysteries
Determine the URL corresponding to the Python object on GitHub
How would you explain what the following Python 3 function does def linkcode_resolve(domain, info): # Only link to Python source if domain != 'py': return None # Get a reference to the object in question modname = info['module'] fullname = info['fullname'] submod = sys.modules.get(modn...
As a Python code translator, you convert algorithms and pseudocode into Python.
Return the path to an included declaration file
Can you generate the documentation for the following Python 3 function def declaration_path(name): from os.path import dirname, join, exists import metatab.declarations from metatab.exc import IncludeError d = dirname(metatab.declarations.__file__) path = join(d, name) if not exists(path): ...
As a Python code translator, you convert algorithms and pseudocode into Python.
def flatten(d, sep='.'): """Flatten a data structure into tuples""" def _flatten(e, parent_key='', sep='.'): import collections prefix = parent_key + sep if parent_key else '' if isinstance(e, collections.MutableMapping): return tuple((prefix + k2, v2) for k, v in e.items(...
Implement a function in Python 3 to flatten a data structure into tuples
You are a Python code generator, capable of creating scripts from specifications.
Make the build directory structure.
Make a summary of the following Python 3 code def make_dir_structure(base_dir): def maybe_makedir(*args): p = join(base_dir, *args) if exists(p) and not isdir(p): raise IOError("File '{}' exists but is not a directory ".format(p)) if not exists(p): makedirs(p) ...
You are a Python code generator, capable of creating scripts from specifications.
def guess_format(url): """Try to guess the format of a resource, possibly with a HEAD request""" import requests from requests.exceptions import InvalidSchema from rowgenerators import parse_url_to_dict parts = parse_url_to_dict(url) # Guess_type fails for root urls like 'http://civicknowledg...
Create a Python 3 function for trying to guess the format of a resource possibly with a HEAD request
As a python code expert, you are capable of creating scripts from specifications.
def walk_up(bottom): """ mimic os.walk, but walk 'up' instead of down the directory tree :param bottom: :return: """ import os from os import path bottom = path.realpath(bottom) # get files in current dir try: names = os.listdir(bottom) except Exception as e: r...
Implement a Python 3 function for mimicing os. walk but instead of down the directory tree
As a Python code translator, you convert algorithms and pseudocode into Python.
def get_materialized_data_cache(doc=None): """Return the cache directory where data can be written during a build, usually for a Jupyter notebook that generates many files for each execution""" from metapack.constants import MATERIALIZED_DATA_PREFIX from os.path import join if not doc: fro...
Implement a function in Python 3 to return the cache directory where data can be written during a build
You are a Python code architect, reviewing and designing scalable and efficient code
Traverse the tree yielding the direction taken to a node the co -ordinates of that node and the directions leading from the children of that node and the routes leading to the children of that node.
Given the following Python 3 function, write the documentation def traverse(self): # A queue of (direction, node) to visit. The direction is the Links # entry which describes the direction in which we last moved to reach # the node (or None for the root). to_visit = deque([(None, self)])...
You are a Python code analyst, evaluating scripts for potential improvements.
Yields all dependencies of a package.
How would you explain what the following Python 3 function does def yield_deps(doc): this_node = DependencyNode(doc, None) for r in doc.references(): other_node = DependencyNode(r, this_node) yield (this_node, other_node) if isinstance(other_node, PackageDependencyNode): ...
As a Python code analyst, you investigate and solve complex coding mysteries
def wrap_url(s, l): """Wrap a URL string""" parts = s.split('/') if len(parts) == 1: return parts[0] else: i = 0 lines = [] for j in range(i, len(parts) + 1): tv = '/'.join(parts[i:j]) nv = '/'.join(parts[i:j + 1]) if len(nv) > l or n...
Can you implement a function in Python 3 that wraps a URL string in a list of lines
As a python code expert, you are capable of creating scripts from specifications.
def _get_rho(self, w, arr): """ Return the least signifiant bit O(N) in the worst case """ lsb = 0 while not (w & arr[lsb]): lsb += 1 return lsb + 1
Implement a Python 3 function for returning the least signifiant bit O ( N in the worst case
You are a Python code analyst, evaluating scripts for potential improvements.
def add(self, uuid): """ Adds a key to the HyperLogLog """ if uuid: # Computing the hash try: x = hash64(uuid) except UnicodeEncodeError: x = hash64(uuid.encode('ascii', 'ignore')) # Finding the register to update by using t...
Write a Python 3 function for adding a key to the HyperLogLog
As a Python code composer, you craft elegant and concise scripts.
Returns the estimate of the cardinality of the class
Make a summary of the following Python 3 code def estimate(self): E = self.alpha * float(self.m ** 2) / np.power(2.0, - self.M).sum() if E <= 2.5 * self.m: # Small range correction V = self.m - np.count_nonzero(self.M) return int(self.m * np.log(self.m / float(V))) if...
As a Python code composer, you craft elegant and concise scripts.
Base URL for resolving resource URLs
Can you tell what is the following Python 3 function doing def base_url(self): if self.doc.package_url: return self.doc.package_url return self.doc._ref
As a Python code composer, you craft elegant and concise scripts.
Return a URL that properly combines the base_url and a possibly relative_url
Here you have a function in Python 3, explain what it does def _resolved_url(self): if not self.url: return None u = parse_app_url(self.url) if u.scheme == 'index': u = u.resolve() if u.scheme != 'file': # Hopefully means the URL is http, https, ft...
You are a Python code generator, capable of creating scripts from specifications.
def schema_term(self): """Return the Table term for this resource, which is referenced either by the `table` property or the `schema` property""" if not self.name: raise MetapackError("Resource for url '{}' doe not have name".format(self.url)) t = self.doc.find_first('Root....
Can you implement a function in Python 3 that returns the Table term for this resource which is referenced either by the table property or the schema property.
You are a Python code analyst, evaluating scripts for potential improvements.
def headers(self): """Return the headers for the resource. Returns the AltName, if specified; if not, then the Name, and if that is empty, a name based on the column position. These headers are specifically applicable to the output table, and may not apply to the resource source. FOr those heade...
Can you create a Python 3 function that returns the headers for the resource.
As a Python code translator, you convert algorithms and pseudocode into Python.
Returns the headers for the resource source. Specifically does not include any header that is the EMPTY_SOURCE_HEADER value of _NONE_
Can you generate the documentation for the following Python 3 function def source_headers(self): t = self.schema_term if t: return [self._name_for_col_term(c, i) for i, c in enumerate(t.children, 1) if c.term_is("Table.Column") and c.get_value('name'...
As a python code expert, you are capable of creating scripts from specifications.
def columns(self): """Return column information from the schema or from an upstreram package""" try: # For resources that are metapack packages. r = self.expanded_url.resource.columns() return list(r) except AttributeError as e: pass ret...
Write a Python 3 script to return column information from the schema or an upstreram package
You are a Python code analyst, evaluating scripts for potential improvements.
def schema_columns(self): """Return column informatino only from this schema""" t = self.schema_term columns = [] if t: for i, c in enumerate(t.children): if c.term_is("Table.Column"): p = c.all_props p['pos'] = i ...
Can you implement a function in Python 3 that returns column informatino only from this schema
As a Python code analyst, you investigate and solve complex coding mysteries
def row_processor_table(self, ignore_none=False): """Create a row processor from the schema, to convert the text values from the CSV into real types""" from rowgenerators.rowpipe import Table type_map = { None: None, 'string': 'str', 'text': 'str', ...
Write a Python 3 function for creating a row processor from the schema to convert the text values from the CSV into real types
As a Python code translator, you convert algorithms and pseudocode into Python.
def raw_row_generator(self): """Like rowgenerator, but does not try to create a row processor table""" from rowgenerators import get_generator self.doc.set_sys_path() # Set sys path to package 'lib' dir in case of python function generator ru = self.resolved_url try: ...
Write a Python 3 script to like rowgenerator but does not try to create a row processor table
As a python code expert, you are capable of creating scripts from specifications.
def _get_header(self): """Get the header from the deinfed header rows, for use on references or resources where the schema has not been run""" try: header_lines = [int(e) for e in str(self.get_value('headerlines', 0)).split(',')] except ValueError as e: header_l...
Implement a function in Python 3 to get the header from the deinfed header rows for use on references or resources where the schema has not been run
You are a Python code generator, capable of creating scripts from specifications.
Iterate over the resource in dict records
Given the following Python 3 function, write the documentation def iterdict(self): from collections import OrderedDict headers = None for row in self: if headers is None: headers = row continue yield OrderedDict(zip(headers, row))
As a Python code composer, you craft elegant and concise scripts.
def iterrows(self): """Iterate over the resource as row proxy objects, which allow acessing colums as attributes""" row_proxy = None headers = None for row in self: if not headers: headers = row row_proxy = RowProxy(headers) ...
Can you create a Python 3 function that iterates over the resource as row proxy objects which allow acessing colums as attributes
As a Python code translator, you convert algorithms and pseudocode into Python.
Iterate over the resource as row proxy objects which allow acessing colums as attributes. Like iterrows this method creates a new RowProxy object for each row.
Make a summary of the following Python 3 code def iterrowproxy(self, cls=RowProxy): row_proxy = None headers = None for row in self: if not headers: headers = row row_proxy = cls(headers) continue yield row_proxy.set_ro...
You are a Python code generator, capable of creating scripts from specifications.
Yields the data structures built from the JSON header specifications in a table.
How would you explain what the following Python 3 function does def iterstruct(self): from rowgenerators.rowpipe.json import add_to_struct json_headers = self.json_headers for row in islice(self, 1, None): # islice skips header d = {} for pos, jh in json_headers: ...
As a Python code analyst, you investigate and solve complex coding mysteries
def iterjson(self, *args, **kwargs): """Yields the data structures from iterstruct as JSON strings""" from rowgenerators.rowpipe.json import VTEncoder import json if 'cls' not in kwargs: kwargs['cls'] = VTEncoder for s in self.iterstruct: yield (json.dum...
How would you implement a function in Python 3 that yields the data structures from iterstruct as JSON strings
As a python code expert, you are capable of creating scripts from specifications.
def iteryaml(self, *args, **kwargs): """Yields the data structures from iterstruct as YAML strings""" from rowgenerators.rowpipe.json import VTEncoder import yaml if 'cls' not in kwargs: kwargs['cls'] = VTEncoder for s in self.iterstruct: yield (yaml.saf...
Write a Python 3 script for yielding the data structures from iterstruct as YAML strings
You are a Python code analyst, evaluating scripts for potential improvements.
Return a pandas datafrome from the resource
Explain what the following Python 3 code does def dataframe(self, dtype=False, parse_dates=True, *args, **kwargs): import pandas as pd rg = self.row_generator t = self.resolved_url.get_resource().get_target() if t.target_format == 'csv': return self.read_csv(dtype, parse...
As a Python code translator, you convert algorithms and pseudocode into Python.
def geoframe(self, *args, **kwargs): """Return a Geo dataframe""" from geopandas import GeoDataFrame import geopandas as gpd from shapely.geometry.polygon import BaseGeometry from shapely.wkt import loads gdf = None try: gdf = self.resolved_url.geofr...
Can you implement a function in Python 3 that returns a Geo dataframe of the current state of the object.
You are a Python code generator, capable of creating scripts from specifications.
Update kwargs suitable for pandas read_csv
Explain what the following Python 3 code does def _update_pandas_kwargs(self, dtype=False, parse_dates=True, kwargs= {}): from datetime import datetime, time, date type_map = { None: None, 'string': str, 'text': str, 'number': float, 'intege...
As a Python code analyst, you investigate and solve complex coding mysteries
def read_csv(self, dtype=False, parse_dates=True, *args, **kwargs): """Fetch the target and pass through to pandas.read_csv Don't provide the first argument of read_csv(); it is supplied internally. """ import pandas t = self.resolved_url.get_resource().get_target() k...
Write a Python 3 function for fetching the target and pass through to pandas. read_csv
You are a Python code architect, reviewing and designing scalable and efficient code
def read_fwf(self, *args, **kwargs): """Fetch the target and pass through to pandas.read_fwf. Don't provide the first argument of read_fwf(); it is supplied internally. """ import pandas t = self.resolved_url.get_resource().get_target() return pandas.read_fwf(t.fspath, *args, ...
Can you write a function in Python 3 where it fetches the target and pass through to pandas. read_fwf.
As a Python code analyst, you investigate and solve complex coding mysteries
def readlines(self): """Load the target, open it, and return the result from readlines()""" t = self.resolved_url.get_resource().get_target() with open(t.fspath) as f: return f.readlines()
Can you implement a function in Python 3 that loads the target open it and return the result from readlines
As a Python code translator, you convert algorithms and pseudocode into Python.
def petl(self, *args, **kwargs): """Return a PETL source object""" import petl t = self.resolved_url.get_resource().get_target() if t.target_format == 'txt': return petl.fromtext(str(t.fspath), *args, **kwargs) elif t.target_format == 'csv': return petl....
Write a Python 3 function that can return a PETL source object
You are a Python code generator, capable of creating scripts from specifications.
Build the interpolation context from the schemas
Here you have a function in Python 3, explain what it does def context(self): # Can't use self.columns b/c of recursion with resolved_url t = self.schema_term if not t: return {} sql_columns = [] all_columns = [] for i, c in enumerate(t.children): ...
As a Python code composer, you craft elegant and concise scripts.
def caller_locals(): """Get the local variables in the caller's frame.""" import inspect frame = inspect.currentframe() try: return frame.f_back.f_back.f_locals finally: del frame
How would you implement a function in Python 3 that gets the local variables in the caller s frame.
As a python code expert, you are capable of creating scripts from specifications.
Like open_package but always open the source package
Explain what the following Python 3 code does def open_source_package(dr=None): if dr is None: dr = getcwd() for i, e in enumerate(walk_up(dr)): intr = set([DEFAULT_METATAB_FILE, LINES_METATAB_FILE, IPYNB_METATAB_FILE]) & set(e[2]) if intr: return op(join(e[0], list(intr)...
As a Python code analyst, you investigate and solve complex coding mysteries
Try to open a package with the metatab_doc variable. If that does not exist try the local _packages directory. If that does not exist try the local _packages directory.
Explain what the following Python 3 code does def open_package(locals=None, dr=None): if locals is None: locals = caller_locals() try: # Running in a package build return op(locals['metatab_doc']) except KeyError: # Running interactively in Jupyter package_name =...
As a Python code translator, you convert algorithms and pseudocode into Python.
Rebuild the schema for a resource based on a dataframe
Make a summary of the following Python 3 code def rebuild_schema(doc, r, df): import numpy as np # Re-get the resource in the doc, since it may be different. try: r = doc.resource(r.name) except AttributeError: # Maybe r is actually a resource name r = doc.resource(r) def a...
You are a Python code generator, capable of creating scripts from specifications.
def rewrite_schema(r, df, doc=None): """Rebuild the schema for a resource based on a dataframe and re-write the doc""" from metapack.cli.core import write_doc if doc is None: doc = open_source_package() rebuild_schema(doc, r, df) write_doc(doc, doc.ref)
How would you code a function in Python 3 to rebuild the schema for a resource based on a dataframe and write the doc
You are a Python code analyst, evaluating scripts for potential improvements.
Rebuild the schema for a resource based on a dataframe and re - write the doc
Given the following Python 3 function, write the documentation def interactive_rewrite_schema(r, df, doc=None): if 'metatab_doc' in caller_locals(): return False if doc is None: doc = open_source_package() rewrite_schema(r, df, doc) return True
You are a Python code generator, capable of creating scripts from specifications.
Yields tuples of dataframe variable name and the dataframe.
Explain what the following Python 3 code does def get_dataframes(): for k, v in caller_locals().items(): if k.startswith('_'): continue if isinstance(v, pd.core.frame.DataFrame): yield k, v
As a Python code analyst, you investigate and solve complex coding mysteries
def get_notebook_path(): """ Return the full path of the jupyter notebook. """ kernel_id = re.search('kernel-(.*).json', ipykernel.connect.get_connection_file()).group(1) servers = list_running_servers() for ss in servers: response = requests.get(urljoin(ss['url...
Implement a Python 3 function for returning the full path of the jupyter notebook.
As a Python code translator, you convert algorithms and pseudocode into Python.
def get_notebook_rel_path(pkg=None): """Get the path of a notebook, relative to the current soruce package""" pkg = pkg or open_source_package() pkg_path = str(pkg.package_url.fspath) nb_path = get_notebook_path() return nb_path.replace(pkg_path, '').strip('/')
Can you implement a function in Python 3 that gets the path of a notebook relative to the current soruce package
As a Python code analyst, you investigate and solve complex coding mysteries
Add a dataframe to a source package.
Here you have a function in Python 3, explain what it does def add_dataframe(df, name, pkg=None, description=''): from warnings import warn from metapack.cli.core import alt_col_name, type_map import numpy as np if name is None or df is None: warn("Did not find dataframe for reference '{}' ".fo...
You are a Python code architect, reviewing and designing scalable and efficient code
def _if_not_closed(f): """Run the method iff. the memory view hasn't been closed and the parent object has not been freed.""" @add_signature_to_docstring(f) @functools.wraps(f) def f_(self, *args, **kwargs): if self.closed or self._parent._freed: raise OSError return f(se...
Create a Python 3 function to run the method iff. the memory view hasn t been closed and the parent Taxonomy object has not been freed.
You are a Python code generator, capable of creating scripts from specifications.
def _if_not_freed(f): """Run the method iff. the memory view hasn't been closed.""" @add_signature_to_docstring(f) @functools.wraps(f) def f_(self, *args, **kwargs): if self._freed: raise OSError return f(self, *args, **kwargs) return f_
Can you implement a function in Python 3 that runs the method iff. the memory view hasn t been closed.
As a Python code analyst, you investigate and solve complex coding mysteries
def unpack_routing_table_entry(packed): """Unpack a routing table entry read from a SpiNNaker machine. Parameters ---------- packet : :py:class:`bytes` Bytes containing a packed routing table. Returns ------- (:py:class:`~rig.routing_table.RoutingTableEntry`, app_id, core) or None ...
How would you implement a function in Python 3 that unpacks a routing table entry from a SpiNNaker machine.
As a Python code composer, you craft elegant and concise scripts.