output
stringlengths
1
928k
instruction
stringlengths
7
928k
system
stringlengths
0
104k
constructs a Transcript object from the database
Can you tell what is the following Python 3 function doing def construct_gene_object(ensembl, transcript_id): # get the sequence for the identified transcript (chrom, start, end, strand, genomic_sequence) = ensembl.get_genomic_seq_for_transcript(transcript_id, expand=10) cds_sequence = ensembl.get_cds_...
You are a Python code generator, capable of creating scripts from specifications.
def get_de_novos_in_transcript(transcript, de_novos): """ get the de novos within the coding sequence of a transcript Args: transcript: Transcript object, which defines the transcript coordinates de_novos: list of chromosome sequence positions for de novo events Returns: li...
How would you implement a function in Python 3 that gets the de novo positions within a given transcript
As a Python code translator, you convert algorithms and pseudocode into Python.
def get_transcript_ids(ensembl, gene_id): """ gets transcript IDs for a gene. Args: ensembl: EnsemblRequest object to request data from ensembl gene_id: HGNC symbol for gene Returns: dictionary of transcript ID: transcript lengths for all transcripts for a given HGN...
Create a Python 3 function for getting transcript IDs for a given gene
You are a Python code architect, reviewing and designing scalable and efficient code
def load_gene(ensembl, gene_id, de_novos=[]): """ sort out all the necessary sequences and positions for a gene Args: ensembl: EnsemblRequest object to request data from ensembl gene_id: HGNC symbol for gene de_novos: list of de novo positions, so we can check they all fit in ...
Write a Python 3 script for loading all the necessary sequences and positions for a gene
You are a Python code architect, reviewing and designing scalable and efficient code
Count the number of de novo positions in a single gene.
Can you tell what is the following Python 3 function doing def count_de_novos_per_transcript(ensembl, gene_id, de_novos=[]): transcripts = get_transcript_ids(ensembl, gene_id) # TODO: allow for genes without any coding sequence. if len(transcripts) == 0: raise IndexError("{0} lacks coding ...
As a python code expert, you are capable of creating scripts from specifications.
def minimise_transcripts(ensembl, gene_id, de_novos): """ get a set of minimal transcripts to contain all the de novos. We identify the minimal number of transcripts to contain all de novos. This allows for de novos on mutually exclusive transcripts. The transcripts are selected on the basis of con...
Can you create a Python 3 function that gets a set of minimal transcripts to contain all the de novos. We identify the minimal number of transcripts to contain all de novos. This allows for de novos on mutually exclusive transcripts. The transcripts are selected on the basis of containing the most number of de novos, w...
You are a Python code generator, capable of creating scripts from specifications.
def dump_simple_db(path): """ Dumps a SimpleDb as string in the following format: <key>: <json-encoded string> """ output = [] simpledb = SimpleDb(path, mode="r", sync=False) with simpledb as db: for key in db: output.append("{0}: {1}".format(key, db.dumpvalue(key))) return "\n".join(output)
Can you write a function in Python 3 where it dumps a SimpleDb as string in the following format : <key > <json - encoded string >
As a Python code analyst, you investigate and solve complex coding mysteries
Retrieve a required variable from the current environment variables. Raises a ValueError if the required variable is not supplied.
Given the following Python 3 function, write the documentation def required_from_env(key): val = os.environ.get(key) if not val: raise ValueError( "Required argument '{}' not supplied and not found in environment variables".format(key)) return val
You are a Python code generator, capable of creating scripts from specifications.
def get(self, url): """ Make a HTTP GET request to the Reader API. :param url: url to which to make a GET request. """ logger.debug('Making GET request to %s', url) return self.oauth_session.get(url)
Create a Python 3 function to make a HTTP GET request to the Reader API.
As a python code expert, you are capable of creating scripts from specifications.
Make a HTTP POST request to the Reader API.
Can you generate the documentation for the following Python 3 function def post(self, url, post_params=None): params = urlencode(post_params) logger.debug('Making POST request to %s with body %s', url, params) return self.oauth_session.post(url, data=params)
As a Python code analyst, you investigate and solve complex coding mysteries
Make a HTTP DELETE request to the Readability API.
Can you generate a brief explanation for the following Python 3 code def delete(self, url): logger.debug('Making DELETE request to %s', url) return self.oauth_session.delete(url)
As a Python code composer, you craft elegant and concise scripts.
def get_article(self, article_id): """ Get a single article represented by `article_id`. :param article_id: ID of the article to retrieve. """ url = self._generate_url('articles/{0}'.format(article_id)) return self.get(url)
Write a Python 3 function for getting a single article represented by article_id.
You are a Python code architect, reviewing and designing scalable and efficient code
def get_bookmarks(self, **filters): """ Get Bookmarks for the current user. Filters: :param archive: Filter Bookmarks returned by archived status. :param favorite: Filter Bookmarks returned by favorite status. :param domain: Filter Bookmarks returned by a domain. ...
Write a Python 3 function that can get all bookmarks for the current user.
As a Python code translator, you convert algorithms and pseudocode into Python.
def get_bookmark(self, bookmark_id): """ Get a single bookmark represented by `bookmark_id`. The requested bookmark must belong to the current user. :param bookmark_id: ID of the bookmark to retrieve. """ url = self._generate_url('bookmarks/{0}'.format(bookmark_id)) ...
Write a Python 3 script to get a single bookmark represented by bookmark_id.
You are a Python code architect, reviewing and designing scalable and efficient code
Adds given bookmark to the authenticated user s user s list of bookmarks.
Can you generate a brief explanation for the following Python 3 code def add_bookmark(self, url, favorite=False, archive=False, allow_duplicates=True): rdb_url = self._generate_url('bookmarks') params = { "url": url, "favorite": int(favorite), "archive": int(archive),...
As a python code expert, you are capable of creating scripts from specifications.
Updates the given bookmark.
How would you explain what the following Python 3 function does def update_bookmark(self, bookmark_id, favorite=None, archive=None, read_percent=None): rdb_url = self._generate_url('bookmarks/{0}'.format(bookmark_id)) params = {} if favorite is not None: params['favorite'] = 1 if fav...
As a Python code translator, you convert algorithms and pseudocode into Python.
Delete a single bookmark represented by bookmark_id.
Here you have a function in Python 3, explain what it does def delete_bookmark(self, bookmark_id): url = self._generate_url('bookmarks/{0}'.format(bookmark_id)) return self.delete(url)
You are a Python code architect, reviewing and designing scalable and efficient code
Retrieves the tags that have been applied to a bookmark.
Given the following Python 3 function, write the documentation def get_bookmark_tags(self, bookmark_id): url = self._generate_url('bookmarks/{0}/tags'.format(bookmark_id)) return self.get(url)
You are a Python code architect, reviewing and designing scalable and efficient code
def add_tags_to_bookmark(self, bookmark_id, tags): """ Add tags to to a bookmark. The identified bookmark must belong to the current user. :param bookmark_id: ID of the bookmark to delete. :param tags: Comma separated tags to be applied. """ url = self._generate...
How would you code a function in Python 3 to add tags to a bookmark.
As a Python code translator, you convert algorithms and pseudocode into Python.
def delete_tag_from_bookmark(self, bookmark_id, tag_id): """ Remove a single tag from a bookmark. The identified bookmark must belong to the current user. :param bookmark_id: ID of the bookmark to delete. """ url = self._generate_url('bookmarks/{0}/tags/{1}'.format( ...
Create a Python 3 function to remove a single tag from a bookmark.
As a Python code composer, you craft elegant and concise scripts.
Get a single tag represented by tag_id.
Here you have a function in Python 3, explain what it does def get_tag(self, tag_id): url = self._generate_url('tags/{0}'.format(tag_id)) return self.get(url)
As a Python code analyst, you investigate and solve complex coding mysteries
def post(self, url, post_params=None): """ Make an HTTP POST request to the Parser API. :param url: url to which to make the request :param post_params: POST data to send along. Expected to be a dict. """ post_params['token'] = self.token params = urlencode(post_...
How would you implement a function in Python 3 that makes an HTTP POST request to the Parser API.
You are a Python code architect, reviewing and designing scalable and efficient code
Build the url to resource.
Explain what the following Python 3 code does def _generate_url(self, resource, query_params=None): resource = '{resource}?token={token}'.format(resource=resource, token=self.token) if query_params: resource += "&{}".format(urlencode(query_params)) return self.base_url_template.forma...
As a Python code analyst, you investigate and solve complex coding mysteries
Send a GET request to the parser API to get the representation of an article.
Given the following Python 3 function, write the documentation def get_article(self, url=None, article_id=None, max_pages=25): query_params = {} if url is not None: query_params['url'] = url if article_id is not None: query_params['article_id'] = article_id query_...
As a Python code analyst, you investigate and solve complex coding mysteries
def post_article_content(self, content, url, max_pages=25): """ POST content to be parsed to the Parser API. Note: Even when POSTing content, a url must still be provided. :param content: the content to be parsed :param url: the url that represents the content :param ma...
Can you write a function in Python 3 where it posts the content to the Parser API.
You are a Python code generator, capable of creating scripts from specifications.
Send a HEAD request to the parser API to get the articles status.
Can you generate the documentation for the following Python 3 function def get_article_status(self, url=None, article_id=None): query_params = {} if url is not None: query_params['url'] = url if article_id is not None: query_params['article_id'] = article_id url =...
You are a Python code analyst, evaluating scripts for potential improvements.
Send a GET request to the Confidence endpoint of the Parser API.
Given the following Python 3 function, write the documentation def get_confidence(self, url=None, article_id=None): query_params = {} if url is not None: query_params['url'] = url if article_id is not None: query_params['article_id'] = article_id url = self._gener...
You are a Python code architect, reviewing and designing scalable and efficient code
Save the word embedding file.
Here you have a function in Python 3, explain what it does def save(f, arr, vocab): itr = iter(vocab) # Avoid empty line at the end word, idx = next(itr) _write_line(f, arr[idx], word) for word, idx in itr: f.write(b'\n') _write_line(f, arr[idx], word)
You are a Python code generator, capable of creating scripts from specifications.
def convert(outputfile, inputfile, to_format, from_format): """ Convert pretrained word embedding file in one format to another. """ emb = word_embedding.WordEmbedding.load( inputfile, format=_input_choices[from_format][1], binary=_input_choices[from_format][2]) emb.save(outputfile, ...
Create a Python 3 function for converting pretrained word embedding file in one format to another.
As a python code expert, you are capable of creating scripts from specifications.
def check_format(inputfile): """ Check format of inputfile. """ t = word_embedding.classify_format(inputfile) if t == word_embedding._glove: _echo_format_result('glove') elif t == word_embedding._word2vec_bin: _echo_format_result('word2vec-binary') elif t == word_embedding._w...
Can you create a Python 3 function that checks format of inputfile.
As a Python code translator, you convert algorithms and pseudocode into Python.
def main(): """Do the default action of `twitter` command.""" from twitter.cmdline import Action, OPTIONS twitter = Twitter.from_oauth_file() Action()(twitter, OPTIONS)
Can you write a function in Python 3 where it does the default action of twitter command.
You are a Python code analyst, evaluating scripts for potential improvements.
def from_oauth_file(cls, filepath=None): """Get an object bound to the Twitter API using your own credentials. The `twitter` library ships with a `twitter` command that uses PIN OAuth. Generate your own OAuth credentials by running `twitter` from the shell, which will open a browser win...
Write a Python 3 script for creating an instance of TwitterAPIAuth using an OAuth file.
As a Python code composer, you craft elegant and concise scripts.
def search(self, q=None, **kw): """Search twitter for ``q``, return `results`__ directly from twitter. __ https://dev.twitter.com/rest/reference/get/search/tweets """ if q is None: raise ValueError('No search query provided for `q` keyword.') return self.twitter.sear...
How would you implement a function in Python 3 that searches twitter for q return results directly from twitter. search. tweets
As a Python code translator, you convert algorithms and pseudocode into Python.
def lookup_search_result(self, result, **kw): """Perform :meth:`lookup` on return value of :meth:`search`.""" return self.lookup(s['id_str'] for s in result['statuses'], **kw)
Can you write a function in Python 3 where it performs : meth : lookup on return value of search.
As a python code expert, you are capable of creating scripts from specifications.
Lookup list of statuses return results directly from twitter.
How would you explain what the following Python 3 function does def lookup(self, id_list, **kw): result_id_pack = ','.join([str(_id) for _id in id_list]) if not result_id_pack: return [] return self.twitter.statuses.lookup(_id=result_id_pack)
As a Python code translator, you convert algorithms and pseudocode into Python.
Plots the probe for a single MEA.
How would you explain what the following Python 3 function does def plot_probe(mea, ax=None, xlim=None, ylim=None, color_currents=False, top=None, bottom=None, cmap='viridis', type='shank', alpha_elec=0.7, alpha_prb=0.3): ''' Parameters ---------- mea axis xlim ylim ...
As a Python code analyst, you investigate and solve complex coding mysteries
Get version without import which avoids dependency issues.
Can you generate the documentation for the following Python 3 function def get_version(filepath='src/birding/version.py'): with open(get_abspath(filepath)) as version_file: return re.search( r"""__version__\s+=\s+(['"])(?P<version>.+?)\1""", version_file.read()).group('version')
As a python code expert, you are capable of creating scripts from specifications.
Search Gnip for given query returning deserialized response.
Can you generate the documentation for the following Python 3 function def search(self, q, **kw): url = '{base_url}/search/{stream}'.format(**vars(self)) params = { 'q': q, } params.update(self.params) params.update(kw) response = self.session.get(url, param...
You are a Python code generator, capable of creating scripts from specifications.
def dump(result): """Dump result into a string, useful for debugging.""" if isinstance(result, dict): # Result is a search result. statuses = result['results'] else: # Result is a lookup result. statuses = result status_str_list = [] ...
Create a Python 3 function for dumping result into a string useful for debugging.
As a python code expert, you are capable of creating scripts from specifications.
def shelf_from_config(config, **default_init): """Get a `Shelf` instance dynamically based on config. `config` is a dictionary containing ``shelf_*`` keys as defined in :mod:`birding.config`. """ shelf_cls = import_name(config['shelf_class'], default_ns='birding.shelf') init = {} init.updat...
How would you implement a function in Python 3 that gets a Shelf instance dynamically based on config.
As a Python code analyst, you investigate and solve complex coding mysteries
Unpack and return value only if it is fresh.
Explain what the following Python 3 code does def unpack(self, key, value): value, freshness = value if not self.is_fresh(freshness): raise KeyError('{} (stale)'.format(key)) return value
As a python code expert, you are capable of creating scripts from specifications.
def is_fresh(self, freshness): """Return False if given freshness value has expired, else True.""" if self.expire_after is None: return True return self.freshness() - freshness <= self.expire_after
Write a Python 3 script for returning True if given freshness value has expired else False.
You are a Python code analyst, evaluating scripts for potential improvements.
def get_form_errors(form): """ Django form errors do not obey natural field order, this template tag returns non-field and field-specific errors :param form: the form instance """ return { 'non_field': form.non_field_errors(), 'field_specific': OrderedDict( (field, fo...
How would you implement a function in Python 3 that returns a dictionary of Django form errors for the given form instance.
You are a Python code architect, reviewing and designing scalable and efficient code
Return a dict with the sub - nav data.
Here you have a function in Python 3, explain what it does def sub_nav(context): request = context.get('request') return { 'alt_urls': make_alternate_language_urls(request), 'breadcrumbs': context.get('breadcrumbs'), 'breadcrumbs_back': context.get('breadcrumbs_back'), }
As a python code expert, you are capable of creating scripts from specifications.
def is_first_instance_aws(): """ Returns True if the current instance is the first instance in the ASG group, sorted by instance_id. """ try: # get instance id and aws region instance_details = requests.get('http://169.254.169.254/latest/dynamic/instance-identity/document', ...
Can you implement a function in Python 3 that returns True if the current instance is the first instance in the ASG group sorted by instance_id.
As a Python code composer, you craft elegant and concise scripts.
Returns True if the current pod is the first instance of Kubernetes cluster.
Can you generate the documentation for the following Python 3 function def is_first_instance_k8s(current_pod_name=None): current_pod_name = current_pod_name or os.environ.get('POD_NAME') if not current_pod_name: raise StackInterrogationException('Pod name not known') namespace = 'money-to-prisoners...
You are a Python code architect, reviewing and designing scalable and efficient code
This function will split arguments separated by spaces or commas
Can you generate the documentation for the following Python 3 function def splitarg(args): ''' This function will split arguments separated by spaces or commas to be backwards compatible with the original ArcGet command line tool ''' if not args: return args split = list() for arg i...
As a Python code analyst, you investigate and solve complex coding mysteries
def login(request, template_name=None, redirect_field_name=REDIRECT_FIELD_NAME, authentication_form=AuthenticationForm, current_app=None, extra_context=None): """ Displays the login form and handles the login action. """ redirect_to = request.POST.get( redirect_fiel...
Write a Python 3 function for handling the login action.
You are a Python code generator, capable of creating scripts from specifications.
Logs out the user.
How would you explain what the following Python 3 function does def logout(request, template_name=None, next_page=None, redirect_field_name=REDIRECT_FIELD_NAME, current_app=None, extra_context=None): """ Logs out the user. """ auth_logout(request) if next_page is no...
You are a Python code architect, reviewing and designing scalable and efficient code
def get_config(filepath=None, default_loader=None, on_missing=None): """Get a dict for the current birding configuration. The resulting dictionary is fully populated with defaults, such that all valid keys will resolve to valid values. Invalid and extra values in the configuration result in an exceptio...
Write a Python 3 script for getting a dictionary of current birding configuration.
As a Python code composer, you craft elegant and concise scripts.
Get a file object with YAML data of configuration defaults. Arguments are passed through to get_defaults_str.
Explain what the following Python 3 code does def get_defaults_file(*a, **kw): fd = StringIO() fd.write(get_defaults_str(*a, **kw)) fd.seek(0) return fd
As a python code expert, you are capable of creating scripts from specifications.
def get_defaults_str(raw=None, after='Defaults::'): """Get the string YAML representation of configuration defaults.""" if raw is None: raw = __doc__ return unicode(textwrap.dedent(raw.split(after)[-1]).strip())
Write a Python 3 function that can get the string YAML representation of configuration defaults.
You are a Python code architect, reviewing and designing scalable and efficient code
Overlays the dict onto the lower dict.
How would you explain what the following Python 3 function does def overlay(upper, lower): result = {} for key in upper: if is_mapping(upper[key]): lower_value = lower.get(key, {}) if not is_mapping(lower_value): msg = 'Attempting to overlay a mapping on a non-map...
As a Python code analyst, you investigate and solve complex coding mysteries
def import_name(name, default_ns=None): """Import an object based on the dotted string. >>> import_name('textwrap') # doctest: +ELLIPSIS <module 'textwrap' from '...'> >>> import_name('birding.config') # doctest: +ELLIPSIS <module 'birding.config' from '...'> >>> import_name('birding.config.get...
How would you implement a function in Python 3 that imports an object based on the dotted string.
As a Python code translator, you convert algorithms and pseudocode into Python.
def follow_topic_from_config(): """Read kafka config, then dispatch to `follow_topic`.""" config = get_config()['ResultTopicBolt'] kafka_class = import_name(config['kafka_class']) return follow_topic(kafka_class, config['topic'], **config['kafka_init'])
Create a Python 3 function to read kafka config then dispatch to follow_topic.
As a python code expert, you are capable of creating scripts from specifications.
def follow_topic(kafka_class, name, retry_interval=1, **kafka_init): """Dump each message from kafka topic to stdio.""" while True: try: client = kafka_class(**kafka_init) topic = client.topics[name] consumer = topic.get_simple_consumer(reset_offset_on_start=True) ...
Implement a Python 3 function for dumping each message from kafka topic to stdio.
You are a Python code generator, capable of creating scripts from specifications.
def follow_fd(fd): """Dump each line of input to stdio.""" dump = Dump() for line in fd: if not line.strip(): continue with flushing(sys.stdout, sys.stderr): status = load(line) if status: dump(status)
How would you implement a function in Python 3 that dumps each line of input to stdio.
As a Python code analyst, you investigate and solve complex coding mysteries
Determine if the error means to retry or fail True to retry.
Can you generate the documentation for the following Python 3 function def should_try_kafka_again(error): msg = 'Unable to retrieve' return isinstance(error, KafkaException) and str(error).startswith(msg)
You are a Python code architect, reviewing and designing scalable and efficient code
Check if a file is valid Glove format.
Explain what the following Python 3 code does def check_valid(line0, line1): data = line0.strip().split(b' ') if len(data) <= 2: return False # check if data[2:] is float values try: map(float, data[2:]) except: return False return True
As a Python code translator, you convert algorithms and pseudocode into Python.
Load word embedding file with predefined vocabulary
Here you have a function in Python 3, explain what it does def load_with_vocab(fin, vocab, dtype=np.float32): arr = None for line in fin: try: token, v = _parse_line(line, dtype) except (ValueError, IndexError): raise ParseError(b'Parsing error in line: ' + line) ...
As a python code expert, you are capable of creating scripts from specifications.
def load(fin, dtype=np.float32, max_vocab=None): """ Load word embedding file. Args: fin (File): File object to read. File should be open for reading ascii. dtype (numpy.dtype): Element data type to use for the array. max_vocab (int): Number of vocabulary to read. Returns: ...
Can you create a Python 3 function that loads word embedding file into numpy array.
You are a Python code architect, reviewing and designing scalable and efficient code
Updates python dependencies with pip install
Given the following Python 3 function, write the documentation def python_dependencies(context: Context, extras=None): with mock.patch('setuptools.setup'): from setup import install_requires, extras_require requirements = install_requires.copy() if extras: requirements.extend(ex...
You are a Python code architect, reviewing and designing scalable and efficient code
Updates the version of the MTP - common item.
Can you generate a brief explanation for the following Python 3 code def set_version(context: Context, version=None, bump=False): if bump and version: raise TaskError('You cannot bump and set a specific version') if bump: from mtp_common import VERSION version = list(VERSION) ve...
As a Python code analyst, you investigate and solve complex coding mysteries
def authenticate(self, username=None, password=None): """ Returns a valid `MojUser` if the authentication is successful or None if the credentials were wrong. """ data = api_client.authenticate(username, password) if not data: return return User( ...
Can you create a Python 3 function that authenticates the user with the given username and password.
As a Python code translator, you convert algorithms and pseudocode into Python.
Requests and stores the NOMIS API client token from mtp - api
Make a summary of the following Python 3 code def get_client_token(): if getattr(settings, 'NOMIS_API_CLIENT_TOKEN', ''): return settings.NOMIS_API_CLIENT_TOKEN global client_token if not client_token or client_token['expires'] and client_token['expires'] - now() < datetime.timedelta(days=1): ...
You are a Python code architect, reviewing and designing scalable and efficient code
Returns a new QuerySet instance that will include related objects.
How would you explain what the following Python 3 function does def include(self, *fields, **kwargs): clone = self._clone() # Preserve the stickiness of related querysets # NOTE: by default _clone will clear this attribute # .include does not modify the actual query, so we # sho...
As a Python code composer, you craft elegant and concise scripts.
def search(d, recursive=True, store_meta=True): ''' Search for DICOM files within a given directory and receive back a dictionary of {StudyInstanceUID: {SeriesNumber: [files]}} Example usage:: >>> import yaxil.dicom >>> yaxil.dicom.search("~/dicoms").keys() ['1.2.340.500067...
Implement a Python 3 function for searching for DICOM files within a given directory and receive back a dictionary of DICOM files.
As a Python code analyst, you investigate and solve complex coding mysteries
def replace_default_error_messages(): """ Replace Django's generic error messages with MTP-specific versions NB: avoid trailing full stops visually, they are added for screen readers in templates """ forms.Field.default_error_messages['required'] = _('This field is required') forms.CharField.def...
Create a Python 3 function to replace Django s generic error messages with MTP - specific versions
You are a Python code architect, reviewing and designing scalable and efficient code
def load_vocab(fin): """ Load vocabulary from vocab file created by word2vec with ``-save-vocab <file>`` option. Args: fin (File): File-like object to read from. encoding (bytes): Encoding of the input file as defined in ``codecs`` module of Python standard library. ...
Implement a function in Python 3 to load vocabulary from file created by word2vec with - save - vocab <file > option.
As a Python code analyst, you investigate and solve complex coding mysteries
Authenticate the user with the API.
How would you explain what the following Python 3 function does def authenticate(username, password): session = MoJOAuth2Session( client=LegacyApplicationClient( client_id=settings.API_CLIENT_ID ) ) token = session.fetch_token( token_url=get_request_token_url(), ...
You are a Python code generator, capable of creating scripts from specifications.
def revoke_token(access_token): """ Instructs the API to delete this access token and associated refresh token """ response = requests.post( get_revoke_token_url(), data={ 'token': access_token, 'client_id': settings.API_CLIENT_ID, 'client_secret': set...
Create a Python 3 function to remove an access token and associated refresh token
As a python code expert, you are capable of creating scripts from specifications.
def get_authenticated_api_session(username, password): """ :return: an authenticated api session """ session = MoJOAuth2Session( client=LegacyApplicationClient( client_id=settings.API_CLIENT_ID ) ) session.fetch_token( token_url=get_request_token_url(), ...
Write a Python 3 function for returning an authenticated api session
As a python code expert, you are capable of creating scripts from specifications.
def check_valid(line0, line1): """ Check :func:`word_embedding_loader.loader.glove.check_valid` for the API. """ data0 = line0.split(b' ') if len(data0) != 2: return False # check if data0 is int values try: map(int, data0) _parse_line(line1, float) except: ...
Write a Python 3 script to check if the line0 and line1 are valid.
As a Python code composer, you craft elegant and concise scripts.
Load a word embedding file with a vocabulary.
Can you generate the documentation for the following Python 3 function def load_with_vocab(fin, vocab, dtype=np.float32): line = next(fin) data = line.strip().split(b' ') assert len(data) == 2 size = int(data[1]) arr = np.empty((len(vocab), size), dtype=dtype) arr.fill(np.NaN) for line in fi...
You are a Python code architect, reviewing and designing scalable and efficient code
Load a sequence of word embedding data from a file - like object.
Can you generate the documentation for the following Python 3 function def load(fin, dtype=np.float32, max_vocab=None): vocab = {} line = next(fin) data = line.strip().split(b' ') assert len(data) == 2 words = int(data[0]) if max_vocab is not None: words = min(max_vocab, words) size ...
As a Python code analyst, you investigate and solve complex coding mysteries
Read connection details from an xnat_auth XML file and return a named tuple of url username password
Can you generate a brief explanation for the following Python 3 code def auth(alias=None, url=None, cfg="~/.xnat_auth"): ''' Read connection details from an xnat_auth XML file Example: >>> import yaxil >>> auth = yaxil.auth('xnatastic') >>> auth.url, auth.username, auth.password ...
As a python code expert, you are capable of creating scripts from specifications.
Retrieve Subject tuples for subjects returned by this function.
Can you generate the documentation for the following Python 3 function def subjects(auth, label=None, project=None): ''' Retrieve Subject tuples for subjects returned by this function. Example: >>> import yaxil >>> auth = yaxil.XnatAuth(url='...', username='...', password='...') ...
You are a Python code generator, capable of creating scripts from specifications.
def experiments(auth, label=None, project=None, subject=None): ''' Retrieve Experiment tuples for experiments returned by this function. Example: >>> import yaxil >>> auth = yaxil.XnatAuth(url='...', username='...', password='...') >>> yaxil.experiment(auth, 'AB1234C') E...
How would you code a function in Python 3 to retrieve experiments for a specific subject.
You are a Python code analyst, evaluating scripts for potential improvements.
def accession(auth, label, project=None): ''' Get the Accession ID for any Experiment label. Example: >>> import yaxil >>> auth = yaxil.XnatAuth(url='...', username='...', password='...') >>> yaxil.accession(auth, 'AB1234C') u'XNAT_E00001' :param auth: XNAT authenticati...
Create a Python 3 function to get the Accession ID for any label.
As a python code expert, you are capable of creating scripts from specifications.
Download scan data from XNAT MR Session.
Make a summary of the following Python 3 code def download(auth, label, scan_ids=None, project=None, aid=None, out_dir='.', in_mem=True, progress=False, attempts=1): ''' Download scan data from XNAT. Example: >>> import yaxil >>> auth = yaxil.XnatAuth(url='...', username='....
As a python code expert, you are capable of creating scripts from specifications.
Extract a Java 1. 6 XNAT ZIP archive into a Python file - like object.
Make a summary of the following Python 3 code def extract(zf, content, out_dir='.'): ''' Extracting a Java 1.6 XNAT ZIP archive in Python. :param zf: ZipFile object :type zf: zipfile.ZipFile :param out_dir: Output directory :type out_dir: str ''' previous_header_offset = 0 compensat...
As a Python code analyst, you investigate and solve complex coding mysteries
Search for scans by supplying a set of SQL - based conditionals.
Can you tell what is the following Python 3 function doing def scansearch(auth, label, filt, project=None, aid=None): ''' Search for scans by supplying a set of SQL-based conditionals. Example: >>> import yaxil >>> auth = yaxil.XnatAuth(url='...', username='...', password='...') >>>...
As a python code expert, you are capable of creating scripts from specifications.
Get information about a MR Session as a sequence of dictionaries.
How would you explain what the following Python 3 function does def scans(auth, label=None, scan_ids=None, project=None, experiment=None): ''' Get scan information for a MR Session as a sequence of dictionaries. Example: >>> import yaxil >>> import json >>> auth = yaxil.XnatAuth(url...
As a python code expert, you are capable of creating scripts from specifications.
def extendedboldqc(auth, label, scan_ids=None, project=None, aid=None): ''' Get ExtendedBOLDQC data as a sequence of dictionaries. Example: >>> import yaxil >>> import json >>> auth = yaxil.XnatAuth(url='...', username='...', password='...') >>> for eqc in yaxil.extendedbold...
Write a Python 3 function for getting ExtendedBOLDQC data as a sequence of dictionaries.
You are a Python code generator, capable of creating scripts from specifications.
Issue a GET request to the XNAT REST API and box the response content.
Make a summary of the following Python 3 code def _get(auth, path, fmt, autobox=True, params=None): ''' Issue a GET request to the XNAT REST API and box the response content. Example: >>> import yaxil >>> from yaxil import Format >>> auth = yaxil.XnatAuth(url='...', username='.....
As a Python code translator, you convert algorithms and pseudocode into Python.
def has(auth, xsitype, project=None): ''' Test if a project contains any items of a particular xsi:type. Example: >>> import yaxil >>> auth = yaxil.XnatAuth(url='...', username='...', password='...') >>> yaxil.has(auth, 'neuroinfo:extendedboldqc', project='MyProject') :param au...
How would you code a function in Python 3 to test if a project contains any items of a particular xsi type.
As a Python code analyst, you investigate and solve complex coding mysteries
Returns a cached copy of the user if it exists.
Can you tell what is the following Python 3 function doing def get_user(request): if not hasattr(request, '_cached_user'): request._cached_user = auth_get_user(request) return request._cached_user
As a Python code composer, you craft elegant and concise scripts.
Decorator that ensures that the user is in exactly one role and that the user is not in prison - pumpk role.
Can you generate the documentation for the following Python 3 function def ensure_compatible_admin(view): def wrapper(request, *args, **kwargs): user_roles = request.user.user_data.get('roles', []) if len(user_roles) != 1: context = { 'message': 'I need to be able to man...
You are a Python code generator, capable of creating scripts from specifications.
Method decorator to catch and log errors then send fail message.
Make a summary of the following Python 3 code def fault_barrier(fn): @functools.wraps(fn) def process(self, tup): try: return fn(self, tup) except Exception as e: if isinstance(e, KeyboardInterrupt): return print(str(e), file=sys.stderr) ...
As a Python code analyst, you investigate and solve complex coding mysteries
Initialization steps: 1. Get :func:`~birding.search.search_manager_from_config`. 2. Prepare to track searched terms as to avoid redundant searches.
Given the following Python 3 function, write the documentation def initialize(self, conf, ctx): self.manager = get_search_manager() config = get_config()['TwitterSearchBolt'] self.term_shelf = shelf_from_config(config)
As a Python code composer, you craft elegant and concise scripts.
def process(self, tup): """Process steps: 1. Stream in (term, timestamp). 2. Perform :meth:`~birding.search.SearchManager.search` on term. 3. Emit (term, timestamp, search_result). """ term, timestamp = tup.values if term not in self.term_shelf: self....
Can you write a function in Python 3 where it processes the term_shelf and emit the results.
As a Python code composer, you craft elegant and concise scripts.
Process the tuple and emit the result.
How would you explain what the following Python 3 function does def process(self, tup): term, timestamp, search_result = tup.values self.log( 'lookup: {term}, {timestamp}' .format(term=term, timestamp=timestamp)) lookup_result = self.manager.lookup_search_result(search_re...
As a python code expert, you are capable of creating scripts from specifications.
Initialization steps: 1. Prepare elasticsearch connection, including details for indexing.
How would you explain what the following Python 3 function does def initialize(self, conf, ctx): config = get_config()['ElasticsearchIndexBolt'] elasticsearch_class = import_name(config['elasticsearch_class']) self.es = elasticsearch_class(**config['elasticsearch_init']) self.index = con...
You are a Python code analyst, evaluating scripts for potential improvements.
Process steps for the get_record method.
Make a summary of the following Python 3 code def process(self, tup): self.es.bulk( self.generate_bulk_body(tup.values[2]), index=self.index, doc_type=self.doc_type)
You are a Python code architect, reviewing and designing scalable and efficient code
Initialize the object with the given configuration.
How would you explain what the following Python 3 function does def initialize(self, conf, ctx): config = get_config()['ResultTopicBolt'] kafka_class = import_name(config['kafka_class']) self.client = kafka_class(**config['kafka_init']) self.topic = self.client.topics[config['topic']] ...
You are a Python code architect, reviewing and designing scalable and efficient code
def process(self, tup): """Process steps: 1. Stream third positional value from input into Kafka topic. """ status_seq = self.iter_using_shelf(tup.values[2], self.tweet_shelf) # This could be more efficient by passing the result from twitter # straight through to the pro...
Implement a Python 3 function for processing steps : 1. Stream third positional value from input into Kafka topic. 2. Stream third positional value from input into Kafka topic.
You are a Python code analyst, evaluating scripts for potential improvements.
Return a SearchManager instance dynamically based on config.
How would you explain what the following Python 3 function does def search_manager_from_config(config, **default_init): manager_cls = import_name(config['class'], default_ns='birding.search') init = {} init.update(default_init) init.update(config['init']) manager = manager_cls(**init) return man...
As a Python code composer, you craft elegant and concise scripts.
Create a BIDS output directory from a configuration file.
Can you generate the documentation for the following Python 3 function def bids_from_config(sess, scans_metadata, config, out_base): ''' Create a BIDS output directory from configuration file ''' # get session and subject labels from scan metadata _item = next(iter(scans_metadata)) session,subje...
As a Python code analyst, you investigate and solve complex coding mysteries
Download anatomical data and convert to BIDS
Given the following Python 3 function, write the documentation def proc_anat(config, args): ''' Download anatomical data and convert to BIDS ''' refs = dict() for scan in iterconfig(config, 'anat'): ref = scan.get('id', None) templ = 'sub-${sub}_ses-${ses}' if 'acquisition' i...
As a python code expert, you are capable of creating scripts from specifications.
Iterate over BIDS configuration file
Given the following Python 3 function, write the documentation def iterconfig(config, scan_type): ''' Iterate over BIDS configuration file ''' if scan_type in config: for modality,scans in iter(config[scan_type].items()): for scan in scans: scan.update({ ...
As a Python code composer, you craft elegant and concise scripts.