code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
text
stringlengths
164
112k
def page_attr(title=None, **kwargs): """ Page Attr allows you to add page meta data in the request `g` context :params **kwargs: meta keys we're expecting: title (str) description (str) url (str) (Will pick it up by itself if not set) image (str) site_name (str) ...
Page Attr allows you to add page meta data in the request `g` context :params **kwargs: meta keys we're expecting: title (str) description (str) url (str) (Will pick it up by itself if not set) image (str) site_name (str) (but can pick it up from config file) obj...
Below is the the instruction that describes the task: ### Input: Page Attr allows you to add page meta data in the request `g` context :params **kwargs: meta keys we're expecting: title (str) description (str) url (str) (Will pick it up by itself if not set) image (str) ...
def vcs_virtual_ipv6_address_ipv6address(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") vcs = ET.SubElement(config, "vcs", xmlns="urn:brocade.com:mgmt:brocade-vcs") virtual = ET.SubElement(vcs, "virtual") ipv6 = ET.SubElement(virtual, "ipv6") ...
Auto Generated Code
Below is the the instruction that describes the task: ### Input: Auto Generated Code ### Response: def vcs_virtual_ipv6_address_ipv6address(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") vcs = ET.SubElement(config, "vcs", xmlns="urn:brocade.com:mgmt:brocad...
def _removepkg(self, package): """removepkg Slackware command """ try: subprocess.call("removepkg {0} {1}".format(self.flag, package), shell=True) if os.path.isfile(self.dep_path + package): os.remove(self.dep_path + package) #...
removepkg Slackware command
Below is the the instruction that describes the task: ### Input: removepkg Slackware command ### Response: def _removepkg(self, package): """removepkg Slackware command """ try: subprocess.call("removepkg {0} {1}".format(self.flag, package), shell=Tru...
def a_message_callback(ctx): """Message the captured pattern.""" message = ctx.ctrl.after.strip().splitlines()[-1] ctx.device.chain.connection.emit_message(message, log_level=logging.INFO) return True
Message the captured pattern.
Below is the the instruction that describes the task: ### Input: Message the captured pattern. ### Response: def a_message_callback(ctx): """Message the captured pattern.""" message = ctx.ctrl.after.strip().splitlines()[-1] ctx.device.chain.connection.emit_message(message, log_level=logging.INFO) r...
def construct_publish_comands(additional_steps=None, nightly=False): '''Get the shell commands we'll use to actually build and publish a package to PyPI.''' publish_commands = ( ['rm -rf dist'] + (additional_steps if additional_steps else []) + [ 'python setup.py sdist bdist_...
Get the shell commands we'll use to actually build and publish a package to PyPI.
Below is the the instruction that describes the task: ### Input: Get the shell commands we'll use to actually build and publish a package to PyPI. ### Response: def construct_publish_comands(additional_steps=None, nightly=False): '''Get the shell commands we'll use to actually build and publish a package to Py...
def ParseArguments(self): """Parses the command line arguments. Returns: bool: True if the arguments were successfully parsed. """ loggers.ConfigureLogging() argument_parser = argparse.ArgumentParser( description=self.DESCRIPTION, epilog=self.EPILOG, add_help=False, formatter...
Parses the command line arguments. Returns: bool: True if the arguments were successfully parsed.
Below is the the instruction that describes the task: ### Input: Parses the command line arguments. Returns: bool: True if the arguments were successfully parsed. ### Response: def ParseArguments(self): """Parses the command line arguments. Returns: bool: True if the arguments were succes...
def blockshaped(arr, nrows, ncols): """ Return an new array of shape (n, nrows, ncols) where n * nrows * ncols = arr.size If arr is a 2D array, the returned array looks like n subblocks with each subblock preserving the "physical" layout of arr. """ h, w = arr.shape return (arr.reshape(...
Return an new array of shape (n, nrows, ncols) where n * nrows * ncols = arr.size If arr is a 2D array, the returned array looks like n subblocks with each subblock preserving the "physical" layout of arr.
Below is the the instruction that describes the task: ### Input: Return an new array of shape (n, nrows, ncols) where n * nrows * ncols = arr.size If arr is a 2D array, the returned array looks like n subblocks with each subblock preserving the "physical" layout of arr. ### Response: def blockshaped(a...
def get_resolved_res_configs(self, rid, config=None): """ Return a list of resolved resource IDs with their corresponding configuration. It has a similar return type as :meth:`get_res_configs` but also handles complex entries and references. Also instead of returning :class:`ARSC...
Return a list of resolved resource IDs with their corresponding configuration. It has a similar return type as :meth:`get_res_configs` but also handles complex entries and references. Also instead of returning :class:`ARSCResTableEntry` in the tuple, the actual values are resolved. This...
Below is the the instruction that describes the task: ### Input: Return a list of resolved resource IDs with their corresponding configuration. It has a similar return type as :meth:`get_res_configs` but also handles complex entries and references. Also instead of returning :class:`ARSCResTa...
def delete_all(self): '''Deletes all feature collections. This does not destroy the ES index, but instead only deletes all FCs with the configured document type (defaults to ``fc``). ''' try: self.conn.indices.delete_mapping( index=self.index,...
Deletes all feature collections. This does not destroy the ES index, but instead only deletes all FCs with the configured document type (defaults to ``fc``).
Below is the the instruction that describes the task: ### Input: Deletes all feature collections. This does not destroy the ES index, but instead only deletes all FCs with the configured document type (defaults to ``fc``). ### Response: def delete_all(self): '''Deletes all feature ...
def _transform(comps, trans): """ Transform the given string with transform type trans """ logging.debug("== In _transform(%s, %s) ==", comps, trans) components = list(comps) action, parameter = _get_action(trans) if action == _Action.ADD_MARK and \ components[2] == "" and \ ...
Transform the given string with transform type trans
Below is the the instruction that describes the task: ### Input: Transform the given string with transform type trans ### Response: def _transform(comps, trans): """ Transform the given string with transform type trans """ logging.debug("== In _transform(%s, %s) ==", comps, trans) components = ...
def _revs_equal(rev1, rev2, rev_type): ''' Shorthand helper function for comparing SHA1s. If rev_type == 'sha1' then the comparison will be done using str.startwith() to allow short SHA1s to compare successfully. NOTE: This means that rev2 must be the short rev. ''' if (rev1 is None and rev...
Shorthand helper function for comparing SHA1s. If rev_type == 'sha1' then the comparison will be done using str.startwith() to allow short SHA1s to compare successfully. NOTE: This means that rev2 must be the short rev.
Below is the the instruction that describes the task: ### Input: Shorthand helper function for comparing SHA1s. If rev_type == 'sha1' then the comparison will be done using str.startwith() to allow short SHA1s to compare successfully. NOTE: This means that rev2 must be the short rev. ### Response: def...
def var_replace(self, text): """Replaces all instances of @VAR with their values in the specified text. """ result = text for var in self._vardict: result = result.replace("@{}".format(var), self._vardict[var]) return result
Replaces all instances of @VAR with their values in the specified text.
Below is the the instruction that describes the task: ### Input: Replaces all instances of @VAR with their values in the specified text. ### Response: def var_replace(self, text): """Replaces all instances of @VAR with their values in the specified text. """ result = text for var in...
def copy_to_tmp(source): """ Copies ``source`` to a temporary directory, and returns the copied location. If source is a file, the copied location is also a file. """ tmp_dir = tempfile.mkdtemp() # Use pathlib because os.path.basename is different depending on whether # the path ends in...
Copies ``source`` to a temporary directory, and returns the copied location. If source is a file, the copied location is also a file.
Below is the the instruction that describes the task: ### Input: Copies ``source`` to a temporary directory, and returns the copied location. If source is a file, the copied location is also a file. ### Response: def copy_to_tmp(source): """ Copies ``source`` to a temporary directory, and returns ...
def delete(name, *effects, **kwargs): """ Annotate a delete action to the model being defined. Should be delete(name, *effects, label=None, desc=None) but it is not supported by python < 3. @param name: item name unique for the model being defined. @type name: str or unicode @param effects: ...
Annotate a delete action to the model being defined. Should be delete(name, *effects, label=None, desc=None) but it is not supported by python < 3. @param name: item name unique for the model being defined. @type name: str or unicode @param effects: @type effects: str or unicode @param label...
Below is the the instruction that describes the task: ### Input: Annotate a delete action to the model being defined. Should be delete(name, *effects, label=None, desc=None) but it is not supported by python < 3. @param name: item name unique for the model being defined. @type name: str or unicode ...
def _extend_nodelist(extends_node, context, instance_types): """ Returns a list of results found in the parent template(s) :type extends_node: ExtendsNode """ results = [] # Find all blocks in the complete inheritance chain blocks = extends_node.blocks.copy() # dict with all blocks in the ...
Returns a list of results found in the parent template(s) :type extends_node: ExtendsNode
Below is the the instruction that describes the task: ### Input: Returns a list of results found in the parent template(s) :type extends_node: ExtendsNode ### Response: def _extend_nodelist(extends_node, context, instance_types): """ Returns a list of results found in the parent template(s) :type e...
def validate_col(self, itemsize=None): """ validate this column: return the compared against itemsize """ # validate this column for string truncation (or reset to the max size) if _ensure_decoded(self.kind) == 'string': c = self.col if c is not None: if ...
validate this column: return the compared against itemsize
Below is the the instruction that describes the task: ### Input: validate this column: return the compared against itemsize ### Response: def validate_col(self, itemsize=None): """ validate this column: return the compared against itemsize """ # validate this column for string truncation (or reset...
def rename(self, newpath): "Move folder to a new name, possibly a whole new path" # POST https://www.jottacloud.com/jfs/**USERNAME**/Jotta/Sync/Ny%20mappe?mvDir=/**USERNAME**/Jotta/Sync/testFolder #url = '%s?mvDir=/%s%s' % (self.path, self.jfs.username, newpath) params = {'mvDir':'/%s%s'...
Move folder to a new name, possibly a whole new path
Below is the the instruction that describes the task: ### Input: Move folder to a new name, possibly a whole new path ### Response: def rename(self, newpath): "Move folder to a new name, possibly a whole new path" # POST https://www.jottacloud.com/jfs/**USERNAME**/Jotta/Sync/Ny%20mappe?mvDir=/**USE...
def _all_dirs(base_path): """ Return all dirs in base_path, relative to base_path """ for root, dirs, files in os.walk(base_path, followlinks=True): for dir in dirs: yield os.path.relpath(os.path.join(root, dir), base_path)
Return all dirs in base_path, relative to base_path
Below is the the instruction that describes the task: ### Input: Return all dirs in base_path, relative to base_path ### Response: def _all_dirs(base_path): """ Return all dirs in base_path, relative to base_path """ for root, dirs, files in os.walk(base_path, followlinks=True): ...
def process(in_path, out_file, n_jobs, framesync): """Computes the features for the selected dataset or file.""" if os.path.isfile(in_path): # Single file mode # Get (if they exitst) or compute features file_struct = msaf.io.FileStruct(in_path) file_struct.features_file = out_fil...
Computes the features for the selected dataset or file.
Below is the the instruction that describes the task: ### Input: Computes the features for the selected dataset or file. ### Response: def process(in_path, out_file, n_jobs, framesync): """Computes the features for the selected dataset or file.""" if os.path.isfile(in_path): # Single file mode ...
def put(self, segment): """Adds a segment to the download pool and write queue.""" if self.closed: return if segment is not None: future = self.executor.submit(self.fetch, segment, retries=self.retries) else: ...
Adds a segment to the download pool and write queue.
Below is the the instruction that describes the task: ### Input: Adds a segment to the download pool and write queue. ### Response: def put(self, segment): """Adds a segment to the download pool and write queue.""" if self.closed: return if segment is not None: futu...
def makenode(clss, symbol, *nexts): """ Stores the symbol in an AST instance, and left and right to the given ones """ result = clss(symbol) for i in nexts: if i is None: continue if not isinstance(i, clss): raise NotAnAstEr...
Stores the symbol in an AST instance, and left and right to the given ones
Below is the the instruction that describes the task: ### Input: Stores the symbol in an AST instance, and left and right to the given ones ### Response: def makenode(clss, symbol, *nexts): """ Stores the symbol in an AST instance, and left and right to the given ones """ re...
def all_dags(self, nodes=None): """ Computes all possible directed acyclic graphs with a given set of nodes, sparse ones first. `2**(n*(n-1))` graphs need to be searched, given `n` nodes, so this is likely not feasible for n>6. This is a generator. Parameters ---------- ...
Computes all possible directed acyclic graphs with a given set of nodes, sparse ones first. `2**(n*(n-1))` graphs need to be searched, given `n` nodes, so this is likely not feasible for n>6. This is a generator. Parameters ---------- nodes: list of nodes for the DAGs (optional)...
Below is the the instruction that describes the task: ### Input: Computes all possible directed acyclic graphs with a given set of nodes, sparse ones first. `2**(n*(n-1))` graphs need to be searched, given `n` nodes, so this is likely not feasible for n>6. This is a generator. Parameters ...
def build_graph(self): """Build a whole graph for the model.""" self.global_step = tf.Variable(0, trainable=False) self._build_model() if self.mode == "train": self._build_train_op() else: # Additional initialization for the test network. self....
Build a whole graph for the model.
Below is the the instruction that describes the task: ### Input: Build a whole graph for the model. ### Response: def build_graph(self): """Build a whole graph for the model.""" self.global_step = tf.Variable(0, trainable=False) self._build_model() if self.mode == "train": ...
def append_position(path, position, separator=''): """ Concatenate a path and a position, between the filename and the extension. """ filename, extension = os.path.splitext(path) return ''.join([filename, separator, str(position), extension])
Concatenate a path and a position, between the filename and the extension.
Below is the the instruction that describes the task: ### Input: Concatenate a path and a position, between the filename and the extension. ### Response: def append_position(path, position, separator=''): """ Concatenate a path and a position, between the filename and the extension. """ fil...
def update(self, *args, **kwargs): """ Equivalent to the python dict update method. Update the dictionary with the key/value pairs from other, overwriting existing keys. Args: other (dict): The source of key value pairs to add to headers Keyword Args: ...
Equivalent to the python dict update method. Update the dictionary with the key/value pairs from other, overwriting existing keys. Args: other (dict): The source of key value pairs to add to headers Keyword Args: All keyword arguments are stored in header direct...
Below is the the instruction that describes the task: ### Input: Equivalent to the python dict update method. Update the dictionary with the key/value pairs from other, overwriting existing keys. Args: other (dict): The source of key value pairs to add to headers Keywor...
def probe_image(self, labels, instance, column_name=None, num_scaled_images=50, top_percent=10): """ Get pixel importance of the image. It performs pixel sensitivity analysis by showing only the most important pixels to a certain label in the image. It uses integrated gradie...
Get pixel importance of the image. It performs pixel sensitivity analysis by showing only the most important pixels to a certain label in the image. It uses integrated gradients to measure the importance of each pixel. Args: labels: labels to compute gradients from. ...
Below is the the instruction that describes the task: ### Input: Get pixel importance of the image. It performs pixel sensitivity analysis by showing only the most important pixels to a certain label in the image. It uses integrated gradients to measure the importance of each pixel. ...
def get_special_elections(self, obj): """States holding a special election on election day.""" return reverse( 'electionnight_api_special-election-list', request=self.context['request'], kwargs={'date': obj.date} )
States holding a special election on election day.
Below is the the instruction that describes the task: ### Input: States holding a special election on election day. ### Response: def get_special_elections(self, obj): """States holding a special election on election day.""" return reverse( 'electionnight_api_special-election-list', ...
def ToJson(self, index): """ Convert object members to a dictionary that can be parsed as JSON. Args: index (int): The index of the output in a transaction Returns: dict: """ return { 'n': index, 'asset': self.AssetId.To0x...
Convert object members to a dictionary that can be parsed as JSON. Args: index (int): The index of the output in a transaction Returns: dict:
Below is the the instruction that describes the task: ### Input: Convert object members to a dictionary that can be parsed as JSON. Args: index (int): The index of the output in a transaction Returns: dict: ### Response: def ToJson(self, index): """ Convert...
def ssl_wrap_socket( socket: socket.socket, ssl_options: Union[Dict[str, Any], ssl.SSLContext], server_hostname: str = None, **kwargs: Any ) -> ssl.SSLSocket: """Returns an ``ssl.SSLSocket`` wrapping the given socket. ``ssl_options`` may be either an `ssl.SSLContext` object or a dictionary ...
Returns an ``ssl.SSLSocket`` wrapping the given socket. ``ssl_options`` may be either an `ssl.SSLContext` object or a dictionary (as accepted by `ssl_options_to_context`). Additional keyword arguments are passed to ``wrap_socket`` (either the `~ssl.SSLContext` method or the `ssl` module function as ...
Below is the the instruction that describes the task: ### Input: Returns an ``ssl.SSLSocket`` wrapping the given socket. ``ssl_options`` may be either an `ssl.SSLContext` object or a dictionary (as accepted by `ssl_options_to_context`). Additional keyword arguments are passed to ``wrap_socket`` (eithe...
def validate_repo_url(url): """ Validates and formats `url` to be valid URL pointing to a repo on bitbucket.org or github.com :param url: str, URL :return: str, valid URL if valid repo, emptry string otherwise """ try: if "github.com" in url: return re.findall(r"https?://w?w?...
Validates and formats `url` to be valid URL pointing to a repo on bitbucket.org or github.com :param url: str, URL :return: str, valid URL if valid repo, emptry string otherwise
Below is the the instruction that describes the task: ### Input: Validates and formats `url` to be valid URL pointing to a repo on bitbucket.org or github.com :param url: str, URL :return: str, valid URL if valid repo, emptry string otherwise ### Response: def validate_repo_url(url): """ Validates ...
def serve_static(request, path, insecure=False, **kwargs): """Collect and serve static files. This view serves up static files, much like Django's :py:func:`~django.views.static.serve` view, with the addition that it collects static files first (if enabled). This allows images, fonts, and other ass...
Collect and serve static files. This view serves up static files, much like Django's :py:func:`~django.views.static.serve` view, with the addition that it collects static files first (if enabled). This allows images, fonts, and other assets to be served up without first loading a page using the ``{...
Below is the the instruction that describes the task: ### Input: Collect and serve static files. This view serves up static files, much like Django's :py:func:`~django.views.static.serve` view, with the addition that it collects static files first (if enabled). This allows images, fonts, and other ...
def key_leaf(self, data, schema, tree): """ The deepest validation we can make in any given circumstance for a key. Does not recurse, it will just receive both values and the tree, passing them on to the :fun:`enforce` function. """ key, value = data schema_key, s...
The deepest validation we can make in any given circumstance for a key. Does not recurse, it will just receive both values and the tree, passing them on to the :fun:`enforce` function.
Below is the the instruction that describes the task: ### Input: The deepest validation we can make in any given circumstance for a key. Does not recurse, it will just receive both values and the tree, passing them on to the :fun:`enforce` function. ### Response: def key_leaf(self, data, schema, tr...
def fs_r(self, percent=0.9, N=None): """Get the row factor scores (dimensionality-reduced representation), choosing how many factors to retain, directly or based on the explained variance. 'percent': The minimum variance that the retained factors are required to explain (default: 90% = 0.9) 'N': The ...
Get the row factor scores (dimensionality-reduced representation), choosing how many factors to retain, directly or based on the explained variance. 'percent': The minimum variance that the retained factors are required to explain (default: 90% = 0.9) 'N': The number of factors to retain. Overrides 'pe...
Below is the the instruction that describes the task: ### Input: Get the row factor scores (dimensionality-reduced representation), choosing how many factors to retain, directly or based on the explained variance. 'percent': The minimum variance that the retained factors are required to explain (defa...
def _assign_enterprise_role_to_users(self, _get_batch_method, options, is_feature_role=False): """ Assigns enterprise role to users. """ role_name = options['role'] batch_limit = options['batch_limit'] batch_sleep = options['batch_sleep'] batch_offset = options['b...
Assigns enterprise role to users.
Below is the the instruction that describes the task: ### Input: Assigns enterprise role to users. ### Response: def _assign_enterprise_role_to_users(self, _get_batch_method, options, is_feature_role=False): """ Assigns enterprise role to users. """ role_name = options['role'] ...
def callbacks(cls, eventType=None): """ Returns a list of callback methods that can be invoked whenever an event is processed. :return: {subclass of <Event>: <list>, ..} """ key = '_{0}__callbacks'.format(cls.__name__) try: callbacks = getattr(cls, key) ...
Returns a list of callback methods that can be invoked whenever an event is processed. :return: {subclass of <Event>: <list>, ..}
Below is the the instruction that describes the task: ### Input: Returns a list of callback methods that can be invoked whenever an event is processed. :return: {subclass of <Event>: <list>, ..} ### Response: def callbacks(cls, eventType=None): """ Returns a list of callback methods that c...
def find_country(session, code): """Find a country. Find a country by its ISO-3166 `code` (i.e ES for Spain, US for United States of America) using the given `session. When the country does not exist the function will return `None`. :param session: database session :param code: ISO-3166 co...
Find a country. Find a country by its ISO-3166 `code` (i.e ES for Spain, US for United States of America) using the given `session. When the country does not exist the function will return `None`. :param session: database session :param code: ISO-3166 code of the country to find :return: ...
Below is the the instruction that describes the task: ### Input: Find a country. Find a country by its ISO-3166 `code` (i.e ES for Spain, US for United States of America) using the given `session. When the country does not exist the function will return `None`. :param session: database session...
def plot_triaxial_depths_speed(tag): '''Plot triaxial accelerometer data for whole deployment, descents, and ascents Only x and z axes are ploted since these are associated with stroking Args ---- tag: pandas.DataFrame Tag dataframe with acceleromter, depth, and propeller columns '...
Plot triaxial accelerometer data for whole deployment, descents, and ascents Only x and z axes are ploted since these are associated with stroking Args ---- tag: pandas.DataFrame Tag dataframe with acceleromter, depth, and propeller columns
Below is the the instruction that describes the task: ### Input: Plot triaxial accelerometer data for whole deployment, descents, and ascents Only x and z axes are ploted since these are associated with stroking Args ---- tag: pandas.DataFrame Tag dataframe with acceleromter, depth, an...
def ram_dumper(**kwargs): """Dump data to 'memory' for later usage.""" logging.debug("trying to save stuff in memory") farms = kwargs["farms"] experiments = kwargs["experiments"] engine = kwargs["engine"] try: engine_name = engine.__name__ except AttributeError: engine_name ...
Dump data to 'memory' for later usage.
Below is the the instruction that describes the task: ### Input: Dump data to 'memory' for later usage. ### Response: def ram_dumper(**kwargs): """Dump data to 'memory' for later usage.""" logging.debug("trying to save stuff in memory") farms = kwargs["farms"] experiments = kwargs["experiments"] ...
def get_ast_field_name(ast): """Return the normalized field name for the given AST node.""" replacements = { # We always rewrite the following field names into their proper underlying counterparts. TYPENAME_META_FIELD_NAME: '@class' } base_field_name = ast.name.value normalized_name ...
Return the normalized field name for the given AST node.
Below is the the instruction that describes the task: ### Input: Return the normalized field name for the given AST node. ### Response: def get_ast_field_name(ast): """Return the normalized field name for the given AST node.""" replacements = { # We always rewrite the following field names into the...
def des_cbc_pkcs5_decrypt(key, data, iv): """ Decrypts DES ciphertext using a 56 bit key :param key: The encryption key - a byte string 8 bytes long (includes error correction bits) :param data: The ciphertext - a byte string :param iv: The initialization vector used for e...
Decrypts DES ciphertext using a 56 bit key :param key: The encryption key - a byte string 8 bytes long (includes error correction bits) :param data: The ciphertext - a byte string :param iv: The initialization vector used for encryption - a byte string :raises: ValueE...
Below is the the instruction that describes the task: ### Input: Decrypts DES ciphertext using a 56 bit key :param key: The encryption key - a byte string 8 bytes long (includes error correction bits) :param data: The ciphertext - a byte string :param iv: The initialization ve...
def _defaultErrorHandler(varBinds, **context): """Raise exception on any error if user callback is missing""" errors = context.get('errors') if errors: err = errors[-1] raise err['error']
Raise exception on any error if user callback is missing
Below is the the instruction that describes the task: ### Input: Raise exception on any error if user callback is missing ### Response: def _defaultErrorHandler(varBinds, **context): """Raise exception on any error if user callback is missing""" errors = context.get('errors') if errors: ...
def annotate(self, gpl, annotation_column, gpl_on="ID", gsm_on="ID_REF", in_place=False): """Annotate GSM with provided GPL Args: gpl (:obj:`pandas.DataFrame`): A Platform or DataFrame to annotate with annotation_column (str`): Column in a table for annotation ...
Annotate GSM with provided GPL Args: gpl (:obj:`pandas.DataFrame`): A Platform or DataFrame to annotate with annotation_column (str`): Column in a table for annotation gpl_on (:obj:`str`): Use this column in GSM to merge. Defaults to "ID". gsm_on (:obj:`str`): Us...
Below is the the instruction that describes the task: ### Input: Annotate GSM with provided GPL Args: gpl (:obj:`pandas.DataFrame`): A Platform or DataFrame to annotate with annotation_column (str`): Column in a table for annotation gpl_on (:obj:`str`): Use this column i...
def export(self, xformat='csv'): """action: export annotations to CSV.""" if self.annot is None: # remove if buttons are disabled self.parent.statusBar().showMessage('No score file loaded') return if xformat == 'csv': filename = splitext(self.annot.xml_file)...
action: export annotations to CSV.
Below is the the instruction that describes the task: ### Input: action: export annotations to CSV. ### Response: def export(self, xformat='csv'): """action: export annotations to CSV.""" if self.annot is None: # remove if buttons are disabled self.parent.statusBar().showMessage('No sc...
def cos_values(period=360): """ Provides an infinite source of values representing a cosine wave (from -1 to +1) which repeats every *period* values. For example, to produce a "siren" effect with a couple of LEDs that repeats once a second:: from gpiozero import PWMLED from gpiozero.too...
Provides an infinite source of values representing a cosine wave (from -1 to +1) which repeats every *period* values. For example, to produce a "siren" effect with a couple of LEDs that repeats once a second:: from gpiozero import PWMLED from gpiozero.tools import cos_values, scaled, inverted ...
Below is the the instruction that describes the task: ### Input: Provides an infinite source of values representing a cosine wave (from -1 to +1) which repeats every *period* values. For example, to produce a "siren" effect with a couple of LEDs that repeats once a second:: from gpiozero import PWM...
def writer(fo, schema, records, codec='null', sync_interval=1000 * SYNC_SIZE, metadata=None, validator=None, sync_marker=None): """Write records to fo (stream) according to schema Parameters ---------- fo: file-like Ou...
Write records to fo (stream) according to schema Parameters ---------- fo: file-like Output stream records: iterable Records to write. This is commonly a list of the dictionary representation of the records, but it can be any iterable codec: string, optional Compress...
Below is the the instruction that describes the task: ### Input: Write records to fo (stream) according to schema Parameters ---------- fo: file-like Output stream records: iterable Records to write. This is commonly a list of the dictionary representation of the records, bu...
def calculate_bmi(closed, submitted): """ BMI is the ratio of the number of closed items to the number of total items submitted in a particular period of analysis. The items can be issues, pull requests and such :param closed: dataframe returned from get_timeseries() containing closed items :pa...
BMI is the ratio of the number of closed items to the number of total items submitted in a particular period of analysis. The items can be issues, pull requests and such :param closed: dataframe returned from get_timeseries() containing closed items :param submitted: dataframe returned from get_timeser...
Below is the the instruction that describes the task: ### Input: BMI is the ratio of the number of closed items to the number of total items submitted in a particular period of analysis. The items can be issues, pull requests and such :param closed: dataframe returned from get_timeseries() containing c...
def get_hosting_devices_for_agent(self, context, host): """Fetches routers that a Cisco cfg agent is managing. This function is supposed to be called when the agent has started, is ready to take on assignments and before any callbacks to fetch logical resources are issued. :par...
Fetches routers that a Cisco cfg agent is managing. This function is supposed to be called when the agent has started, is ready to take on assignments and before any callbacks to fetch logical resources are issued. :param context: contains user information :param host: originat...
Below is the the instruction that describes the task: ### Input: Fetches routers that a Cisco cfg agent is managing. This function is supposed to be called when the agent has started, is ready to take on assignments and before any callbacks to fetch logical resources are issued. :p...
def get_collections(self, username="", calculate_size=False, ext_preload=False, offset=0, limit=10): """Fetch collection folders :param username: The user to list folders for, if omitted the authenticated user is used :param calculate_size: The option to include the content count per each coll...
Fetch collection folders :param username: The user to list folders for, if omitted the authenticated user is used :param calculate_size: The option to include the content count per each collection folder :param ext_preload: Include first 5 deviations from the folder :param offset: the p...
Below is the the instruction that describes the task: ### Input: Fetch collection folders :param username: The user to list folders for, if omitted the authenticated user is used :param calculate_size: The option to include the content count per each collection folder :param ext_preload: In...
def getText(cls, parent=None, windowTitle='Get Text', label='', text='', plain=True, wrapped=True): """ Prompts the user for a text entry using the text edit class. :param pare...
Prompts the user for a text entry using the text edit class. :param parent | <QWidget> windowTitle | <str> label | <str> text | <str> plain | <bool> | return plain text or not ...
Below is the the instruction that describes the task: ### Input: Prompts the user for a text entry using the text edit class. :param parent | <QWidget> windowTitle | <str> label | <str> text | <str> ...
def dwell_axes(self, axes): ''' Sets motors to low current, for when they are not moving. Dwell for XYZA axes is only called after HOMING Dwell for BC axes is called after both HOMING and MOVING axes: String containing the axes to set to low current (eg: 'XYZABC') ...
Sets motors to low current, for when they are not moving. Dwell for XYZA axes is only called after HOMING Dwell for BC axes is called after both HOMING and MOVING axes: String containing the axes to set to low current (eg: 'XYZABC')
Below is the the instruction that describes the task: ### Input: Sets motors to low current, for when they are not moving. Dwell for XYZA axes is only called after HOMING Dwell for BC axes is called after both HOMING and MOVING axes: String containing the axes to set to low cur...
def frontogenesis(thta, u, v, dx, dy, dim_order='yx'): r"""Calculate the 2D kinematic frontogenesis of a temperature field. The implementation is a form of the Petterssen Frontogenesis and uses the formula outlined in [Bluestein1993]_ pg.248-253. .. math:: F=\frac{1}{2}\left|\nabla \theta\right|[D cos...
r"""Calculate the 2D kinematic frontogenesis of a temperature field. The implementation is a form of the Petterssen Frontogenesis and uses the formula outlined in [Bluestein1993]_ pg.248-253. .. math:: F=\frac{1}{2}\left|\nabla \theta\right|[D cos(2\beta)-\delta] * :math:`F` is 2D kinematic frontogen...
Below is the the instruction that describes the task: ### Input: r"""Calculate the 2D kinematic frontogenesis of a temperature field. The implementation is a form of the Petterssen Frontogenesis and uses the formula outlined in [Bluestein1993]_ pg.248-253. .. math:: F=\frac{1}{2}\left|\nabla \theta\ri...
def add_image_info_cb(self, viewer, channel, image_info): """Almost the same as add_image_cb(), except that the image may not be loaded in memory. """ chname = channel.name name = image_info.name self.logger.debug("name=%s" % (name)) # Updates of any extant infor...
Almost the same as add_image_cb(), except that the image may not be loaded in memory.
Below is the the instruction that describes the task: ### Input: Almost the same as add_image_cb(), except that the image may not be loaded in memory. ### Response: def add_image_info_cb(self, viewer, channel, image_info): """Almost the same as add_image_cb(), except that the image may not ...
def read_i2c_block_data(self, addr, cmd, length=32): """Perform a read from the specified cmd register of device. Length number of bytes (default of 32) will be read and returned as a bytearray. """ assert self._device is not None, 'Bus must be opened before operations are made against ...
Perform a read from the specified cmd register of device. Length number of bytes (default of 32) will be read and returned as a bytearray.
Below is the the instruction that describes the task: ### Input: Perform a read from the specified cmd register of device. Length number of bytes (default of 32) will be read and returned as a bytearray. ### Response: def read_i2c_block_data(self, addr, cmd, length=32): """Perform a read from the ...
def _initSymbols(ptc): """ Helper function to initialize the single character constants and other symbols needed. """ ptc.timeSep = [ u':' ] ptc.dateSep = [ u'/' ] ptc.meridian = [ u'AM', u'PM' ] ptc.usesMeridian = True ptc.uses24 = False if pyicu and ptc.usePyICU: ...
Helper function to initialize the single character constants and other symbols needed.
Below is the the instruction that describes the task: ### Input: Helper function to initialize the single character constants and other symbols needed. ### Response: def _initSymbols(ptc): """ Helper function to initialize the single character constants and other symbols needed. """ ptc.tim...
def create(cls, name, port=179, external_distance=20, internal_distance=200, local_distance=200, subnet_distance=None): """ Create a custom BGP Profile :param str name: name of profile :param int port: port for BGP process :param int external_distance: external ad...
Create a custom BGP Profile :param str name: name of profile :param int port: port for BGP process :param int external_distance: external administrative distance; (1-255) :param int internal_distance: internal administrative distance (1-255) :param int local_distance: local admi...
Below is the the instruction that describes the task: ### Input: Create a custom BGP Profile :param str name: name of profile :param int port: port for BGP process :param int external_distance: external administrative distance; (1-255) :param int internal_distance: internal administ...
def _add_nonce(self, response): """ Store a nonce from a response we received. :param twisted.web.iweb.IResponse response: The HTTP response. :return: The response, unmodified. """ nonce = response.headers.getRawHeaders( REPLAY_NONCE_HEADER, [None])[0] ...
Store a nonce from a response we received. :param twisted.web.iweb.IResponse response: The HTTP response. :return: The response, unmodified.
Below is the the instruction that describes the task: ### Input: Store a nonce from a response we received. :param twisted.web.iweb.IResponse response: The HTTP response. :return: The response, unmodified. ### Response: def _add_nonce(self, response): """ Store a nonce from a resp...
def load_data(limit=0, split=0.8): """Load data from the IMDB dataset.""" # Partition off part of the train data for evaluation train_data, _ = thinc.extra.datasets.imdb() random.shuffle(train_data) train_data = train_data[-limit:] texts, labels = zip(*train_data) cats = [{"POSITIVE": bool(y...
Load data from the IMDB dataset.
Below is the the instruction that describes the task: ### Input: Load data from the IMDB dataset. ### Response: def load_data(limit=0, split=0.8): """Load data from the IMDB dataset.""" # Partition off part of the train data for evaluation train_data, _ = thinc.extra.datasets.imdb() random.shuffle(...
def GetStat(self): """Retrieves information about the file entry. Returns: VFSStat: a stat object or None if not available. """ if self._stat_object is None: self._stat_object = self._GetStat() return self._stat_object
Retrieves information about the file entry. Returns: VFSStat: a stat object or None if not available.
Below is the the instruction that describes the task: ### Input: Retrieves information about the file entry. Returns: VFSStat: a stat object or None if not available. ### Response: def GetStat(self): """Retrieves information about the file entry. Returns: VFSStat: a stat object or None if...
def get_cov(config): """Returns the coverage object of pytest-cov.""" # Check with hasplugin to avoid getplugin exception in older pytest. if config.pluginmanager.hasplugin('_cov'): plugin = config.pluginmanager.getplugin('_cov') if plugin.cov_controller: return plugin.cov_contr...
Returns the coverage object of pytest-cov.
Below is the the instruction that describes the task: ### Input: Returns the coverage object of pytest-cov. ### Response: def get_cov(config): """Returns the coverage object of pytest-cov.""" # Check with hasplugin to avoid getplugin exception in older pytest. if config.pluginmanager.hasplugin('_cov')...
def _get_location(self, state, hash_id): """ Get previously saved location A location is composed of: address, pc, finding, at_init, condition """ return state.context.setdefault('{:s}.locations'.format(self.name), {})[hash_id]
Get previously saved location A location is composed of: address, pc, finding, at_init, condition
Below is the the instruction that describes the task: ### Input: Get previously saved location A location is composed of: address, pc, finding, at_init, condition ### Response: def _get_location(self, state, hash_id): """ Get previously saved location A location is composed of: addr...
async def async_connect(self): """Connect to the ASUS-WRT Telnet server.""" self._reader, self._writer = await asyncio.open_connection( self._host, self._port) with (await self._io_lock): try: await asyncio.wait_for(self._reader.readuntil(b'login: '), 9) ...
Connect to the ASUS-WRT Telnet server.
Below is the the instruction that describes the task: ### Input: Connect to the ASUS-WRT Telnet server. ### Response: async def async_connect(self): """Connect to the ASUS-WRT Telnet server.""" self._reader, self._writer = await asyncio.open_connection( self._host, self._port) ...
def _generate_symbol(path, width, height, command='C'): """Sequence generator for SVG path.""" if len(path) == 0: return # Initial point. yield 'M' yield path[0].anchor[1] * width yield path[0].anchor[0] * height yield command # Closed path or open path points = (zip(path, ...
Sequence generator for SVG path.
Below is the the instruction that describes the task: ### Input: Sequence generator for SVG path. ### Response: def _generate_symbol(path, width, height, command='C'): """Sequence generator for SVG path.""" if len(path) == 0: return # Initial point. yield 'M' yield path[0].anchor[1] * ...
def _prepare_batch_request(self): """Prepares headers and body for a batch request. :rtype: tuple (dict, str) :returns: The pair of headers and body of the batch request to be sent. :raises: :class:`ValueError` if no requests have been deferred. """ if len(self._requests...
Prepares headers and body for a batch request. :rtype: tuple (dict, str) :returns: The pair of headers and body of the batch request to be sent. :raises: :class:`ValueError` if no requests have been deferred.
Below is the the instruction that describes the task: ### Input: Prepares headers and body for a batch request. :rtype: tuple (dict, str) :returns: The pair of headers and body of the batch request to be sent. :raises: :class:`ValueError` if no requests have been deferred. ### Response: de...
def dump_commands(commands, directory=None, sub_dir=None): """ Dump SQL commands to .sql files. :param commands: List of SQL commands :param directory: Directory to dump commands to :param sub_dir: Sub directory :return: Directory failed commands were dumped to """ print('\t' + str(len(...
Dump SQL commands to .sql files. :param commands: List of SQL commands :param directory: Directory to dump commands to :param sub_dir: Sub directory :return: Directory failed commands were dumped to
Below is the the instruction that describes the task: ### Input: Dump SQL commands to .sql files. :param commands: List of SQL commands :param directory: Directory to dump commands to :param sub_dir: Sub directory :return: Directory failed commands were dumped to ### Response: def dump_commands(co...
def to_constant(expression): """ Iff the expression can be simplified to a Constant get the actual concrete value. This discards/ignore any taint """ value = simplify(expression) if isinstance(value, Expression) and value.taint: raise ValueError("Can not simplify tainted values t...
Iff the expression can be simplified to a Constant get the actual concrete value. This discards/ignore any taint
Below is the the instruction that describes the task: ### Input: Iff the expression can be simplified to a Constant get the actual concrete value. This discards/ignore any taint ### Response: def to_constant(expression): """ Iff the expression can be simplified to a Constant get the actual conc...
def draw_pathfinder_trajectory( self, trajectory, color="#ff0000", offset=None, scale=(1, 1), show_dt=False, dt_offset=0.0, **kwargs ): """ Special helper function for drawing trajectories generated by robotpy-pathfinder...
Special helper function for drawing trajectories generated by robotpy-pathfinder :param trajectory: A list of pathfinder segment objects :param offset: If specified, should be x/y tuple to add to the path relative to the robot coordinates ...
Below is the the instruction that describes the task: ### Input: Special helper function for drawing trajectories generated by robotpy-pathfinder :param trajectory: A list of pathfinder segment objects :param offset: If specified, should be x/y tuple to add to the pa...
def _bootstrap_fedora(name, **kwargs): ''' Bootstrap a Fedora container ''' dst = _make_container_root(name) if not kwargs.get('version', False): if __grains__['os'].lower() == 'fedora': version = __grains__['osrelease'] else: version = '21' else: ...
Bootstrap a Fedora container
Below is the the instruction that describes the task: ### Input: Bootstrap a Fedora container ### Response: def _bootstrap_fedora(name, **kwargs): ''' Bootstrap a Fedora container ''' dst = _make_container_root(name) if not kwargs.get('version', False): if __grains__['os'].lower() == 'f...
def parse_segdict_key(self, key): """ Return ifo and name from the segdict key. """ splt = key.split(':') if len(splt) == 2: return splt[0], splt[1] else: err_msg = "Key should be of the format 'ifo:name', got %s." %(key,) raise ValueEr...
Return ifo and name from the segdict key.
Below is the the instruction that describes the task: ### Input: Return ifo and name from the segdict key. ### Response: def parse_segdict_key(self, key): """ Return ifo and name from the segdict key. """ splt = key.split(':') if len(splt) == 2: return splt[0], s...
def show_firmware_version_output_show_firmware_version_switchid(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") show_firmware_version = ET.Element("show_firmware_version") config = show_firmware_version output = ET.SubElement(show_firmware_versio...
Auto Generated Code
Below is the the instruction that describes the task: ### Input: Auto Generated Code ### Response: def show_firmware_version_output_show_firmware_version_switchid(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") show_firmware_version = ET.Element("show_firmw...
def action_factory(name, parameter=False): """Factory method for creating new actions (w/wo parameters). :param name: Name of the action (prefix with your module name). :param parameter: Determines if action should take parameters or not. Default is ``False``. """ if parameter: retu...
Factory method for creating new actions (w/wo parameters). :param name: Name of the action (prefix with your module name). :param parameter: Determines if action should take parameters or not. Default is ``False``.
Below is the the instruction that describes the task: ### Input: Factory method for creating new actions (w/wo parameters). :param name: Name of the action (prefix with your module name). :param parameter: Determines if action should take parameters or not. Default is ``False``. ### Response: def ...
def _prep_bins(): """ Support for running straight out of a cloned source directory instead of an installed distribution """ from os import path from sys import platform, maxsize from shutil import copy bit_suffix = "-x86_64" if maxsize > 2**32 else "-x86" package_root = path.abspat...
Support for running straight out of a cloned source directory instead of an installed distribution
Below is the the instruction that describes the task: ### Input: Support for running straight out of a cloned source directory instead of an installed distribution ### Response: def _prep_bins(): """ Support for running straight out of a cloned source directory instead of an installed distribution ...
def set_level(self, level, console_only=False): """ Defines the logging level (from standard logging module) for log messages. :param level: Level of logging for the file logger. :param console_only: [Optional] If True then the file logger...
Defines the logging level (from standard logging module) for log messages. :param level: Level of logging for the file logger. :param console_only: [Optional] If True then the file logger will not be affected.
Below is the the instruction that describes the task: ### Input: Defines the logging level (from standard logging module) for log messages. :param level: Level of logging for the file logger. :param console_only: [Optional] If True then the file logger will not be affected. ### Response...
def copyNodeList(self): """Do a recursive copy of the node list. Use xmlDocCopyNodeList() if possible to ensure string interning. """ ret = libxml2mod.xmlCopyNodeList(self._o) if ret is None:raise treeError('xmlCopyNodeList() failed') __tmp = xmlNode(_obj=ret) return __...
Do a recursive copy of the node list. Use xmlDocCopyNodeList() if possible to ensure string interning.
Below is the the instruction that describes the task: ### Input: Do a recursive copy of the node list. Use xmlDocCopyNodeList() if possible to ensure string interning. ### Response: def copyNodeList(self): """Do a recursive copy of the node list. Use xmlDocCopyNodeList() if possible to ...
def dsort(self, order): r""" Sort rows. :param order: Sort order :type order: :ref:`CsvColFilter` .. [[[cog cog.out(exobj.get_sphinx_autodoc()) ]]] .. Auto-generated exceptions documentation for .. pcsv.csv_file.CsvFile.dsort :raises: * Runtim...
r""" Sort rows. :param order: Sort order :type order: :ref:`CsvColFilter` .. [[[cog cog.out(exobj.get_sphinx_autodoc()) ]]] .. Auto-generated exceptions documentation for .. pcsv.csv_file.CsvFile.dsort :raises: * RuntimeError (Argument \`order\` is no...
Below is the the instruction that describes the task: ### Input: r""" Sort rows. :param order: Sort order :type order: :ref:`CsvColFilter` .. [[[cog cog.out(exobj.get_sphinx_autodoc()) ]]] .. Auto-generated exceptions documentation for .. pcsv.csv_file.CsvFile.dsor...
def _escapify(label): """Escape the characters in label which need it. @returns: the escaped string @rtype: string""" text = '' for c in label: if c in _escaped: text += '\\' + c elif ord(c) > 0x20 and ord(c) < 0x7F: text += c else: text +=...
Escape the characters in label which need it. @returns: the escaped string @rtype: string
Below is the the instruction that describes the task: ### Input: Escape the characters in label which need it. @returns: the escaped string @rtype: string ### Response: def _escapify(label): """Escape the characters in label which need it. @returns: the escaped string @rtype: string""" text...
def deduplicate(directories: List[str], recursive: bool, dummy_run: bool) -> None: """ De-duplicate files within one or more directories. Remove files that are identical to ones already considered. Args: directories: list of directories to process recursive: process subd...
De-duplicate files within one or more directories. Remove files that are identical to ones already considered. Args: directories: list of directories to process recursive: process subdirectories (recursively)? dummy_run: say what it'll do, but don't do it
Below is the the instruction that describes the task: ### Input: De-duplicate files within one or more directories. Remove files that are identical to ones already considered. Args: directories: list of directories to process recursive: process subdirectories (recursively)? dummy_ru...
def replace(self, key, value, expire=0, noreply=None): """ The memcached "replace" command. Args: key: str, see class docs for details. value: str, see class docs for details. expire: optional int, number of seconds until the item is expired from ...
The memcached "replace" command. Args: key: str, see class docs for details. value: str, see class docs for details. expire: optional int, number of seconds until the item is expired from the cache, or zero for no expiry (the default). noreply: optional...
Below is the the instruction that describes the task: ### Input: The memcached "replace" command. Args: key: str, see class docs for details. value: str, see class docs for details. expire: optional int, number of seconds until the item is expired from the ca...
def add_colortable(self, fobj, name): r"""Add a color table from a file to the registry. Parameters ---------- fobj : file-like object The file to read the color table from name : str The name under which the color table will be stored """ ...
r"""Add a color table from a file to the registry. Parameters ---------- fobj : file-like object The file to read the color table from name : str The name under which the color table will be stored
Below is the the instruction that describes the task: ### Input: r"""Add a color table from a file to the registry. Parameters ---------- fobj : file-like object The file to read the color table from name : str The name under which the color table will be sto...
def range(self, count): """ Create a list of colors evenly spaced along this scale's domain. :param int count: The number of colors to return. :rtype: list :returns: A list of spectra.Color objects. """ if count <= 1: raise ValueError("Range size mus...
Create a list of colors evenly spaced along this scale's domain. :param int count: The number of colors to return. :rtype: list :returns: A list of spectra.Color objects.
Below is the the instruction that describes the task: ### Input: Create a list of colors evenly spaced along this scale's domain. :param int count: The number of colors to return. :rtype: list :returns: A list of spectra.Color objects. ### Response: def range(self, count): """ ...
def set_custom_serializer(self, _type, serializer): """ Assign a serializer for the type. :param _type: (Type), the target type of the serializer :param serializer: (Serializer), Custom Serializer constructor function """ validate_type(_type) validate_serializer(...
Assign a serializer for the type. :param _type: (Type), the target type of the serializer :param serializer: (Serializer), Custom Serializer constructor function
Below is the the instruction that describes the task: ### Input: Assign a serializer for the type. :param _type: (Type), the target type of the serializer :param serializer: (Serializer), Custom Serializer constructor function ### Response: def set_custom_serializer(self, _type, serializer): ...
def batch_write(self, tablename, return_capacity=None, return_item_collection_metrics=NONE): """ Perform a batch write on a table Parameters ---------- tablename : str Name of the table to write to return_capacity : {NONE, INDEXES, TOTAL},...
Perform a batch write on a table Parameters ---------- tablename : str Name of the table to write to return_capacity : {NONE, INDEXES, TOTAL}, optional INDEXES will return the consumed capacity for indexes, TOTAL will return the consumed capacity for ...
Below is the the instruction that describes the task: ### Input: Perform a batch write on a table Parameters ---------- tablename : str Name of the table to write to return_capacity : {NONE, INDEXES, TOTAL}, optional INDEXES will return the consumed capacity ...
def get_sentence_ngrams(mention, attrib="words", n_min=1, n_max=1, lower=True): """Get the ngrams that are in the Sentence of the given Mention, not including itself. Note that if a candidate is passed in, all of its Mentions will be searched. :param mention: The Mention whose Sentence is being search...
Get the ngrams that are in the Sentence of the given Mention, not including itself. Note that if a candidate is passed in, all of its Mentions will be searched. :param mention: The Mention whose Sentence is being searched :param attrib: The token attribute type (e.g. words, lemmas, poses) :param n...
Below is the the instruction that describes the task: ### Input: Get the ngrams that are in the Sentence of the given Mention, not including itself. Note that if a candidate is passed in, all of its Mentions will be searched. :param mention: The Mention whose Sentence is being searched :param attr...
def fromxml(node): """Static method returning an MetaField instance (any subclass of AbstractMetaField) from the given XML description. Node can be a string or an etree._Element.""" if not isinstance(node,ElementTree._Element): #pylint: disable=protected-access node = parsexmlstring(node) ...
Static method returning an MetaField instance (any subclass of AbstractMetaField) from the given XML description. Node can be a string or an etree._Element.
Below is the the instruction that describes the task: ### Input: Static method returning an MetaField instance (any subclass of AbstractMetaField) from the given XML description. Node can be a string or an etree._Element. ### Response: def fromxml(node): """Static method returning an MetaField instance (an...
def to_match(self): """Return a unicode object with the MATCH representation of this Variable.""" self.validate() # We don't want the dollar sign as part of the variable name. variable_with_no_dollar_sign = self.variable_name[1:] match_variable_name = '{%s}' % (six.text_type(va...
Return a unicode object with the MATCH representation of this Variable.
Below is the the instruction that describes the task: ### Input: Return a unicode object with the MATCH representation of this Variable. ### Response: def to_match(self): """Return a unicode object with the MATCH representation of this Variable.""" self.validate() # We don't want the dolla...
def rpc_get_historic_names_by_address(self, address, offset, count, **con_info): """ Get the list of names owned by an address throughout history Return {'status': True, 'names': [{'name': ..., 'block_id': ..., 'vtxindex': ...}]} on success Return {'error': ...} on error """ ...
Get the list of names owned by an address throughout history Return {'status': True, 'names': [{'name': ..., 'block_id': ..., 'vtxindex': ...}]} on success Return {'error': ...} on error
Below is the the instruction that describes the task: ### Input: Get the list of names owned by an address throughout history Return {'status': True, 'names': [{'name': ..., 'block_id': ..., 'vtxindex': ...}]} on success Return {'error': ...} on error ### Response: def rpc_get_historic_names_by_add...
def setup_rules_file(): """ Copy the udev rules file for Opentrons Modules to opentrons_data directory and trigger the new rules. This rules file in opentrons_data is symlinked into udev rules directory TODO: Move this file to resources and move the symlink to point to /data/system/ """ ...
Copy the udev rules file for Opentrons Modules to opentrons_data directory and trigger the new rules. This rules file in opentrons_data is symlinked into udev rules directory TODO: Move this file to resources and move the symlink to point to /data/system/
Below is the the instruction that describes the task: ### Input: Copy the udev rules file for Opentrons Modules to opentrons_data directory and trigger the new rules. This rules file in opentrons_data is symlinked into udev rules directory TODO: Move this file to resources and move the symlink to point...
def is_enabled(self, cls): """Return whether the given component class is enabled.""" if cls not in self.enabled: self.enabled[cls] = self.is_component_enabled(cls) return self.enabled[cls]
Return whether the given component class is enabled.
Below is the the instruction that describes the task: ### Input: Return whether the given component class is enabled. ### Response: def is_enabled(self, cls): """Return whether the given component class is enabled.""" if cls not in self.enabled: self.enabled[cls] = self.is_component_ena...
def _prepare_photometry_input(data, error, mask, wcs, unit): """ Parse the inputs to `aperture_photometry`. `aperture_photometry` accepts a wide range of inputs, e.g. ``data`` could be a numpy array, a Quantity array, or a fits HDU. This requires some parsing and validation to ensure that all inpu...
Parse the inputs to `aperture_photometry`. `aperture_photometry` accepts a wide range of inputs, e.g. ``data`` could be a numpy array, a Quantity array, or a fits HDU. This requires some parsing and validation to ensure that all inputs are complete and consistent. For example, the data could carry a ...
Below is the the instruction that describes the task: ### Input: Parse the inputs to `aperture_photometry`. `aperture_photometry` accepts a wide range of inputs, e.g. ``data`` could be a numpy array, a Quantity array, or a fits HDU. This requires some parsing and validation to ensure that all inputs a...
def always(self, method, path=None, headers=None, text=None, json=None): ''' Sends response every time matching parameters are found util :func:`Server.reset` is called :type method: str :param method: request method: ``'GET'``, ``'POST'``, etc. can be some custom string :type ...
Sends response every time matching parameters are found util :func:`Server.reset` is called :type method: str :param method: request method: ``'GET'``, ``'POST'``, etc. can be some custom string :type path: str :param path: request path including query parameters :type headers...
Below is the the instruction that describes the task: ### Input: Sends response every time matching parameters are found util :func:`Server.reset` is called :type method: str :param method: request method: ``'GET'``, ``'POST'``, etc. can be some custom string :type path: str :param...
def to_jd(year, month, day): '''Determine Julian day from Persian date''' if year >= 0: y = 474 else: y = 473 epbase = year - y epyear = 474 + (epbase % 2820) if month <= 7: m = (month - 1) * 31 else: m = (month - 1) * 30 + 6 return day + m + trunc(((ep...
Determine Julian day from Persian date
Below is the the instruction that describes the task: ### Input: Determine Julian day from Persian date ### Response: def to_jd(year, month, day): '''Determine Julian day from Persian date''' if year >= 0: y = 474 else: y = 473 epbase = year - y epyear = 474 + (epbase % 2820) ...
def hypermedia_out(): ''' Determine the best handler for the requested content type Wrap the normal handler and transform the output from that handler into the requested content type ''' request = cherrypy.serving.request request._hypermedia_inner_handler = request.handler # If handler...
Determine the best handler for the requested content type Wrap the normal handler and transform the output from that handler into the requested content type
Below is the the instruction that describes the task: ### Input: Determine the best handler for the requested content type Wrap the normal handler and transform the output from that handler into the requested content type ### Response: def hypermedia_out(): ''' Determine the best handler for the r...
def raw(config): # pragma: no cover """Dump the contents of LDAP to console in raw format.""" client = Client() client.prepare_connection() audit_api = API(client) print(audit_api.raw())
Dump the contents of LDAP to console in raw format.
Below is the the instruction that describes the task: ### Input: Dump the contents of LDAP to console in raw format. ### Response: def raw(config): # pragma: no cover """Dump the contents of LDAP to console in raw format.""" client = Client() client.prepare_connection() audit_api =...
def make_crossroad_router(source, drain=False): ''' legacy crossroad implementation. deprecated ''' sink_observer = None def on_sink_subscribe(observer): nonlocal sink_observer sink_observer = observer def dispose(): nonlocal sink_observer sink_observer ...
legacy crossroad implementation. deprecated
Below is the the instruction that describes the task: ### Input: legacy crossroad implementation. deprecated ### Response: def make_crossroad_router(source, drain=False): ''' legacy crossroad implementation. deprecated ''' sink_observer = None def on_sink_subscribe(observer): nonlocal sink...
def bootstrap_prompt(prompt_kwargs, group): """ Bootstrap prompt_toolkit kwargs or use user defined values. :param prompt_kwargs: The user specified prompt kwargs. """ prompt_kwargs = prompt_kwargs or {} defaults = { "history": InMemoryHistory(), "completer": ClickCompleter(gro...
Bootstrap prompt_toolkit kwargs or use user defined values. :param prompt_kwargs: The user specified prompt kwargs.
Below is the the instruction that describes the task: ### Input: Bootstrap prompt_toolkit kwargs or use user defined values. :param prompt_kwargs: The user specified prompt kwargs. ### Response: def bootstrap_prompt(prompt_kwargs, group): """ Bootstrap prompt_toolkit kwargs or use user defined values....
def get_oc_api_token(): """ Get token of user logged in OpenShift cluster :return: str, API token """ oc_command_exists() try: return run_cmd(["oc", "whoami", "-t"], return_output=True).rstrip() # remove '\n' except subprocess.CalledProcessError as ex: raise ConuException("...
Get token of user logged in OpenShift cluster :return: str, API token
Below is the the instruction that describes the task: ### Input: Get token of user logged in OpenShift cluster :return: str, API token ### Response: def get_oc_api_token(): """ Get token of user logged in OpenShift cluster :return: str, API token """ oc_command_exists() try: re...
def allocate(self, pool, tenant_id=None, **params): """Allocates a floating IP to the tenant. You must provide a pool name or id for which you would like to allocate a floating IP. :returns: FloatingIp object corresponding to an allocated floating IP """ if not tenant_i...
Allocates a floating IP to the tenant. You must provide a pool name or id for which you would like to allocate a floating IP. :returns: FloatingIp object corresponding to an allocated floating IP
Below is the the instruction that describes the task: ### Input: Allocates a floating IP to the tenant. You must provide a pool name or id for which you would like to allocate a floating IP. :returns: FloatingIp object corresponding to an allocated floating IP ### Response: def allocate(s...
def send(self, *args): """Sends a single raw message to the IRC server. Arguments are automatically joined by spaces. No newlines are allowed. """ msg = " ".join(a.nick if isinstance(a, User) else str(a) for a in args) if "\n" in msg: raise ValueError("Cannot send() ...
Sends a single raw message to the IRC server. Arguments are automatically joined by spaces. No newlines are allowed.
Below is the the instruction that describes the task: ### Input: Sends a single raw message to the IRC server. Arguments are automatically joined by spaces. No newlines are allowed. ### Response: def send(self, *args): """Sends a single raw message to the IRC server. Arguments are automat...
def remove_user_from_group(self, username, groupname, raise_on_error=False): """Remove a user from a group Attempts to remove a user from a group Args username: The username to remove from the group. groupname: The group name to be removed from the user. Returns: ...
Remove a user from a group Attempts to remove a user from a group Args username: The username to remove from the group. groupname: The group name to be removed from the user. Returns: True: Succeeded False: If unsuccessful
Below is the the instruction that describes the task: ### Input: Remove a user from a group Attempts to remove a user from a group Args username: The username to remove from the group. groupname: The group name to be removed from the user. Returns: True: Succeeded ...
def exit_if_no_roles(roles_count, roles_path): """ Exit if there were no roles found. """ if roles_count == 0: ui.warn(c.MESSAGES["empty_roles_path"], roles_path) sys.exit()
Exit if there were no roles found.
Below is the the instruction that describes the task: ### Input: Exit if there were no roles found. ### Response: def exit_if_no_roles(roles_count, roles_path): """ Exit if there were no roles found. """ if roles_count == 0: ui.warn(c.MESSAGES["empty_roles_path"], roles_path) sys.ex...
def get_new_edges(self, level): """Get new edges from the pattern graph for the graph search algorithm The level argument denotes the distance of the new edges from the starting vertex in the pattern graph. """ return ( self.level_edges.get(level, []), ...
Get new edges from the pattern graph for the graph search algorithm The level argument denotes the distance of the new edges from the starting vertex in the pattern graph.
Below is the the instruction that describes the task: ### Input: Get new edges from the pattern graph for the graph search algorithm The level argument denotes the distance of the new edges from the starting vertex in the pattern graph. ### Response: def get_new_edges(self, level): "...