code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
text
stringlengths
164
112k
def add_media_description(self, media_description): """Adds a media_description. arg: media_description (displayText): the new media_description raise: InvalidArgument - ``media_description`` is invalid raise: NoAccess - ``Metadata.isReadOnly()`` is ``true`` raise: NullArg...
Adds a media_description. arg: media_description (displayText): the new media_description raise: InvalidArgument - ``media_description`` is invalid raise: NoAccess - ``Metadata.isReadOnly()`` is ``true`` raise: NullArgument - ``media_description`` is ``null`` *compliance: ...
Below is the the instruction that describes the task: ### Input: Adds a media_description. arg: media_description (displayText): the new media_description raise: InvalidArgument - ``media_description`` is invalid raise: NoAccess - ``Metadata.isReadOnly()`` is ``true`` raise: N...
def inferObjectsWithRandomMovements(self): """ Infer each object without any location input. """ for objectName, objectFeatures in self.objects.iteritems(): self.reset() inferred = False prevTouchSequence = None for _ in xrange(4): while True: touchSequence =...
Infer each object without any location input.
Below is the the instruction that describes the task: ### Input: Infer each object without any location input. ### Response: def inferObjectsWithRandomMovements(self): """ Infer each object without any location input. """ for objectName, objectFeatures in self.objects.iteritems(): self.reset(...
def _element_to_bson(key, value, check_keys, opts): """Encode a single key, value pair.""" if not isinstance(key, string_type): raise InvalidDocument("documents must have only string keys, " "key was %r" % (key,)) if check_keys: if key.startswith("$"): ...
Encode a single key, value pair.
Below is the the instruction that describes the task: ### Input: Encode a single key, value pair. ### Response: def _element_to_bson(key, value, check_keys, opts): """Encode a single key, value pair.""" if not isinstance(key, string_type): raise InvalidDocument("documents must have only string keys...
def get_doc(self, objtxt): """Get object documentation dictionary""" if self._reading: return wait_loop = QEventLoop() self.sig_got_reply.connect(wait_loop.quit) self.silent_exec_method("get_ipython().kernel.get_doc('%s')" % objtxt) wait_loop.exec_() ...
Get object documentation dictionary
Below is the the instruction that describes the task: ### Input: Get object documentation dictionary ### Response: def get_doc(self, objtxt): """Get object documentation dictionary""" if self._reading: return wait_loop = QEventLoop() self.sig_got_reply.connect(wait_loop....
def mod_watch(name, **kwargs): ''' Install/reinstall a package based on a watch requisite .. note:: This state exists to support special handling of the ``watch`` :ref:`requisite <requisites>`. It should not be called directly. Parameters for this function should be set by the stat...
Install/reinstall a package based on a watch requisite .. note:: This state exists to support special handling of the ``watch`` :ref:`requisite <requisites>`. It should not be called directly. Parameters for this function should be set by the state being triggered.
Below is the the instruction that describes the task: ### Input: Install/reinstall a package based on a watch requisite .. note:: This state exists to support special handling of the ``watch`` :ref:`requisite <requisites>`. It should not be called directly. Parameters for this function...
def loadNetworkbyName(self, name, callback=None, errback=None): """ Load an existing Network by name into a high level Network object :param str name: Name of an existing Network """ import ns1.ipam network = ns1.ipam.Network(self.config, name=name) return networ...
Load an existing Network by name into a high level Network object :param str name: Name of an existing Network
Below is the the instruction that describes the task: ### Input: Load an existing Network by name into a high level Network object :param str name: Name of an existing Network ### Response: def loadNetworkbyName(self, name, callback=None, errback=None): """ Load an existing Network by name...
def _set_hw_state(self, v, load=False): """ Setter method for hw_state, mapped from YANG variable /hw_state (container) If this variable is read-only (config: false) in the source YANG file, then _set_hw_state is considered as a private method. Backends looking to populate this variable should d...
Setter method for hw_state, mapped from YANG variable /hw_state (container) If this variable is read-only (config: false) in the source YANG file, then _set_hw_state is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_hw_state() directly. ...
Below is the the instruction that describes the task: ### Input: Setter method for hw_state, mapped from YANG variable /hw_state (container) If this variable is read-only (config: false) in the source YANG file, then _set_hw_state is considered as a private method. Backends looking to populate this vari...
def getPotential(self, columnIndex, potential): """ :param columnIndex: (int) column index to get potential for. :param potential: (list) will be overwritten with column potentials. Must match the number of inputs. """ assert(columnIndex < self._numColumns) potential[:] = self._poten...
:param columnIndex: (int) column index to get potential for. :param potential: (list) will be overwritten with column potentials. Must match the number of inputs.
Below is the the instruction that describes the task: ### Input: :param columnIndex: (int) column index to get potential for. :param potential: (list) will be overwritten with column potentials. Must match the number of inputs. ### Response: def getPotential(self, columnIndex, potential): """ ...
def name(self, new_name): """ Sets the name of this VPCS VM. :param new_name: name """ if self.script_file: content = self.startup_script content = content.replace(self._name, new_name) escaped_name = new_name.replace('\\', '') co...
Sets the name of this VPCS VM. :param new_name: name
Below is the the instruction that describes the task: ### Input: Sets the name of this VPCS VM. :param new_name: name ### Response: def name(self, new_name): """ Sets the name of this VPCS VM. :param new_name: name """ if self.script_file: content = se...
def put(self, url, html, cache_info=None): """ Put response into cache :param url: Url to cache :type url: str | unicode :param html: HTML content of url :type html: str | unicode :param cache_info: Cache Info (default: None) :type cache_info: floscraper....
Put response into cache :param url: Url to cache :type url: str | unicode :param html: HTML content of url :type html: str | unicode :param cache_info: Cache Info (default: None) :type cache_info: floscraper.models.CacheInfo :rtype: None
Below is the the instruction that describes the task: ### Input: Put response into cache :param url: Url to cache :type url: str | unicode :param html: HTML content of url :type html: str | unicode :param cache_info: Cache Info (default: None) :type cache_info: flosc...
def simulate_leapfrog(config_func: Callable, accel_func: Callable, t0: date, t1: date, steps_per_day: int): """ Simulate the earth-sun system from t0 to t1 using Leapfrog Integration. INPUTS: config_func: function taking a date or date range and returning position and velocity of ...
Simulate the earth-sun system from t0 to t1 using Leapfrog Integration. INPUTS: config_func: function taking a date or date range and returning position and velocity of bodies accel_func: function taking positions of the bodies and returning their accelerations t0: start date of the simulation; a pytho...
Below is the the instruction that describes the task: ### Input: Simulate the earth-sun system from t0 to t1 using Leapfrog Integration. INPUTS: config_func: function taking a date or date range and returning position and velocity of bodies accel_func: function taking positions of the bodies and return...
def print_about(self): """Print an info message about the tool.""" filepath = os.path.join(self.suite_path, "bin", self.tool_name) print "Tool: %s" % self.tool_name print "Path: %s" % filepath print "Suite: %s" % self.suite_path msg = "%s (%r)" % (self.context...
Print an info message about the tool.
Below is the the instruction that describes the task: ### Input: Print an info message about the tool. ### Response: def print_about(self): """Print an info message about the tool.""" filepath = os.path.join(self.suite_path, "bin", self.tool_name) print "Tool: %s" % self.tool_name ...
def search(query, team=None): """ Search for packages """ if team is None: team = _find_logged_in_team() if team is not None: session = _get_session(team) response = session.get("%s/api/search/" % get_registry_url(team), params=dict(q=query)) print("* Packages in tea...
Search for packages
Below is the the instruction that describes the task: ### Input: Search for packages ### Response: def search(query, team=None): """ Search for packages """ if team is None: team = _find_logged_in_team() if team is not None: session = _get_session(team) response = sessi...
def messages(self): """ Access the messages :returns: twilio.rest.messaging.v1.session.message.MessageList :rtype: twilio.rest.messaging.v1.session.message.MessageList """ if self._messages is None: self._messages = MessageList(self._version, session_sid=self...
Access the messages :returns: twilio.rest.messaging.v1.session.message.MessageList :rtype: twilio.rest.messaging.v1.session.message.MessageList
Below is the the instruction that describes the task: ### Input: Access the messages :returns: twilio.rest.messaging.v1.session.message.MessageList :rtype: twilio.rest.messaging.v1.session.message.MessageList ### Response: def messages(self): """ Access the messages :retur...
def dumps(number): """Dumps an integer into a base36 string. :param number: the 10-based integer. :returns: the base36 string. """ if not isinstance(number, integer_types): raise TypeError('number must be an integer') if number < 0: return '-' + dumps(-number) value = '' ...
Dumps an integer into a base36 string. :param number: the 10-based integer. :returns: the base36 string.
Below is the the instruction that describes the task: ### Input: Dumps an integer into a base36 string. :param number: the 10-based integer. :returns: the base36 string. ### Response: def dumps(number): """Dumps an integer into a base36 string. :param number: the 10-based integer. :returns: t...
def reset_stats(self): """ Returns: mean, max: two stats of the runners, to be added to backend """ scores = list(itertools.chain.from_iterable([v.total_scores for v in self._runners])) for v in self._runners: v.total_scores.clear() try: ...
Returns: mean, max: two stats of the runners, to be added to backend
Below is the the instruction that describes the task: ### Input: Returns: mean, max: two stats of the runners, to be added to backend ### Response: def reset_stats(self): """ Returns: mean, max: two stats of the runners, to be added to backend """ scores = li...
async def dump_variant(self, elem, elem_type=None, params=None, obj=None): """ Dumps variant type to the writer. Supports both wrapped and raw variant. :param elem: :param elem_type: :param params: :param obj: :return: """ fvalue = None ...
Dumps variant type to the writer. Supports both wrapped and raw variant. :param elem: :param elem_type: :param params: :param obj: :return:
Below is the the instruction that describes the task: ### Input: Dumps variant type to the writer. Supports both wrapped and raw variant. :param elem: :param elem_type: :param params: :param obj: :return: ### Response: async def dump_variant(self, elem, elem_type=No...
def ParseFileObject(self, parser_mediator, file_object): """Parses a PLSRecall.dat file-like object. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. file_object (dfvfs.FileIO): a file-like object. Raises: ...
Parses a PLSRecall.dat file-like object. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. file_object (dfvfs.FileIO): a file-like object. Raises: UnableToParseFile: when the file cannot be parsed.
Below is the the instruction that describes the task: ### Input: Parses a PLSRecall.dat file-like object. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. file_object (dfvfs.FileIO): a file-like object. Rai...
def filter_factory(global_conf, **local_conf): """Returns a WSGI filter app for use with paste.deploy.""" conf = global_conf.copy() conf.update(local_conf) def visible(app): return VisibleFilter(app, conf) return visible
Returns a WSGI filter app for use with paste.deploy.
Below is the the instruction that describes the task: ### Input: Returns a WSGI filter app for use with paste.deploy. ### Response: def filter_factory(global_conf, **local_conf): """Returns a WSGI filter app for use with paste.deploy.""" conf = global_conf.copy() conf.update(local_conf) def visibl...
async def echo_all(app, message): """Send and recieve a message from all running echo servers""" # Loop through all registered server addresses for address in app.kv.get_prefix('address.').values(): # Parse the host and port from the stored address host, port = address.decode().split(':') ...
Send and recieve a message from all running echo servers
Below is the the instruction that describes the task: ### Input: Send and recieve a message from all running echo servers ### Response: async def echo_all(app, message): """Send and recieve a message from all running echo servers""" # Loop through all registered server addresses for address in app.kv.g...
def label(self): """Provide access to the notification label. Returns: str: The notification label """ with self.selenium.context(self.selenium.CONTEXT_CHROME): return self.root.get_attribute("label")
Provide access to the notification label. Returns: str: The notification label
Below is the the instruction that describes the task: ### Input: Provide access to the notification label. Returns: str: The notification label ### Response: def label(self): """Provide access to the notification label. Returns: str: The notification label ...
def get_setup_version(reponame): """Use autover to get up to date version.""" # importing self into setup.py is unorthodox, but param has no # required dependencies outside of python from param.version import Version return Version.setup_version(os.path.dirname(__file__),reponame,archive_commit="$Fo...
Use autover to get up to date version.
Below is the the instruction that describes the task: ### Input: Use autover to get up to date version. ### Response: def get_setup_version(reponame): """Use autover to get up to date version.""" # importing self into setup.py is unorthodox, but param has no # required dependencies outside of python ...
def gssa(model, maxit=100, tol=1e-8, initial_dr=None, verbose=False, n_sim=10000, deg=3, damp=0.1, seed=42): """ Sketch of algorithm: 0. Choose levels for the initial states and the simulation length (n_sim) 1. Obtain an initial decision rule -- here using first order perturbation 2. Draw ...
Sketch of algorithm: 0. Choose levels for the initial states and the simulation length (n_sim) 1. Obtain an initial decision rule -- here using first order perturbation 2. Draw a sequence of innovations epsilon 3. Iterate on the following steps: - Use the epsilons, initial states, and proposed ...
Below is the the instruction that describes the task: ### Input: Sketch of algorithm: 0. Choose levels for the initial states and the simulation length (n_sim) 1. Obtain an initial decision rule -- here using first order perturbation 2. Draw a sequence of innovations epsilon 3. Iterate on the follo...
def on_scenario_directory_radio_toggled(self, flag): """Autoconnect slot activated when scenario_directory_radio is checked. :param flag: Flag indicating whether the checkbox was toggled on or off. :type flag: bool """ if flag: self.output_directory.setTe...
Autoconnect slot activated when scenario_directory_radio is checked. :param flag: Flag indicating whether the checkbox was toggled on or off. :type flag: bool
Below is the the instruction that describes the task: ### Input: Autoconnect slot activated when scenario_directory_radio is checked. :param flag: Flag indicating whether the checkbox was toggled on or off. :type flag: bool ### Response: def on_scenario_directory_radio_toggled(self, fl...
def __build_parser_for_fileobject_and_desiredtype(self, obj_on_filesystem: PersistedObject, object_typ: Type[T], logger: Logger = None) -> Parser: """ Builds from the registry, a parser to parse object obj_on_filesystem as an object of type object_ty...
Builds from the registry, a parser to parse object obj_on_filesystem as an object of type object_type. To do that, it iterates through all registered parsers in the list in reverse order (last inserted first), and checks if they support the provided object format (single or multifile) and type. ...
Below is the the instruction that describes the task: ### Input: Builds from the registry, a parser to parse object obj_on_filesystem as an object of type object_type. To do that, it iterates through all registered parsers in the list in reverse order (last inserted first), and checks if they suppo...
def _t_of_e(self, a0=None, t_start=None, f0=None, ef=None, t_obs=5.0): """Rearranged versions of Peters equations This function calculates the semi-major axis and eccentricity over time. """ if ef is None: ef = np.ones_like(self.e0)*0.0000001 beta = 64.0/5.0*self.m...
Rearranged versions of Peters equations This function calculates the semi-major axis and eccentricity over time.
Below is the the instruction that describes the task: ### Input: Rearranged versions of Peters equations This function calculates the semi-major axis and eccentricity over time. ### Response: def _t_of_e(self, a0=None, t_start=None, f0=None, ef=None, t_obs=5.0): """Rearranged versions of Peters eq...
def set_outflow_BC(self, pores, mode='merge'): r""" Adds outflow boundary condition to the selected pores. Outflow condition simply means that the gradient of the solved quantity does not change, i.e. is 0. """ # Hijack the parse_mode function to verify mode/pores argum...
r""" Adds outflow boundary condition to the selected pores. Outflow condition simply means that the gradient of the solved quantity does not change, i.e. is 0.
Below is the the instruction that describes the task: ### Input: r""" Adds outflow boundary condition to the selected pores. Outflow condition simply means that the gradient of the solved quantity does not change, i.e. is 0. ### Response: def set_outflow_BC(self, pores, mode='merge'): ...
def dims(x): """Returns a list of dimension sizes, or `None` if `rank` is unknown. For more details, see `help(tf.TensorShape.dims)`. Args: x: object representing a shape; convertible to `tf.TensorShape`. Returns: shape_as_list: list of sizes or `None` values representing each dimensions size i...
Returns a list of dimension sizes, or `None` if `rank` is unknown. For more details, see `help(tf.TensorShape.dims)`. Args: x: object representing a shape; convertible to `tf.TensorShape`. Returns: shape_as_list: list of sizes or `None` values representing each dimensions size if known. A size is...
Below is the the instruction that describes the task: ### Input: Returns a list of dimension sizes, or `None` if `rank` is unknown. For more details, see `help(tf.TensorShape.dims)`. Args: x: object representing a shape; convertible to `tf.TensorShape`. Returns: shape_as_list: list of sizes or `Non...
def msgmerge(self, locale_file, po_string): """ Runs msgmerge on a locale_file and po_string """ cmd = "msgmerge -q %s -" % locale_file p = subprocess.Popen(cmd, shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) (msg, err) = p...
Runs msgmerge on a locale_file and po_string
Below is the the instruction that describes the task: ### Input: Runs msgmerge on a locale_file and po_string ### Response: def msgmerge(self, locale_file, po_string): """ Runs msgmerge on a locale_file and po_string """ cmd = "msgmerge -q %s -" % locale_file p = subprocess...
def build_board_checkers(): """ builds a checkers starting board Printing Grid 0 B 0 B 0 B 0 B B 0 B 0 B 0 B 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0...
builds a checkers starting board Printing Grid 0 B 0 B 0 B 0 B B 0 B 0 B 0 B 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 ...
Below is the the instruction that describes the task: ### Input: builds a checkers starting board Printing Grid 0 B 0 B 0 B 0 B B 0 B 0 B 0 B 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 ...
def merge_with(self, other): """Returns a `TensorShape` combining the information in `self` and `other`. The dimensions in `self` and `other` are merged elementwise, according to the rules defined for `Dimension.merge_with()`. Args: other: Another `TensorShape`. Retu...
Returns a `TensorShape` combining the information in `self` and `other`. The dimensions in `self` and `other` are merged elementwise, according to the rules defined for `Dimension.merge_with()`. Args: other: Another `TensorShape`. Returns: A `TensorShape` containin...
Below is the the instruction that describes the task: ### Input: Returns a `TensorShape` combining the information in `self` and `other`. The dimensions in `self` and `other` are merged elementwise, according to the rules defined for `Dimension.merge_with()`. Args: other: Another...
def _post(url, headers={}, data=None, files=None): """Tries to POST data to an endpoint""" try: response = requests.post(url, headers=headers, data=data, files=files, verify=VERIFY_SSL) return _process_response(response) except requests.exceptions.RequestException as e: _log_and_rais...
Tries to POST data to an endpoint
Below is the the instruction that describes the task: ### Input: Tries to POST data to an endpoint ### Response: def _post(url, headers={}, data=None, files=None): """Tries to POST data to an endpoint""" try: response = requests.post(url, headers=headers, data=data, files=files, verify=VERIFY_SSL) ...
def is_entailed_by(self, other): """ Given two beliefstates, returns True iff the calling instance implies the other beliefstate, meaning it contains at least the same structure (for all structures) and all values (for all defined values). Inverse of `entails`. ...
Given two beliefstates, returns True iff the calling instance implies the other beliefstate, meaning it contains at least the same structure (for all structures) and all values (for all defined values). Inverse of `entails`. Note: this only compares the items in the DictCell, n...
Below is the the instruction that describes the task: ### Input: Given two beliefstates, returns True iff the calling instance implies the other beliefstate, meaning it contains at least the same structure (for all structures) and all values (for all defined values). Inverse of `ent...
def request(self, action, data={}, headers={}, method='GET'): """ Append the REST headers to every request """ headers = { "Authorization": "Bearer " + self.token, "Content-Type": "application/json", "X-Version": "1", "Accept": "application...
Append the REST headers to every request
Below is the the instruction that describes the task: ### Input: Append the REST headers to every request ### Response: def request(self, action, data={}, headers={}, method='GET'): """ Append the REST headers to every request """ headers = { "Authorization": "Bearer " +...
def process_inlines(parser, token): """ Searches through the provided content and applies inlines where ever they are found. Syntax:: {% process_inlines entry.body [in template_dir] [as varname] } Examples:: {% process_inlines entry.body %} {% process_inlines entry.body ...
Searches through the provided content and applies inlines where ever they are found. Syntax:: {% process_inlines entry.body [in template_dir] [as varname] } Examples:: {% process_inlines entry.body %} {% process_inlines entry.body as body %} {% process_inlines entry.bod...
Below is the the instruction that describes the task: ### Input: Searches through the provided content and applies inlines where ever they are found. Syntax:: {% process_inlines entry.body [in template_dir] [as varname] } Examples:: {% process_inlines entry.body %} {% proces...
def amount(self): """ Determine the sum of mole amounts of all the compounds. :returns: Amount. [kmol] """ return sum(self.get_compound_amount(c) for c in self.material.compounds)
Determine the sum of mole amounts of all the compounds. :returns: Amount. [kmol]
Below is the the instruction that describes the task: ### Input: Determine the sum of mole amounts of all the compounds. :returns: Amount. [kmol] ### Response: def amount(self): """ Determine the sum of mole amounts of all the compounds. :returns: Amount. [kmol] """ ...
def overlay_gateway_sflow_sflow_vlan_action(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") overlay_gateway = ET.SubElement(config, "overlay-gateway", xmlns="urn:brocade.com:mgmt:brocade-tunnels") name_key = ET.SubElement(overlay_gateway, "name") ...
Auto Generated Code
Below is the the instruction that describes the task: ### Input: Auto Generated Code ### Response: def overlay_gateway_sflow_sflow_vlan_action(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") overlay_gateway = ET.SubElement(config, "overlay-gateway", xmlns="...
def main(): """Entry point for command line usage.""" import colorama import argparse import logging import sys import os parser = argparse.ArgumentParser(prog="gulpless", description="Simple build system.") parser.add_argument("-v", "--version", ...
Entry point for command line usage.
Below is the the instruction that describes the task: ### Input: Entry point for command line usage. ### Response: def main(): """Entry point for command line usage.""" import colorama import argparse import logging import sys import os parser = argparse.ArgumentParser(prog="gulpless",...
def members(name, members_list, root=None): ''' Replaces members of the group with a provided list. CLI Example: salt '*' group.members foo 'user1,user2,user3,...' Replaces a membership list for a local group 'foo'. foo:x:1234:user1,user2,user3,... ''' cmd = 'chgrpmem -m = {0}...
Replaces members of the group with a provided list. CLI Example: salt '*' group.members foo 'user1,user2,user3,...' Replaces a membership list for a local group 'foo'. foo:x:1234:user1,user2,user3,...
Below is the the instruction that describes the task: ### Input: Replaces members of the group with a provided list. CLI Example: salt '*' group.members foo 'user1,user2,user3,...' Replaces a membership list for a local group 'foo'. foo:x:1234:user1,user2,user3,... ### Response: def memb...
def to_dict(self, save_data=True): """ Convert the object into a json serializable dictionary. :param boolean save_data: if true, it adds the training data self.X and self.Y to the dictionary :return dict: json serializable dictionary containing the needed information to instantiate the...
Convert the object into a json serializable dictionary. :param boolean save_data: if true, it adds the training data self.X and self.Y to the dictionary :return dict: json serializable dictionary containing the needed information to instantiate the object
Below is the the instruction that describes the task: ### Input: Convert the object into a json serializable dictionary. :param boolean save_data: if true, it adds the training data self.X and self.Y to the dictionary :return dict: json serializable dictionary containing the needed information to i...
def acl_show(self, msg, args): """Show current allow and deny blocks for the given acl.""" name = args[0] if len(args) > 0 else None if name is None: return "%s: The following ACLs are defined: %s" % (msg.user, ', '.join(self._acl.keys())) if name not in self._acl: ...
Show current allow and deny blocks for the given acl.
Below is the the instruction that describes the task: ### Input: Show current allow and deny blocks for the given acl. ### Response: def acl_show(self, msg, args): """Show current allow and deny blocks for the given acl.""" name = args[0] if len(args) > 0 else None if name is None: ...
def extract_ipv4(roster_order, ipv4): ''' Extract the preferred IP address from the ipv4 grain ''' for ip_type in roster_order: for ip_ in ipv4: if ':' in ip_: continue if not salt.utils.validate.net.ipv4_addr(ip_): continue if ...
Extract the preferred IP address from the ipv4 grain
Below is the the instruction that describes the task: ### Input: Extract the preferred IP address from the ipv4 grain ### Response: def extract_ipv4(roster_order, ipv4): ''' Extract the preferred IP address from the ipv4 grain ''' for ip_type in roster_order: for ip_ in ipv4: if...
def assign_tip_labels_and_colors(self): "assign tip labels based on user provided kwargs" # COLOR # tip color overrides tipstyle.fill if self.style.tip_labels_colors: #if self.style.tip_labels_style.fill: # self.style.tip_labels_style.fill = None if...
assign tip labels based on user provided kwargs
Below is the the instruction that describes the task: ### Input: assign tip labels based on user provided kwargs ### Response: def assign_tip_labels_and_colors(self): "assign tip labels based on user provided kwargs" # COLOR # tip color overrides tipstyle.fill if self.style.tip_labe...
def setup_handlers(): ''' sets up the sentry handler ''' __grains__ = salt.loader.grains(__opts__) __salt__ = salt.loader.minion_mods(__opts__) if 'sentry_handler' not in __opts__: log.debug('No \'sentry_handler\' key was found in the configuration') return False options = {}...
sets up the sentry handler
Below is the the instruction that describes the task: ### Input: sets up the sentry handler ### Response: def setup_handlers(): ''' sets up the sentry handler ''' __grains__ = salt.loader.grains(__opts__) __salt__ = salt.loader.minion_mods(__opts__) if 'sentry_handler' not in __opts__: ...
def delete_contacts( self, ids: List[int] ): """Use this method to delete contacts from your Telegram address book. Args: ids (List of ``int``): A list of unique identifiers for the target users. Can be an ID (int), a username (string) or ...
Use this method to delete contacts from your Telegram address book. Args: ids (List of ``int``): A list of unique identifiers for the target users. Can be an ID (int), a username (string) or phone number (string). Returns: True on success. ...
Below is the the instruction that describes the task: ### Input: Use this method to delete contacts from your Telegram address book. Args: ids (List of ``int``): A list of unique identifiers for the target users. Can be an ID (int), a username (string) or phone n...
def detached_signature_for(plaintext_str, keys): """ Signs the given plaintext string and returns the detached signature. A detached signature in GPG speak is a separate blob of data containing a signature for the specified plaintext. :param bytes plaintext_str: bytestring to sign :param keys:...
Signs the given plaintext string and returns the detached signature. A detached signature in GPG speak is a separate blob of data containing a signature for the specified plaintext. :param bytes plaintext_str: bytestring to sign :param keys: list of one or more key to sign with. :type keys: list[g...
Below is the the instruction that describes the task: ### Input: Signs the given plaintext string and returns the detached signature. A detached signature in GPG speak is a separate blob of data containing a signature for the specified plaintext. :param bytes plaintext_str: bytestring to sign :par...
def rename_variables(expression: Expression, renaming: Dict[str, str]) -> Expression: """Rename the variables in the expression according to the given dictionary. Args: expression: The expression in which the variables are renamed. renaming: The renaming dictionary. Maps...
Rename the variables in the expression according to the given dictionary. Args: expression: The expression in which the variables are renamed. renaming: The renaming dictionary. Maps old variable names to new ones. Variable names not occuring in the dictionary ar...
Below is the the instruction that describes the task: ### Input: Rename the variables in the expression according to the given dictionary. Args: expression: The expression in which the variables are renamed. renaming: The renaming dictionary. Maps old variable names to n...
def unwrap(self): """ Unwraps an RSA public key into an RSAPublicKey object. Does not support DSA or EC public keys since they do not have an unwrapped form. :return: An RSAPublicKey object """ if self.algorithm == 'rsa': return self['public_key'...
Unwraps an RSA public key into an RSAPublicKey object. Does not support DSA or EC public keys since they do not have an unwrapped form. :return: An RSAPublicKey object
Below is the the instruction that describes the task: ### Input: Unwraps an RSA public key into an RSAPublicKey object. Does not support DSA or EC public keys since they do not have an unwrapped form. :return: An RSAPublicKey object ### Response: def unwrap(self): """ U...
def index_all(self): """ Index all records under :attr:`record_path`. """ self.logger.debug('Start indexing all records under: %s', self.record_path) with self.db.connection(): for json_path in sorted(self.find_record_files()): ...
Index all records under :attr:`record_path`.
Below is the the instruction that describes the task: ### Input: Index all records under :attr:`record_path`. ### Response: def index_all(self): """ Index all records under :attr:`record_path`. """ self.logger.debug('Start indexing all records under: %s', s...
def decorate_class_method(func, classkey=None, skipmain=False): """ Will inject all decorated function as methods of classkey classkey is some identifying string, tuple, or object func can also be a tuple """ #import utool as ut global __CLASSTYPE_ATTRIBUTES__ assert classkey is not No...
Will inject all decorated function as methods of classkey classkey is some identifying string, tuple, or object func can also be a tuple
Below is the the instruction that describes the task: ### Input: Will inject all decorated function as methods of classkey classkey is some identifying string, tuple, or object func can also be a tuple ### Response: def decorate_class_method(func, classkey=None, skipmain=False): """ Will inject a...
def cli(): """ Command line interface """ ch = logging.StreamHandler() ch.setFormatter(logging.Formatter( '%(asctime)s.%(msecs)03d %(levelname)s: %(message)s', datefmt="%Y-%m-%d %H:%M:%S" )) logger.addHandler(ch) import argparse parser = argparse.ArgumentParser(description="...
Command line interface
Below is the the instruction that describes the task: ### Input: Command line interface ### Response: def cli(): """ Command line interface """ ch = logging.StreamHandler() ch.setFormatter(logging.Formatter( '%(asctime)s.%(msecs)03d %(levelname)s: %(message)s', datefmt="%Y-%m-%d %H:%M:%...
def p_element_list(self, p): """element_list : elision_opt assignment_expr | element_list COMMA elision_opt assignment_expr """ if len(p) == 3: p[0] = p[1] + [p[2]] else: p[1].extend(p[3]) p[1].append(p[4]) p[0] = p[...
element_list : elision_opt assignment_expr | element_list COMMA elision_opt assignment_expr
Below is the the instruction that describes the task: ### Input: element_list : elision_opt assignment_expr | element_list COMMA elision_opt assignment_expr ### Response: def p_element_list(self, p): """element_list : elision_opt assignment_expr | element_lis...
def pagure_specific_project_tag_filter(config, message, tags=None, *args, **kw): """ Particular pagure project tags Adding this rule allows you to get notifications for one or more `pagure.io <https://pagure.io>`_ projects having the specified tags. Specify multiple tags by separating them with a co...
Particular pagure project tags Adding this rule allows you to get notifications for one or more `pagure.io <https://pagure.io>`_ projects having the specified tags. Specify multiple tags by separating them with a comma ','.
Below is the the instruction that describes the task: ### Input: Particular pagure project tags Adding this rule allows you to get notifications for one or more `pagure.io <https://pagure.io>`_ projects having the specified tags. Specify multiple tags by separating them with a comma ','. ### Respons...
def createEncoder(): """Create the encoder instance for our test and return it.""" consumption_encoder = ScalarEncoder(21, 0.0, 100.0, n=50, name="consumption", clipInput=True) time_encoder = DateEncoder(timeOfDay=(21, 9.5), name="timestamp_timeOfDay") encoder = MultiEncoder() encoder.addEncoder("consu...
Create the encoder instance for our test and return it.
Below is the the instruction that describes the task: ### Input: Create the encoder instance for our test and return it. ### Response: def createEncoder(): """Create the encoder instance for our test and return it.""" consumption_encoder = ScalarEncoder(21, 0.0, 100.0, n=50, name="consumption", clipInput...
def Create(path, password, generate_default_key=True): """ Create a new user wallet. Args: path (str): A path indicating where to create or open the wallet e.g. "/Wallets/mywallet". password (str): a 10 characters minimum password to secure the wallet with. Retu...
Create a new user wallet. Args: path (str): A path indicating where to create or open the wallet e.g. "/Wallets/mywallet". password (str): a 10 characters minimum password to secure the wallet with. Returns: UserWallet: a UserWallet instance.
Below is the the instruction that describes the task: ### Input: Create a new user wallet. Args: path (str): A path indicating where to create or open the wallet e.g. "/Wallets/mywallet". password (str): a 10 characters minimum password to secure the wallet with. Returns: ...
def to_dict(self): """ Convert the object into a json serializable dictionary. Note: It uses the private method _save_to_input_dict of the parent. :return dict: json serializable dictionary containing the needed information to instantiate the object """ input_dict = su...
Convert the object into a json serializable dictionary. Note: It uses the private method _save_to_input_dict of the parent. :return dict: json serializable dictionary containing the needed information to instantiate the object
Below is the the instruction that describes the task: ### Input: Convert the object into a json serializable dictionary. Note: It uses the private method _save_to_input_dict of the parent. :return dict: json serializable dictionary containing the needed information to instantiate the object ### Re...
def prune_old_authorization_codes(): """ Removes all unused and expired authorization codes from the database. """ from .compat import now from .models import AuthorizationCode AuthorizationCode.objects.with_expiration_before(now()).delete()
Removes all unused and expired authorization codes from the database.
Below is the the instruction that describes the task: ### Input: Removes all unused and expired authorization codes from the database. ### Response: def prune_old_authorization_codes(): """ Removes all unused and expired authorization codes from the database. """ from .compat import now from ....
async def storm(self, text, opts=None): ''' Evaluate a storm query and yield result messages. Yields: ((str,dict)): Storm messages. ''' async for mesg in self.cell.streamstorm(text, opts, user=self.user): yield mesg
Evaluate a storm query and yield result messages. Yields: ((str,dict)): Storm messages.
Below is the the instruction that describes the task: ### Input: Evaluate a storm query and yield result messages. Yields: ((str,dict)): Storm messages. ### Response: async def storm(self, text, opts=None): ''' Evaluate a storm query and yield result messages. Yields: ...
def get_token_issuer(token): """ Issuer of a token is the identifier used to recover the secret Need to extract this from token to ensure we can proceed to the signature validation stage Does not check validity of the token :param token: signed JWT token :return issuer: iss field of the JWT toke...
Issuer of a token is the identifier used to recover the secret Need to extract this from token to ensure we can proceed to the signature validation stage Does not check validity of the token :param token: signed JWT token :return issuer: iss field of the JWT token :raises TokenIssuerError: if iss fi...
Below is the the instruction that describes the task: ### Input: Issuer of a token is the identifier used to recover the secret Need to extract this from token to ensure we can proceed to the signature validation stage Does not check validity of the token :param token: signed JWT token :return issue...
def get_verb_phrases(sentence_doc): """ Returns an object like, [(1), (5,6,7)] where this means 2 verb phrases. a single verb at index 1, another verb phrase 5,6,7. - Adverbs are not included. - Infinitive phrases (and verb phrases that are subsets of infinitive phrase...
Returns an object like, [(1), (5,6,7)] where this means 2 verb phrases. a single verb at index 1, another verb phrase 5,6,7. - Adverbs are not included. - Infinitive phrases (and verb phrases that are subsets of infinitive phrases) are not included
Below is the the instruction that describes the task: ### Input: Returns an object like, [(1), (5,6,7)] where this means 2 verb phrases. a single verb at index 1, another verb phrase 5,6,7. - Adverbs are not included. - Infinitive phrases (and verb phrases that are subsets...
def run(path, code=None, params=None, **meta): """pydocstyle code checking. :return list: List of errors. """ if 'ignore_decorators' in params: ignore_decorators = params['ignore_decorators'] else: ignore_decorators = None check_source_args = (cod...
pydocstyle code checking. :return list: List of errors.
Below is the the instruction that describes the task: ### Input: pydocstyle code checking. :return list: List of errors. ### Response: def run(path, code=None, params=None, **meta): """pydocstyle code checking. :return list: List of errors. """ if 'ignore_decorators' in pa...
def hazards_for_layer(layer_geometry_key): """Get hazard categories form layer_geometry_key. :param layer_geometry_key: The geometry id :type layer_geometry_key: str :returns: List of hazard :rtype: list """ result = [] for hazard in hazard_all: if layer_geometry_key in hazard....
Get hazard categories form layer_geometry_key. :param layer_geometry_key: The geometry id :type layer_geometry_key: str :returns: List of hazard :rtype: list
Below is the the instruction that describes the task: ### Input: Get hazard categories form layer_geometry_key. :param layer_geometry_key: The geometry id :type layer_geometry_key: str :returns: List of hazard :rtype: list ### Response: def hazards_for_layer(layer_geometry_key): """Get hazard...
def flo(string): '''Return the string given by param formatted with the callers locals.''' callers_locals = {} frame = inspect.currentframe() try: outerframe = frame.f_back callers_locals = outerframe.f_locals finally: del frame return string.format(**callers_locals)
Return the string given by param formatted with the callers locals.
Below is the the instruction that describes the task: ### Input: Return the string given by param formatted with the callers locals. ### Response: def flo(string): '''Return the string given by param formatted with the callers locals.''' callers_locals = {} frame = inspect.currentframe() try: ...
def clip_foreign(network): """ Delete all components and timelines located outside of Germany. Add transborder flows divided by country of origin as network.foreign_trade. Parameters ---------- network : :class:`pypsa.Network Overall container of PyPSA Returns ------- n...
Delete all components and timelines located outside of Germany. Add transborder flows divided by country of origin as network.foreign_trade. Parameters ---------- network : :class:`pypsa.Network Overall container of PyPSA Returns ------- network : :class:`pypsa.Network ...
Below is the the instruction that describes the task: ### Input: Delete all components and timelines located outside of Germany. Add transborder flows divided by country of origin as network.foreign_trade. Parameters ---------- network : :class:`pypsa.Network Overall container of PyPSA ...
def solve(succ, orien, i, direc): """Can a laser leaving mirror i in direction direc reach exit ? :param i: mirror index :param direc: direction leaving mirror i :param orient: orient[i]=orientation of mirror i :param succ: succ[i][direc]=succ mirror reached when leaving i in direc...
Can a laser leaving mirror i in direction direc reach exit ? :param i: mirror index :param direc: direction leaving mirror i :param orient: orient[i]=orientation of mirror i :param succ: succ[i][direc]=succ mirror reached when leaving i in direction direc
Below is the the instruction that describes the task: ### Input: Can a laser leaving mirror i in direction direc reach exit ? :param i: mirror index :param direc: direction leaving mirror i :param orient: orient[i]=orientation of mirror i :param succ: succ[i][direc]=succ mirror reached ...
def generator_checker_py2(gen, gen_type, bound_Generic, bound_typevars, bound_typevars_readonly, follow_fwd_refs, _recursion_check): """Builds a typechecking wrapper around a Python 2 style generator object. """ initialized = False sn = None while True: a = gen.send(sn) i...
Builds a typechecking wrapper around a Python 2 style generator object.
Below is the the instruction that describes the task: ### Input: Builds a typechecking wrapper around a Python 2 style generator object. ### Response: def generator_checker_py2(gen, gen_type, bound_Generic, bound_typevars, bound_typevars_readonly, follow_fwd_refs, _recursion_check): """Builds a typ...
def process_remote_sources(self): """Create synthetic targets with populated sources from remote_sources targets.""" unpacked_sources = self.context.products.get_data(UnpackedArchives) remote_sources_targets = self.context.targets(predicate=lambda t: isinstance(t, RemoteSources)) if not remote_sources_t...
Create synthetic targets with populated sources from remote_sources targets.
Below is the the instruction that describes the task: ### Input: Create synthetic targets with populated sources from remote_sources targets. ### Response: def process_remote_sources(self): """Create synthetic targets with populated sources from remote_sources targets.""" unpacked_sources = self.context.pr...
def add_volume_bricks(name, bricks): ''' Add brick(s) to an existing volume name Volume name bricks List of bricks to add to the volume CLI Example: .. code-block:: bash salt '*' glusterfs.add_volume_bricks <volume> <bricks> ''' volinfo = info() if name ...
Add brick(s) to an existing volume name Volume name bricks List of bricks to add to the volume CLI Example: .. code-block:: bash salt '*' glusterfs.add_volume_bricks <volume> <bricks>
Below is the the instruction that describes the task: ### Input: Add brick(s) to an existing volume name Volume name bricks List of bricks to add to the volume CLI Example: .. code-block:: bash salt '*' glusterfs.add_volume_bricks <volume> <bricks> ### Response: def add...
def flat_list_to_polymer(atom_list, atom_group_s=4): """Takes a flat list of atomic coordinates and converts it to a `Polymer`. Parameters ---------- atom_list : [Atom] Flat list of coordinates. atom_group_s : int, optional Size of atom groups. Returns ------- polymer :...
Takes a flat list of atomic coordinates and converts it to a `Polymer`. Parameters ---------- atom_list : [Atom] Flat list of coordinates. atom_group_s : int, optional Size of atom groups. Returns ------- polymer : Polypeptide `Polymer` object containing atom coords...
Below is the the instruction that describes the task: ### Input: Takes a flat list of atomic coordinates and converts it to a `Polymer`. Parameters ---------- atom_list : [Atom] Flat list of coordinates. atom_group_s : int, optional Size of atom groups. Returns ------- ...
def open_zarr(store, group=None, synchronizer=None, chunks='auto', decode_cf=True, mask_and_scale=True, decode_times=True, concat_characters=True, decode_coords=True, drop_variables=None, consolidated=False, overwrite_encoded_chunks=False, **kwargs): """Load a...
Load and decode a dataset from a Zarr store. .. note:: Experimental The Zarr backend is new and experimental. Please report any unexpected behavior via github issues. The `store` object should be a valid store for a Zarr group. `store` variables must contain dimension metadata ...
Below is the the instruction that describes the task: ### Input: Load and decode a dataset from a Zarr store. .. note:: Experimental The Zarr backend is new and experimental. Please report any unexpected behavior via github issues. The `store` object should be a valid store for...
def module_can_run_parallel(test_module: unittest.TestSuite) -> bool: """ Checks if a given module of tests can be run in parallel or not :param test_module: the module to run :return: True if the module can be run on parallel, False otherwise """ for test_class in test_...
Checks if a given module of tests can be run in parallel or not :param test_module: the module to run :return: True if the module can be run on parallel, False otherwise
Below is the the instruction that describes the task: ### Input: Checks if a given module of tests can be run in parallel or not :param test_module: the module to run :return: True if the module can be run on parallel, False otherwise ### Response: def module_can_run_parallel(test_module: unittest...
def _generate_struct(self, struct_type, extra_parameters=None, nameOverride=None): """ Emits a JSDoc @typedef for a struct. """ extra_parameters = extra_parameters if extra_parameters is not None else [] self._emit_jsdoc_header(struct_type.doc) self.emit( ' * ...
Emits a JSDoc @typedef for a struct.
Below is the the instruction that describes the task: ### Input: Emits a JSDoc @typedef for a struct. ### Response: def _generate_struct(self, struct_type, extra_parameters=None, nameOverride=None): """ Emits a JSDoc @typedef for a struct. """ extra_parameters = extra_parameters if ...
def add_ms1_quant_from_top3_mzidtsv(proteins, psms, headerfields, protcol): """Collects PSMs with the highes precursor quant values, adds sum of the top 3 of these to a protein table""" if not protcol: protcol = mzidtsvdata.HEADER_MASTER_PROT top_ms1_psms = generate_top_psms(psms, protcol) f...
Collects PSMs with the highes precursor quant values, adds sum of the top 3 of these to a protein table
Below is the the instruction that describes the task: ### Input: Collects PSMs with the highes precursor quant values, adds sum of the top 3 of these to a protein table ### Response: def add_ms1_quant_from_top3_mzidtsv(proteins, psms, headerfields, protcol): """Collects PSMs with the highes precursor quant...
def print_status(self, repo): """Print status """ print(" {0}{1}{2}".format(repo, " " * (19 - len(repo)), self.st))
Print status
Below is the the instruction that describes the task: ### Input: Print status ### Response: def print_status(self, repo): """Print status """ print(" {0}{1}{2}".format(repo, " " * (19 - len(repo)), self.st))
def analyze(self, output_folder=".", auto_remove=False): """ :type auto_remove: boolean :param boolean auto_remove: auto remove previous files in analyze folder """ if auto_remove: try: shutil.rmtree(output_folder) except: p...
:type auto_remove: boolean :param boolean auto_remove: auto remove previous files in analyze folder
Below is the the instruction that describes the task: ### Input: :type auto_remove: boolean :param boolean auto_remove: auto remove previous files in analyze folder ### Response: def analyze(self, output_folder=".", auto_remove=False): """ :type auto_remove: boolean :param boolean a...
def enable_gtk3(self, app=None): """Enable event loop integration with Gtk3 (gir bindings). Parameters ---------- app : ignored Ignored, it's only a placeholder to keep the call signature of all gui activation methods consistent, which simplifies the logic of ...
Enable event loop integration with Gtk3 (gir bindings). Parameters ---------- app : ignored Ignored, it's only a placeholder to keep the call signature of all gui activation methods consistent, which simplifies the logic of supporting magics. Notes ...
Below is the the instruction that describes the task: ### Input: Enable event loop integration with Gtk3 (gir bindings). Parameters ---------- app : ignored Ignored, it's only a placeholder to keep the call signature of all gui activation methods consistent, which simp...
def _clear(self, pipe=None): """Helper for clear operations. :param pipe: Redis pipe in case update is performed as a part of transaction. :type pipe: :class:`redis.client.StrictPipeline` or :class:`redis.client.StrictRedis` """ redis = s...
Helper for clear operations. :param pipe: Redis pipe in case update is performed as a part of transaction. :type pipe: :class:`redis.client.StrictPipeline` or :class:`redis.client.StrictRedis`
Below is the the instruction that describes the task: ### Input: Helper for clear operations. :param pipe: Redis pipe in case update is performed as a part of transaction. :type pipe: :class:`redis.client.StrictPipeline` or :class:`redis.client.StrictRedis` ...
def send_command_ack(self, device_id, action): """Send command, wait for gateway to repond with acknowledgment.""" # serialize commands yield from self._ready_to_send.acquire() acknowledgement = None try: self._command_ack.clear() self.send_command(device_...
Send command, wait for gateway to repond with acknowledgment.
Below is the the instruction that describes the task: ### Input: Send command, wait for gateway to repond with acknowledgment. ### Response: def send_command_ack(self, device_id, action): """Send command, wait for gateway to repond with acknowledgment.""" # serialize commands yield from sel...
def _stripe_object_to_refunds(cls, target_cls, data, charge): """ Retrieves Refunds for a charge :param target_cls: The target class to instantiate per invoice item. :type target_cls: ``Refund`` :param data: The data dictionary received from the Stripe API. :type data: dict :param charge: The charge objec...
Retrieves Refunds for a charge :param target_cls: The target class to instantiate per invoice item. :type target_cls: ``Refund`` :param data: The data dictionary received from the Stripe API. :type data: dict :param charge: The charge object that refunds are for. :type invoice: ``djstripe.models.Refund`` ...
Below is the the instruction that describes the task: ### Input: Retrieves Refunds for a charge :param target_cls: The target class to instantiate per invoice item. :type target_cls: ``Refund`` :param data: The data dictionary received from the Stripe API. :type data: dict :param charge: The charge object...
def is_valid_catalog(catalog, validator=None): """Valida que un archivo `data.json` cumpla con el schema definido. Chequea que el data.json tiene todos los campos obligatorios y que tanto los campos obligatorios como los opcionales siguen la estructura definida en el schema. Args: catalog ...
Valida que un archivo `data.json` cumpla con el schema definido. Chequea que el data.json tiene todos los campos obligatorios y que tanto los campos obligatorios como los opcionales siguen la estructura definida en el schema. Args: catalog (str o dict): Catálogo (dict, JSON o XLSX) a ser valid...
Below is the the instruction that describes the task: ### Input: Valida que un archivo `data.json` cumpla con el schema definido. Chequea que el data.json tiene todos los campos obligatorios y que tanto los campos obligatorios como los opcionales siguen la estructura definida en el schema. Args: ...
def _write_wrapper(self, name): """Wrap write() to adapt return value for Python 2. Returns: Wrapper which is described below. """ io_attr = getattr(self._io, name) def write_wrapper(*args, **kwargs): """Wrap all write calls to the stream object.""" ...
Wrap write() to adapt return value for Python 2. Returns: Wrapper which is described below.
Below is the the instruction that describes the task: ### Input: Wrap write() to adapt return value for Python 2. Returns: Wrapper which is described below. ### Response: def _write_wrapper(self, name): """Wrap write() to adapt return value for Python 2. Returns: W...
def advance_job_status(namespace: str, job: Job, duration: float, err: Optional[Exception]): """Advance the status of a job depending on its execution. This function is called after a job has been executed. It calculates its next status and calls the appropriate signals. """ ...
Advance the status of a job depending on its execution. This function is called after a job has been executed. It calculates its next status and calls the appropriate signals.
Below is the the instruction that describes the task: ### Input: Advance the status of a job depending on its execution. This function is called after a job has been executed. It calculates its next status and calls the appropriate signals. ### Response: def advance_job_status(namespace: str, job: Job, du...
def pipes(stream, *transformers): """Pipe several transformers end to end.""" for transformer in transformers: stream = stream.pipe(transformer) return stream
Pipe several transformers end to end.
Below is the the instruction that describes the task: ### Input: Pipe several transformers end to end. ### Response: def pipes(stream, *transformers): """Pipe several transformers end to end.""" for transformer in transformers: stream = stream.pipe(transformer) return stream
def delete(queue, items): ''' Delete an item or items from a queue ''' with _conn(commit=True) as cur: if isinstance(items, dict): cmd = str("""DELETE FROM {0} WHERE data = '{1}'""").format( # future lint: disable=blacklisted-function queue, salt.util...
Delete an item or items from a queue
Below is the the instruction that describes the task: ### Input: Delete an item or items from a queue ### Response: def delete(queue, items): ''' Delete an item or items from a queue ''' with _conn(commit=True) as cur: if isinstance(items, dict): cmd = str("""DELETE FROM {0} WHE...
def aggregate(self, aggregates=None, drilldowns=None, cuts=None, order=None, page=None, page_size=None, page_max=None): """Main aggregation function. This is used to compute a given set of aggregates, grouped by a given set of drilldown dimensions (i.e. dividers). The query can...
Main aggregation function. This is used to compute a given set of aggregates, grouped by a given set of drilldown dimensions (i.e. dividers). The query can also be filtered and sorted.
Below is the the instruction that describes the task: ### Input: Main aggregation function. This is used to compute a given set of aggregates, grouped by a given set of drilldown dimensions (i.e. dividers). The query can also be filtered and sorted. ### Response: def aggregate(self, aggregates=None...
def add_size_info (self): """Get size of URL content from HTTP header.""" if self.headers and "Content-Length" in self.headers and \ "Transfer-Encoding" not in self.headers: # Note that content-encoding causes size differences since # the content data is always decoded...
Get size of URL content from HTTP header.
Below is the the instruction that describes the task: ### Input: Get size of URL content from HTTP header. ### Response: def add_size_info (self): """Get size of URL content from HTTP header.""" if self.headers and "Content-Length" in self.headers and \ "Transfer-Encoding" not in self.he...
def get_parameter_dict(self, include_frozen=False): """ Get an ordered dictionary of the parameters Args: include_frozen (Optional[bool]): Should the frozen parameters be included in the returned value? (default: ``False``) """ return OrderedDict(zip...
Get an ordered dictionary of the parameters Args: include_frozen (Optional[bool]): Should the frozen parameters be included in the returned value? (default: ``False``)
Below is the the instruction that describes the task: ### Input: Get an ordered dictionary of the parameters Args: include_frozen (Optional[bool]): Should the frozen parameters be included in the returned value? (default: ``False``) ### Response: def get_parameter_dict(self, in...
def _other_dpss_method(N, NW, Kmax): """Returns the Discrete Prolate Spheroidal Sequences of orders [0,Kmax-1] for a given frequency-spacing multiple NW and sequence length N. See dpss function that is the official version. This version is indepedant of the C code and relies on Scipy function. However,...
Returns the Discrete Prolate Spheroidal Sequences of orders [0,Kmax-1] for a given frequency-spacing multiple NW and sequence length N. See dpss function that is the official version. This version is indepedant of the C code and relies on Scipy function. However, it is slower by a factor 3 Tridiagonal...
Below is the the instruction that describes the task: ### Input: Returns the Discrete Prolate Spheroidal Sequences of orders [0,Kmax-1] for a given frequency-spacing multiple NW and sequence length N. See dpss function that is the official version. This version is indepedant of the C code and relies on...
def attach_http_service(cls, http_service: HTTPService): """ Attaches a service for hosting :param http_service: A HTTPService instance """ if cls._http_service is None: cls._http_service = http_service cls._set_bus(http_service) else: warnings...
Attaches a service for hosting :param http_service: A HTTPService instance
Below is the the instruction that describes the task: ### Input: Attaches a service for hosting :param http_service: A HTTPService instance ### Response: def attach_http_service(cls, http_service: HTTPService): """ Attaches a service for hosting :param http_service: A HTTPService instance ...
def open(self, url): """ Open a WSDL at the specified I{url}. First, the WSDL attempted to be retrieved from the I{object cache}. After unpickled from the cache, the I{options} attribute is restored. If not found, it is downloaded and instantiated using the I{fn}...
Open a WSDL at the specified I{url}. First, the WSDL attempted to be retrieved from the I{object cache}. After unpickled from the cache, the I{options} attribute is restored. If not found, it is downloaded and instantiated using the I{fn} constructor and added to the cache for t...
Below is the the instruction that describes the task: ### Input: Open a WSDL at the specified I{url}. First, the WSDL attempted to be retrieved from the I{object cache}. After unpickled from the cache, the I{options} attribute is restored. If not found, it is downloaded and instanti...
def parse_sections(self, offset): """Fetch the PE file sections. The sections will be readily available in the "sections" attribute. Its attributes will contain all the section information plus "data" a buffer containing the section's data. The "Characteristics"...
Fetch the PE file sections. The sections will be readily available in the "sections" attribute. Its attributes will contain all the section information plus "data" a buffer containing the section's data. The "Characteristics" member will be processed and attributes ...
Below is the the instruction that describes the task: ### Input: Fetch the PE file sections. The sections will be readily available in the "sections" attribute. Its attributes will contain all the section information plus "data" a buffer containing the section's data. ...
def visit(self, visitor, predicate=None, **kw): """ Apply a function to matching nodes in the (sub)tree rooted at self. :param visitor: A callable accepting a Node object as single argument.. :param predicate: A callable accepting a Node object as single argument and \ returning...
Apply a function to matching nodes in the (sub)tree rooted at self. :param visitor: A callable accepting a Node object as single argument.. :param predicate: A callable accepting a Node object as single argument and \ returning a boolean signaling whether Node matches; if `None` all nodes match...
Below is the the instruction that describes the task: ### Input: Apply a function to matching nodes in the (sub)tree rooted at self. :param visitor: A callable accepting a Node object as single argument.. :param predicate: A callable accepting a Node object as single argument and \ returnin...
def sample_categorical(prob, rng): """Sample from independent categorical distributions Each batch is an independent categorical distribution. Parameters ---------- prob : numpy.ndarray Probability of the categorical distribution. Shape --> (batch_num, category_num) rng : numpy.random.Ra...
Sample from independent categorical distributions Each batch is an independent categorical distribution. Parameters ---------- prob : numpy.ndarray Probability of the categorical distribution. Shape --> (batch_num, category_num) rng : numpy.random.RandomState Returns ------- ret...
Below is the the instruction that describes the task: ### Input: Sample from independent categorical distributions Each batch is an independent categorical distribution. Parameters ---------- prob : numpy.ndarray Probability of the categorical distribution. Shape --> (batch_num, category_num...
def get_module_verbosity_flags(*labels): """ checks for standard flags for enableing module specific verbosity """ verbose_prefix_list = ['--verbose-', '--verb', '--verb-'] veryverbose_prefix_list = ['--veryverbose-', '--veryverb', '--veryverb-'] verbose_flags = tuple( [prefix + lbl for prefix, ...
checks for standard flags for enableing module specific verbosity
Below is the the instruction that describes the task: ### Input: checks for standard flags for enableing module specific verbosity ### Response: def get_module_verbosity_flags(*labels): """ checks for standard flags for enableing module specific verbosity """ verbose_prefix_list = ['--verbose-', '--verb', ...
def from_export(cls, endpoint): # type: (ExportEndpoint) -> EndpointDescription """ Converts an ExportEndpoint bean to an EndpointDescription :param endpoint: An ExportEndpoint bean :return: An EndpointDescription bean """ assert isinstance(endpoint, ExportEndpoi...
Converts an ExportEndpoint bean to an EndpointDescription :param endpoint: An ExportEndpoint bean :return: An EndpointDescription bean
Below is the the instruction that describes the task: ### Input: Converts an ExportEndpoint bean to an EndpointDescription :param endpoint: An ExportEndpoint bean :return: An EndpointDescription bean ### Response: def from_export(cls, endpoint): # type: (ExportEndpoint) -> EndpointDescript...
def addHydrogens(molecule, usedPyroles=None): """(molecule) -> add implicit hydrogens to a molecule. If the atom has specified valences and the atom must be charged then a Valence Error is raised""" for atom in molecule.atoms: # if the atom has an explicit hcount, we can't set the # hcou...
(molecule) -> add implicit hydrogens to a molecule. If the atom has specified valences and the atom must be charged then a Valence Error is raised
Below is the the instruction that describes the task: ### Input: (molecule) -> add implicit hydrogens to a molecule. If the atom has specified valences and the atom must be charged then a Valence Error is raised ### Response: def addHydrogens(molecule, usedPyroles=None): """(molecule) -> add implicit h...
def _set_load_interval(self, v, load=False): """ Setter method for load_interval, mapped from YANG variable /mpls_config/router/mpls/mpls_cmds_holder/policy/load_interval (uint32) If this variable is read-only (config: false) in the source YANG file, then _set_load_interval is considered as a private ...
Setter method for load_interval, mapped from YANG variable /mpls_config/router/mpls/mpls_cmds_holder/policy/load_interval (uint32) If this variable is read-only (config: false) in the source YANG file, then _set_load_interval is considered as a private method. Backends looking to populate this variable shou...
Below is the the instruction that describes the task: ### Input: Setter method for load_interval, mapped from YANG variable /mpls_config/router/mpls/mpls_cmds_holder/policy/load_interval (uint32) If this variable is read-only (config: false) in the source YANG file, then _set_load_interval is considered as ...
def cd_to(path, mkdir=False): """make a generator like cd, but use it for function Usage:: >>> @cd_to("/") ... def say_where(): ... print(os.getcwd()) ... >>> say_where() / """ def cd_to_decorator(func): @functools.wraps(func) def _c...
make a generator like cd, but use it for function Usage:: >>> @cd_to("/") ... def say_where(): ... print(os.getcwd()) ... >>> say_where() /
Below is the the instruction that describes the task: ### Input: make a generator like cd, but use it for function Usage:: >>> @cd_to("/") ... def say_where(): ... print(os.getcwd()) ... >>> say_where() / ### Response: def cd_to(path, mkdir=False): """m...
def sparql_query(self, query, flush=None, limit=None): """ Run a Sparql query. :param query: sparql query string :rtype: list of dictionary """ return self.find_statements(query, language='sparql', type='tuples', flush=flush, limit=limit)
Run a Sparql query. :param query: sparql query string :rtype: list of dictionary
Below is the the instruction that describes the task: ### Input: Run a Sparql query. :param query: sparql query string :rtype: list of dictionary ### Response: def sparql_query(self, query, flush=None, limit=None): """ Run a Sparql query. :param query: sparql query string ...
def _preprocess(self, struct1, struct2, niggli=True): """ Rescales, finds the reduced structures (primitive and niggli), and finds fu, the supercell size to make struct1 comparable to s2 """ struct1 = struct1.copy() struct2 = struct2.copy() if niggli: ...
Rescales, finds the reduced structures (primitive and niggli), and finds fu, the supercell size to make struct1 comparable to s2
Below is the the instruction that describes the task: ### Input: Rescales, finds the reduced structures (primitive and niggli), and finds fu, the supercell size to make struct1 comparable to s2 ### Response: def _preprocess(self, struct1, struct2, niggli=True): """ Rescales, finds t...