code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
text
stringlengths
164
112k
def validate(self, **kwargs): '''Validate device group state among given devices. :param kwargs: dict -- keyword args of device group information :raises: UnexpectedDeviceGroupType, UnexpectedDeviceGroupDevices ''' self._set_attributes(**kwargs) self._check_type() ...
Validate device group state among given devices. :param kwargs: dict -- keyword args of device group information :raises: UnexpectedDeviceGroupType, UnexpectedDeviceGroupDevices
Below is the the instruction that describes the task: ### Input: Validate device group state among given devices. :param kwargs: dict -- keyword args of device group information :raises: UnexpectedDeviceGroupType, UnexpectedDeviceGroupDevices ### Response: def validate(self, **kwargs): '''...
def grid(self,EdgeAttribute=None,network=None,NodeAttribute=None,\ nodeHorizontalSpacing=None,nodeList=None,nodeVerticalSpacing=None,verbose=None): """ Execute the Grid Layout on a network. :param EdgeAttribute (string, optional): The name of the edge column contai ning numeric values that will be used as w...
Execute the Grid Layout on a network. :param EdgeAttribute (string, optional): The name of the edge column contai ning numeric values that will be used as weights in the layout algor ithm. Only columns containing numeric values are shown :param network (string, optional): Specifies a network by name, or by S...
Below is the the instruction that describes the task: ### Input: Execute the Grid Layout on a network. :param EdgeAttribute (string, optional): The name of the edge column contai ning numeric values that will be used as weights in the layout algor ithm. Only columns containing numeric values are shown :p...
def ReadConflict(self, conflict_link, options=None): """Reads a conflict. :param str conflict_link: The link to the conflict. :param dict options: :return: The read Conflict. :rtype: dict """ if options is None: o...
Reads a conflict. :param str conflict_link: The link to the conflict. :param dict options: :return: The read Conflict. :rtype: dict
Below is the the instruction that describes the task: ### Input: Reads a conflict. :param str conflict_link: The link to the conflict. :param dict options: :return: The read Conflict. :rtype: dict ### Response: def ReadConflict(self, conflict_li...
def on_hazard_exposure_bookmark_toggled(self, enabled): """Update the UI when the user toggles the bookmarks radiobutton. :param enabled: The status of the radiobutton. :type enabled: bool """ if enabled: self.bookmarks_index_changed() else: self....
Update the UI when the user toggles the bookmarks radiobutton. :param enabled: The status of the radiobutton. :type enabled: bool
Below is the the instruction that describes the task: ### Input: Update the UI when the user toggles the bookmarks radiobutton. :param enabled: The status of the radiobutton. :type enabled: bool ### Response: def on_hazard_exposure_bookmark_toggled(self, enabled): """Update the UI when the...
async def set_power(self, value: bool): """Toggle the device on and off.""" if value: status = "active" else: status = "off" # TODO WoL works when quickboot is not enabled return await self.services["system"]["setPowerStatus"](status=status)
Toggle the device on and off.
Below is the the instruction that describes the task: ### Input: Toggle the device on and off. ### Response: async def set_power(self, value: bool): """Toggle the device on and off.""" if value: status = "active" else: status = "off" # TODO WoL works when qui...
def mute(self): """Mutes all existing communication, most notably the device will no longer generate a 13.56 MHz carrier signal when operating as Initiator. """ fname = "mute" cname = self.__class__.__module__ + '.' + self.__class__.__name__ raise NotImplementedE...
Mutes all existing communication, most notably the device will no longer generate a 13.56 MHz carrier signal when operating as Initiator.
Below is the the instruction that describes the task: ### Input: Mutes all existing communication, most notably the device will no longer generate a 13.56 MHz carrier signal when operating as Initiator. ### Response: def mute(self): """Mutes all existing communication, most notably the devi...
def params(self) -> T.List[DocstringParam]: """Return parameters indicated in docstring.""" return [ DocstringParam.from_meta(meta) for meta in self.meta if meta.args[0] in {"param", "parameter", "arg", "argument", "key", "keyword"} ]
Return parameters indicated in docstring.
Below is the the instruction that describes the task: ### Input: Return parameters indicated in docstring. ### Response: def params(self) -> T.List[DocstringParam]: """Return parameters indicated in docstring.""" return [ DocstringParam.from_meta(meta) for meta in self.meta ...
def getInstalledOfferings(self): """ Return a mapping from the name of each L{InstalledOffering} in C{self._siteStore} to the corresponding L{IOffering} plugins. """ d = {} installed = self._siteStore.query(InstalledOffering) for installation in installed: ...
Return a mapping from the name of each L{InstalledOffering} in C{self._siteStore} to the corresponding L{IOffering} plugins.
Below is the the instruction that describes the task: ### Input: Return a mapping from the name of each L{InstalledOffering} in C{self._siteStore} to the corresponding L{IOffering} plugins. ### Response: def getInstalledOfferings(self): """ Return a mapping from the name of each L{Installed...
def html_authors(self): """HTML5-formatted authors (`list` of `str`).""" return self.format_authors(format='html5', deparagraph=True, mathjax=False, smart=True)
HTML5-formatted authors (`list` of `str`).
Below is the the instruction that describes the task: ### Input: HTML5-formatted authors (`list` of `str`). ### Response: def html_authors(self): """HTML5-formatted authors (`list` of `str`).""" return self.format_authors(format='html5', deparagraph=True, mathjax=...
def unwrap_raw(content): """ unwraps the callback and returns the raw content """ starting_symbol = get_start_symbol(content) ending_symbol = ']' if starting_symbol == '[' else '}' start = content.find(starting_symbol, 0) end = content.rfind(ending_symbol) return content[start:end+1]
unwraps the callback and returns the raw content
Below is the the instruction that describes the task: ### Input: unwraps the callback and returns the raw content ### Response: def unwrap_raw(content): """ unwraps the callback and returns the raw content """ starting_symbol = get_start_symbol(content) ending_symbol = ']' if starting_symbol == '['...
def _get_all_positional_parameter_names(fn): """Returns the names of all positional arguments to the given function.""" arg_spec = _get_cached_arg_spec(fn) args = arg_spec.args if arg_spec.defaults: args = args[:-len(arg_spec.defaults)] return args
Returns the names of all positional arguments to the given function.
Below is the the instruction that describes the task: ### Input: Returns the names of all positional arguments to the given function. ### Response: def _get_all_positional_parameter_names(fn): """Returns the names of all positional arguments to the given function.""" arg_spec = _get_cached_arg_spec(fn) args ...
def supernodes(self, reordered = True): """ Returns a list of supernode sets """ if reordered: return [list(self.snode[self.snptr[k]:self.snptr[k+1]]) for k in range(self.Nsn)] else: return [list(self.__p[self.snode[self.snptr[k]:self.snptr[k+1]]]) for k i...
Returns a list of supernode sets
Below is the the instruction that describes the task: ### Input: Returns a list of supernode sets ### Response: def supernodes(self, reordered = True): """ Returns a list of supernode sets """ if reordered: return [list(self.snode[self.snptr[k]:self.snptr[k+1]]) for k in...
def run(self, circuit): """Run all the passes on a QuantumCircuit Args: circuit (QuantumCircuit): circuit to transform via all the registered passes Returns: QuantumCircuit: Transformed circuit. """ name = circuit.name dag = circuit_to_dag(circui...
Run all the passes on a QuantumCircuit Args: circuit (QuantumCircuit): circuit to transform via all the registered passes Returns: QuantumCircuit: Transformed circuit.
Below is the the instruction that describes the task: ### Input: Run all the passes on a QuantumCircuit Args: circuit (QuantumCircuit): circuit to transform via all the registered passes Returns: QuantumCircuit: Transformed circuit. ### Response: def run(self, circuit): ...
def start(self): """ Start the worker processes. TODO: Move task receiving to a thread """ start = time.time() self._kill_event = threading.Event() self.procs = {} for worker_id in range(self.worker_count): p = multiprocessing.Process(target=worker, ...
Start the worker processes. TODO: Move task receiving to a thread
Below is the the instruction that describes the task: ### Input: Start the worker processes. TODO: Move task receiving to a thread ### Response: def start(self): """ Start the worker processes. TODO: Move task receiving to a thread """ start = time.time() self._kil...
def register(request): ''' Register new user. ''' serializer_class = registration_settings.REGISTER_SERIALIZER_CLASS serializer = serializer_class(data=request.data) serializer.is_valid(raise_exception=True) kwargs = {} if registration_settings.REGISTER_VERIFICATION_ENABLED: ve...
Register new user.
Below is the the instruction that describes the task: ### Input: Register new user. ### Response: def register(request): ''' Register new user. ''' serializer_class = registration_settings.REGISTER_SERIALIZER_CLASS serializer = serializer_class(data=request.data) serializer.is_valid(raise_e...
def _get_optional_args(args, opts, err_on_missing=False, **kwargs): """Convenience function to retrieve arguments from an argparse namespace. Parameters ---------- args : list of str List of arguments to retreive. opts : argparse.namespace Namespa...
Convenience function to retrieve arguments from an argparse namespace. Parameters ---------- args : list of str List of arguments to retreive. opts : argparse.namespace Namespace to retreive arguments for. err_on_missing : bool, optional ...
Below is the the instruction that describes the task: ### Input: Convenience function to retrieve arguments from an argparse namespace. Parameters ---------- args : list of str List of arguments to retreive. opts : argparse.namespace Namespace to retr...
def encode16Int(value): ''' Encodes a 16 bit unsigned integer into MQTT format. Returns a bytearray ''' value = int(value) encoded = bytearray(2) encoded[0] = value >> 8 encoded[1] = value & 0xFF return encoded
Encodes a 16 bit unsigned integer into MQTT format. Returns a bytearray
Below is the the instruction that describes the task: ### Input: Encodes a 16 bit unsigned integer into MQTT format. Returns a bytearray ### Response: def encode16Int(value): ''' Encodes a 16 bit unsigned integer into MQTT format. Returns a bytearray ''' value = int(value) encoded ...
def _wait_and_except_if_failed(self, event, timeout=None): """Combines waiting for event and call to `_except_if_failed`. If timeout is not specified the configured sync_timeout is used. """ event.wait(timeout or self.__sync_timeout) self._except_if_failed(event)
Combines waiting for event and call to `_except_if_failed`. If timeout is not specified the configured sync_timeout is used.
Below is the the instruction that describes the task: ### Input: Combines waiting for event and call to `_except_if_failed`. If timeout is not specified the configured sync_timeout is used. ### Response: def _wait_and_except_if_failed(self, event, timeout=None): """Combines waiting for event and ca...
def register_module_alias(self, alias, module_path, after_init=False): """Adds an alias for a module. http://uwsgi-docs.readthedocs.io/en/latest/PythonModuleAlias.html :param str|unicode alias: :param str|unicode module_path: :param bool after_init: add a python module alias af...
Adds an alias for a module. http://uwsgi-docs.readthedocs.io/en/latest/PythonModuleAlias.html :param str|unicode alias: :param str|unicode module_path: :param bool after_init: add a python module alias after uwsgi module initialization
Below is the the instruction that describes the task: ### Input: Adds an alias for a module. http://uwsgi-docs.readthedocs.io/en/latest/PythonModuleAlias.html :param str|unicode alias: :param str|unicode module_path: :param bool after_init: add a python module alias after uwsgi mod...
def compute_err(self, solution_y, coefficients): """ Return an error value by finding the absolute difference for each element in a list of solution-generated y-values versus expected values. Compounds error by 50% for each negative coefficient in the solution. solution_y: lis...
Return an error value by finding the absolute difference for each element in a list of solution-generated y-values versus expected values. Compounds error by 50% for each negative coefficient in the solution. solution_y: list of y-values produced by a solution coefficients: list of p...
Below is the the instruction that describes the task: ### Input: Return an error value by finding the absolute difference for each element in a list of solution-generated y-values versus expected values. Compounds error by 50% for each negative coefficient in the solution. solution_y: lis...
def build_endpoint_route_name(cls, method_name, class_name=None): """ Build the route endpoint It is recommended to place your views in /views directory, so it can build the endpoint from it. If not, it will make the endpoint from the module name The main reason for having the views directory, it is...
Build the route endpoint It is recommended to place your views in /views directory, so it can build the endpoint from it. If not, it will make the endpoint from the module name The main reason for having the views directory, it is explicitly easy to see the path of the view :param cls: The view cla...
Below is the the instruction that describes the task: ### Input: Build the route endpoint It is recommended to place your views in /views directory, so it can build the endpoint from it. If not, it will make the endpoint from the module name The main reason for having the views directory, it is explicit...
def emg_parameters(data, sample_rate, raw_to_mv=True, device="biosignalsplux", resolution=16): """ ----- Brief ----- Function for extracting EMG parameters from time and frequency domains. ----------- Description ----------- EMG signals have specific properties that are different fr...
----- Brief ----- Function for extracting EMG parameters from time and frequency domains. ----------- Description ----------- EMG signals have specific properties that are different from other biosignals. For example, it is not periodic, contrary to ECG signals. This type of biosign...
Below is the the instruction that describes the task: ### Input: ----- Brief ----- Function for extracting EMG parameters from time and frequency domains. ----------- Description ----------- EMG signals have specific properties that are different from other biosignals. For example, it i...
def points(self): """ returns a pointer to the points as a numpy object """ # Get grid dimensions nx, ny, nz = self.dimensions nx -= 1 ny -= 1 nz -= 1 # get the points and convert to spacings dx, dy, dz = self.spacing # Now make the cell arrays ...
returns a pointer to the points as a numpy object
Below is the the instruction that describes the task: ### Input: returns a pointer to the points as a numpy object ### Response: def points(self): """ returns a pointer to the points as a numpy object """ # Get grid dimensions nx, ny, nz = self.dimensions nx -= 1 ny -= 1 ...
def _internal_sub(self, other, method=None): """ Used for specifing addition methods for __add__, __iadd__, __radd__ """ if hasattr(other, "datatype"): if other.datatype == self.datatype: oval = other.value else: oval = int(other...
Used for specifing addition methods for __add__, __iadd__, __radd__
Below is the the instruction that describes the task: ### Input: Used for specifing addition methods for __add__, __iadd__, __radd__ ### Response: def _internal_sub(self, other, method=None): """ Used for specifing addition methods for __add__, __iadd__, __radd__ """ i...
def set_interrupt_limits(self, low, high): """Set the interrupt limits to provied unsigned 16-bit threshold values. """ self.i2c.write8(0x04, low & 0xFF) self.i2c.write8(0x05, low >> 8) self.i2c.write8(0x06, high & 0xFF) self.i2c.write8(0x07, high >> 8)
Set the interrupt limits to provied unsigned 16-bit threshold values.
Below is the the instruction that describes the task: ### Input: Set the interrupt limits to provied unsigned 16-bit threshold values. ### Response: def set_interrupt_limits(self, low, high): """Set the interrupt limits to provied unsigned 16-bit threshold values. """ self.i2c.write8(0x04, ...
def ensure_dir(path): """ :param path: path to directory to be created Create a directory if it does not already exist. """ if not os.path.exists(path): # path does not exist, create the directory os.mkdir(path) else: # The path exists, check that it is not a file ...
:param path: path to directory to be created Create a directory if it does not already exist.
Below is the the instruction that describes the task: ### Input: :param path: path to directory to be created Create a directory if it does not already exist. ### Response: def ensure_dir(path): """ :param path: path to directory to be created Create a directory if it does not already exist. ...
def get_scheme_cartocss(column, scheme_info): """Get TurboCARTO CartoCSS based on input parameters""" if 'colors' in scheme_info: color_scheme = '({})'.format(','.join(scheme_info['colors'])) else: color_scheme = 'cartocolor({})'.format(scheme_info['name']) if not isinstance(scheme_info[...
Get TurboCARTO CartoCSS based on input parameters
Below is the the instruction that describes the task: ### Input: Get TurboCARTO CartoCSS based on input parameters ### Response: def get_scheme_cartocss(column, scheme_info): """Get TurboCARTO CartoCSS based on input parameters""" if 'colors' in scheme_info: color_scheme = '({})'.format(','.join(sc...
def save(self, path_info, checksum): """Save checksum for the specified path info. Args: path_info (dict): path_info to save checksum for. checksum (str): checksum to save. """ assert path_info["scheme"] == "local" assert checksum is not None pat...
Save checksum for the specified path info. Args: path_info (dict): path_info to save checksum for. checksum (str): checksum to save.
Below is the the instruction that describes the task: ### Input: Save checksum for the specified path info. Args: path_info (dict): path_info to save checksum for. checksum (str): checksum to save. ### Response: def save(self, path_info, checksum): """Save checksum for the ...
def close(self): """This method closes the canvas and writes contents to the associated file. Calling this procedure is optional, because Pychart calls this procedure for every open canvas on normal exit.""" for i in range(0, len(active_canvases)): if active_canvases[...
This method closes the canvas and writes contents to the associated file. Calling this procedure is optional, because Pychart calls this procedure for every open canvas on normal exit.
Below is the the instruction that describes the task: ### Input: This method closes the canvas and writes contents to the associated file. Calling this procedure is optional, because Pychart calls this procedure for every open canvas on normal exit. ### Response: def close(self): ""...
def toggle_codecompletion(self, checked): """Toggle automatic code completion""" self.shell.set_codecompletion_auto(checked) self.set_option('codecompletion/auto', checked)
Toggle automatic code completion
Below is the the instruction that describes the task: ### Input: Toggle automatic code completion ### Response: def toggle_codecompletion(self, checked): """Toggle automatic code completion""" self.shell.set_codecompletion_auto(checked) self.set_option('codecompletion/auto', checked)
def enable(self, cmd="enable-admin", pattern="ssword", re_flags=re.IGNORECASE): """Enter enable mode.""" return super(AlcatelSrosSSH, self).enable( cmd=cmd, pattern=pattern, re_flags=re_flags )
Enter enable mode.
Below is the the instruction that describes the task: ### Input: Enter enable mode. ### Response: def enable(self, cmd="enable-admin", pattern="ssword", re_flags=re.IGNORECASE): """Enter enable mode.""" return super(AlcatelSrosSSH, self).enable( cmd=cmd, pattern=pattern, re_flags=re_fla...
def get_m49_from_iso3(cls, iso3, use_live=True, exception=None): # type: (str, bool, Optional[ExceptionUpperBound]) -> Optional[int] """Get M49 from ISO3 code Args: iso3 (str): ISO3 code for which to get M49 code use_live (bool): Try to get use latest data from web rathe...
Get M49 from ISO3 code Args: iso3 (str): ISO3 code for which to get M49 code use_live (bool): Try to get use latest data from web rather than file in package. Defaults to True. exception (Optional[ExceptionUpperBound]): An exception to raise if country not found. Defaults to...
Below is the the instruction that describes the task: ### Input: Get M49 from ISO3 code Args: iso3 (str): ISO3 code for which to get M49 code use_live (bool): Try to get use latest data from web rather than file in package. Defaults to True. exception (Optional[Exception...
def build(self, builder): """Build XML by appending to builder""" builder.start("BasicDefinitions", {}) for child in self.measurement_units: child.build(builder) builder.end("BasicDefinitions")
Build XML by appending to builder
Below is the the instruction that describes the task: ### Input: Build XML by appending to builder ### Response: def build(self, builder): """Build XML by appending to builder""" builder.start("BasicDefinitions", {}) for child in self.measurement_units: child.build(builder) ...
def download(self, remotepath = '/', localpath = ''): ''' Usage: download [remotepath] [localpath] - \ download a remote directory (recursively) / file remotepath - remote path at Baidu Yun (after app root directory), if not specified, it is set to the root directory at Baidu Yun localpath - local path. if not sp...
Usage: download [remotepath] [localpath] - \ download a remote directory (recursively) / file remotepath - remote path at Baidu Yun (after app root directory), if not specified, it is set to the root directory at Baidu Yun localpath - local path. if not specified, it is set to the current directory
Below is the the instruction that describes the task: ### Input: Usage: download [remotepath] [localpath] - \ download a remote directory (recursively) / file remotepath - remote path at Baidu Yun (after app root directory), if not specified, it is set to the root directory at Baidu Yun localpath - local path. ...
def assign(self, node): """ Translate an assign node into SQLQuery. :param node: a treebrd node :return: a SQLQuery object for the tree rooted at node """ child_object = self.translate(node.child) child_object.prefix = 'CREATE TEMPORARY TABLE {name}({attributes}) ...
Translate an assign node into SQLQuery. :param node: a treebrd node :return: a SQLQuery object for the tree rooted at node
Below is the the instruction that describes the task: ### Input: Translate an assign node into SQLQuery. :param node: a treebrd node :return: a SQLQuery object for the tree rooted at node ### Response: def assign(self, node): """ Translate an assign node into SQLQuery. :para...
def rbnf_lexing(text: str): """Read loudly for documentation.""" cast_map: const = _cast_map lexer_table: const = _lexer_table keyword: const = _keyword drop_table: const = _DropTable end: const = _END unknown: const = _UNKNOWN text_length = len(text) colno ...
Read loudly for documentation.
Below is the the instruction that describes the task: ### Input: Read loudly for documentation. ### Response: def rbnf_lexing(text: str): """Read loudly for documentation.""" cast_map: const = _cast_map lexer_table: const = _lexer_table keyword: const = _keyword drop_table: const = _Dr...
def safe_eval(value): """ Converts the inputted text value to a standard python value (if possible). :param value | <str> || <unicode> :return <variant> """ if not isinstance(value, (str, unicode)): return value try: return CONSTANT_EVALS[value] except KeyErro...
Converts the inputted text value to a standard python value (if possible). :param value | <str> || <unicode> :return <variant>
Below is the the instruction that describes the task: ### Input: Converts the inputted text value to a standard python value (if possible). :param value | <str> || <unicode> :return <variant> ### Response: def safe_eval(value): """ Converts the inputted text value to a standard python va...
def monitor_key_exists(service, key): """ Searches for the existence of a key in the monitor cluster. :param service: six.string_types. The Ceph user name to run the command under :param key: six.string_types. The key to search for :return: Returns True if the key exists, False if not and raises an...
Searches for the existence of a key in the monitor cluster. :param service: six.string_types. The Ceph user name to run the command under :param key: six.string_types. The key to search for :return: Returns True if the key exists, False if not and raises an exception if an unknown error occurs. :raise...
Below is the the instruction that describes the task: ### Input: Searches for the existence of a key in the monitor cluster. :param service: six.string_types. The Ceph user name to run the command under :param key: six.string_types. The key to search for :return: Returns True if the key exists, False i...
def _parse_query(self, source): """Parse one of the rules as either objectfilter or dottysql. Example: _parse_query("5 + 5") # Returns Sum(Literal(5), Literal(5)) Arguments: source: A rule in either objectfilter or dottysql syntax. Returns: ...
Parse one of the rules as either objectfilter or dottysql. Example: _parse_query("5 + 5") # Returns Sum(Literal(5), Literal(5)) Arguments: source: A rule in either objectfilter or dottysql syntax. Returns: The AST to represent the rule.
Below is the the instruction that describes the task: ### Input: Parse one of the rules as either objectfilter or dottysql. Example: _parse_query("5 + 5") # Returns Sum(Literal(5), Literal(5)) Arguments: source: A rule in either objectfilter or dottysql syntax. ...
def parse_encoded_styles(text, normalize_key=None): """ Parse text styles encoded in a string into a nested data structure. :param text: The encoded styles (a string). :returns: A dictionary in the structure of the :data:`DEFAULT_FIELD_STYLES` and :data:`DEFAULT_LEVEL_STYLES` dictionaries...
Parse text styles encoded in a string into a nested data structure. :param text: The encoded styles (a string). :returns: A dictionary in the structure of the :data:`DEFAULT_FIELD_STYLES` and :data:`DEFAULT_LEVEL_STYLES` dictionaries. Here's an example of how this function works: >>> fr...
Below is the the instruction that describes the task: ### Input: Parse text styles encoded in a string into a nested data structure. :param text: The encoded styles (a string). :returns: A dictionary in the structure of the :data:`DEFAULT_FIELD_STYLES` and :data:`DEFAULT_LEVEL_STYLES` diction...
def GetPointWithDistanceTraveled(self, shape_dist_traveled): """Returns a point on the shape polyline with the input shape_dist_traveled. Args: shape_dist_traveled: The input shape_dist_traveled. Returns: The shape point as a tuple (lat, lng, shape_dist_traveled), where lat and lng is th...
Returns a point on the shape polyline with the input shape_dist_traveled. Args: shape_dist_traveled: The input shape_dist_traveled. Returns: The shape point as a tuple (lat, lng, shape_dist_traveled), where lat and lng is the location of the shape point, and shape_dist_traveled is an i...
Below is the the instruction that describes the task: ### Input: Returns a point on the shape polyline with the input shape_dist_traveled. Args: shape_dist_traveled: The input shape_dist_traveled. Returns: The shape point as a tuple (lat, lng, shape_dist_traveled), where lat and lng is t...
def new_context(environment, template_name, blocks, vars=None, shared=None, globals=None, locals=None): """Internal helper to for context creation.""" if vars is None: vars = {} if shared: parent = vars else: parent = dict(globals or (), **vars) if locals: ...
Internal helper to for context creation.
Below is the the instruction that describes the task: ### Input: Internal helper to for context creation. ### Response: def new_context(environment, template_name, blocks, vars=None, shared=None, globals=None, locals=None): """Internal helper to for context creation.""" if vars is None: ...
def create_training_job(self, config, wait_for_completion=True, print_log=True, check_interval=30, max_ingestion_time=None): """ Create a training job :param config: the config for training :type config: dict :param wait_for_completion: if the program...
Create a training job :param config: the config for training :type config: dict :param wait_for_completion: if the program should keep running until job finishes :type wait_for_completion: bool :param check_interval: the time interval in seconds which the operator wi...
Below is the the instruction that describes the task: ### Input: Create a training job :param config: the config for training :type config: dict :param wait_for_completion: if the program should keep running until job finishes :type wait_for_completion: bool :param check_int...
def _contains_nd(nodes, point): r"""Predicate indicating if a point is within a bounding box. .. note:: There is also a Fortran implementation of this function, which will be used if it can be built. Args: nodes (numpy.ndarray): A set of points. point (numpy.ndarray): A 1D Num...
r"""Predicate indicating if a point is within a bounding box. .. note:: There is also a Fortran implementation of this function, which will be used if it can be built. Args: nodes (numpy.ndarray): A set of points. point (numpy.ndarray): A 1D NumPy array representing a point ...
Below is the the instruction that describes the task: ### Input: r"""Predicate indicating if a point is within a bounding box. .. note:: There is also a Fortran implementation of this function, which will be used if it can be built. Args: nodes (numpy.ndarray): A set of points. ...
def getSequenceDollarID(self, strIndex, returnOffset=False): ''' This will take a given index and work backwards until it encounters a '$' indicating which dollar ID is associated with this read @param strIndex - the index of the character to start with @return - an integer indic...
This will take a given index and work backwards until it encounters a '$' indicating which dollar ID is associated with this read @param strIndex - the index of the character to start with @return - an integer indicating the dollar ID of the string the given character belongs to
Below is the the instruction that describes the task: ### Input: This will take a given index and work backwards until it encounters a '$' indicating which dollar ID is associated with this read @param strIndex - the index of the character to start with @return - an integer indicating the do...
def format_bytes(bytes): """ Get human readable version of given bytes. Ripped from https://github.com/rg3/youtube-dl """ if bytes is None: return 'N/A' if type(bytes) is str: bytes = float(bytes) if bytes == 0.0: exponent = 0 else: exponent = int(math.log...
Get human readable version of given bytes. Ripped from https://github.com/rg3/youtube-dl
Below is the the instruction that describes the task: ### Input: Get human readable version of given bytes. Ripped from https://github.com/rg3/youtube-dl ### Response: def format_bytes(bytes): """ Get human readable version of given bytes. Ripped from https://github.com/rg3/youtube-dl """ i...
def from_xml(xml): """ Pick informations from :class:`.MARCXMLRecord` object and use it to build :class:`.SemanticInfo` structure. Args: xml (str/MARCXMLRecord): MarcXML which will be converted to SemanticInfo. In case of str, ``<record>`` tag is required. ...
Pick informations from :class:`.MARCXMLRecord` object and use it to build :class:`.SemanticInfo` structure. Args: xml (str/MARCXMLRecord): MarcXML which will be converted to SemanticInfo. In case of str, ``<record>`` tag is required. Returns: structure: ...
Below is the the instruction that describes the task: ### Input: Pick informations from :class:`.MARCXMLRecord` object and use it to build :class:`.SemanticInfo` structure. Args: xml (str/MARCXMLRecord): MarcXML which will be converted to SemanticInfo. In case of str, ``...
def _format_list(self, extracted_list): """Format a list of traceback entry tuples for printing. Given a list of tuples as returned by extract_tb() or extract_stack(), return a list of strings ready for printing. Each string in the resulting list corresponds to the item with the ...
Format a list of traceback entry tuples for printing. Given a list of tuples as returned by extract_tb() or extract_stack(), return a list of strings ready for printing. Each string in the resulting list corresponds to the item with the same index in the argument list. Each string ends...
Below is the the instruction that describes the task: ### Input: Format a list of traceback entry tuples for printing. Given a list of tuples as returned by extract_tb() or extract_stack(), return a list of strings ready for printing. Each string in the resulting list corresponds to the ite...
def load_file(self, app, pathname, relpath, pypath): """Loads a file and creates a View from it. Files are split between a YAML front-matter and the content (unless it is a .yml file). """ try: view_class = self.get_file_view_cls(relpath) return create_view_from_f...
Loads a file and creates a View from it. Files are split between a YAML front-matter and the content (unless it is a .yml file).
Below is the the instruction that describes the task: ### Input: Loads a file and creates a View from it. Files are split between a YAML front-matter and the content (unless it is a .yml file). ### Response: def load_file(self, app, pathname, relpath, pypath): """Loads a file and creates a View fro...
def feed(self, from_date=None, from_offset=None, category=None, latest_items=None, arthur_items=None, filter_classified=None): """ Feed data in Elastic from Perceval or Arthur """ if self.fetch_archive: items = self.perceval_backend.fetch_from_archive() self.feed_it...
Feed data in Elastic from Perceval or Arthur
Below is the the instruction that describes the task: ### Input: Feed data in Elastic from Perceval or Arthur ### Response: def feed(self, from_date=None, from_offset=None, category=None, latest_items=None, arthur_items=None, filter_classified=None): """ Feed data in Elastic from Perceval or A...
def get_xattrs(self, path, xattr_name=None, encoding='text', **kwargs): """Get one or more xattr values for a file or directory. :param xattr_name: ``str`` to get one attribute, ``list`` to get multiple attributes, ``None`` to get all attributes. :param encoding: ``text`` | ``hex`` ...
Get one or more xattr values for a file or directory. :param xattr_name: ``str`` to get one attribute, ``list`` to get multiple attributes, ``None`` to get all attributes. :param encoding: ``text`` | ``hex`` | ``base64``, defaults to ``text`` :returns: Dictionary mapping xattr name...
Below is the the instruction that describes the task: ### Input: Get one or more xattr values for a file or directory. :param xattr_name: ``str`` to get one attribute, ``list`` to get multiple attributes, ``None`` to get all attributes. :param encoding: ``text`` | ``hex`` | ``base64``, ...
def transfer_to_row(self, new_row): """Transfer this instruction to a new row. :param knittingpattern.Row.Row new_row: the new row the instruction is in. """ if new_row != self._row: index = self.get_index_in_row() if index is not None: ...
Transfer this instruction to a new row. :param knittingpattern.Row.Row new_row: the new row the instruction is in.
Below is the the instruction that describes the task: ### Input: Transfer this instruction to a new row. :param knittingpattern.Row.Row new_row: the new row the instruction is in. ### Response: def transfer_to_row(self, new_row): """Transfer this instruction to a new row. :param...
def _chunk_iter_progress(it, log, prefix): """Wrap a chunk iterator for progress logging.""" n_variants = 0 before_all = time.time() before_chunk = before_all for chunk, chunk_length, chrom, pos in it: after_chunk = time.time() elapsed_chunk = after_chunk - before_chunk elaps...
Wrap a chunk iterator for progress logging.
Below is the the instruction that describes the task: ### Input: Wrap a chunk iterator for progress logging. ### Response: def _chunk_iter_progress(it, log, prefix): """Wrap a chunk iterator for progress logging.""" n_variants = 0 before_all = time.time() before_chunk = before_all for chunk, ch...
def _make_annulus_path(patch_inner, patch_outer): """ Defines a matplotlib annulus path from two patches. This preserves the cubic Bezier curves (CURVE4) of the aperture paths. # This is borrowed from photutils aperture. """ import matplotlib.path as mpath ...
Defines a matplotlib annulus path from two patches. This preserves the cubic Bezier curves (CURVE4) of the aperture paths. # This is borrowed from photutils aperture.
Below is the the instruction that describes the task: ### Input: Defines a matplotlib annulus path from two patches. This preserves the cubic Bezier curves (CURVE4) of the aperture paths. # This is borrowed from photutils aperture. ### Response: def _make_annulus_path(patch_inner, patch_o...
def _read( filename, schema, seq_label='sequence', alphabet=None, use_uids=True, **kwargs): """Use BioPython's sequence parsing module to convert any file format to a Pandas DataFrame. The resulting DataFrame has the following columns: - name - id - descripti...
Use BioPython's sequence parsing module to convert any file format to a Pandas DataFrame. The resulting DataFrame has the following columns: - name - id - description - sequence
Below is the the instruction that describes the task: ### Input: Use BioPython's sequence parsing module to convert any file format to a Pandas DataFrame. The resulting DataFrame has the following columns: - name - id - description - sequence ### Response: def _read( fi...
def QA_SU_save_stock_list(client=DATABASE, ui_log=None, ui_progress=None): """save stock_list Keyword Arguments: client {[type]} -- [description] (default: {DATABASE}) """ client.drop_collection('stock_list') coll = client.stock_list coll.create_index('code') try: # 🛠todo ...
save stock_list Keyword Arguments: client {[type]} -- [description] (default: {DATABASE})
Below is the the instruction that describes the task: ### Input: save stock_list Keyword Arguments: client {[type]} -- [description] (default: {DATABASE}) ### Response: def QA_SU_save_stock_list(client=DATABASE, ui_log=None, ui_progress=None): """save stock_list Keyword Arguments: cli...
def setPhase(self, tlsID, index): """setPhase(string, integer) -> None . """ self._connection._sendIntCmd( tc.CMD_SET_TL_VARIABLE, tc.TL_PHASE_INDEX, tlsID, index)
setPhase(string, integer) -> None .
Below is the the instruction that describes the task: ### Input: setPhase(string, integer) -> None . ### Response: def setPhase(self, tlsID, index): """setPhase(string, integer) -> None . """ self._connection._sendIntCmd( tc.CMD_SET_TL_VARIABLE, tc.TL_PHASE_IND...
def convert_markdown(message): """Convert markdown in message text to HTML.""" assert message['Content-Type'].startswith("text/markdown") del message['Content-Type'] # Convert the text from markdown and then make the message multipart message = make_message_multipart(message) for payload_item in...
Convert markdown in message text to HTML.
Below is the the instruction that describes the task: ### Input: Convert markdown in message text to HTML. ### Response: def convert_markdown(message): """Convert markdown in message text to HTML.""" assert message['Content-Type'].startswith("text/markdown") del message['Content-Type'] # Convert th...
def ekssum(handle, segno): """ Return summary information for a specified segment in a specified EK. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ekssum_c.html :param handle: Handle of EK. :type handle: int :param segno: Number of segment to be summarized. :type segno: int :...
Return summary information for a specified segment in a specified EK. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ekssum_c.html :param handle: Handle of EK. :type handle: int :param segno: Number of segment to be summarized. :type segno: int :return: EK segment summary. :rtype:...
Below is the the instruction that describes the task: ### Input: Return summary information for a specified segment in a specified EK. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ekssum_c.html :param handle: Handle of EK. :type handle: int :param segno: Number of segment to be summariz...
async def unpack(self, ciphertext: bytes) -> (str, str, str): """ Unpack a message. Return triple with cleartext, sender verification key, and recipient verification key. Raise AbsentMessage for missing ciphertext, or WalletState if wallet is closed. Raise AbsentRecord if wallet has no k...
Unpack a message. Return triple with cleartext, sender verification key, and recipient verification key. Raise AbsentMessage for missing ciphertext, or WalletState if wallet is closed. Raise AbsentRecord if wallet has no key to unpack ciphertext. :param ciphertext: JWE-like formatted message as...
Below is the the instruction that describes the task: ### Input: Unpack a message. Return triple with cleartext, sender verification key, and recipient verification key. Raise AbsentMessage for missing ciphertext, or WalletState if wallet is closed. Raise AbsentRecord if wallet has no key to unpack ...
def assignrepr(self, prefix='') -> str: """Return a |repr| string with a prefixed assignment.""" with objecttools.repr_.preserve_strings(True): with hydpy.pub.options.ellipsis(2, optional=True): prefix += '%s(' % objecttools.classname(self) repr_ = objecttools...
Return a |repr| string with a prefixed assignment.
Below is the the instruction that describes the task: ### Input: Return a |repr| string with a prefixed assignment. ### Response: def assignrepr(self, prefix='') -> str: """Return a |repr| string with a prefixed assignment.""" with objecttools.repr_.preserve_strings(True): with hydpy.pu...
def firmware_version(self): """Returns a firmware identification string of the connected J-Link. It consists of the following: - Product Name (e.g. J-Link) - The string: compiled - Compile data and time. - Optional additional information. Args: ...
Returns a firmware identification string of the connected J-Link. It consists of the following: - Product Name (e.g. J-Link) - The string: compiled - Compile data and time. - Optional additional information. Args: self (JLink): the ``JLink`` instance ...
Below is the the instruction that describes the task: ### Input: Returns a firmware identification string of the connected J-Link. It consists of the following: - Product Name (e.g. J-Link) - The string: compiled - Compile data and time. - Optional additional informa...
def is_perfect_consonant(note1, note2, include_fourths=True): """Return True if the interval is a perfect consonant one. Perfect consonances are either unisons, perfect fourths or fifths, or octaves (which is the same as a unison in this model). Perfect fourths are usually included as well, but are co...
Return True if the interval is a perfect consonant one. Perfect consonances are either unisons, perfect fourths or fifths, or octaves (which is the same as a unison in this model). Perfect fourths are usually included as well, but are considered dissonant when used contrapuntal, which is why you can e...
Below is the the instruction that describes the task: ### Input: Return True if the interval is a perfect consonant one. Perfect consonances are either unisons, perfect fourths or fifths, or octaves (which is the same as a unison in this model). Perfect fourths are usually included as well, but are co...
def _parse_mode(client, command, actor, args): """Parse a mode changes, update states, and dispatch MODE events.""" chantypes = client.server.features.get("CHANTYPES", "#") channel, _, args = args.partition(" ") args = args.lstrip(":") if channel[0] not in chantypes: # Personal modes ...
Parse a mode changes, update states, and dispatch MODE events.
Below is the the instruction that describes the task: ### Input: Parse a mode changes, update states, and dispatch MODE events. ### Response: def _parse_mode(client, command, actor, args): """Parse a mode changes, update states, and dispatch MODE events.""" chantypes = client.server.features.get("CHANTYPES...
def _chain_forks(elements): """Detect whether a sequence of elements leads to a fork of streams""" # we are only interested in the result, so unwind from the end for element in reversed(elements): if element.chain_fork: return True elif element.chain_join:...
Detect whether a sequence of elements leads to a fork of streams
Below is the the instruction that describes the task: ### Input: Detect whether a sequence of elements leads to a fork of streams ### Response: def _chain_forks(elements): """Detect whether a sequence of elements leads to a fork of streams""" # we are only interested in the result, so unwind from t...
def sankey(*args, projection=None, start=None, end=None, path=None, hue=None, categorical=False, scheme=None, k=5, cmap='viridis', vmin=None, vmax=None, legend=False, legend_kwargs=None, legend_labels=None, legend_values=None, legend_var=None, extent=None, figsize=(8, 6), ax=...
Spatial Sankey or flow map. Parameters ---------- df : GeoDataFrame, optional. The data being plotted. This parameter is optional - it is not needed if ``start`` and ``end`` (and ``hue``, if provided) are iterables. projection : geoplot.crs object instance, optional A geographic...
Below is the the instruction that describes the task: ### Input: Spatial Sankey or flow map. Parameters ---------- df : GeoDataFrame, optional. The data being plotted. This parameter is optional - it is not needed if ``start`` and ``end`` (and ``hue``, if provided) are iterables. pr...
def get_design(self, design_name): """ Returns dict representation of the design document with the matching name design_name <str> name of the design """ try: r = requests.request( "GET", "%s/%s/_design/%s" % ( self.host, self.database_name, ...
Returns dict representation of the design document with the matching name design_name <str> name of the design
Below is the the instruction that describes the task: ### Input: Returns dict representation of the design document with the matching name design_name <str> name of the design ### Response: def get_design(self, design_name): """ Returns dict representation of the design document with the matching ...
def get_thing_shadow(self, **kwargs): r""" Call shadow lambda to obtain current shadow state. :Keyword Arguments: * *thingName* (``string``) -- [REQUIRED] The name of the thing. :returns: (``dict``) -- The output from the GetThingShadow o...
r""" Call shadow lambda to obtain current shadow state. :Keyword Arguments: * *thingName* (``string``) -- [REQUIRED] The name of the thing. :returns: (``dict``) -- The output from the GetThingShadow operation * *payload* (``bytes``) -...
Below is the the instruction that describes the task: ### Input: r""" Call shadow lambda to obtain current shadow state. :Keyword Arguments: * *thingName* (``string``) -- [REQUIRED] The name of the thing. :returns: (``dict``) -- The output fr...
def state_type_changed(self, model, prop_name, info): """Reopen state editor when state type is changed When the type of the observed state changes, a new model is created. The look of this controller's view depends on the kind of model. Therefore, we have to destroy this editor and open a new ...
Reopen state editor when state type is changed When the type of the observed state changes, a new model is created. The look of this controller's view depends on the kind of model. Therefore, we have to destroy this editor and open a new one with the new model.
Below is the the instruction that describes the task: ### Input: Reopen state editor when state type is changed When the type of the observed state changes, a new model is created. The look of this controller's view depends on the kind of model. Therefore, we have to destroy this editor and open a ...
def get_specs(data): """ Takes a magic format file and returns a list of unique specimen names """ # sort the specimen names speclist = [] for rec in data: try: spec = rec["er_specimen_name"] except KeyError as e: spec = rec["specimen"] if spec not...
Takes a magic format file and returns a list of unique specimen names
Below is the the instruction that describes the task: ### Input: Takes a magic format file and returns a list of unique specimen names ### Response: def get_specs(data): """ Takes a magic format file and returns a list of unique specimen names """ # sort the specimen names speclist = [] for...
def freeRenderModel(self): """ Frees a previously returned render model It is safe to call this on a null ptr. """ fn = self.function_table.freeRenderModel pRenderModel = RenderModel_t() fn(byref(pRenderModel)) return pRenderModel
Frees a previously returned render model It is safe to call this on a null ptr.
Below is the the instruction that describes the task: ### Input: Frees a previously returned render model It is safe to call this on a null ptr. ### Response: def freeRenderModel(self): """ Frees a previously returned render model It is safe to call this on a null ptr. "...
def _load_from_hdx(self, object_type, id_field): # type: (str, str) -> bool """Helper method to load the HDX object given by identifier from HDX Args: object_type (str): Description of HDX object type (for messages) id_field (str): HDX object identifier Returns:...
Helper method to load the HDX object given by identifier from HDX Args: object_type (str): Description of HDX object type (for messages) id_field (str): HDX object identifier Returns: bool: True if loaded, False if not
Below is the the instruction that describes the task: ### Input: Helper method to load the HDX object given by identifier from HDX Args: object_type (str): Description of HDX object type (for messages) id_field (str): HDX object identifier Returns: bool: True if...
def DELETE_SLICE_0(self, instr): 'obj[:] = expr' value = self.ast_stack.pop() kw = dict(lineno=instr.lineno, col_offset=0) slice = _ast.Slice(lower=None, step=None, upper=None, **kw) subscr = _ast.Subscript(value=value, slice=slice, ctx=_ast.Del(), **kw) delete = _ast.D...
obj[:] = expr
Below is the the instruction that describes the task: ### Input: obj[:] = expr ### Response: def DELETE_SLICE_0(self, instr): 'obj[:] = expr' value = self.ast_stack.pop() kw = dict(lineno=instr.lineno, col_offset=0) slice = _ast.Slice(lower=None, step=None, upper=None, **kw) ...
async def set_presence(self, status: str = "online", ignore_cache: bool = False): """ Set the online status of the user. See also: `API reference`_ Args: status: The online status of the user. Allowed values: "online", "offline", "unavailable". ignore_cache: Whether or n...
Set the online status of the user. See also: `API reference`_ Args: status: The online status of the user. Allowed values: "online", "offline", "unavailable". ignore_cache: Whether or not to set presence even if the cache says the presence is already set to that value. ...
Below is the the instruction that describes the task: ### Input: Set the online status of the user. See also: `API reference`_ Args: status: The online status of the user. Allowed values: "online", "offline", "unavailable". ignore_cache: Whether or not to set presence even if the ca...
def x(self): ''' np.array: The grid points in x. ''' if None not in (self.x_min, self.x_max, self.x_step) and \ self.x_min != self.x_max: x = np.arange(self.x_min, self.x_max+self.x_step-self.y_step*0.1, self.x_step) else: x = np.array([]) ...
np.array: The grid points in x.
Below is the the instruction that describes the task: ### Input: np.array: The grid points in x. ### Response: def x(self): ''' np.array: The grid points in x. ''' if None not in (self.x_min, self.x_max, self.x_step) and \ self.x_min != self.x_max: x = np...
def add_virtual_columns_cartesian_angular_momenta(self, x='x', y='y', z='z', vx='vx', vy='vy', vz='vz', Lx='Lx', Ly='Ly', Lz='Lz', propagate_uncertainties=False): """...
Calculate the angular momentum components provided Cartesian positions and velocities. Be mindful of the point of origin: ex. if considering Galactic dynamics, and positions and velocities should be as seen from the Galactic centre. :param x: x-position Cartesian component :param y: y-position Cartesia...
Below is the the instruction that describes the task: ### Input: Calculate the angular momentum components provided Cartesian positions and velocities. Be mindful of the point of origin: ex. if considering Galactic dynamics, and positions and velocities should be as seen from the Galactic centre. :para...
def joinswarm(remote_addr=int, listen_addr=int, token=str): ''' Join a Swarm Worker to the cluster remote_addr The manager node you want to connect to for the swarm listen_addr Listen address used for inter-manager communication if the node gets promoted to ...
Join a Swarm Worker to the cluster remote_addr The manager node you want to connect to for the swarm listen_addr Listen address used for inter-manager communication if the node gets promoted to manager, as well as determining the networking interface used for the VXLAN Tunnel Endpoint ...
Below is the the instruction that describes the task: ### Input: Join a Swarm Worker to the cluster remote_addr The manager node you want to connect to for the swarm listen_addr Listen address used for inter-manager communication if the node gets promoted to manager, as well as det...
def _prt_edge(dag_edge, attr): """Print edge attribute""" # sequence parent_graph points attributes type parent_edge_list print("Edge {ATTR}: {VAL}".format(ATTR=attr, VAL=dag_edge.obj_dict[attr]))
Print edge attribute
Below is the the instruction that describes the task: ### Input: Print edge attribute ### Response: def _prt_edge(dag_edge, attr): """Print edge attribute""" # sequence parent_graph points attributes type parent_edge_list print("Edge {ATTR}: {VAL}".format(ATTR=attr, VAL=dag_edge.obj_dict[at...
def _getTPClass(temporalImp): """ Return the class corresponding to the given temporalImp string """ if temporalImp == 'py': return backtracking_tm.BacktrackingTM elif temporalImp == 'cpp': return backtracking_tm_cpp.BacktrackingTMCPP elif temporalImp == 'tm_py': return backtracking_tm_shim.TMShi...
Return the class corresponding to the given temporalImp string
Below is the the instruction that describes the task: ### Input: Return the class corresponding to the given temporalImp string ### Response: def _getTPClass(temporalImp): """ Return the class corresponding to the given temporalImp string """ if temporalImp == 'py': return backtracking_tm.BacktrackingTM...
def generate_data(path, tokenizer, char_vcb, word_vcb, is_training=False): ''' Generate data ''' global root_path qp_pairs = data.load_from_file(path=path, is_training=is_training) tokenized_sent = 0 # qp_pairs = qp_pairs[:1000]1 for qp_pair in qp_pairs: tokenized_sent += 1 ...
Generate data
Below is the the instruction that describes the task: ### Input: Generate data ### Response: def generate_data(path, tokenizer, char_vcb, word_vcb, is_training=False): ''' Generate data ''' global root_path qp_pairs = data.load_from_file(path=path, is_training=is_training) tokenized_sent =...
def rfc2426(self): """RFC2426-encode the field content. :return: the field in the RFC 2426 format. :returntype: `str`""" if self.uri: return rfc2425encode(self.name,self.uri,{"value":"uri"}) elif self.sound: return rfc2425encode(self.name,self.sound)
RFC2426-encode the field content. :return: the field in the RFC 2426 format. :returntype: `str`
Below is the the instruction that describes the task: ### Input: RFC2426-encode the field content. :return: the field in the RFC 2426 format. :returntype: `str` ### Response: def rfc2426(self): """RFC2426-encode the field content. :return: the field in the RFC 2426 format. ...
def _write_for_dstype(self, learn:Learner, batch:Tuple, iteration:int, tbwriter:SummaryWriter, ds_type:DatasetType)->None: "Writes batch images of specified DatasetType to Tensorboard." request = ImageTBRequest(learn=learn, batch=batch, iteration=iteration, tbwriter=tbwriter, ds_type=ds_type) as...
Writes batch images of specified DatasetType to Tensorboard.
Below is the the instruction that describes the task: ### Input: Writes batch images of specified DatasetType to Tensorboard. ### Response: def _write_for_dstype(self, learn:Learner, batch:Tuple, iteration:int, tbwriter:SummaryWriter, ds_type:DatasetType)->None: "Writes batch images of specified DatasetTyp...
def _add_utterance_to_document(self, utterance): """add an utterance to this docgraph (as a spanning relation)""" utter_id = 'utterance_{}'.format(utterance.attrib['nrgen']) norm, lemma, pos = [elem.text.split() for elem in utterance.iterchildren()] for i, wor...
add an utterance to this docgraph (as a spanning relation)
Below is the the instruction that describes the task: ### Input: add an utterance to this docgraph (as a spanning relation) ### Response: def _add_utterance_to_document(self, utterance): """add an utterance to this docgraph (as a spanning relation)""" utter_id = 'utterance_{}'.format(utterance.attr...
def solve_one(self, expr, constrain=False): """ Concretize a symbolic :class:`~manticore.core.smtlib.expression.Expression` into one solution. :param manticore.core.smtlib.Expression expr: Symbolic value to concretize :param bool constrain: If True, constrain expr to concretized...
Concretize a symbolic :class:`~manticore.core.smtlib.expression.Expression` into one solution. :param manticore.core.smtlib.Expression expr: Symbolic value to concretize :param bool constrain: If True, constrain expr to concretized value :return: Concrete value :rtype: int
Below is the the instruction that describes the task: ### Input: Concretize a symbolic :class:`~manticore.core.smtlib.expression.Expression` into one solution. :param manticore.core.smtlib.Expression expr: Symbolic value to concretize :param bool constrain: If True, constrain expr to concre...
def metadataContributer(self): """gets the metadata featurelayer object""" if self._metaFL is None: fl = FeatureService(url=self._metadataURL, proxy_url=self._proxy_url, proxy_port=self._proxy_port) self._metaFS = fl ...
gets the metadata featurelayer object
Below is the the instruction that describes the task: ### Input: gets the metadata featurelayer object ### Response: def metadataContributer(self): """gets the metadata featurelayer object""" if self._metaFL is None: fl = FeatureService(url=self._metadataURL, ...
def notify(self, notices): """Send notifications to the users via. the provided methods Args: notices (:obj:`dict` of `str`: `dict`): List of the notifications to send Returns: `None` """ issues_html = get_template('unattached_ebs_volume.html') i...
Send notifications to the users via. the provided methods Args: notices (:obj:`dict` of `str`: `dict`): List of the notifications to send Returns: `None`
Below is the the instruction that describes the task: ### Input: Send notifications to the users via. the provided methods Args: notices (:obj:`dict` of `str`: `dict`): List of the notifications to send Returns: `None` ### Response: def notify(self, notices): """Se...
def words(quantity=10, as_list=False): """Return random words.""" global _words if not _words: _words = ' '.join(get_dictionary('lorem_ipsum')).lower().\ replace('\n', '') _words = re.sub(r'\.|,|;/', '', _words) _words = _words.split(' ') result = random.sample(_wor...
Return random words.
Below is the the instruction that describes the task: ### Input: Return random words. ### Response: def words(quantity=10, as_list=False): """Return random words.""" global _words if not _words: _words = ' '.join(get_dictionary('lorem_ipsum')).lower().\ replace('\n', '') _w...
def _set_loopback(self, v, load=False): """ Setter method for loopback, mapped from YANG variable /overlay_gateway/ip/interface/loopback (container) If this variable is read-only (config: false) in the source YANG file, then _set_loopback is considered as a private method. Backends looking to popula...
Setter method for loopback, mapped from YANG variable /overlay_gateway/ip/interface/loopback (container) If this variable is read-only (config: false) in the source YANG file, then _set_loopback is considered as a private method. Backends looking to populate this variable should do so via calling thisOb...
Below is the the instruction that describes the task: ### Input: Setter method for loopback, mapped from YANG variable /overlay_gateway/ip/interface/loopback (container) If this variable is read-only (config: false) in the source YANG file, then _set_loopback is considered as a private method. Backends ...
def pull(self, project, run=None, entity=None): """Download files from W&B Args: project (str): The project to download run (str, optional): The run to upload to entity (str, optional): The entity to scope this project to. Defaults to wandb models Returns: ...
Download files from W&B Args: project (str): The project to download run (str, optional): The run to upload to entity (str, optional): The entity to scope this project to. Defaults to wandb models Returns: The requests library response object
Below is the the instruction that describes the task: ### Input: Download files from W&B Args: project (str): The project to download run (str, optional): The run to upload to entity (str, optional): The entity to scope this project to. Defaults to wandb models ...
def get_enum_from_name(self, enum_name): """ Return an enum from a name Args: enum_name (str): name of the enum Returns: Enum """ return next((e for e in self.enums if e.name == enum_name), None)
Return an enum from a name Args: enum_name (str): name of the enum Returns: Enum
Below is the the instruction that describes the task: ### Input: Return an enum from a name Args: enum_name (str): name of the enum Returns: Enum ### Response: def get_enum_from_name(self, enum_name): """ Return an enum from a name Args: ...
def _read_indexlist(self, name): """Read a list of indexes.""" setattr(self, '_' + name, [self._timeline[int(i)] for i in self.db.lrange('site:{0}'.format(name), 0, -1)])
Read a list of indexes.
Below is the the instruction that describes the task: ### Input: Read a list of indexes. ### Response: def _read_indexlist(self, name): """Read a list of indexes.""" setattr(self, '_' + name, [self._timeline[int(i)] for i in self.db.lrange('site:{0}'.format(name),...
def processTPED(uniqueSamples, duplicatedSamples, fileName, prefix): """Process the TPED file. :param uniqueSamples: the position of unique samples. :param duplicatedSamples: the position of duplicated samples. :param fileName: the name of the file. :param prefix: the prefix of all the files. ...
Process the TPED file. :param uniqueSamples: the position of unique samples. :param duplicatedSamples: the position of duplicated samples. :param fileName: the name of the file. :param prefix: the prefix of all the files. :type uniqueSamples: dict :type duplicatedSamples: collections.defaultdi...
Below is the the instruction that describes the task: ### Input: Process the TPED file. :param uniqueSamples: the position of unique samples. :param duplicatedSamples: the position of duplicated samples. :param fileName: the name of the file. :param prefix: the prefix of all the files. :type u...
def _add_warc_action_log(self, path, url): '''Add the action log to the WARC file.''' _logger.debug('Adding action log record.') actions = [] with open(path, 'r', encoding='utf-8', errors='replace') as file: for line in file: actions.append(json.loads(line)) ...
Add the action log to the WARC file.
Below is the the instruction that describes the task: ### Input: Add the action log to the WARC file. ### Response: def _add_warc_action_log(self, path, url): '''Add the action log to the WARC file.''' _logger.debug('Adding action log record.') actions = [] with open(path, 'r', enc...
def _encode_message_set(cls, messages, offset=None): """ Encode a MessageSet. Unlike other arrays in the protocol, MessageSets are not length-prefixed. Format:: MessageSet => [Offset MessageSize Message] Offset => int64 MessageSize => int32 """ ...
Encode a MessageSet. Unlike other arrays in the protocol, MessageSets are not length-prefixed. Format:: MessageSet => [Offset MessageSize Message] Offset => int64 MessageSize => int32
Below is the the instruction that describes the task: ### Input: Encode a MessageSet. Unlike other arrays in the protocol, MessageSets are not length-prefixed. Format:: MessageSet => [Offset MessageSize Message] Offset => int64 MessageSize => int32 ### Response: de...
def mk_subsuper_association(m, r_subsup): ''' Create pyxtuml associations from a sub/super association in BridgePoint. ''' r_rel = one(r_subsup).R_REL[206]() r_rto = one(r_subsup).R_SUPER[212].R_RTO[204]() target_o_obj = one(r_rto).R_OIR[203].O_OBJ[201]() for r_sub in many(r_subsup).R_S...
Create pyxtuml associations from a sub/super association in BridgePoint.
Below is the the instruction that describes the task: ### Input: Create pyxtuml associations from a sub/super association in BridgePoint. ### Response: def mk_subsuper_association(m, r_subsup): ''' Create pyxtuml associations from a sub/super association in BridgePoint. ''' r_rel = one(r_subsup).R_...
def csv(self, sep=',', branches=None, include_labels=True, limit=None, stream=None): """ Print csv representation of tree only including branches of basic types (no objects, vectors, etc..) Parameters ---------- sep : str, optional (default=',') ...
Print csv representation of tree only including branches of basic types (no objects, vectors, etc..) Parameters ---------- sep : str, optional (default=',') The delimiter used to separate columns branches : list, optional (default=None) Only include thes...
Below is the the instruction that describes the task: ### Input: Print csv representation of tree only including branches of basic types (no objects, vectors, etc..) Parameters ---------- sep : str, optional (default=',') The delimiter used to separate columns b...
def load_datetime(value, dt_format): """ Create timezone-aware datetime object """ if dt_format.endswith('%z'): dt_format = dt_format[:-2] offset = value[-5:] value = value[:-5] if offset != offset.replace(':', ''): # strip : from HHMM if needed (isoformat() a...
Create timezone-aware datetime object
Below is the the instruction that describes the task: ### Input: Create timezone-aware datetime object ### Response: def load_datetime(value, dt_format): """ Create timezone-aware datetime object """ if dt_format.endswith('%z'): dt_format = dt_format[:-2] offset = value[-5:] ...
def merge_stats(self, other_col_counters): """ Merge statistics from a different column stats counter in to this one. Parameters ---------- other_column_counters: Other col_stat_counter to marge in to this one. """ for column_name, _ in self._column_stats.items():...
Merge statistics from a different column stats counter in to this one. Parameters ---------- other_column_counters: Other col_stat_counter to marge in to this one.
Below is the the instruction that describes the task: ### Input: Merge statistics from a different column stats counter in to this one. Parameters ---------- other_column_counters: Other col_stat_counter to marge in to this one. ### Response: def merge_stats(self, other_col_counters): ...
def show_floatingip(self, floatingip, **_params): """Fetches information of a certain floatingip.""" return self.get(self.floatingip_path % (floatingip), params=_params)
Fetches information of a certain floatingip.
Below is the the instruction that describes the task: ### Input: Fetches information of a certain floatingip. ### Response: def show_floatingip(self, floatingip, **_params): """Fetches information of a certain floatingip.""" return self.get(self.floatingip_path % (floatingip), params=_params)
def next_prime( starting_value ): "Return the smallest prime larger than the starting value." if starting_value < 2: return 2 result = ( starting_value + 1 ) | 1 while not is_prime( result ): result = result + 2 return result
Return the smallest prime larger than the starting value.
Below is the the instruction that describes the task: ### Input: Return the smallest prime larger than the starting value. ### Response: def next_prime( starting_value ): "Return the smallest prime larger than the starting value." if starting_value < 2: return 2 result = ( starting_value + 1 ) | 1 while n...