output
stringlengths
1
928k
instruction
stringlengths
7
928k
system
stringlengths
0
104k
Handles SIGTERM like SIGINT and SIGTERM.
Here you have a function in Python 3, explain what it does def handle_sigterm(): original_sigterm_handler = signal.getsignal(signal.SIGTERM) signal.signal(signal.SIGTERM, signal.default_int_handler) try: yield finally: signal.signal(signal.SIGTERM, original_sigterm_handler)
As a Python code translator, you convert algorithms and pseudocode into Python.
Return a function to convert a floating point value to a fixed - point value.
How would you explain what the following Python 3 function does def float_to_fp(signed, n_bits, n_frac): # Calculate the maximum and minimum values if signed: max_v = (1 << (n_bits - 1)) - 1 min_v = -max_v - 1 else: min_v = 0 max_v = (1 << n_bits) - 1 # Compute the scale...
You are a Python code generator, capable of creating scripts from specifications.
def float_to_fix(signed, n_bits, n_frac): """**DEPRECATED** Return a function to convert a floating point value to a fixed point value. .. warning:: This function is deprecated in favour of :py:meth:`~.float_to_fp`. For example, a function to convert a float to a signed fractional represen...
How would you implement a function in Python 3 that returns a function to convert a float to a fixed - point value.
As a python code expert, you are capable of creating scripts from specifications.
Return a function to convert a fixed - point value to a float.
Explain what the following Python 3 code does def fix_to_float(signed, n_bits, n_frac): warnings.warn("fix_to_float() is deprecated, see fp_to_float", DeprecationWarning) validate_fp_params(signed, n_bits, n_frac) def kbits(value): """Convert a fixed point value to a float. ...
As a Python code translator, you convert algorithms and pseudocode into Python.
def get_metadata_path(name): """Get reference metadata file path.""" return pkg_resources.resource_filename('voobly', os.path.join(METADATA_PATH, '{}.json'.format(name)))
Create a Python 3 function to get reference metadata file path.
As a Python code translator, you convert algorithms and pseudocode into Python.
Save cookies to a file.
How would you explain what the following Python 3 function does def _save_cookies(requests_cookiejar, filename): with open(filename, 'wb') as handle: pickle.dump(requests_cookiejar, handle)
You are a Python code generator, capable of creating scripts from specifications.
Make a request to the API endpoint.
Make a summary of the following Python 3 code def _make_request(session, url, argument=None, params=None, raw=False): if not params: params = {} params['key'] = session.auth.key try: if argument: request_url = '{}{}{}{}'.format(session.auth.base_url, VOOBLY_API_URL, url, argument...
As a Python code analyst, you investigate and solve complex coding mysteries
def make_scrape_request(session, url, mode='get', data=None): """Make a request to URL.""" try: html = session.request(mode, url, data=data) except RequestException: raise VooblyError('failed to connect') if SCRAPE_FETCH_ERROR in html.text: raise VooblyError('not logged in') ...
Implement a Python 3 function for making a request to URL.
You are a Python code architect, reviewing and designing scalable and efficient code
Get a single ladder.
Can you tell what is the following Python 3 function doing def get_ladder(session, ladder_id, user_id=None, user_ids=None, start=0, limit=LADDER_RESULT_LIMIT): params = { 'start': start, 'limit': limit } if isinstance(ladder_id, str): ladder_id = lookup_ladder_id(ladder_id) if li...
As a python code expert, you are capable of creating scripts from specifications.
def get_lobbies(session, game_id): """Get lobbies for a game.""" if isinstance(game_id, str): game_id = lookup_game_id(game_id) lobbies = _make_request(session, LOBBY_URL, game_id) for lobby in lobbies: # pylint: disable=len-as-condition if len(lobby['ladders']) > 0: ...
How would you code a function in Python 3 to get lobbies for a game.
You are a Python code architect, reviewing and designing scalable and efficient code
Find user by name - returns user ID.
Can you tell what is the following Python 3 function doing def find_user(session, username): resp = _make_request(session, FIND_USER_URL, username) if not resp: raise VooblyError('user not found') try: return int(resp[0]['uid']) except ValueError: raise VooblyError('user not foun...
As a Python code translator, you convert algorithms and pseudocode into Python.
def find_users(session, *usernames): """Find multiple users by name.""" user_string = ','.join(usernames) return _make_request(session, FIND_USERS_URL, user_string)
Create a Python 3 function to find multiple users by name.
As a Python code translator, you convert algorithms and pseudocode into Python.
def user(session, uid, ladder_ids=None): """Get all possible user info by name.""" data = get_user(session, uid) resp = dict(data) if not ladder_ids: return resp resp['ladders'] = {} for ladder_id in ladder_ids: if isinstance(ladder_id, str): ladder_id = lookup_ladder...
Create a Python 3 function to get all possible user info by name.
You are a Python code generator, capable of creating scripts from specifications.
Get a list of ladder IDs.
Can you tell what is the following Python 3 function doing def ladders(session, game_id): if isinstance(game_id, str): game_id = lookup_game_id(game_id) lobbies = get_lobbies(session, game_id) ladder_ids = set() for lobby in lobbies: ladder_ids |= set(lobby['ladders']) return list(la...
You are a Python code analyst, evaluating scripts for potential improvements.
def authenticated(function): """Re-authenticate if session expired.""" def wrapped(session, *args, **kwargs): """Wrap function.""" try: return function(session, *args, **kwargs) except VooblyError: with session.cache_disabled(): _LOGGER.info("attem...
Can you create a Python 3 function that wraps function to re - authenticate session.
As a Python code analyst, you investigate and solve complex coding mysteries
Get recent matches by clan.
Given the following Python 3 function, write the documentation def get_clan_matches(session, subdomain, clan_id, from_timestamp=None, limit=None): return get_recent_matches(session, 'https://{}.voobly.com/{}/{}/0'.format( subdomain, TEAM_MATCHES_URL, clan_id), from_timestamp, limit)
You are a Python code generator, capable of creating scripts from specifications.
def get_user_matches(session, user_id, from_timestamp=None, limit=None): """Get recent matches by user.""" return get_recent_matches(session, '{}{}/{}/Matches/games/matches/user/{}/0'.format( session.auth.base_url, PROFILE_URL, user_id, user_id), from_timestamp, limit)
Implement a function in Python 3 to get recent matches by user.
As a Python code analyst, you investigate and solve complex coding mysteries
def get_recent_matches(session, init_url, from_timestamp, limit): """Get recently played user matches.""" if not from_timestamp: from_timestamp = datetime.datetime.now() - datetime.timedelta(days=1) matches = [] page_id = 0 done = False while not done and page_id < MAX_MATCH_PAGE_ID: ...
How would you code a function in Python 3 to get recently played user matches.
You are a Python code architect, reviewing and designing scalable and efficient code
Get recently played ladder matches.
Given the following Python 3 function, write the documentation def get_ladder_matches(session, ladder_id, from_timestamp=None, limit=LADDER_MATCH_LIMIT): if not from_timestamp: from_timestamp = datetime.datetime.now() - datetime.timedelta(days=1) matches = [] page_id = 0 done = False i = 0 ...
As a Python code analyst, you investigate and solve complex coding mysteries
Download and extract a recorded game.
Can you tell what is the following Python 3 function doing def download_rec(session, rec_url, target_path): try: resp = session.get(session.auth.base_url + rec_url) except RequestException: raise VooblyError('failed to connect for download') try: downloaded = zipfile.ZipFile(io.Bytes...
As a python code expert, you are capable of creating scripts from specifications.
Get a session object for a Voobly API.
Can you tell what is the following Python 3 function doing def get_session(key=None, username=None, password=None, cache=True, cache_expiry=datetime.timedelta(days=7), cookie_path=COOKIE_PATH, backend='memory', version=VERSION_GLOBAL): """Get Voobly API session.""" class VooblyAu...
As a Python code composer, you craft elegant and concise scripts.
The main entry point for the Hyper - V Neutron Agent.
Here you have a function in Python 3, explain what it does def main(): neutron_config.register_agent_state_opts_helper(CONF) common_config.init(sys.argv[1:]) neutron_config.setup_logging() hyperv_agent = HyperVNeutronAgent() # Start everything. LOG.info("Agent initialized successfully, now run...
You are a Python code analyst, evaluating scripts for potential improvements.
Setup the QOS extension if it is required.
Explain what the following Python 3 code does def _setup_qos_extension(self): if not CONF.AGENT.enable_qos_extension: return self._qos_ext = qos_extension.QosAgentExtension() self._qos_ext.consume_api(self) self._qos_ext.initialize(self._connection, 'hyperv')
You are a Python code architect, reviewing and designing scalable and efficient code
Provision the network with the received information.
Make a summary of the following Python 3 code def _provision_network(self, port_id, net_uuid, network_type, physical_network, segmentation_id): """Provision the network with the received information.""" LOG.info("Provisioning network %s", net_uuid) vswitch_name = self...
You are a Python code generator, capable of creating scripts from specifications.
Bind the port to the recived network.
Given the following Python 3 function, write the documentation def _port_bound(self, port_id, network_id, network_type, physical_network, segmentation_id, port_security_enabled, set_port_sriov): """Bind the port to the recived network.""" super(HyperVNeutronAgent, self)._port_bound( ...
As a Python code translator, you convert algorithms and pseudocode into Python.
def _work(self): """Process the information regarding the available ports.""" super(HyperVNeutronAgent, self)._work() if self._nvgre_enabled: self._nvgre_ops.refresh_nvgre_records() self._port_enable_control_metrics()
Write a Python 3 script to process the information regarding the available ports.
You are a Python code analyst, evaluating scripts for potential improvements.
def run_cell_magic(self, magic_name, line, cell): """Run a limited number of magics from scripts, without IPython""" if magic_name == 'bash': self.shebang("bash", cell) elif magic_name == 'metatab': self.mm.metatab(line, cell)
Create a Python 3 function for running a limited number of magics from scripts without IPython
As a Python code translator, you convert algorithms and pseudocode into Python.
Call the given cmd in a subprocess piping stdout and err ArcGIS output.
Here you have a function in Python 3, explain what it does def system_piped(self, cmd): if cmd.rstrip().endswith('&'): # this is *far* from a rigorous test # We do not support backgrounding processes because we either use # pexpect or pipes to read from. Users can always jus...
As a Python code composer, you craft elegant and concise scripts.
Expand python variables in a string.
How would you explain what the following Python 3 function does def var_expand(self, cmd, depth=0, formatter=DollarFormatter()): ns = self.user_ns.copy() try: frame = sys._getframe(depth + 1) except ValueError: # This is thrown if there aren't that many frames on the stac...
As a python code expert, you are capable of creating scripts from specifications.
def shebang(self, line, cell): """Run a cell via a shell command The `%%script` line is like the #! line of script, specifying a program (bash, perl, ruby, etc.) with which to run. The rest of the cell is run by that program. Examples -------- :: I...
Write a Python 3 script for running a cell via a shell command.
You are a Python code architect, reviewing and designing scalable and efficient code
def _get_vertices_neighbours(nets): """Generate a listing of each vertex's immedate neighbours in an undirected interpretation of a graph. Returns ------- {vertex: {vertex: weight, ...}), ...} """ zero_fn = (lambda: 0) vertices_neighbours = defaultdict(lambda: defaultdict(zero_fn)) ...
Implement a function in Python 3 to generate a listing of each vertex s immedate neighbours in an undirected un
You are a Python code generator, capable of creating scripts from specifications.
Generate all the vertices connected to the supplied vertex in alphabetical order.
Can you tell what is the following Python 3 function doing def _dfs(vertex, vertices_neighbours): visited = set() to_visit = deque([vertex]) while to_visit: vertex = to_visit.pop() if vertex not in visited: yield vertex visited.add(vertex) to_visit.extend(...
You are a Python code generator, capable of creating scripts from specifications.
def _get_connected_subgraphs(vertices, vertices_neighbours): """Break a graph containing unconnected subgraphs into a list of connected subgraphs. Returns ------- [set([vertex, ...]), ...] """ remaining_vertices = set(vertices) subgraphs = [] while remaining_vertices: subgra...
Implement a function in Python 3 to break a graph containing unconnected subgraphs into a list of connected subgraphs.
As a Python code composer, you craft elegant and concise scripts.
Yields the Cuthill - McKee order for a connected undirected graph.
Make a summary of the following Python 3 code def _cuthill_mckee(vertices, vertices_neighbours): vertices_degrees = {v: sum(itervalues(vertices_neighbours[v])) for v in vertices} peripheral_vertex = min(vertices, key=(lambda v: vertices_degrees[v])) visited = set([peripheral_vertex...
As a python code expert, you are capable of creating scripts from specifications.
A generator which iterates over the vertices in Reverse - Cuthill - McKee - vertex order.
Given the following Python 3 function, write the documentation def rcm_vertex_order(vertices_resources, nets): vertices_neighbours = _get_vertices_neighbours(nets) for subgraph_vertices in _get_connected_subgraphs(vertices_resources, vertices_neighbours): ...
As a Python code analyst, you investigate and solve complex coding mysteries
Places vertices in reverse - cuthill - McKee order.
Can you generate a brief explanation for the following Python 3 code def place(vertices_resources, nets, machine, constraints): return sequential_place(vertices_resources, nets, machine, constraints, rcm_vertex_order(vertices_resources, nets), ...
As a Python code analyst, you investigate and solve complex coding mysteries
Register the Datadog integration.
Here you have a function in Python 3, explain what it does def register_datadog(tracer=None, namespace: Optional[str]=None, service: str='spinach'): """Register the Datadog integration. Exceptions making jobs fail are sent to Sentry. :param tracer: optionally use a custom ddtrace Trac...
You are a Python code analyst, evaluating scripts for potential improvements.
A row - generating function that yields from a reference
Can you generate the documentation for the following Python 3 function def copy_reference(resource, doc, env, *args, **kwargs): yield from doc.reference(resource.name)
As a Python code translator, you convert algorithms and pseudocode into Python.
A generator function that copies all of the references that have the same Group argument as this reference group.
Can you generate the documentation for the following Python 3 function def copy_reference_group(resource, doc, env, *args, **kwargs): all_headers = [] # Combine all of the headers into a list of tuples by position for ref in doc.references(): if ref.get_value('Group') == resource.get_value('Group'...
As a Python code translator, you convert algorithms and pseudocode into Python.
Returns True if the package save file is older than the metadata.
Can you generate a brief explanation for the following Python 3 code def is_older_than_metadata(self): try: path = self.doc_file.path except AttributeError: path = self.doc_file source_ref = self._doc.ref.path try: age_diff = getmtime(source_ref) - ...
As a Python code translator, you convert algorithms and pseudocode into Python.
Load the resource from a source_r into the current resource and return the resource object.
Can you generate a brief explanation for the following Python 3 code def _load_resource(self, source_r, abs_path=False): from itertools import islice from metapack.exc import MetapackError from os.path import splitext # Refetch the resource ... IIRC b/c the source_r resource may actual...
You are a Python code generator, capable of creating scripts from specifications.
def _load_documentation(self, term, contents, file_name): """Load a single documentation entry""" try: title = term['title'].value except KeyError: self.warn("Documentation has no title, skipping: '{}' ".format(term.value)) return if term.term_is('Ro...
Can you write a function in Python 3 where it loads a single documentation entry from a term.
You are a Python code generator, capable of creating scripts from specifications.
JSON serializer for objects not serializable by default json code
Can you tell what is the following Python 3 function doing def serialize(obj): if isinstance(obj, datetime.datetime): serial = obj.isoformat(sep='T') return serial if isinstance(obj, uuid.UUID): serial = str(obj) return serial try: return obj.__dict__ except Att...
As a Python code composer, you craft elegant and concise scripts.
def _getPayload(self, record): """ The data that will be sent to the RESTful API """ try: # top level payload items d = record.__dict__ pid = d.pop('process', 'nopid') tid = d.pop('thread', 'notid') payload = { ...
Implement a Python 3 function for returning the payload of the record.
You are a Python code architect, reviewing and designing scalable and efficient code
Preps the payload to be formatted in whatever content - type is expected from the RESTful API.
Can you generate a brief explanation for the following Python 3 code def _prepPayload(self, record): payload = self._getPayload(record) json_data = json.dumps(payload, default=serialize) return { 'json': (json_data, 'application/json') }.get(self.content_type, (json_data, 't...
As a python code expert, you are capable of creating scripts from specifications.
Send log record to RESTful API.
Here you have a function in Python 3, explain what it does def emit(self, record): # avoid infinite recursion if record.name.startswith('requests'): return data, header = self._prepPayload(record) try: self.session.post(self._getEndpoint(), ...
You are a Python code architect, reviewing and designing scalable and efficient code
def _getPayload(self, record): """ The data that will be sent to loggly. """ payload = super(LogglyHandler, self)._getPayload(record) payload['tags'] = self._implodeTags() return payload
Write a Python 3 function for returning the payload of the loggly message.
You are a Python code architect, reviewing and designing scalable and efficient code
def emit(self, record): """ Override emit() method in handler parent for sending log to RESTful API """ pid = os.getpid() if pid != self.pid: self.pid = pid self.logs = [] self.timer = self._flushAndRepeatTimer() atexit.reg...
How would you code a function in Python 3 to override emit method for sending log to RESTful
You are a Python code analyst, evaluating scripts for potential improvements.
def nonver_name(self): """Return the non versioned name""" nv = self.as_version(None) if not nv: import re nv = re.sub(r'-[^-]+$', '', self.name) return nv
Write a Python 3 function for returning the non versioned name
As a Python code analyst, you investigate and solve complex coding mysteries
def wrappable_term(self, term): """Return the Root.Description, possibly combining multiple terms. :return: """ return ' '.join(e.value.strip() for e in self['Root'].find(term) if e and e.value)
Create a Python 3 function for returning the Root. Description possibly combining multiple terms.
You are a Python code analyst, evaluating scripts for potential improvements.
Set the Root. Description possibly splitting long descriptions across multiple terms.
Here you have a function in Python 3, explain what it does def set_wrappable_term(self, v, term): import textwrap for t in self['Root'].find(term): self.remove_term(t) for l in textwrap.wrap(v, 80): self['Root'].new_term(term, l)
As a Python code translator, you convert algorithms and pseudocode into Python.
def get_lib_module_dict(self): """Load the 'lib' directory as a python module, so it can be used to provide functions for rowpipe transforms. This only works filesystem packages""" from importlib import import_module if not self.ref: return {} u = parse_app_url(se...
Can you write a function in Python 3 where it loads the lib directory as a python module so it can be used to provide functions for rowpipe transforms. This only works filesystem packages.
As a Python code translator, you convert algorithms and pseudocode into Python.
Produce HTML for Jupyter Notebook
How would you explain what the following Python 3 function does def _repr_html_(self, **kwargs): from jinja2 import Template from markdown import markdown as convert_markdown extensions = [ 'markdown.extensions.extra', 'markdown.extensions.admonition' ] ...
As a Python code composer, you craft elegant and concise scripts.
Write the CSV file.
Explain what the following Python 3 code does def write_csv(self, path=None): # Sort the Sections self.sort_sections(['Root', 'Contacts', 'Documentation', 'References', 'Resources', 'Citations', 'Schema']) # Sort Terms in the root section # Re-wrap the description and abstract ...
You are a Python code generator, capable of creating scripts from specifications.
A wizard which attempts to determine the dimensions of a SpiNNaker system.
Can you generate a brief explanation for the following Python 3 code def dimensions_wizard(): option = yield MultipleChoice( "What type of SpiNNaker system to you have?", ["A single four-chip 'SpiNN-3' board", "A single forty-eight-chip 'SpiNN-5' board", "Multiple forty-eight-chip ...
As a Python code translator, you convert algorithms and pseudocode into Python.
A wizard that implements an interactive command - line human - friendly command - line human - friendly command - line interface for it.
Can you generate the documentation for the following Python 3 function def cli_wrapper(generator): first = True response = None while True: # Insert blank lines between prompts if not first: print() first = False try: message = generator.send(response...
You are a Python code analyst, evaluating scripts for potential improvements.
This function calculates the cost of a given net.
Here you have a function in Python 3, explain what it does def _net_cost(net, placements, has_wrap_around_links, machine): # This function is by far the hottest code in the entire algorithm, as a # result, small performance improvements in here can have significant # impact on the runtime of the overall alg...
You are a Python code generator, capable of creating scripts from specifications.
Get the total cost of the nets connected to the given vertex.
Given the following Python 3 function, write the documentation def _vertex_net_cost(vertex, v2n, placements, has_wrap_around_links, machine): total_cost = 0.0 for net in v2n[vertex]: total_cost += _net_cost(net, placements, has_wrap_around_links, machine) return tota...
As a Python code composer, you craft elegant and concise scripts.
Given a set of vertices and a set of resources and a machine return a list of vertices that should be moved elsewhere to accommodate the arrival of the specified set of resources.
Here you have a function in Python 3, explain what it does def _get_candidate_swap(resources, location, l2v, vertices_resources, fixed_vertices, machine): """Given a chip location, select a set of vertices which would have to be moved elsewhere to accommodate the arrival of the specified...
As a Python code analyst, you investigate and solve complex coding mysteries
def _swap(vas, vas_location, vbs, vbs_location, l2v, vertices_resources, placements, machine): """Swap the positions of two sets of vertices. Parameters ---------- vas : [vertex, ...] A set of vertices currently at vas_location. vas_location : (x, y) vbs : [vertex, ...] ...
Write a Python 3 script to swap the positions of two sets of vertices in a single tree.
You are a Python code architect, reviewing and designing scalable and efficient code
def _step(vertices, d_limit, temperature, placements, l2v, v2n, vertices_resources, fixed_vertices, machine, has_wrap_around_links, random): """Attempt a single swap operation: the kernel of the Simulated Annealing algorithm. Parameters ---------- vertices : [vertex, ...] ...
How would you implement a function in Python 3 that attempts a single swap operation: the kernel of the Simulated Annealing algorithm. Parameters ---------- vertices : [vertex, ...] The set of *movable* vertices. d_limit : int The maximum distance over-which swaps are allowed. temperature : float > 0.0 or None The temp...
As a Python code analyst, you investigate and solve complex coding mysteries
Reset the internal state of the broker.
Make a summary of the following Python 3 code def _reset(self): self._subscriber_thread = None self._must_stop = threading.Event() self._number_periodic_tasks = 0
As a python code expert, you are capable of creating scripts from specifications.
Load a Lua script file and return a Script object.
Make a summary of the following Python 3 code def _load_script(self, filename: str) -> Script: with open(path.join(here, 'redis_scripts', filename), mode='rb') as f: script_data = f.read() rv = self._r.register_script(script_data) if script_data.startswith(b'-- idempotency protected ...
You are a Python code architect, reviewing and designing scalable and efficient code
Enqueue a batch of jobs.
How would you explain what the following Python 3 function does def enqueue_jobs(self, jobs: Iterable[Job]): jobs_to_queue = list() for job in jobs: if job.should_start: job.status = JobStatus.QUEUED else: job.status = JobStatus.WAITING ...
You are a Python code architect, reviewing and designing scalable and efficient code
Get jobs from a queue.
Can you generate a brief explanation for the following Python 3 code def get_jobs_from_queue(self, queue: str, max_jobs: int) -> List[Job]: jobs_json_string = self._run_script( self._get_jobs_from_queue, self._to_namespaced(queue), self._to_namespaced(RUNNING_JOBS_KEY.format(...
You are a Python code architect, reviewing and designing scalable and efficient code
Register tasks that need to be scheduled periodically.
Can you generate a brief explanation for the following Python 3 code def register_periodic_tasks(self, tasks: Iterable[Task]): tasks = [task.serialize() for task in tasks] self._number_periodic_tasks = len(tasks) self._run_script( self._register_periodic_tasks, math.ceil(...
As a Python code composer, you craft elegant and concise scripts.
def inspect_periodic_tasks(self) -> List[Tuple[int, str]]: """Get the next periodic task schedule. Used only for debugging and during tests. """ rv = self._r.zrangebyscore( self._to_namespaced(PERIODIC_TASKS_QUEUE_KEY), '-inf', '+inf', withscores=True ) ...
Write a Python 3 script for getting the next periodic task schedule.
You are a Python code analyst, evaluating scripts for potential improvements.
def next_future_periodic_delta(self) -> Optional[float]: """Give the amount of seconds before the next periodic task is due.""" rv = self._r.zrangebyscore( self._to_namespaced(PERIODIC_TASKS_QUEUE_KEY), '-inf', '+inf', start=0, num=1, withscores=True, score_cast_func=...
Create a Python 3 function for giving the amount of seconds before the next periodic task is due.
You are a Python code analyst, evaluating scripts for potential improvements.
Provision the network with the received information.
Explain what the following Python 3 code does def _provision_network(self, port_id, net_uuid, network_type, physical_network, segmentation_id): """Provision the network with the received information.""" LOG.info("Provisioning network %s", net_uuid) vswitch_name = self...
As a Python code translator, you convert algorithms and pseudocode into Python.
Bind the port to the recived network.
Given the following Python 3 function, write the documentation def _port_bound(self, port_id, network_id, network_type, physical_network, segmentation_id, port_security_enabled, set_port_sriov): """Bind the port to the recived network.""" super(HNVAgent, self)._port_bound(port_id, ne...
As a Python code translator, you convert algorithms and pseudocode into Python.
def send_scp(self, buffer_size, x, y, p, cmd, arg1=0, arg2=0, arg3=0, data=b'', expected_args=3, timeout=0.0): """Transmit a packet to the SpiNNaker machine and block until an acknowledgement is received. Parameters ---------- buffer_size : int Numbe...
Can you write a function in Python 3 where it transmits a SCP packet to the SpiNNaker machine and block until acknowledgement is received.
You are a Python code generator, capable of creating scripts from specifications.
def send_scp_burst(self, buffer_size, window_size, parameters_and_callbacks): """Send a burst of SCP packets and call a callback for each returned packet. Parameters ---------- buffer_size : int Number of bytes held in an SCP buffer by SARK, de...
How would you code a function in Python 3 to send a burst of SCP packets and call a callback for each returned ArcGIS Packet.
As a python code expert, you are capable of creating scripts from specifications.
def read(self, buffer_size, window_size, x, y, p, address, length_bytes): """Read a bytestring from an address in memory. ..note:: This method is included here to maintain API compatibility with an `alternative implementation of SCP <https://github.com/project-rig/ri...
Implement a Python 3 function for reading a bytestring from an address in memory.
As a Python code analyst, you investigate and solve complex coding mysteries
def write(self, buffer_size, window_size, x, y, p, address, data): """Write a bytestring to an address in memory. ..note:: This method is included here to maintain API compatibility with an `alternative implementation of SCP <https://github.com/project-rig/rig-scp>`_...
Write a Python 3 script for writing a bytestring to an address in memory.
You are a Python code analyst, evaluating scripts for potential improvements.
Convert \ n into a <BR > for an HTML formatted message
Explain what the following Python 3 code does def convert_msg_to_html(msg): msg = re.sub("\n", "<br />", msg, flags=re.MULTILINE) return msg
As a Python code composer, you craft elegant and concise scripts.
Validate Nanopub Error Levels are similar to log levels - selecting WARNING includes both WARNING and ERROR, selecting ERROR just includes ERROR The validation result is a list of objects containing { 'level': 'Warning|Error', 'section': 'Assertion|Annotation|Structure', ...
Given the following Python 3 function, write the documentation def validate(nanopub: dict, error_level: str = "WARNING") -> Tuple[str, str, str]: # Validation results v = [] bel_version = config["bel"]["lang"]["default_bel_version"] # Structural checks try: if not isinstance(nanopub["nano...
You are a Python code analyst, evaluating scripts for potential improvements.
def get_specification(version: str) -> Mapping[str, Any]: """Get BEL Specification The json file this depends on is generated by belspec_yaml2json as part of the update_specifications function Args: version: e.g. 2.0.0 where the filename """ spec_dir = config["bel"]["lang"]["specifica...
Write a Python 3 script to get BEL Specification The json file this depends on is generated by belspec_yaml2json as part of the update_specifications function Args: version: e.g. 2.0.0 where the filename
As a Python code translator, you convert algorithms and pseudocode into Python.
Get the list of all BEL Language versions supported by BEL
Can you tell what is the following Python 3 function doing def get_bel_versions() -> List[str]: spec_dir = config["bel"]["lang"]["specifications"] fn = f"{spec_dir}/versions.json" with open(fn, "r") as f: versions = json.load(f) return versions
As a python code expert, you are capable of creating scripts from specifications.
Update BEL Specifications in local directory and store in local directory specified in belbio_conf. yaml
Make a summary of the following Python 3 code def update_specifications(force: bool = False): spec_dir = config["bel"]["lang"]["specifications"] if not os.path.isdir(spec_dir): os.mkdir(spec_dir) log.info(f"Updating BEL Specifications - stored in {spec_dir}") # Collect new specifications from...
As a Python code translator, you convert algorithms and pseudocode into Python.
def github_belspec_files(spec_dir, force: bool = False): """Get belspec files from Github repo Args: spec_dir: directory to store the BEL Specification and derived files force: force update of BEL Specifications from Github - skipped if local files less than 1 day old """ if not force...
Write a Python 3 script for getting BEL Spec files from Github repo
As a Python code translator, you convert algorithms and pseudocode into Python.
def belspec_yaml2json(yaml_fn: str, json_fn: str) -> str: """Enhance BEL specification and save as JSON file Load all BEL Specification YAML files and convert to JSON files after enhancing them. Also create a bel_versions.json file with all available BEL versions for fast loading. Args: y...
Implement a function in Python 3 to enhance BEL Specification and save as JSON file
As a Python code composer, you craft elegant and concise scripts.
def add_function_signature_help(spec_dict: dict) -> dict: """Add function signature help Simplify the function signatures for presentation to BEL Editor users """ for f in spec_dict["functions"]["signatures"]: for argset_idx, argset in enumerate(spec_dict["functions"]["signatures"][f]["signatur...
Can you implement a function in Python 3 that adds function signature help to BEL Editor users
As a Python code translator, you convert algorithms and pseudocode into Python.
Add relation keys to the BEL specification dictionary
Make a summary of the following Python 3 code def add_relations(spec_dict: Mapping[str, Any]) -> Mapping[str, Any]: # Class 'Mapping' does not define '__setitem__', so the '[]' operator cannot be used on its instances spec_dict["relations"]["list"] = [] spec_dict["relations"]["list_short"] = [] spec_di...
As a Python code analyst, you investigate and solve complex coding mysteries
Add function keys to BEL specification dictionary.
Can you generate a brief explanation for the following Python 3 code def add_functions(spec_dict: Mapping[str, Any]) -> Mapping[str, Any]: # Class 'Mapping' does not define '__setitem__', so the '[]' operator cannot be used on its instances spec_dict["functions"]["list"] = [] spec_dict["functions"]["list_l...
You are a Python code generator, capable of creating scripts from specifications.
Add namespace convenience keys list list_long to_short to_long
Here you have a function in Python 3, explain what it does def add_namespaces(spec_dict): for ns in spec_dict["namespaces"]: spec_dict["namespaces"][ns]["list"] = [] spec_dict["namespaces"][ns]["list_long"] = [] spec_dict["namespaces"][ns]["list_short"] = [] spec_dict["namespaces"]...
You are a Python code generator, capable of creating scripts from specifications.
Enhance function signatures in BEL Specification dictionary.
Can you generate a brief explanation for the following Python 3 code def enhance_function_signatures(spec_dict: Mapping[str, Any]) -> Mapping[str, Any]: for func in spec_dict["functions"]["signatures"]: for i, sig in enumerate(spec_dict["functions"]["signatures"][func]["signatures"]): args = si...
As a Python code analyst, you investigate and solve complex coding mysteries
def get_ebnf_template(): """Get EBNF template from Github belbio/bel_specifications repo""" spec_dir = config["bel"]["lang"]["specifications"] local_fp = f"{spec_dir}/bel.ebnf.j2" repo_url = ( "https://api.github.com/repos/belbio/bel_specifications/contents/resources/bel.ebnf.j2" ) pa...
Can you write a function in Python 3 where it gets the EBNF template from Github belbio - bel. ebnf. j2
As a Python code composer, you craft elegant and concise scripts.
def create_ebnf_parser(files): """Create EBNF files and EBNF-based parsers""" flag = False for belspec_fn in files: # Get EBNF Jinja template from Github if enabled if config["bel"]["lang"]["specification_github_repo"]: tmpl_fn = get_ebnf_template() # Check if EBNF file...
How would you code a function in Python 3 to create EBNF files and EBNF - based parsers
You are a Python code generator, capable of creating scripts from specifications.
def get_function_help(function: str, bel_spec: BELSpec): """Get function_help given function name This will get the function summary template (argument summary in signature) and the argument help listing. """ function_long = bel_spec["functions"]["to_long"].get(function) function_help = [] ...
Write a Python 3 function for getting function_help given function name
You are a Python code generator, capable of creating scripts from specifications.
def in_span(loc: int, span: Span) -> bool: """Checks if loc is inside span""" if loc >= span[0] and loc <= span[1]: return True else: return False
How would you implement a function in Python 3 that checks if loc is inside span
You are a Python code generator, capable of creating scripts from specifications.
def cursor( belstr: str, ast: AST, cursor_loc: int, result: Mapping[str, Any] = None ) -> Mapping[str, Any]: """Find BEL function or argument at cursor location Args: belstr: BEL String used to create the completion_text ast (Mapping[str, Any]): AST (dict) of BEL String cursor_loc (...
Can you write a function in Python 3 where it finds BEL function or argument at cursor location
As a Python code composer, you craft elegant and concise scripts.
Search for completions in the current namespace.
Can you generate a brief explanation for the following Python 3 code def nsarg_completions( completion_text: str, entity_types: list, bel_spec: BELSpec, namespace: str, species_id: str, bel_fmt: str, size: int, ): """Namespace completions Args: completion_text entity...
As a Python code composer, you craft elegant and concise scripts.
def relation_completions( completion_text: str, bel_spec: BELSpec, bel_fmt: str, size: int ) -> list: """Filter BEL relations by prefix Args: prefix: completion string bel_fmt: short, medium, long BEL formats spec: BEL specification Returns: list: list of BEL relations ...
How would you code a function in Python 3 to filter BEL relations by prefix
As a Python code analyst, you investigate and solve complex coding mysteries
def function_completions( completion_text: str, bel_spec: BELSpec, function_list: list, bel_fmt: str, size: int, ) -> list: """Filter BEL functions by prefix Args: prefix: completion string bel_fmt: short, medium, long BEL formats spec: BEL specification Returns...
Create a Python 3 function for filtering function list by prefix
As a Python code composer, you craft elegant and concise scripts.
Function argument completion function
Explain what the following Python 3 code does def arg_completions( completion_text: str, parent_function: str, args: list, arg_idx: int, bel_spec: BELSpec, bel_fmt: str, species_id: str, namespace: str, size: int, ): """Function argument completion Only allow legal options f...
As a Python code translator, you convert algorithms and pseudocode into Python.
Create completions for given replacement list and BEL string.
Can you generate the documentation for the following Python 3 function def add_completions( replace_list: list, belstr: str, replace_span: Span, completion_text: str ) -> List[Mapping[str, Any]]: """Create completions to return given replacement list Args: replace_list: list of completion replaceme...
As a Python code translator, you convert algorithms and pseudocode into Python.
Get BEL Assertion completions
How would you explain what the following Python 3 function does def get_completions( belstr: str, cursor_loc: int, bel_spec: BELSpec, bel_comp: str, bel_fmt: str, species_id: str, size: int, ): """Get BEL Assertion completions Args: Results: """ ast, errors = pparse.g...
As a python code expert, you are capable of creating scripts from specifications.
def parse_chars(bels: list, errors: Errors) -> Tuple[CharLocs, Errors]: """Scan BEL string to map parens, quotes, commas Args: bels: bel string as an array of characters errors: list of error tuples ('<type>', '<msg>') Returns: (char_locs, errors): character locations and errors ...
Write a Python 3 script for scanning BEL string to find the corresponding set of character locations and return a list of character locations and a list of errors.
As a Python code analyst, you investigate and solve complex coding mysteries
def parse_functions( bels: list, char_locs: CharLocs, parsed: Parsed, errors: Errors ) -> Tuple[Parsed, Errors]: """Parse functions from BEL using paren, comma, quote character locations Args: bels: BEL string as list of chars char_locs: paren, comma, quote character locations error...
Can you create a Python 3 function that parses functions from BEL string using paren comma quote character locations and return parsed and errors.
You are a Python code analyst, evaluating scripts for potential improvements.
def parse_args( bels: list, char_locs: CharLocs, parsed: Parsed, errors: Errors ) -> Tuple[Parsed, Errors]: """Parse arguments from functions Args: bels: BEL string as list of chars char_locs: char locations for parens, commas and quotes parsed: function locations errors: er...
Implement a Python 3 function for parsing arguments from functions Formula.
You are a Python code analyst, evaluating scripts for potential improvements.