code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
text
stringlengths
164
112k
def run_ahead(self, time, framerate): """Run the particle system for the specified time frame at the specified framerate to move time forward as quickly as possible. Useful for "warming up" the particle system to reach a steady-state before anything is drawn or to simply "skip ahead" in ...
Run the particle system for the specified time frame at the specified framerate to move time forward as quickly as possible. Useful for "warming up" the particle system to reach a steady-state before anything is drawn or to simply "skip ahead" in time. time -- The amount of simulation t...
Below is the the instruction that describes the task: ### Input: Run the particle system for the specified time frame at the specified framerate to move time forward as quickly as possible. Useful for "warming up" the particle system to reach a steady-state before anything is drawn or to sim...
def _file_path(self, uid): """Create and return full file path for DayOne entry""" file_name = '%s.doentry' % (uid) return os.path.join(self.dayone_journal_path, file_name)
Create and return full file path for DayOne entry
Below is the the instruction that describes the task: ### Input: Create and return full file path for DayOne entry ### Response: def _file_path(self, uid): """Create and return full file path for DayOne entry""" file_name = '%s.doentry' % (uid) return os.path.join(self.dayone_journal_path, ...
def follow_hand(poppy, delta): """Tell the right hand to follow the left hand""" right_arm_position = poppy.l_arm_chain.end_effector + delta poppy.r_arm_chain.goto(right_arm_position, 0.5, wait=True)
Tell the right hand to follow the left hand
Below is the the instruction that describes the task: ### Input: Tell the right hand to follow the left hand ### Response: def follow_hand(poppy, delta): """Tell the right hand to follow the left hand""" right_arm_position = poppy.l_arm_chain.end_effector + delta poppy.r_arm_chain.goto(right_arm_positi...
def GetString(self, text, idx): '''Internal method. Retrieves a string from the #STRINGS buffer. ''' next = string.find(text, '\x00', idx) chunk = text[idx:next] return chunk
Internal method. Retrieves a string from the #STRINGS buffer.
Below is the the instruction that describes the task: ### Input: Internal method. Retrieves a string from the #STRINGS buffer. ### Response: def GetString(self, text, idx): '''Internal method. Retrieves a string from the #STRINGS buffer. ''' next = string.find(text, '\x00', ...
def normal_var(data, mean): """ Creates a segment cost function for a time series with a Normal distribution with changing variance Args: data (:obj:`list` of float): 1D time series data variance (float): variance Returns: function: Function with signature (int, ...
Creates a segment cost function for a time series with a Normal distribution with changing variance Args: data (:obj:`list` of float): 1D time series data variance (float): variance Returns: function: Function with signature (int, int) -> float where the ...
Below is the the instruction that describes the task: ### Input: Creates a segment cost function for a time series with a Normal distribution with changing variance Args: data (:obj:`list` of float): 1D time series data variance (float): variance Returns: function: Function ...
def inverse_transform(self, y, exogenous=None): """Inverse transform a transformed array Inverse the Box-Cox transformation on the transformed array. Note that if truncation happened in the ``transform`` method, invertibility will not be preserved, and the transformed array may not be p...
Inverse transform a transformed array Inverse the Box-Cox transformation on the transformed array. Note that if truncation happened in the ``transform`` method, invertibility will not be preserved, and the transformed array may not be perfectly inverse-transformed. Parameters ...
Below is the the instruction that describes the task: ### Input: Inverse transform a transformed array Inverse the Box-Cox transformation on the transformed array. Note that if truncation happened in the ``transform`` method, invertibility will not be preserved, and the transformed array ma...
def ip_rtm_config_route_static_bfd_bfd_static_route_bfd_interval_attributes_interval(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") ip = ET.SubElement(config, "ip", xmlns="urn:brocade.com:mgmt:brocade-common-def") rtm_config = ET.SubElement(ip, "rtm-con...
Auto Generated Code
Below is the the instruction that describes the task: ### Input: Auto Generated Code ### Response: def ip_rtm_config_route_static_bfd_bfd_static_route_bfd_interval_attributes_interval(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") ip = ET.SubElement(config...
def describe_autocomplete(self, service, operation, param): """Describe operation and args needed for server side completion. :type service: str :param service: The AWS service name. :type operation: str :param operation: The AWS operation name. :type param: str ...
Describe operation and args needed for server side completion. :type service: str :param service: The AWS service name. :type operation: str :param operation: The AWS operation name. :type param: str :param param: The name of the parameter being completed. This must ...
Below is the the instruction that describes the task: ### Input: Describe operation and args needed for server side completion. :type service: str :param service: The AWS service name. :type operation: str :param operation: The AWS operation name. :type param: str ...
def matrix_asformat(lvl, name, format, blocksize=None): """Set a matrix to a specific format. This routine looks for the matrix "name" in the specified format as a member of the level instance, lvl. For example, if name='A', format='bsr' and blocksize=(4,4), and if lvl.Absr44 exists with the correct b...
Set a matrix to a specific format. This routine looks for the matrix "name" in the specified format as a member of the level instance, lvl. For example, if name='A', format='bsr' and blocksize=(4,4), and if lvl.Absr44 exists with the correct blocksize, then lvl.Absr is returned. If the matrix doesn't...
Below is the the instruction that describes the task: ### Input: Set a matrix to a specific format. This routine looks for the matrix "name" in the specified format as a member of the level instance, lvl. For example, if name='A', format='bsr' and blocksize=(4,4), and if lvl.Absr44 exists with the cor...
def _assert_ssl_exc_contains(exc, *msgs): """Check whether SSL exception contains either of messages provided.""" if len(msgs) < 1: raise TypeError( '_assert_ssl_exc_contains() requires ' 'at least one message to be passed.', ) err_msg_lower = str(exc).lower() ret...
Check whether SSL exception contains either of messages provided.
Below is the the instruction that describes the task: ### Input: Check whether SSL exception contains either of messages provided. ### Response: def _assert_ssl_exc_contains(exc, *msgs): """Check whether SSL exception contains either of messages provided.""" if len(msgs) < 1: raise TypeError( ...
def _setsizes(self, cursor=None): """Set stored input and output sizes for cursor execution.""" if cursor is None: cursor = self._cursor if self._inputsizes: cursor.setinputsizes(self._inputsizes) for column, size in self._outputsizes.items(): if colum...
Set stored input and output sizes for cursor execution.
Below is the the instruction that describes the task: ### Input: Set stored input and output sizes for cursor execution. ### Response: def _setsizes(self, cursor=None): """Set stored input and output sizes for cursor execution.""" if cursor is None: cursor = self._cursor if self...
def text_if_str(to_type, text_or_primitive): """ Convert to a type, assuming that strings can be only unicode text (not a hexstr) @param to_type is a function that takes the arguments (primitive, hexstr=hexstr, text=text), eg~ to_bytes, to_text, to_hex, to_int, etc @param hexstr_or_primitive in...
Convert to a type, assuming that strings can be only unicode text (not a hexstr) @param to_type is a function that takes the arguments (primitive, hexstr=hexstr, text=text), eg~ to_bytes, to_text, to_hex, to_int, etc @param hexstr_or_primitive in bytes, str, or int.
Below is the the instruction that describes the task: ### Input: Convert to a type, assuming that strings can be only unicode text (not a hexstr) @param to_type is a function that takes the arguments (primitive, hexstr=hexstr, text=text), eg~ to_bytes, to_text, to_hex, to_int, etc @param hexstr_or_...
def isValidSemver(version): """Semantic version number - determines whether the version is qualified. The format is MAJOR.Minor.PATCH, more with https://semver.org/""" if version and isinstance(version, string_types): try: semver.parse(version) except (TypeError,ValueError): ...
Semantic version number - determines whether the version is qualified. The format is MAJOR.Minor.PATCH, more with https://semver.org/
Below is the the instruction that describes the task: ### Input: Semantic version number - determines whether the version is qualified. The format is MAJOR.Minor.PATCH, more with https://semver.org/ ### Response: def isValidSemver(version): """Semantic version number - determines whether the version is qualifi...
def query_image_metadata(self, image, metadata_type=""): '''**Description** Find the image with the tag <image> and return its metadata. **Arguments** - image: Input image can be in the following formats: registry/repo:tag - metadata_type: The metadata type can be on...
**Description** Find the image with the tag <image> and return its metadata. **Arguments** - image: Input image can be in the following formats: registry/repo:tag - metadata_type: The metadata type can be one of the types returned by running without a type specified ...
Below is the the instruction that describes the task: ### Input: **Description** Find the image with the tag <image> and return its metadata. **Arguments** - image: Input image can be in the following formats: registry/repo:tag - metadata_type: The metadata type can be o...
def _get_programs_dict(pkgname_only, flag_protected, flag_no_pfant=False): """Returns dictionary {(package description): [ExeInfo0, ...], ...}""" allinfo = f311.get_programs_dict(pkgname_only, flag_protected) if not flag_no_pfant and "pyfant" in allinfo: _add_PFANT(allinfo) return allinfo
Returns dictionary {(package description): [ExeInfo0, ...], ...}
Below is the the instruction that describes the task: ### Input: Returns dictionary {(package description): [ExeInfo0, ...], ...} ### Response: def _get_programs_dict(pkgname_only, flag_protected, flag_no_pfant=False): """Returns dictionary {(package description): [ExeInfo0, ...], ...}""" allinfo = f311.g...
def raw_abundance(biomf, sampleIDs=None, sample_abd=True): """ Calculate the total number of sequences in each OTU or SampleID. :type biomf: A BIOM file. :param biomf: OTU table format. :type sampleIDs: List :param sampleIDs: A list of column id's from BIOM format OTU table. By default, the ...
Calculate the total number of sequences in each OTU or SampleID. :type biomf: A BIOM file. :param biomf: OTU table format. :type sampleIDs: List :param sampleIDs: A list of column id's from BIOM format OTU table. By default, the list has been set to None. :type sample_abd: B...
Below is the the instruction that describes the task: ### Input: Calculate the total number of sequences in each OTU or SampleID. :type biomf: A BIOM file. :param biomf: OTU table format. :type sampleIDs: List :param sampleIDs: A list of column id's from BIOM format OTU table. By default, the ...
def _setSpeed(self, speed, motor, device): """ Set motor speed. This method takes into consideration the PWM frequency that the hardware is currently running at and limits the values passed to the hardware accordingly. :Parameters: speed : `int` Motor speed...
Set motor speed. This method takes into consideration the PWM frequency that the hardware is currently running at and limits the values passed to the hardware accordingly. :Parameters: speed : `int` Motor speed as an integer. Negative numbers indicate reverse s...
Below is the the instruction that describes the task: ### Input: Set motor speed. This method takes into consideration the PWM frequency that the hardware is currently running at and limits the values passed to the hardware accordingly. :Parameters: speed : `int` Motor...
def upstream_structure(self): """Build dictionary with entire upstream pipeline structure (with regard to the current Step). Returns: dict: dictionary describing the upstream pipeline structure. It has two keys: ``'edges'`` and ``'nodes'``, where: - value of...
Build dictionary with entire upstream pipeline structure (with regard to the current Step). Returns: dict: dictionary describing the upstream pipeline structure. It has two keys: ``'edges'`` and ``'nodes'``, where: - value of ``'edges'`` is set of tuples ``(input_st...
Below is the the instruction that describes the task: ### Input: Build dictionary with entire upstream pipeline structure (with regard to the current Step). Returns: dict: dictionary describing the upstream pipeline structure. It has two keys: ``'edges'`` and ``'nodes'``, wh...
def convert(self, blob, **kw): """Convert using unoconv converter.""" timeout = self.run_timeout with make_temp_file(blob) as in_fn, make_temp_file( prefix="tmp-unoconv-", suffix=".pdf" ) as out_fn: args = ["-f", "pdf", "-o", out_fn, in_fn] # Hack for...
Convert using unoconv converter.
Below is the the instruction that describes the task: ### Input: Convert using unoconv converter. ### Response: def convert(self, blob, **kw): """Convert using unoconv converter.""" timeout = self.run_timeout with make_temp_file(blob) as in_fn, make_temp_file( prefix="tmp-unocon...
def lib_dir(self): """Return standard library directory path used by RPM libs.""" if not self._lib_dir: lib_files = glob.glob("/usr/lib/*/librpm.so*") if not lib_files: raise InstallError("Can not find lib directory.") self._lib_dir = os.path.dirname(l...
Return standard library directory path used by RPM libs.
Below is the the instruction that describes the task: ### Input: Return standard library directory path used by RPM libs. ### Response: def lib_dir(self): """Return standard library directory path used by RPM libs.""" if not self._lib_dir: lib_files = glob.glob("/usr/lib/*/librpm.so*") ...
def get_latex(ink_filename): """Get the LaTeX string from a file by the *.ink filename.""" tex_file = os.path.splitext(ink_filename)[0] + ".tex" with open(tex_file) as f: tex_content = f.read().strip() pattern = re.compile(r"\\begin\{displaymath\}(.*?)\\end\{displaymath\}", ...
Get the LaTeX string from a file by the *.ink filename.
Below is the the instruction that describes the task: ### Input: Get the LaTeX string from a file by the *.ink filename. ### Response: def get_latex(ink_filename): """Get the LaTeX string from a file by the *.ink filename.""" tex_file = os.path.splitext(ink_filename)[0] + ".tex" with open(tex_file) as ...
def _apply_single_step(dist, params_event_ndims, slices, params_overrides): """Applies a single slicing step to `dist`, returning a new instance.""" if len(slices) == 1 and slices[0] == Ellipsis: # The path used by Distribution.copy: batch_slice(...args..., Ellipsis) override_dict = {} else: override_...
Applies a single slicing step to `dist`, returning a new instance.
Below is the the instruction that describes the task: ### Input: Applies a single slicing step to `dist`, returning a new instance. ### Response: def _apply_single_step(dist, params_event_ndims, slices, params_overrides): """Applies a single slicing step to `dist`, returning a new instance.""" if len(slices) =...
def evaluate_all_configs( hparams, agent_model_dir, eval_fn=_eval_fn_with_learner ): """Evaluate the agent with multiple eval configurations.""" metrics = {} # Iterate over all combinations of sampling temperatures and whether to do # initial no-ops. for sampling_temp in hparams.eval_sampling_temps: #...
Evaluate the agent with multiple eval configurations.
Below is the the instruction that describes the task: ### Input: Evaluate the agent with multiple eval configurations. ### Response: def evaluate_all_configs( hparams, agent_model_dir, eval_fn=_eval_fn_with_learner ): """Evaluate the agent with multiple eval configurations.""" metrics = {} # Iterate over...
def scale_geom_opt_threshold(self, gradient=0.1, displacement=0.1, energy=0.1): """ Adjust the convergence criteria of geometry optimization. Args: gradient: the scale factor for gradient criteria. If less than 1.0, you are tightening...
Adjust the convergence criteria of geometry optimization. Args: gradient: the scale factor for gradient criteria. If less than 1.0, you are tightening the threshold. The base value is 300 × 10E−6 displacement: the scale factor for atomic displacement. If ...
Below is the the instruction that describes the task: ### Input: Adjust the convergence criteria of geometry optimization. Args: gradient: the scale factor for gradient criteria. If less than 1.0, you are tightening the threshold. The base value is 300 × 10E−6 ...
def update_submit_s3_uri(estimator, job_name): """Updated the S3 URI of the framework source directory in given estimator. Args: estimator (sagemaker.estimator.Framework): The Framework estimator to update. job_name (str): The new job name included in the submit S3 URI Returns: str...
Updated the S3 URI of the framework source directory in given estimator. Args: estimator (sagemaker.estimator.Framework): The Framework estimator to update. job_name (str): The new job name included in the submit S3 URI Returns: str: The updated S3 URI of framework source directory
Below is the the instruction that describes the task: ### Input: Updated the S3 URI of the framework source directory in given estimator. Args: estimator (sagemaker.estimator.Framework): The Framework estimator to update. job_name (str): The new job name included in the submit S3 URI Retur...
def connect(): """Try to connect to the router. Returns: u (miniupnc.UPnP): the connected upnp-instance router (string): the connection information """ upnp = miniupnpc.UPnP() upnp.discoverdelay = 200 providers = upnp.discover() if providers > 1: log.debug('multiple ...
Try to connect to the router. Returns: u (miniupnc.UPnP): the connected upnp-instance router (string): the connection information
Below is the the instruction that describes the task: ### Input: Try to connect to the router. Returns: u (miniupnc.UPnP): the connected upnp-instance router (string): the connection information ### Response: def connect(): """Try to connect to the router. Returns: u (miniupnc...
def validate_args(args): """Validate provided arguments and act on --help.""" if args.list_embedding_sources: print('Listing all sources for {} embeddings.'.format( args.embedding_name)) print('Specify --embedding-name if you wish to ' 'list sources of other embeddings'...
Validate provided arguments and act on --help.
Below is the the instruction that describes the task: ### Input: Validate provided arguments and act on --help. ### Response: def validate_args(args): """Validate provided arguments and act on --help.""" if args.list_embedding_sources: print('Listing all sources for {} embeddings.'.format( ...
def get_att_mats(translate_model): """Get's the tensors representing the attentions from a build model. The attentions are stored in a dict on the Transformer object while building the graph. Args: translate_model: Transformer object to fetch the attention weights from. Returns: Tuple of attention ma...
Get's the tensors representing the attentions from a build model. The attentions are stored in a dict on the Transformer object while building the graph. Args: translate_model: Transformer object to fetch the attention weights from. Returns: Tuple of attention matrices; ( enc_atts: Encoder self a...
Below is the the instruction that describes the task: ### Input: Get's the tensors representing the attentions from a build model. The attentions are stored in a dict on the Transformer object while building the graph. Args: translate_model: Transformer object to fetch the attention weights from. Ret...
def _get_block_manager_axis(cls, axis): """Map the axis to the block_manager axis.""" axis = cls._get_axis_number(axis) if cls._AXIS_REVERSED: m = cls._AXIS_LEN - 1 return m - axis return axis
Map the axis to the block_manager axis.
Below is the the instruction that describes the task: ### Input: Map the axis to the block_manager axis. ### Response: def _get_block_manager_axis(cls, axis): """Map the axis to the block_manager axis.""" axis = cls._get_axis_number(axis) if cls._AXIS_REVERSED: m = cls._AXIS_LEN...
def measure_int_put(self, measure, value): """associates the measure of type Int with the given value""" if value < 0: # Should be an error in a later release. logger.warning("Cannot record negative values") self._measurement_map[measure] = value
associates the measure of type Int with the given value
Below is the the instruction that describes the task: ### Input: associates the measure of type Int with the given value ### Response: def measure_int_put(self, measure, value): """associates the measure of type Int with the given value""" if value < 0: # Should be an error in a later r...
def Process(self, parser_mediator, root_item=None, **kwargs): """Parses an OLECF file. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. root_item (Optional[pyolecf.item]): root item of the OLECF file. Raise...
Parses an OLECF file. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. root_item (Optional[pyolecf.item]): root item of the OLECF file. Raises: ValueError: If the root_item is not set.
Below is the the instruction that describes the task: ### Input: Parses an OLECF file. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. root_item (Optional[pyolecf.item]): root item of the OLECF file. Raise...
def flatten_txns_by_hash(tx_list, nesting=True): ''' Flattens a response from querying a list of address (or wallet) transactions If nesting==True then it will return an ordered dictionary where the keys are tranasaction hashes, otherwise it will be a list of dicts. (nesting==False is good for django t...
Flattens a response from querying a list of address (or wallet) transactions If nesting==True then it will return an ordered dictionary where the keys are tranasaction hashes, otherwise it will be a list of dicts. (nesting==False is good for django templates)
Below is the the instruction that describes the task: ### Input: Flattens a response from querying a list of address (or wallet) transactions If nesting==True then it will return an ordered dictionary where the keys are tranasaction hashes, otherwise it will be a list of dicts. (nesting==False is good for ...
def draw_selection(self, surf): """Draw the selection rectange.""" select_start = self._select_start # Cache to avoid a race condition. if select_start: mouse_pos = self.get_mouse_pos() if (mouse_pos and mouse_pos.surf.surf_type & SurfType.SCREEN and mouse_pos.surf.surf_type == select...
Draw the selection rectange.
Below is the the instruction that describes the task: ### Input: Draw the selection rectange. ### Response: def draw_selection(self, surf): """Draw the selection rectange.""" select_start = self._select_start # Cache to avoid a race condition. if select_start: mouse_pos = self.get_mouse_pos() ...
def parse_config_file(): """ Find the .splunk_logger config file in the current directory, or in the user's home and parse it. The one in the current directory has precedence. :return: A tuple with: - project_id - access_token """ for filename in ('.splunk_lo...
Find the .splunk_logger config file in the current directory, or in the user's home and parse it. The one in the current directory has precedence. :return: A tuple with: - project_id - access_token
Below is the the instruction that describes the task: ### Input: Find the .splunk_logger config file in the current directory, or in the user's home and parse it. The one in the current directory has precedence. :return: A tuple with: - project_id - access_token ### Resp...
def interpolate(self, tres="<default>", fres="<default>", logf=False, outseg=None): """Interpolate this `QGram` over a regularly-gridded spectrogram Parameters ---------- tres : `float`, optional desired time resolution (seconds) of output `Spectrogram`, ...
Interpolate this `QGram` over a regularly-gridded spectrogram Parameters ---------- tres : `float`, optional desired time resolution (seconds) of output `Spectrogram`, default is `abs(outseg) / 1000.` fres : `float`, `int`, `None`, optional desired f...
Below is the the instruction that describes the task: ### Input: Interpolate this `QGram` over a regularly-gridded spectrogram Parameters ---------- tres : `float`, optional desired time resolution (seconds) of output `Spectrogram`, default is `abs(outseg) / 1000.` ...
def handle_error(self, error, req, schema, error_status_code, error_headers): """Handles errors during parsing. Aborts the current request with a 400 error. """ status_code = error_status_code or self.DEFAULT_VALIDATION_STATUS raise bottle.HTTPError( status=status_cod...
Handles errors during parsing. Aborts the current request with a 400 error.
Below is the the instruction that describes the task: ### Input: Handles errors during parsing. Aborts the current request with a 400 error. ### Response: def handle_error(self, error, req, schema, error_status_code, error_headers): """Handles errors during parsing. Aborts the current request with ...
def path_to_url(path): # type: (Union[str, Text]) -> str """ Convert a path to a file: URL. The path will be made absolute and have quoted path parts. """ path = os.path.normpath(os.path.abspath(path)) url = urllib_parse.urljoin('file:', urllib_request.pathname2url(path)) return url
Convert a path to a file: URL. The path will be made absolute and have quoted path parts.
Below is the the instruction that describes the task: ### Input: Convert a path to a file: URL. The path will be made absolute and have quoted path parts. ### Response: def path_to_url(path): # type: (Union[str, Text]) -> str """ Convert a path to a file: URL. The path will be made absolute and h...
def encode(self, txt): '''Encode a text string by replacing characters with alphabet index. Parameters ---------- txt : str A string to encode. Returns ------- classes : list of int A sequence of alphabet index values corresponding to the...
Encode a text string by replacing characters with alphabet index. Parameters ---------- txt : str A string to encode. Returns ------- classes : list of int A sequence of alphabet index values corresponding to the given text.
Below is the the instruction that describes the task: ### Input: Encode a text string by replacing characters with alphabet index. Parameters ---------- txt : str A string to encode. Returns ------- classes : list of int A sequence of alphabe...
def toFloat(value): """ Converts string or signed list to float. """ if isinstance(value, str): return strFloat(value) elif isinstance(value, list): return slistFloat(value) else: return value
Converts string or signed list to float.
Below is the the instruction that describes the task: ### Input: Converts string or signed list to float. ### Response: def toFloat(value): """ Converts string or signed list to float. """ if isinstance(value, str): return strFloat(value) elif isinstance(value, list): return slistFloat(...
def connect(self, addr): """ Call the :meth:`connect` method of the underlying socket and set up SSL on the socket, using the :class:`Context` object supplied to this :class:`Connection` object at creation. :param addr: A remote address :return: What the socket's connect...
Call the :meth:`connect` method of the underlying socket and set up SSL on the socket, using the :class:`Context` object supplied to this :class:`Connection` object at creation. :param addr: A remote address :return: What the socket's connect method returns
Below is the the instruction that describes the task: ### Input: Call the :meth:`connect` method of the underlying socket and set up SSL on the socket, using the :class:`Context` object supplied to this :class:`Connection` object at creation. :param addr: A remote address :return: W...
def _get_min_val(spaceshift, *params): r"""Calculate minimum resolved amplitude or maximum r.""" # Get parameters from tuples spacing, shift = spaceshift n, fI, fC, r, r_def, error, reim, cvar, verb, plot, log = params # Get filter for these parameters dlf = _calculate_filter(n, spacing, shift...
r"""Calculate minimum resolved amplitude or maximum r.
Below is the the instruction that describes the task: ### Input: r"""Calculate minimum resolved amplitude or maximum r. ### Response: def _get_min_val(spaceshift, *params): r"""Calculate minimum resolved amplitude or maximum r.""" # Get parameters from tuples spacing, shift = spaceshift n, fI, fC,...
def mcf(n,c): """mcf: multi-commodity flow formulation for the (asymmetric) traveling salesman problem Parameters: - n: number of nodes - c[i,j]: cost for traversing arc (i,j) Returns a model, ready to be solved. """ model = Model("mcf") x,f = {},{} for i in range(1,n+1): ...
mcf: multi-commodity flow formulation for the (asymmetric) traveling salesman problem Parameters: - n: number of nodes - c[i,j]: cost for traversing arc (i,j) Returns a model, ready to be solved.
Below is the the instruction that describes the task: ### Input: mcf: multi-commodity flow formulation for the (asymmetric) traveling salesman problem Parameters: - n: number of nodes - c[i,j]: cost for traversing arc (i,j) Returns a model, ready to be solved. ### Response: def mcf(n,c): ...
def extract_cycles(series, left=False, right=False): """Iterate cycles in the series. Parameters ---------- series : iterable sequence of numbers left: bool, optional If True, treat the first point in the series as a reversal. right: bool, optional If True, treat the last point ...
Iterate cycles in the series. Parameters ---------- series : iterable sequence of numbers left: bool, optional If True, treat the first point in the series as a reversal. right: bool, optional If True, treat the last point in the series as a reversal. Yields ------ cycl...
Below is the the instruction that describes the task: ### Input: Iterate cycles in the series. Parameters ---------- series : iterable sequence of numbers left: bool, optional If True, treat the first point in the series as a reversal. right: bool, optional If True, treat the la...
def load(self, definitions): """ Load the object by opening the URL """ url = self.location log.debug('importing (%s)', url) if '://' not in url: url = urljoin(definitions.url, url) options = definitions.options d = Definitions(url, options) if d.root....
Load the object by opening the URL
Below is the the instruction that describes the task: ### Input: Load the object by opening the URL ### Response: def load(self, definitions): """ Load the object by opening the URL """ url = self.location log.debug('importing (%s)', url) if '://' not in url: url = urljo...
def optimize_thumbnail(thumbnail): '''Optimize thumbnail images by removing unnecessary data''' try: optimize_command = settings.THUMBNAIL_OPTIMIZE_COMMAND[ determinetype(thumbnail.path)] if not optimize_command: return except (TypeError, KeyError, NotImplementedError...
Optimize thumbnail images by removing unnecessary data
Below is the the instruction that describes the task: ### Input: Optimize thumbnail images by removing unnecessary data ### Response: def optimize_thumbnail(thumbnail): '''Optimize thumbnail images by removing unnecessary data''' try: optimize_command = settings.THUMBNAIL_OPTIMIZE_COMMAND[ ...
def getschemacls(resource, besteffort=False): """Get schema class related to input resource. :param resource: resource from which get schema class. :param bool besteffort: if True (default) try a best effort in parsing the inheritance tree of resource if resource is a class. :rtype: type ...
Get schema class related to input resource. :param resource: resource from which get schema class. :param bool besteffort: if True (default) try a best effort in parsing the inheritance tree of resource if resource is a class. :rtype: type
Below is the the instruction that describes the task: ### Input: Get schema class related to input resource. :param resource: resource from which get schema class. :param bool besteffort: if True (default) try a best effort in parsing the inheritance tree of resource if resource is a class. ...
def preferred_change(data): ''' Determines preferred existing id based on curie prefix in the ranking list ''' ranking = [ 'CHEBI', 'NCBITaxon', 'COGPO', 'CAO', 'DICOM', 'UBERON', 'NLX', 'NLXANAT', 'NLXCELL', 'NLXFUNC', 'NLX...
Determines preferred existing id based on curie prefix in the ranking list
Below is the the instruction that describes the task: ### Input: Determines preferred existing id based on curie prefix in the ranking list ### Response: def preferred_change(data): ''' Determines preferred existing id based on curie prefix in the ranking list ''' ranking = [ 'CHEBI', 'NCBI...
def update(self, name, rssi): """Update the device name and/or RSSI. During an ongoing scan, multiple records from the same device can be received during the scan. Each time that happens this method is called to update the :attr:`name` and/or :attr:`rssi` attributes. """ ...
Update the device name and/or RSSI. During an ongoing scan, multiple records from the same device can be received during the scan. Each time that happens this method is called to update the :attr:`name` and/or :attr:`rssi` attributes.
Below is the the instruction that describes the task: ### Input: Update the device name and/or RSSI. During an ongoing scan, multiple records from the same device can be received during the scan. Each time that happens this method is called to update the :attr:`name` and/or :attr:`rssi` a...
def arguments_from_optionable(parser, component, prefix=""): """ Add argparse arguments from all options of one :class:`Optionable` >>> # Let's build a dummy optionable component: >>> comp = Optionable() >>> comp.add_option("num", Numeric(default=1, max=12, help="An exemple of option")) >>> comp.ad...
Add argparse arguments from all options of one :class:`Optionable` >>> # Let's build a dummy optionable component: >>> comp = Optionable() >>> comp.add_option("num", Numeric(default=1, max=12, help="An exemple of option")) >>> comp.add_option("title", Text(help="The title of the title")) >>> comp.a...
Below is the the instruction that describes the task: ### Input: Add argparse arguments from all options of one :class:`Optionable` >>> # Let's build a dummy optionable component: >>> comp = Optionable() >>> comp.add_option("num", Numeric(default=1, max=12, help="An exemple of option")) >>> comp.ad...
def get_imported_data(csv_file, **kwargs): """Reads the content of the Polarion exported csv file and returns imported data.""" open_args = [] open_kwargs = {} try: # pylint: disable=pointless-statement unicode open_args.append("rb") except NameError: open_kwargs["enc...
Reads the content of the Polarion exported csv file and returns imported data.
Below is the the instruction that describes the task: ### Input: Reads the content of the Polarion exported csv file and returns imported data. ### Response: def get_imported_data(csv_file, **kwargs): """Reads the content of the Polarion exported csv file and returns imported data.""" open_args = [] op...
def get_agent_ids_by_resource(self, resource_id): """Gets the list of ``Agent`` ``Ids`` mapped to a ``Resource``. arg: resource_id (osid.id.Id): ``Id`` of a ``Resource`` return: (osid.id.IdList) - list of agent ``Ids`` raise: NotFound - ``resource_id`` is not found raise: ...
Gets the list of ``Agent`` ``Ids`` mapped to a ``Resource``. arg: resource_id (osid.id.Id): ``Id`` of a ``Resource`` return: (osid.id.IdList) - list of agent ``Ids`` raise: NotFound - ``resource_id`` is not found raise: NullArgument - ``resource_id`` is ``null`` raise: Op...
Below is the the instruction that describes the task: ### Input: Gets the list of ``Agent`` ``Ids`` mapped to a ``Resource``. arg: resource_id (osid.id.Id): ``Id`` of a ``Resource`` return: (osid.id.IdList) - list of agent ``Ids`` raise: NotFound - ``resource_id`` is not found ...
def directive(apply_globally=False, api=None): """A decorator that registers a single hug directive""" def decorator(directive_method): if apply_globally: hug.defaults.directives[underscore(directive_method.__name__)] = directive_method else: apply_to_api = hug.API(api) i...
A decorator that registers a single hug directive
Below is the the instruction that describes the task: ### Input: A decorator that registers a single hug directive ### Response: def directive(apply_globally=False, api=None): """A decorator that registers a single hug directive""" def decorator(directive_method): if apply_globally: hug...
def post_process_get(self, result): """ Given an object with identifiers, fetches the data for that object from the service. This alters the data on the object itself & simply passes through what was received. :param result: The response data :type result: dict ...
Given an object with identifiers, fetches the data for that object from the service. This alters the data on the object itself & simply passes through what was received. :param result: The response data :type result: dict :returns: The unmodified response data
Below is the the instruction that describes the task: ### Input: Given an object with identifiers, fetches the data for that object from the service. This alters the data on the object itself & simply passes through what was received. :param result: The response data :type ...
def get_user_profile_photos(self, *args, **kwargs): """See :func:`get_user_profile_photos`""" return get_user_profile_photos(*args, **self._merge_overrides(**kwargs)).run()
See :func:`get_user_profile_photos`
Below is the the instruction that describes the task: ### Input: See :func:`get_user_profile_photos` ### Response: def get_user_profile_photos(self, *args, **kwargs): """See :func:`get_user_profile_photos`""" return get_user_profile_photos(*args, **self._merge_overrides(**kwargs)).run()
def get_block_type(values, dtype=None): """ Find the appropriate Block subclass to use for the given values and dtype. Parameters ---------- values : ndarray-like dtype : numpy or pandas dtype Returns ------- cls : class, subclass of Block """ dtype = dtype or values.dtype ...
Find the appropriate Block subclass to use for the given values and dtype. Parameters ---------- values : ndarray-like dtype : numpy or pandas dtype Returns ------- cls : class, subclass of Block
Below is the the instruction that describes the task: ### Input: Find the appropriate Block subclass to use for the given values and dtype. Parameters ---------- values : ndarray-like dtype : numpy or pandas dtype Returns ------- cls : class, subclass of Block ### Response: def get_bl...
def set_focus_to_state_model(self, state_m, ratio_requested=0.8): """ Focus a state view of respective state model :param rafcon.gui.model.state state_m: Respective state model of state view to be focused :param ratio_requested: Minimum ratio of the screen which is requested, so can be more ...
Focus a state view of respective state model :param rafcon.gui.model.state state_m: Respective state model of state view to be focused :param ratio_requested: Minimum ratio of the screen which is requested, so can be more :return:
Below is the the instruction that describes the task: ### Input: Focus a state view of respective state model :param rafcon.gui.model.state state_m: Respective state model of state view to be focused :param ratio_requested: Minimum ratio of the screen which is requested, so can be more :retu...
def cmvn(vec, variance_normalization=False): """ This function is aimed to perform global cepstral mean and variance normalization (CMVN) on input feature vector "vec". The code assumes that there is one observation per row. Args: vec (array): input feature matrix (size:(num...
This function is aimed to perform global cepstral mean and variance normalization (CMVN) on input feature vector "vec". The code assumes that there is one observation per row. Args: vec (array): input feature matrix (size:(num_observation,num_features)) variance_normaliz...
Below is the the instruction that describes the task: ### Input: This function is aimed to perform global cepstral mean and variance normalization (CMVN) on input feature vector "vec". The code assumes that there is one observation per row. Args: vec (array): input feature matrix ...
def pick(choices, default=None, str_choices=None, prompt=None, allow_mult=False, more_choices=False): ''' :param choices: Strings between which the user will make a choice :type choices: list of strings :param default: Number the index to be used as the default :type default: int or None :param ...
:param choices: Strings between which the user will make a choice :type choices: list of strings :param default: Number the index to be used as the default :type default: int or None :param str_choices: Strings to be used as aliases for the choices; must be of the same length as choices and each string ...
Below is the the instruction that describes the task: ### Input: :param choices: Strings between which the user will make a choice :type choices: list of strings :param default: Number the index to be used as the default :type default: int or None :param str_choices: Strings to be used as aliases fo...
def cleanup_nodes(doc): """ Remove text nodes containing only whitespace """ for node in doc.documentElement.childNodes: if node.nodeType == Node.TEXT_NODE and node.nodeValue.isspace(): doc.documentElement.removeChild(node) return doc
Remove text nodes containing only whitespace
Below is the the instruction that describes the task: ### Input: Remove text nodes containing only whitespace ### Response: def cleanup_nodes(doc): """ Remove text nodes containing only whitespace """ for node in doc.documentElement.childNodes: if node.nodeType == Node.TEXT_NODE and node.no...
def build(self, recipe): """ Builds a recipe :param recipe: Name of the recipe to build. """ return self.__app.recipes.build(recipe, self._plugin)
Builds a recipe :param recipe: Name of the recipe to build.
Below is the the instruction that describes the task: ### Input: Builds a recipe :param recipe: Name of the recipe to build. ### Response: def build(self, recipe): """ Builds a recipe :param recipe: Name of the recipe to build. """ return self.__app.recipes.build(r...
def can_connect_to(self, other): """Whether a connection can be established between those two meshes.""" assert other.is_mesh() disconnected = not other.is_connected() and not self.is_connected() types_differ = self._is_consumed_mesh() != other._is_consumed_mesh() return disconne...
Whether a connection can be established between those two meshes.
Below is the the instruction that describes the task: ### Input: Whether a connection can be established between those two meshes. ### Response: def can_connect_to(self, other): """Whether a connection can be established between those two meshes.""" assert other.is_mesh() disconnected = not...
def generate_dc_json(dc_dict): """Generate DC JSON data. Returns data as a JSON formatted string. """ formatted_dict = formatted_dc_dict(dc_dict) return json.dumps(formatted_dict, sort_keys=True, indent=4)
Generate DC JSON data. Returns data as a JSON formatted string.
Below is the the instruction that describes the task: ### Input: Generate DC JSON data. Returns data as a JSON formatted string. ### Response: def generate_dc_json(dc_dict): """Generate DC JSON data. Returns data as a JSON formatted string. """ formatted_dict = formatted_dc_dict(dc_dict) ...
def make(base_classes=(), have_mt=False): """Use this static method to build a model class that possibly derives from other classes. If have_mt is True, then returned class will take into account multi-threading issues when dealing with observable properties.""" good_bc = ModelF...
Use this static method to build a model class that possibly derives from other classes. If have_mt is True, then returned class will take into account multi-threading issues when dealing with observable properties.
Below is the the instruction that describes the task: ### Input: Use this static method to build a model class that possibly derives from other classes. If have_mt is True, then returned class will take into account multi-threading issues when dealing with observable properties. ### Response...
def default_error_handler(exception): """ Default error handler Will display an error page with the corresponding error code from template directory, for example, a not found will load a 404.html etc. Will first look in userland app templates and if not found, fallback to boiler templates to dis...
Default error handler Will display an error page with the corresponding error code from template directory, for example, a not found will load a 404.html etc. Will first look in userland app templates and if not found, fallback to boiler templates to display a default page. :param exception: Except...
Below is the the instruction that describes the task: ### Input: Default error handler Will display an error page with the corresponding error code from template directory, for example, a not found will load a 404.html etc. Will first look in userland app templates and if not found, fallback to boil...
def get_xsession(self, item): """ Returns the XNAT session and cache dir corresponding to the item. """ subj_label, sess_label = self._get_item_labels(item) with self: xproject = self._login.projects[self.project_id] try: xsubject =...
Returns the XNAT session and cache dir corresponding to the item.
Below is the the instruction that describes the task: ### Input: Returns the XNAT session and cache dir corresponding to the item. ### Response: def get_xsession(self, item): """ Returns the XNAT session and cache dir corresponding to the item. """ subj_label, sess_l...
def head(self, n=5): """ Return first n rows of each group. Essentially equivalent to ``.apply(lambda x: x.head(n))``, except ignores as_index flag. %(see_also)s Examples -------- >>> df = pd.DataFrame([[1, 2], [1, 4], [5, 6]], ...
Return first n rows of each group. Essentially equivalent to ``.apply(lambda x: x.head(n))``, except ignores as_index flag. %(see_also)s Examples -------- >>> df = pd.DataFrame([[1, 2], [1, 4], [5, 6]], columns=['A', 'B']) >>> df.gr...
Below is the the instruction that describes the task: ### Input: Return first n rows of each group. Essentially equivalent to ``.apply(lambda x: x.head(n))``, except ignores as_index flag. %(see_also)s Examples -------- >>> df = pd.DataFrame([[1, 2], [1, 4], [5, 6]]...
def remote_port_uneq_store(self, remote_port): """This function saves the port, if different from stored. """ if remote_port != self.remote_port: self.remote_port = remote_port return True return False
This function saves the port, if different from stored.
Below is the the instruction that describes the task: ### Input: This function saves the port, if different from stored. ### Response: def remote_port_uneq_store(self, remote_port): """This function saves the port, if different from stored. """ if remote_port != self.remote_port: self.r...
def preview(request, content_type_id, object_id): """ This is an override for django.views.default.shortcut. It assumes that get_absolute_url returns an absolute url, so it does not do any of the very elaborate link checking that shortcut does. This version adds the language code to the url. (/...
This is an override for django.views.default.shortcut. It assumes that get_absolute_url returns an absolute url, so it does not do any of the very elaborate link checking that shortcut does. This version adds the language code to the url. (/en/blaat/).
Below is the the instruction that describes the task: ### Input: This is an override for django.views.default.shortcut. It assumes that get_absolute_url returns an absolute url, so it does not do any of the very elaborate link checking that shortcut does. This version adds the language code to the ...
def username_user_password(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") username = ET.SubElement(config, "username", xmlns="urn:brocade.com:mgmt:brocade-aaa") name_key = ET.SubElement(username, "name") name_key.text = kwargs.pop('name') ...
Auto Generated Code
Below is the the instruction that describes the task: ### Input: Auto Generated Code ### Response: def username_user_password(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") username = ET.SubElement(config, "username", xmlns="urn:brocade.com:mgmt:brocade-aa...
def _basic_return(self, args, msg): """ return a failed message This method returns an undeliverable message that was published with the "immediate" flag set, or an unroutable message published with the "mandatory" flag set. The reply code and text provide information ab...
return a failed message This method returns an undeliverable message that was published with the "immediate" flag set, or an unroutable message published with the "mandatory" flag set. The reply code and text provide information about the reason that the message was undeliverabl...
Below is the the instruction that describes the task: ### Input: return a failed message This method returns an undeliverable message that was published with the "immediate" flag set, or an unroutable message published with the "mandatory" flag set. The reply code and text provide i...
def neighbors(*asns, **kwargs): ''' Search for BGP neighbors details in the mines of the ``bgp.neighbors`` function. Arguments: asns A list of AS numbers to search for. The runner will return only the neighbors of these AS numbers. device Filter by device name (minion ID)....
Search for BGP neighbors details in the mines of the ``bgp.neighbors`` function. Arguments: asns A list of AS numbers to search for. The runner will return only the neighbors of these AS numbers. device Filter by device name (minion ID). ip Search BGP neighbor using t...
Below is the the instruction that describes the task: ### Input: Search for BGP neighbors details in the mines of the ``bgp.neighbors`` function. Arguments: asns A list of AS numbers to search for. The runner will return only the neighbors of these AS numbers. device Filter by...
def launch_process(self, command): # type: (Union[bytes,text_type])->None """* What you can do - It starts process and keep it. """ if not self.option is None: command_plus_option = self.command + " " + self.option else: command_plus_option = self....
* What you can do - It starts process and keep it.
Below is the the instruction that describes the task: ### Input: * What you can do - It starts process and keep it. ### Response: def launch_process(self, command): # type: (Union[bytes,text_type])->None """* What you can do - It starts process and keep it. """ if no...
def sort_queryset(queryset, request, context=None): """ Returns a sorted queryset The context argument is only used in the template tag """ sort_by = request.GET.get('sort_by') if sort_by: if sort_by in [el.name for el in queryset.model._meta.fields]: queryset = queryset.order_by...
Returns a sorted queryset The context argument is only used in the template tag
Below is the the instruction that describes the task: ### Input: Returns a sorted queryset The context argument is only used in the template tag ### Response: def sort_queryset(queryset, request, context=None): """ Returns a sorted queryset The context argument is only used in the template tag """ ...
def deposit(self, amount): """ :param amount: (int +/-) amount to be deposited or withdrawn in cents """ _json = {"amount": amount} self.api_interface.piggy_bank_deposit(self, _json)
:param amount: (int +/-) amount to be deposited or withdrawn in cents
Below is the the instruction that describes the task: ### Input: :param amount: (int +/-) amount to be deposited or withdrawn in cents ### Response: def deposit(self, amount): """ :param amount: (int +/-) amount to be deposited or withdrawn in cents """ _json = {"amount": amou...
def compare(optimizers, problems, runs=20, all_kwargs={}): """Compare a set of optimizers. Args: optimizers: list/Optimizer; Either a list of optimizers to compare, or a single optimizer to test on each problem. problems: list/Problem; Either a problem instance or a list of problem ...
Compare a set of optimizers. Args: optimizers: list/Optimizer; Either a list of optimizers to compare, or a single optimizer to test on each problem. problems: list/Problem; Either a problem instance or a list of problem instances, one for each optimizer. all_kwargs:...
Below is the the instruction that describes the task: ### Input: Compare a set of optimizers. Args: optimizers: list/Optimizer; Either a list of optimizers to compare, or a single optimizer to test on each problem. problems: list/Problem; Either a problem instance or a list of probl...
def from_dict(cls, D, is_json=False): '''This factory for :class:`Model` takes either a native Python dictionary or a JSON dictionary/object if ``is_json`` is ``True``. The dictionary passed does not need to contain all of the values that the Model declares. ''' instance...
This factory for :class:`Model` takes either a native Python dictionary or a JSON dictionary/object if ``is_json`` is ``True``. The dictionary passed does not need to contain all of the values that the Model declares.
Below is the the instruction that describes the task: ### Input: This factory for :class:`Model` takes either a native Python dictionary or a JSON dictionary/object if ``is_json`` is ``True``. The dictionary passed does not need to contain all of the values that the Model declares. ### Respo...
def main(): """ Send data """ try: args = get_config() result = webpush( args.sub_info, data=args.data, vapid_private_key=args.key, vapid_claims=args.claims, curl=args.curl, content_encoding=args.encoding) print(res...
Send data
Below is the the instruction that describes the task: ### Input: Send data ### Response: def main(): """ Send data """ try: args = get_config() result = webpush( args.sub_info, data=args.data, vapid_private_key=args.key, vapid_claims=args.cla...
def post_event(self, id, **data): """ POST /events/:id/ Updates an event. Returns an :format:`event` for the specified event. Does not support updating a repeating event series parent (see POST /series/:id/). """ return self.post("/events/{0}/".format(id), data=d...
POST /events/:id/ Updates an event. Returns an :format:`event` for the specified event. Does not support updating a repeating event series parent (see POST /series/:id/).
Below is the the instruction that describes the task: ### Input: POST /events/:id/ Updates an event. Returns an :format:`event` for the specified event. Does not support updating a repeating event series parent (see POST /series/:id/). ### Response: def post_event(self, id, **data): """ ...
def visitIriRange(self, ctx: ShExDocParser.IriRangeContext): """ iriRange: iri (STEM_MARK iriExclusion*)? """ baseiri = self.context.iri_to_iriref(ctx.iri()) if not ctx.STEM_MARK(): vsvalue = baseiri # valueSetValue = objectValue / objectValue = IRI else: ...
iriRange: iri (STEM_MARK iriExclusion*)?
Below is the the instruction that describes the task: ### Input: iriRange: iri (STEM_MARK iriExclusion*)? ### Response: def visitIriRange(self, ctx: ShExDocParser.IriRangeContext): """ iriRange: iri (STEM_MARK iriExclusion*)? """ baseiri = self.context.iri_to_iriref(ctx.iri()) if not ctx.ST...
def getATR(reader): """Return the ATR of the card inserted into the reader.""" connection = reader.createConnection() atr = "" try: connection.connect() atr = smartcard.util.toHexString(connection.getATR()) connection.disconnect() except smartcard.Exceptions.NoCardException: ...
Return the ATR of the card inserted into the reader.
Below is the the instruction that describes the task: ### Input: Return the ATR of the card inserted into the reader. ### Response: def getATR(reader): """Return the ATR of the card inserted into the reader.""" connection = reader.createConnection() atr = "" try: connection.connect() ...
def create_case_observable(self, case_id, case_observable): """ :param case_id: Case identifier :param case_observable: TheHive observable :type case_observable: CaseObservable defined in models.py :return: TheHive observable :rtype: json """ req = self....
:param case_id: Case identifier :param case_observable: TheHive observable :type case_observable: CaseObservable defined in models.py :return: TheHive observable :rtype: json
Below is the the instruction that describes the task: ### Input: :param case_id: Case identifier :param case_observable: TheHive observable :type case_observable: CaseObservable defined in models.py :return: TheHive observable :rtype: json ### Response: def create_case_observable(se...
def combinations(iterable, r): """Calculate combinations >>> list(combinations('ABCD',2)) [['A', 'B'], ['A', 'C'], ['A', 'D'], ['B', 'C'], ['B', 'D'], ['C', 'D']] >>> list(combinations(range(4), 3)) [[0, 1, 2], [0, 1, 3], [0, 2, 3], [1, 2, 3]] Args: iterable: Any iterable object. ...
Calculate combinations >>> list(combinations('ABCD',2)) [['A', 'B'], ['A', 'C'], ['A', 'D'], ['B', 'C'], ['B', 'D'], ['C', 'D']] >>> list(combinations(range(4), 3)) [[0, 1, 2], [0, 1, 3], [0, 2, 3], [1, 2, 3]] Args: iterable: Any iterable object. r: Size of combination. Yield...
Below is the the instruction that describes the task: ### Input: Calculate combinations >>> list(combinations('ABCD',2)) [['A', 'B'], ['A', 'C'], ['A', 'D'], ['B', 'C'], ['B', 'D'], ['C', 'D']] >>> list(combinations(range(4), 3)) [[0, 1, 2], [0, 1, 3], [0, 2, 3], [1, 2, 3]] Args: iter...
def emit(self, item, defaults=None, stencil=None, to_log=False, item_formatter=None): """ Print an item to stdout, or the log on INFO level. """ item_text = self.format_item(item, defaults, stencil) # Post-process line? if item_formatter: item_text = item_formatter(i...
Print an item to stdout, or the log on INFO level.
Below is the the instruction that describes the task: ### Input: Print an item to stdout, or the log on INFO level. ### Response: def emit(self, item, defaults=None, stencil=None, to_log=False, item_formatter=None): """ Print an item to stdout, or the log on INFO level. """ item_text = self...
def patch_cluster_custom_object_scale(self, group, version, plural, name, body, **kwargs): # noqa: E501 """patch_cluster_custom_object_scale # noqa: E501 partially update scale of the specified cluster scoped custom object # noqa: E501 This method makes a synchronous HTTP request by default....
patch_cluster_custom_object_scale # noqa: E501 partially update scale of the specified cluster scoped custom object # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.patch_cluster_cus...
Below is the the instruction that describes the task: ### Input: patch_cluster_custom_object_scale # noqa: E501 partially update scale of the specified cluster scoped custom object # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, ...
def set(self, stats, value): """ Log set >>> client = StatsdClient() >>> client.set('example.set', "set") >>> client.set(('example.set61', 'example.set67'), "2701") """ self.update_stats(stats, value, self.SC_SET)
Log set >>> client = StatsdClient() >>> client.set('example.set', "set") >>> client.set(('example.set61', 'example.set67'), "2701")
Below is the the instruction that describes the task: ### Input: Log set >>> client = StatsdClient() >>> client.set('example.set', "set") >>> client.set(('example.set61', 'example.set67'), "2701") ### Response: def set(self, stats, value): """ Log set >>> client = ...
def connected(self, *, presence=structs.PresenceState(False), **kwargs): """ Return a :class:`.node.UseConnected` context manager which does not modify the presence settings. The keyword arguments are passed to the :class:`.node.UseConnected` context manager constructor. ...
Return a :class:`.node.UseConnected` context manager which does not modify the presence settings. The keyword arguments are passed to the :class:`.node.UseConnected` context manager constructor. .. versionadded:: 0.8
Below is the the instruction that describes the task: ### Input: Return a :class:`.node.UseConnected` context manager which does not modify the presence settings. The keyword arguments are passed to the :class:`.node.UseConnected` context manager constructor. .. versionadded:: 0.8 ...
def process(self, article): """ Ingests an Article to create navigation structures and parse global metadata. """ if self.article is not None and not self.collection: log.warning('Could not process additional article. Navigation only \ handles one article unless colle...
Ingests an Article to create navigation structures and parse global metadata.
Below is the the instruction that describes the task: ### Input: Ingests an Article to create navigation structures and parse global metadata. ### Response: def process(self, article): """ Ingests an Article to create navigation structures and parse global metadata. """ ...
def __place_order(self, token): """ Use the struts token to place the order. Parameters ---------- token : string The struts token received from the place order page Returns ------- int The completed order ID. """ ...
Use the struts token to place the order. Parameters ---------- token : string The struts token received from the place order page Returns ------- int The completed order ID.
Below is the the instruction that describes the task: ### Input: Use the struts token to place the order. Parameters ---------- token : string The struts token received from the place order page Returns ------- int The completed order ID. ###...
def post_data(self, path, data, content_type, **params): """ Make a POST request to the given path, with `data` in its body. Return the JSON-decoded result. The content_type must be set to reflect the kind of data being sent, which is often `application/json`. Keyword p...
Make a POST request to the given path, with `data` in its body. Return the JSON-decoded result. The content_type must be set to reflect the kind of data being sent, which is often `application/json`. Keyword parameters will be converted to URL parameters. This is unlike other P...
Below is the the instruction that describes the task: ### Input: Make a POST request to the given path, with `data` in its body. Return the JSON-decoded result. The content_type must be set to reflect the kind of data being sent, which is often `application/json`. Keyword parameter...
def object_to_dict(cls, obj): """ This function converts Objects into Dictionary """ dict_obj = dict() if obj is not None: if type(obj) == list: dict_list = [] for inst in obj: dict_list.append(cls.object_to_dict...
This function converts Objects into Dictionary
Below is the the instruction that describes the task: ### Input: This function converts Objects into Dictionary ### Response: def object_to_dict(cls, obj): """ This function converts Objects into Dictionary """ dict_obj = dict() if obj is not None: if type(ob...
def draw(self, can=None): "Draw the charts." if can == None: can = canvas.default_canvas() assert self.check_integrity() for plot in self.__plots: plot.check_integrity() self.x_range, self.x_grid_interval = \ self.__get_data_range(self.x_ra...
Draw the charts.
Below is the the instruction that describes the task: ### Input: Draw the charts. ### Response: def draw(self, can=None): "Draw the charts." if can == None: can = canvas.default_canvas() assert self.check_integrity() for plot in self.__plots: plot.check_in...
def std_filter(array, n_std=2.0, return_index=False): """Standard deviation outlier detector. :param array: array of data. :param n_std: default 2.0, exclude data out of ``n_std`` standard deviation. :param return_index: boolean, default False, if True, only returns index. """ if not isinstance...
Standard deviation outlier detector. :param array: array of data. :param n_std: default 2.0, exclude data out of ``n_std`` standard deviation. :param return_index: boolean, default False, if True, only returns index.
Below is the the instruction that describes the task: ### Input: Standard deviation outlier detector. :param array: array of data. :param n_std: default 2.0, exclude data out of ``n_std`` standard deviation. :param return_index: boolean, default False, if True, only returns index. ### Response: def st...
def exit(self, code=None, message=None, perfdata=None, extdata=None): """ manual exit from the plugin arguments: code: exit status code message: a short, one-line message to display perfdata: perfdata, if any extdata: multi-line message to give mo...
manual exit from the plugin arguments: code: exit status code message: a short, one-line message to display perfdata: perfdata, if any extdata: multi-line message to give more details
Below is the the instruction that describes the task: ### Input: manual exit from the plugin arguments: code: exit status code message: a short, one-line message to display perfdata: perfdata, if any extdata: multi-line message to give more details ### Respon...
def hashify_targets(targets: list, build_context) -> list: """Return sorted hashes of `targets`.""" return sorted(build_context.targets[target_name].hash(build_context) for target_name in listify(targets))
Return sorted hashes of `targets`.
Below is the the instruction that describes the task: ### Input: Return sorted hashes of `targets`. ### Response: def hashify_targets(targets: list, build_context) -> list: """Return sorted hashes of `targets`.""" return sorted(build_context.targets[target_name].hash(build_context) for ta...
def _child_inst_names(self) -> Set[InstanceName]: """Return the set of instance names under the receiver.""" return frozenset([c.iname() for c in self.data_children()])
Return the set of instance names under the receiver.
Below is the the instruction that describes the task: ### Input: Return the set of instance names under the receiver. ### Response: def _child_inst_names(self) -> Set[InstanceName]: """Return the set of instance names under the receiver.""" return frozenset([c.iname() for c in self.data_children()]...
def execute(self, command): """Start a new MIP run.""" process = subprocess.Popen( command, preexec_fn=lambda: signal.signal(signal.SIGPIPE, signal.SIG_DFL) ) return process
Start a new MIP run.
Below is the the instruction that describes the task: ### Input: Start a new MIP run. ### Response: def execute(self, command): """Start a new MIP run.""" process = subprocess.Popen( command, preexec_fn=lambda: signal.signal(signal.SIGPIPE, signal.SIG_DFL) ) ...
def recommend_get(self, adgroup_id, **kwargs): '''xxxxx.xxxxx.keywords.recommend.get =================================== 取得一个推广组的推荐关键词列表''' request = TOPRequest('xxxxx.xxxxx.keywords.recommend.get') request['adgroup_id'] = adgroup_id for k, v in kwargs.iteritems(): ...
xxxxx.xxxxx.keywords.recommend.get =================================== 取得一个推广组的推荐关键词列表
Below is the the instruction that describes the task: ### Input: xxxxx.xxxxx.keywords.recommend.get =================================== 取得一个推广组的推荐关键词列表 ### Response: def recommend_get(self, adgroup_id, **kwargs): '''xxxxx.xxxxx.keywords.recommend.get ================================...
def deploy_from_image(self, context, deploy_action, cancellation_context): """ Deploy From Image Command, will deploy vm from ovf image :param CancellationContext cancellation_context: :param ResourceCommandContext context: the context of the command :param DeployApp deploy_acti...
Deploy From Image Command, will deploy vm from ovf image :param CancellationContext cancellation_context: :param ResourceCommandContext context: the context of the command :param DeployApp deploy_action: :return str deploy results
Below is the the instruction that describes the task: ### Input: Deploy From Image Command, will deploy vm from ovf image :param CancellationContext cancellation_context: :param ResourceCommandContext context: the context of the command :param DeployApp deploy_action: :return str de...
def walk( self, path="/", # type: Text namespaces=None, # type: Optional[Collection[Text]] **kwargs # type: Any ): # type: (...) -> Iterator[Step] """Walk the directory structure of a filesystem. Arguments: path (str): namespaces (l...
Walk the directory structure of a filesystem. Arguments: path (str): namespaces (list, optional): A list of namespaces to include in the resource information, e.g. ``['basic', 'access']`` (defaults to ``['basic']``). Keyword Arguments: ...
Below is the the instruction that describes the task: ### Input: Walk the directory structure of a filesystem. Arguments: path (str): namespaces (list, optional): A list of namespaces to include in the resource information, e.g. ``['basic', 'access']`` ...
def put(self, src, dst): '''Upload a file to HDFS This will take a file from the ``testfiles_path`` supplied in the constuctor. ''' src = "%s%s" % (self._testfiles_path, src) return self._getStdOutCmd([self._hadoop_cmd, 'fs', '-put', src, self._full_hdfs_path(dst)], True)
Upload a file to HDFS This will take a file from the ``testfiles_path`` supplied in the constuctor.
Below is the the instruction that describes the task: ### Input: Upload a file to HDFS This will take a file from the ``testfiles_path`` supplied in the constuctor. ### Response: def put(self, src, dst): '''Upload a file to HDFS This will take a file from the ``testfiles_path`` supplied i...