output
stringlengths
1
928k
instruction
stringlengths
7
928k
system
stringlengths
0
104k
def _download_ned_source_metadata( self): """*Query NED using the names of the NED sources in our local database to retrieve extra metadata* *Usage:* .. code-block:: python stream._download_ned_source_metadata() """ self.log.debug('starting the ...
Write a Python 3 function for downloading NED metadata for the specified source.
You are a Python code architect, reviewing and designing scalable and efficient code
Get the names of NED sources that still require metabase in the database
Can you generate the documentation for the following Python 3 function def _get_ned_sources_needing_metadata( self): """*Get the names of 50000 or less NED sources that still require metabase in the database* **Return:** - ``len(self.theseIds)`` -- the number of NED IDs returned...
As a Python code analyst, you investigate and solve complex coding mysteries
Query NED via name searcha and add result metadata to database
How would you explain what the following Python 3 function does def _do_ned_namesearch_queries_and_add_resulting_metadata_to_database( self, batchCount): """*Query NED via name searcha and add result metadata to database* **Key Arguments:** - ``batchCount`` - the ind...
As a python code expert, you are capable of creating scripts from specifications.
Counts the number of sources in the NED table requiring metadata
Explain what the following Python 3 code does def _count_ned_sources_in_database_requiring_metadata( self): """*Count the sources in the NED table requiring metadata* **Return:** - ``self.total``, ``self.batches`` -- total number of galaxies needing metadata & the number of batc...
As a Python code analyst, you investigate and solve complex coding mysteries
def get(self, name=""): """Get the address(es). """ addrs = [] with self._address_lock: for metadata in self._addresses.values(): if (name == "" or (name and name in metadata["service"])): mda = copy.copy(metadata) ...
Write a Python 3 function that can get the address list.
As a Python code composer, you craft elegant and concise scripts.
def _check_age(self, pub, min_interval=timedelta(seconds=0)): """Check the age of the receiver. """ now = datetime.utcnow() if (now - self._last_age_check) <= min_interval: return LOGGER.debug("%s - checking addresses", str(datetime.utcnow())) self._last_age_...
How would you implement a function in Python 3 that checks the age of the receiver.
You are a Python code analyst, evaluating scripts for potential improvements.
A function to convert a file size in bytes into a human - readable form.
Given the following Python 3 function, write the documentation def approximate_size(size, a_kilobyte_is_1024_bytes=True): ''' Humansize.py from Dive into Python3 Mark Pilgrim - http://www.diveintopython3.net/ Copyright (c) 2009, Mark Pilgrim, All rights reserved. Convert a file size to human-readab...
As a Python code analyst, you investigate and solve complex coding mysteries
Return the width of the console area. Autodetection works for Windows and POSIX platforms. Returns 80 for others.
Can you tell what is the following Python 3 function doing def get_console_width(): if os.name == 'nt': STD_INPUT_HANDLE = -10 STD_OUTPUT_HANDLE = -11 STD_ERROR_HANDLE = -12 # get console handle from ctypes import windll, Structure, byref try: from ctype...
As a python code expert, you are capable of creating scripts from specifications.
def filename_from_url(url): """:return: detected filename or None""" fname = os.path.basename(urlparse.urlparse(url).path) if len(fname.strip(" \n\t.")) == 0: return None return fname
Implement a Python 3 function for returning the filename from the url
You are a Python code generator, capable of creating scripts from specifications.
def filename_from_headers(headers): """Detect filename from Content-Disposition headers if present. http://greenbytes.de/tech/tc2231/ :param: headers as dict, list or string :return: filename from content-disposition header or None """ if type(headers) == str: headers = headers.splitlin...
Write a Python 3 function that can detect filename from Content - Disposition header if present.
As a Python code analyst, you investigate and solve complex coding mysteries
def filename_fix_existing(filename, dirname): """Expands name portion of filename with numeric ' (x)' suffix to return filename that doesn't exist already. """ name, ext = filename.rsplit('.', 1) names = [x for x in os.listdir(dirname) if x.startswith(name)] names = [x.rsplit('.', 1)[0] for x in...
Can you write a function in Python 3 where it expands name portion of filename with numeric x suffix to return filename that doesn t exist already.
You are a Python code generator, capable of creating scripts from specifications.
This callback is used to print only the sizes of the available bytes so far.
How would you explain what the following Python 3 function does def report_onlysize(bytes_so_far, total_size, speed, eta): ''' This callback for the download function is used when console width is not enough to print the bar. It prints only the sizes ''' percent = int(bytes_so_far * 100 / total_...
You are a Python code analyst, evaluating scripts for potential improvements.
This function downloads a given link and saves it on outdir.
Can you tell what is the following Python 3 function doing def download(link, outdir='.', chunk_size=4096): ''' This is the Main function, which downloads a given link and saves on outdir (default = current directory) ''' url = None fh = None eta = 'unknown ' bytes_so_far = 0 filenam...
You are a Python code analyst, evaluating scripts for potential improvements.
def ls_cmd(context, before, status): """Display recent logs for analyses.""" runs = context.obj['store'].analyses( status=status, deleted=False, before=parse_date(before) if before else None, ).limit(30) for run_obj in runs: if run_obj.status == 'pending': mes...
Can you create a Python 3 function that displays recent logs for analyses.
You are a Python code analyst, evaluating scripts for potential improvements.
Simple Google Analytics integration.
Make a summary of the following Python 3 code def analytics(account=None, *args, **kwargs): if not account: try: account = settings.GOOGLE_ANALYTICS_ACCOUNT except: raise template.TemplateSyntaxError( "Analytics account could not found either " ...
As a python code expert, you are capable of creating scripts from specifications.
def analysis(analysis_id): """Display a single analysis.""" analysis_obj = store.analysis(analysis_id) if analysis_obj is None: return abort(404) if request.method == 'PUT': analysis_obj.update(request.json) store.commit() data = analysis_obj.to_dict() data['failed_jobs...
Implement a Python 3 function for displaying a single analysis.
You are a Python code generator, capable of creating scripts from specifications.
def get_gravatar(email, size=80, default='identicon'): """ Get's a Gravatar for a email address. :param size: The size in pixels of one side of the Gravatar's square image. Optional, if not supplied will default to ``80``. :param default: Defines what should be displayed if no imag...
Create a Python 3 function to get s a Gravatar for a user s email address.
As a Python code translator, you convert algorithms and pseudocode into Python.
Returns the URI to redirect to after successful sign in.
Given the following Python 3 function, write the documentation def login_redirect(redirect=None, user=None): if redirect: return redirect elif user is not None: return defaults.ACCOUNTS_LOGIN_REDIRECT_URL % \ {'username': user.username} else: return settings.LOGIN_REDIRECT_URL
As a Python code analyst, you investigate and solve complex coding mysteries
Generates a sha1 hash for the supplied string.
Can you generate the documentation for the following Python 3 function def generate_sha1(string, salt=None): if not salt: salt = hashlib.sha1(str(random.random()).encode('utf-8')).hexdigest()[:5] hash = hashlib.sha1((salt+str(string)).encode('utf-8')).hexdigest() return (salt, hash)
As a Python code analyst, you investigate and solve complex coding mysteries
Returns a datetime object with current point in time.
Here you have a function in Python 3, explain what it does def get_datetime_now(): try: from django.utils import timezone return timezone.now() except ImportError: return datetime.datetime.now()
You are a Python code generator, capable of creating scripts from specifications.
This function demonstrates a more complex usage of the HandleError. handle_errors method.
Explain what the following Python 3 code does def complex_handle_errors(): print("Demonstrating complex handle_errors example") def _handler_function(err, final_message, trace): """ This function is a helper function for handling an exception from the handle_errors ctx_mgr. """ ...
You are a Python code analyst, evaluating scripts for potential improvements.
Check if data is JSON serializable.
Can you generate a brief explanation for the following Python 3 code def is_valid_data(obj): if obj: try: tmp = json.dumps(obj, default=datetime_encoder) del tmp except (TypeError, UnicodeDecodeError): return False return True
You are a Python code generator, capable of creating scripts from specifications.
def datetime_decoder(dct): """Decode datetimes to python objects. """ if isinstance(dct, list): pairs = enumerate(dct) elif isinstance(dct, dict): pairs = dct.items() result = [] for key, val in pairs: if isinstance(val, six.string_types): try: ...
Write a Python 3 script to decode datetimes to python objects.
You are a Python code generator, capable of creating scripts from specifications.
def _decode(rawstr): """Convert a raw string to a Message. """ # Check for the magick word. try: rawstr = rawstr.decode('utf-8') except (AttributeError, UnicodeEncodeError): pass except (UnicodeDecodeError): try: rawstr = rawstr.decode('iso-8859-1') ex...
Write a Python 3 script to convert a raw string to a Message.
You are a Python code architect, reviewing and designing scalable and efficient code
def _encode(msg, head=False, binary=False): """Convert a Message to a raw string. """ rawstr = str(_MAGICK) + u"{0:s} {1:s} {2:s} {3:s} {4:s}".format( msg.subject, msg.type, msg.sender, msg.time.isoformat(), msg.version) if not head and msg.data: if not binary and isinstance(msg.data, s...
Can you write a function in Python 3 where it converts a Message to a raw string.
As a Python code composer, you craft elegant and concise scripts.
Return local sender. Don't use the getpass module, it looks at various environment variables and is unreliable.
How would you explain what the following Python 3 function does def _getsender(): import os import pwd import socket host = socket.gethostname() user = pwd.getpwuid(os.getuid())[0] return "%s@%s" % (user, host)
You are a Python code architect, reviewing and designing scalable and efficient code
Validate a messages attributes.
Can you tell what is the following Python 3 function doing def _validate(self): if not is_valid_subject(self.subject): raise MessageError("Invalid subject: '%s'" % self.subject) if not is_valid_type(self.type): raise MessageError("Invalid type: '%s'" % self.type) if not i...
As a Python code translator, you convert algorithms and pseudocode into Python.
Generate a new PK and sign its public key using the IK and add the timestamp aswell to allow for periodic rotations.
Can you tell what is the following Python 3 function doing def __generateSPK(self): key = self.__KeyPair.generate() key_serialized = self.__PublicKeyEncoder.encodePublicKey( key.pub, self.__curve ) signature = self.__XEdDSA(mont_priv = self.__ik.priv).sign(key_...
You are a Python code analyst, evaluating scripts for potential improvements.
Generates the given amount of OTPKs.
Here you have a function in Python 3, explain what it does def __generateOTPKs(self, num_otpks = None): if num_otpks == None: num_otpks = self.__max_num_otpks otpks = [] for _ in range(num_otpks): otpks.append(self.__KeyPair.generate()) try: ...
As a Python code analyst, you investigate and solve complex coding mysteries
Derive the shared secret key from the secret key material.
Explain what the following Python 3 code does def __kdf(self, secret_key_material): salt = b"\x00" * self.__hash_function().digest_size if self.__curve == "25519": input_key_material = b"\xFF" * 32 if self.__curve == "448": input_key_material = b"\xFF" * 57 inp...
As a Python code composer, you craft elegant and concise scripts.
def __checkSPKTimestamp(self): """ Check whether the SPK is too old and generate a new one in that case. """ if time.time() - self.__spk["timestamp"] > self.__spk_timeout: self.__generateSPK()
Write a Python 3 function that can check whether the SPK is too old and generate a new one if it is too old.
You are a Python code analyst, evaluating scripts for potential improvements.
def __refillOTPKs(self): """ If the amount of available OTPKs fell under the minimum, refills the OTPKs up to the maximum limit again. """ remainingOTPKs = len(self.__otpks) if remainingOTPKs < self.__min_num_otpks: self.__generateOTPKs(self.__max_num_otpks ...
Write a Python 3 function that can refill the OTPKs of the current class if they are not longer than the minimum.
You are a Python code generator, capable of creating scripts from specifications.
def hideFromPublicBundle(self, otpk_pub): """ Hide a one-time pre key from the public bundle. :param otpk_pub: The public key of the one-time pre key to hide, encoded as a bytes-like object. """ self.__checkSPKTimestamp() for otpk in self.__otpks: ...
Can you create a Python 3 function that hides a one - time pre key from the public bundle.
As a Python code translator, you convert algorithms and pseudocode into Python.
Delete a one - time pre key.
How would you explain what the following Python 3 function does def deleteOTPK(self, otpk_pub): self.__checkSPKTimestamp() for otpk in self.__otpks: if otpk.pub == otpk_pub: self.__otpks.remove(otpk) for otpk in self.__hidden_otpks: if otpk.pub == otpk_...
As a python code expert, you are capable of creating scripts from specifications.
def getPublicBundle(self): """ Fill a PublicBundle object with the public bundle data of this State. :returns: An instance of PublicBundle, filled with the public data of this State. """ self.__checkSPKTimestamp() ik_pub = self.__ik.pub spk_pub = self.__sp...
Write a Python 3 script to return an instance of PublicBundle filled with the public data of this State.
You are a Python code generator, capable of creating scripts from specifications.
Returns True if the state has changed since the last flag was loaded or cleared.
How would you explain what the following Python 3 function does def changed(self): self.__checkSPKTimestamp() changed = self._changed self._changed = False return changed
As a Python code composer, you craft elegant and concise scripts.
This method returns the shared secret for the active party.
Given the following Python 3 function, write the documentation def getSharedSecretActive( self, other_public_bundle, allow_zero_otpks = False ): """ Do the key exchange, as the active party. This involves selecting keys from the passive parties' public bundle. ...
You are a Python code architect, reviewing and designing scalable and efficient code
This method is used to get the shared secret for a specific key exchange.
Can you tell what is the following Python 3 function doing def getSharedSecretPassive( self, passive_exchange_data, allow_no_otpk = False, keep_otpk = False ): """ Do the key exchange, as the passive party. This involves retrieving data about the key exchange ...
You are a Python code analyst, evaluating scripts for potential improvements.
def save(self, mode=0o600): """ Serialize the config data to the user home directory. :param mode: The octal Unix mode (permissions) for the config file. """ if self._parent is not None: self._parent.save(mode=mode) else: config_dir = os.path.dirn...
How would you implement a function in Python 3 that serializes the config data to the user home directory.
You are a Python code generator, capable of creating scripts from specifications.
def getChemicalPotential(self, solution): """Call solver in order to calculate chemical potential. """ if isinstance(solution, Solution): solution = solution.getSolution() self.mu = self.solver.chemicalPotential(solution) return self.mu
Create a Python 3 function to call solver in order to calculate chemical potential.
As a Python code analyst, you investigate and solve complex coding mysteries
Store object to mat - file.
Can you generate a brief explanation for the following Python 3 code def store(self, filename=None, label=None, desc=None, date=None): date = date if date else datetime.now() date = date.replace(microsecond=0).isoformat() filename = filename if filename else date + '.mat' matfile = { ...
You are a Python code generator, capable of creating scripts from specifications.
def restore(self, filename): """Restore object from mat-file. TODO: determine format specification """ matfile = loadmat(filename) matfile['originals'] = matfile['originals'][0, 0] if matfile['dim'] == 1: matfile['init_solution'] = matfile['init_solution'][0, :] ...
Can you write a function in Python 3 where it restores object from mat - file.
You are a Python code generator, capable of creating scripts from specifications.
def getDampingIntegral(self): """Calculate integral of damping terms of hamiltonian using rectangular method. """ reservoir = self.getReservoir() density = self.getDensity() length = self.model.getSpatialStep() if self.solution.ndim == 1: nodes = self.model.g...
Create a Python 3 function to calculate integral of damping terms of hamiltonian using rectangular method.
As a Python code analyst, you investigate and solve complex coding mysteries
Store object to mat - file.
Can you generate a brief explanation for the following Python 3 code def store(self, filename=None, label=None, desc=None, date=None): date = datetime.now() if date is None else date filename = filename if filename else date.replace(microsecond=0).isoformat() + '.mat' def storeWithFileLikeObjec...
As a Python code analyst, you investigate and solve complex coding mysteries
Restore object from mat - file.
Explain what the following Python 3 code does def restore(self, filename): matfile = loadmat(filename) if matfile['dim'] == 1: matfile['solution'] = matfile['solution'][0, :] self.elapsed_time = matfile['elapsed_time'][0, 0] self.solution = matfile['solution'] retu...
As a Python code analyst, you investigate and solve complex coding mysteries
def fmt_val(val, shorten=True): """Format a value for inclusion in an informative text string. """ val = repr(val) max = 50 if shorten: if len(val) > max: close = val[-1] val = val[0:max-4] + "..." if close in (">", "'", '"', ']', '}', ')'): ...
Can you implement a function in Python 3 that formats a value for inclusion in an informative text string.
You are a Python code architect, reviewing and designing scalable and efficient code
Formats a dictionary of key = val pairs for inclusion in an informative text string.
Given the following Python 3 function, write the documentation def fmt_dict_vals(dict_vals, shorten=True): items = dict_vals.items() if not items: return [fmt_val(None, shorten=shorten)] return ["%s=%s" % (k, fmt_val(v, shorten=shorten)) for k,v in items]
As a python code expert, you are capable of creating scripts from specifications.
def build_command(self, config, **kwargs): """Builds the command to execute MIP.""" command = ['perl', self.script, CLI_OPTIONS['config']['option'], config] for key, value in kwargs.items(): # enable passing in flags as "False" - shouldn't add command if value: ...
Can you implement a function in Python 3 that builds the command to execute MIP.
As a Python code composer, you craft elegant and concise scripts.
def execute(self, command): """Start a new MIP run.""" process = subprocess.Popen( command, preexec_fn=lambda: signal.signal(signal.SIGPIPE, signal.SIG_DFL) ) return process
Create a Python 3 function to start a new MIP run.
You are a Python code analyst, evaluating scripts for potential improvements.
def update(self): """ Update wiki pages See class docstring for usage """ self.log.debug('starting the ``update`` method') if "sherlock wiki root" not in self.settings: print "Sherlock wiki settings not found in settings file" return sta...
Create a Python 3 function for updating wiki pages and github tables
As a Python code composer, you craft elegant and concise scripts.
def _get_table_infos( self, trimmed=False): """query the sherlock-catalogues database table metadata """ self.log.debug('starting the ``_get_table_infos`` method') sqlQuery = u""" SELECT * FROM crossmatch_catalogues.tcs_helper_catalogue_tables_info wh...
Write a Python 3 function that can get the table info from the crossmatch - catalogues database
As a Python code composer, you craft elegant and concise scripts.
get the view info for the current user
Explain what the following Python 3 code does def _get_view_infos( self, trimmed=False): """query the sherlock-catalogues database view metadata """ self.log.debug('starting the ``_get_view_infos`` method') sqlQuery = u""" SELECT v.*, t.description as...
As a python code expert, you are capable of creating scripts from specifications.
query the sherlock - catalogues database streamed data tables info
Explain what the following Python 3 code does def _get_stream_view_infos( self, trimmed=False): """query the sherlock-catalogues database streamed data tables' metadata """ self.log.debug('starting the ``_get_stream_view_infos`` method') sqlQuery = u""" ...
As a Python code translator, you convert algorithms and pseudocode into Python.
generate markdown format tables from the database query results
Can you tell what is the following Python 3 function doing def _create_md_tables( self, tableData, viewData, streamData ): """generate markdown format tables from the database query results **Key Arguments:** - ``tableData`` -- the sherlock-catalogues dat...
As a Python code translator, you convert algorithms and pseudocode into Python.
write the markdown formated content of the database tables views and streams to local wiki pages
How would you explain what the following Python 3 function does def _write_wiki_pages( self): """write the markdown formated content of the database tables' metadata to local wiki pages """ self.log.debug('starting the ``_write_wiki_pages`` method') pathToWriteFile = self.se...
You are a Python code analyst, evaluating scripts for potential improvements.
commit the changes and push them to github
Can you generate the documentation for the following Python 3 function def _update_github( self): """commit the changes and push them to github """ self.log.debug('starting the ``_update_github`` method') from subprocess import Popen, PIPE, STDOUT gdir = self.setting...
As a Python code analyst, you investigate and solve complex coding mysteries
Sends an email to the user with the specified subject and message.
How would you explain what the following Python 3 function does def email_user( self, subject, message, from_email=settings.DEFAULT_FROM_EMAIL, **kwargs ): """ Sends an email to this User. If settings.EMAIL_OVERRIDE_ADDRESS is set, this mail will be redirected to the alternate mail...
You are a Python code generator, capable of creating scripts from specifications.
def clean(context, days_ago, yes): """Clean up files from "old" analyses runs.""" number_of_days_ago = dt.datetime.now() - dt.timedelta(days=days_ago) analyses = context.obj['store'].analyses( status='completed', before=number_of_days_ago, deleted=False, ) for analysis_obj in...
How would you code a function in Python 3 to clean up files from old analyses runs.
You are a Python code analyst, evaluating scripts for potential improvements.
Grep out all lines with scancel example.
Given the following Python 3 function, write the documentation def job_ids(log_stream): id_rows = [line for line in log_stream if 'scancel' in line] jobs = [id_row.strip()[-7:-1] for id_row in id_rows] return jobs
You are a Python code architect, reviewing and designing scalable and efficient code
def get_or_create_config(path, config): """Using TOML format, load config from given path, or write out example based on defaults""" if os.path.isfile(path): with open(path) as fh: _LOG.debug("loading config from %s", os.path.abspath(path)) config._inflate(toml.load(fh)) else...
Write a Python 3 script to load or create a config from a file or create it if it doesn t exist.
You are a Python code analyst, evaluating scripts for potential improvements.
Prepare for serialisation - returns a dictionary
Given the following Python 3 function, write the documentation def _deflate(cls): data = {k: v for k, v in vars(cls).items() if not k.startswith("_")} return {Constants.CONFIG_KEY: data}
You are a Python code generator, capable of creating scripts from specifications.
def _inflate(cls, data): """Update config by deserialising input dictionary""" for k, v in data[Constants.CONFIG_KEY].items(): setattr(cls, k, v) return cls._deflate()
How would you code a function in Python 3 to update config by deserialising input dictionary
As a python code expert, you are capable of creating scripts from specifications.
Decorator that patches an object before the decorated method is called and restores it afterwards.
Can you tell what is the following Python 3 function doing def with_patched_object(obj, attr_name, patched_value): def patcher(method): @wraps(method) def method_call(*m_args, **m_kw): patched_obj = patch_object(obj, attr_name, patched_value) try: return metho...
As a Python code analyst, you investigate and solve complex coding mysteries
def patch_object(obj, attr_name, patched_value): """Patches an object and returns an instance of :class:`fudge.patcher.PatchHandler` for later restoration. Note that if *obj* is not an object but a path to a module then it will be imported. You may want to use a more convenient wrapper :func:`with_patched...
Can you implement a function in Python 3 that patches an object and returns an instance of fudge. patcher. PatchHandler for later restoration.
As a Python code composer, you craft elegant and concise scripts.
def patch(self, patched_value): """Set a new value for the attribute of the object.""" try: if self.getter: setattr(self.getter_class, self.attr_name, patched_value) else: setattr(self.orig_object, self.attr_name, patched_value) except Type...
Create a Python 3 function for setting a new value for the attribute of the object.
As a Python code translator, you convert algorithms and pseudocode into Python.
Restore the saved value for the attribute of the object.
Make a summary of the following Python 3 code def restore(self): if self.proxy_object is None: if self.getter: setattr(self.getter_class, self.attr_name, self.getter) elif self.is_local: setattr(self.orig_object, self.attr_name, self.orig_value) ...
As a Python code translator, you convert algorithms and pseudocode into Python.
Parse MIP config file.
Make a summary of the following Python 3 code def parse_config(data: dict) -> dict: return { 'email': data.get('email'), 'family': data['family_id'], 'samples': [{ 'id': sample_id, 'type': analysis_type, } for sample_id, analysis_type in data['analysis_type']....
As a Python code composer, you craft elegant and concise scripts.
Parse MIP sample info file.
Given the following Python 3 function, write the documentation def parse_sampleinfo(data: dict) -> dict: genome_build = data['human_genome_build'] genome_build_str = f"{genome_build['source']}{genome_build['version']}" if 'svdb' in data['program']: svdb_outpath = (f"{data['program']['svdb']['path']...
You are a Python code architect, reviewing and designing scalable and efficient code
def parse_qcmetrics(metrics: dict) -> dict: """Parse MIP qc metrics file. Args: metrics (dict): raw YAML input from MIP qc metrics file Returns: dict: parsed data """ data = { 'versions': { 'freebayes': metrics['program']['freebayes']['version'], 'gat...
Can you create a Python 3 function that parses MIP qc metrics file.
As a python code expert, you are capable of creating scripts from specifications.
Parse Peddy sexcheck output.
Make a summary of the following Python 3 code def parse_peddy_sexcheck(handle: TextIO): data = {} samples = csv.DictReader(handle) for sample in samples: data[sample['sample_id']] = { 'predicted_sex': sample['predicted_sex'], 'het_ratio': float(sample['het_ratio']), ...
As a Python code composer, you craft elegant and concise scripts.
def parse_chanjo_sexcheck(handle: TextIO): """Parse Chanjo sex-check output.""" samples = csv.DictReader(handle, delimiter='\t') for sample in samples: return { 'predicted_sex': sample['sex'], 'x_coverage': float(sample['#X_coverage']), 'y_coverage': float(sample[...
Implement a Python 3 function for parsing Chanjo sex - check output.
You are a Python code generator, capable of creating scripts from specifications.
Lazily imports a utils class from a module or function or variable.
Can you generate a brief explanation for the following Python 3 code def import_util(imp): ''' Lazily imports a utils (class, function,or variable) from a module) from a string. @param imp: ''' mod_name, obj_name = imp.rsplit('.', 1) mod = importlib.import_module(mod_name) return ge...
As a Python code composer, you craft elegant and concise scripts.
def draw_segments(image, segments, color=(255, 0, 0), line_width=1): """draws segments on image""" for segment in segments: x, y, w, h = segment cv2.rectangle(image, (x, y), (x + w, y + h), color, line_width)
Can you implement a function in Python 3 that draws segments on image
As a Python code translator, you convert algorithms and pseudocode into Python.
def time_to_sec(time_str: str) -> int: """Convert time in string format to seconds. Skipping seconds since sometimes the last column is truncated for entries where >10 days. """ total_sec = 0 if '-' in time_str: # parse out days days, time_str = time_str.split('-') total...
Can you write a function in Python 3 where it converts time in string format to seconds.
As a Python code analyst, you investigate and solve complex coding mysteries
def convert_job(row: list) -> dict: """Convert sacct row to dict.""" state = row[-2] start_time_raw = row[-4] end_time_raw = row[-3] if state not in ('PENDING', 'CANCELLED'): start_time = datetime.strptime(start_time_raw, '%Y-%m-%dT%H:%M:%S') if state != 'RUNNING': end_ti...
Implement a Python 3 function for converting sacct row to dict.
You are a Python code analyst, evaluating scripts for potential improvements.
def parse_sacct(sacct_stream): """Parse out information from sacct status output.""" rows = (line.split() for line in sacct_stream) # filter rows that begin with a SLURM job id relevant_rows = (row for row in rows if row[0].isdigit()) jobs = [convert_job(row) for row in relevant_rows] return job...
Create a Python 3 function to parse out information from sacct status output.
As a python code expert, you are capable of creating scripts from specifications.
def filter_jobs(sacct_jobs, failed=True): """Filter jobs that have a FAILED etc. status.""" categories = FAILED_CATEGORIES if failed else NORMAL_CATEGORIES filtered_jobs = [job for job in sacct_jobs if job['state'] in categories] return filtered_jobs
Can you create a Python 3 function that filters jobs that have a FAILED etc. status.
You are a Python code analyst, evaluating scripts for potential improvements.
def guess_segments_lines(segments, lines, nearline_tolerance=5.0): """ given segments, outputs a array of line numbers, or -1 if it doesn't belong to any """ ys = segments[:, 1] closeness = numpy.abs(numpy.subtract.outer(ys, lines)) # each row a y, each collumn a distance to each line line_...
Can you create a Python 3 function that gives a list of segments outputs a array of line numbers or - 1 if it doesn t belong to any segment
As a Python code analyst, you investigate and solve complex coding mysteries
givens a n * n matrix m n = len ( segments ) means segments[i ] is contained inside segments[j ]
Here you have a function in Python 3, explain what it does def contained_segments_matrix(segments): x1, y1 = segments[:, 0], segments[:, 1] x2, y2 = x1 + segments[:, 2], y1 + segments[:, 3] n = len(segments) x1so, x2so, y1so, y2so = list(map(numpy.argsort, (x1, x2, y1, y2))) x1soi, x2soi, y1soi, y2...
As a Python code translator, you convert algorithms and pseudocode into Python.
sort segments in read order - left to right up to down
Can you tell what is the following Python 3 function doing def _process(self, segments): # sort_f= lambda r: max_line_width*(r[1]/max_line_height)+r[0] # segments= sorted(segments, key=sort_f) # segments= segments_to_numpy( segments ) # return segments mlh, mlw = self.max_line_he...
As a python code expert, you are capable of creating scripts from specifications.
send data to address and verify response
Can you generate the documentation for the following Python 3 function def _send_to_address(self, address, data, timeout=10): # Socket to talk to server socket = get_context().socket(REQ) try: socket.setsockopt(LINGER, timeout * 1000) if address.find(":") == -1: ...
As a Python code composer, you craft elegant and concise scripts.
Create a resource out of a JSON dict.
Can you generate the documentation for the following Python 3 function def from_json(self, json): res_type = json['sys']['type'] if ResourceType.Array.value == res_type: return self.create_array(json) elif ResourceType.Entry.value == res_type: return self.create_entry(js...
As a Python code analyst, you investigate and solve complex coding mysteries
Create a new Entry instance from a JSON dict.
Here you have a function in Python 3, explain what it does def create_entry(self, json): sys = json['sys'] ct = sys['contentType']['sys']['id'] fields = json['fields'] raw_fields = copy.deepcopy(fields) # Replace links with :class:`.resources.ResourceLink` objects. for k...
You are a Python code generator, capable of creating scripts from specifications.
Create Asset instance from JSON dict.
Make a summary of the following Python 3 code def create_asset(json): result = Asset(json['sys']) file_dict = json['fields']['file'] result.fields = json['fields'] result.url = file_dict['url'] result.mimeType = file_dict['contentType'] return result
As a python code expert, you are capable of creating scripts from specifications.
def create_content_type(json): """Create :class:`.resource.ContentType` from JSON. :param json: JSON dict. :return: ContentType instance. """ result = ContentType(json['sys']) for field in json['fields']: field_id = field['id'] del field['id'] ...
Implement a function in Python 3 to create a ContentType instance from a JSON dict.
You are a Python code architect, reviewing and designing scalable and efficient code
def convert_value(value, field): """Given a :class:`.fields.Field` and a value, ensure that the value matches the given type, otherwise attempt to convert it. :param value: field value. :param field: :class:`.fields.Field` instance. :return: Result value. """ clz...
Implement a function in Python 3 to give a value and a field instance convert it to the correct type.
You are a Python code analyst, evaluating scripts for potential improvements.
def process_array_items(self, array, json): """Iterate through all `items` and create a resource for each. In addition map the resources under the `items_mapped` by the resource id and type. :param array: Array resource. :param json: Raw JSON dictionary. """ for item in...
How would you implement a function in Python 3 that iterates through all items and create a resource for each.
As a Python code analyst, you investigate and solve complex coding mysteries
Iterate through all includes and create a resource for every item.
Make a summary of the following Python 3 code def process_array_includes(self, array, json): includes = json.get('includes') or {} for key in array.items_mapped.keys(): if key in includes: for resource in includes[key]: processed = self.from_json(resource)...
As a Python code translator, you convert algorithms and pseudocode into Python.
def create_array(self, json): """Create :class:`.resources.Array` from JSON. :param json: JSON dict. :return: Array instance. """ result = Array(json['sys']) result.total = json['total'] result.skip = json['skip'] result.limit = json['limit'] resu...
Write a Python 3 function for creating an array instance from JSON dict.
You are a Python code architect, reviewing and designing scalable and efficient code
def clear_calls(self): """Clears out any calls that were made on previously registered fake objects and resets all call stacks. You do not need to use this directly. Use fudge.clear_calls() """ self.clear_actual_calls() for stack in self.call_stacks: stack.r...
How would you code a function in Python 3 to clear out any calls that were made on previously registered fake objects and resets all call stacks.
As a Python code translator, you convert algorithms and pseudocode into Python.
def verify(self): """Ensure all expected calls were called, raise AssertionError otherwise. You do not need to use this directly. Use fudge.verify() """ try: for exp in self.get_expected_calls(): exp.assert_called() exp.assert_times_c...
Write a Python 3 script for ensuring all expected calls were called and that all expected calls were met.
As a python code expert, you are capable of creating scripts from specifications.
assert that all calls have been made in the right order.
Can you generate the documentation for the following Python 3 function def assert_order_met(self, finalize=False): error = None actual_call_len = len(self._actual_calls) expected_call_len = len(self._call_order) if actual_call_len == 0: error = "Not enough calls were made" ...
As a python code expert, you are capable of creating scripts from specifications.
def calls(self, call): """Redefine a call. The fake method will execute your function. I.E.:: >>> f = Fake().provides('hello').calls(lambda: 'Why, hello there') >>> f.hello() 'Why, hello there' """ exp = self._get_current_call() exp.call_re...
Can you implement a function in Python 3 that redefines a call. The fake method will execute your function.
As a Python code analyst, you investigate and solve complex coding mysteries
def expects(self, call_name): """Expect a call. .. doctest:: :hide: >>> import fudge >>> fudge.clear_expectations() >>> fudge.clear_calls() If the method *call_name* is never called, then raise an error. I.E.:: >>> session = Fake('...
Can you write a function in Python 3 where it expects a call. .. doctest:: :hide: >>> import fudge >>> fudge.clear_expectations() >>> fudge.clear_calls() If the method *call_name* is never called, then raise an error. I.E.:: >>> session = Fake('session').expects('open').expects('close') >>> session.open() >>> fudge.ver...
You are a Python code architect, reviewing and designing scalable and efficient code
Start expecting or provides multiple calls.
Given the following Python 3 function, write the documentation def next_call(self, for_method=None): last_call_name = self._last_declared_call_name if for_method: if for_method not in self._declared_calls: raise FakeDeclarationError( "next_call(for...
You are a Python code analyst, evaluating scripts for potential improvements.
def provides(self, call_name): """Provide a call. The call acts as a stub -- no error is raised if it is not called.:: >>> session = Fake('session').provides('open').provides('close') >>> import fudge >>> fudge.clear_expectations() # from any previously declared fak...
Create a Python 3 function for providing a call. The call acts as a stub -- no error is raised if it is not called.:: >>> session = Fake('session').provides('open').provides('close') >>> import fudge >>> fudge.clear_expectations() # from any previously declared fakes >>> fudge.clear_calls() >>> session.open() >>> fudge...
As a Python code composer, you craft elegant and concise scripts.
Set the last call to raise an exception class or instance.
Can you generate a brief explanation for the following Python 3 code def raises(self, exc): exp = self._get_current_call() exp.exception_to_raise = exc return self
You are a Python code generator, capable of creating scripts from specifications.
def remember_order(self): """Verify that subsequent :func:`fudge.Fake.expects` are called in the right order. For example:: >>> import fudge >>> db = fudge.Fake('db').remember_order().expects('insert').expects('update') >>> db.update() Traceback (most re...
Create a Python 3 function for verifying that all subsequent calls to get_id are in the right order.
You are a Python code generator, capable of creating scripts from specifications.
def returns(self, val): """Set the last call to return a value. Set a static value to return when a method is called. I.E.:: >>> f = Fake().provides('get_number').returns(64) >>> f.get_number() 64 """ exp = self._get_current_call() exp.retu...
Can you create a Python 3 function that sets the last call to return a value.
You are a Python code analyst, evaluating scripts for potential improvements.
Set the last call to return a fake object.
Here you have a function in Python 3, explain what it does def returns_fake(self, *args, **kwargs): exp = self._get_current_call() endpoint = kwargs.get('name', exp.call_name) name = self._endpoint_name(endpoint) kwargs['name'] = '%s()' % name fake = self.__class__(*args, **kwarg...
As a Python code translator, you convert algorithms and pseudocode into Python.