code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
text
stringlengths
164
112k
async def send_contact(self, chat_id: typing.Union[base.Integer, base.String], phone_number: base.String, first_name: base.String, last_name: typing.Union[base.String, None] = None, vcard: typing.Union[base.String, None] = None, ...
Use this method to send phone contacts. Source: https://core.telegram.org/bots/api#sendcontact :param chat_id: Unique identifier for the target chat or username of the target channel :type chat_id: :obj:`typing.Union[base.Integer, base.String]` :param phone_number: Contact's phone numb...
Below is the the instruction that describes the task: ### Input: Use this method to send phone contacts. Source: https://core.telegram.org/bots/api#sendcontact :param chat_id: Unique identifier for the target chat or username of the target channel :type chat_id: :obj:`typing.Union[base.Int...
def gather_command_line_options(filter_disabled=None): """Get a sorted list of all CommandLineOption subclasses.""" if filter_disabled is None: filter_disabled = not SETTINGS.COMMAND_LINE.SHOW_DISABLED_OPTIONS options = [opt for opt in get_inheritors(CommandLineOption) if not filter_d...
Get a sorted list of all CommandLineOption subclasses.
Below is the the instruction that describes the task: ### Input: Get a sorted list of all CommandLineOption subclasses. ### Response: def gather_command_line_options(filter_disabled=None): """Get a sorted list of all CommandLineOption subclasses.""" if filter_disabled is None: filter_disabled = not...
def mine_sub_trees(self, threshold): """ Generate subtrees and mine them for patterns. """ patterns = {} mining_order = sorted(self.frequent.keys(), key=lambda x: self.frequent[x]) # Get items in tree in reverse order of occurrences. ...
Generate subtrees and mine them for patterns.
Below is the the instruction that describes the task: ### Input: Generate subtrees and mine them for patterns. ### Response: def mine_sub_trees(self, threshold): """ Generate subtrees and mine them for patterns. """ patterns = {} mining_order = sorted(self.frequent.keys(), ...
def _execute(self, request): """Run execute with retries and rate limiting. Args: request (object): The HttpRequest object to execute. Returns: dict: The response from the API. """ if self._rate_limiter: # Since the ratelimiter library only e...
Run execute with retries and rate limiting. Args: request (object): The HttpRequest object to execute. Returns: dict: The response from the API.
Below is the the instruction that describes the task: ### Input: Run execute with retries and rate limiting. Args: request (object): The HttpRequest object to execute. Returns: dict: The response from the API. ### Response: def _execute(self, request): """Run execu...
def compute_sector_exposures(positions, sectors, sector_dict=SECTORS): """ Returns arrays of long, short and gross sector exposures of an algorithm's positions Parameters ---------- positions : pd.DataFrame Daily equity positions of algorithm, in dollars. - See full explanation ...
Returns arrays of long, short and gross sector exposures of an algorithm's positions Parameters ---------- positions : pd.DataFrame Daily equity positions of algorithm, in dollars. - See full explanation in compute_style_factor_exposures. sectors : pd.DataFrame Daily Mornin...
Below is the the instruction that describes the task: ### Input: Returns arrays of long, short and gross sector exposures of an algorithm's positions Parameters ---------- positions : pd.DataFrame Daily equity positions of algorithm, in dollars. - See full explanation in compute_sty...
def set_default_init_cli_cmds(self): """ Default init commands are set --retcode true, echo off, set --vt100 off, set dut <dut name> and set testcase <tc name> :return: List of default cli initialization commands. """ init_cli_cmds = [] init_cli_cmds.append("set ...
Default init commands are set --retcode true, echo off, set --vt100 off, set dut <dut name> and set testcase <tc name> :return: List of default cli initialization commands.
Below is the the instruction that describes the task: ### Input: Default init commands are set --retcode true, echo off, set --vt100 off, set dut <dut name> and set testcase <tc name> :return: List of default cli initialization commands. ### Response: def set_default_init_cli_cmds(self): "...
def _suicide_when_without_parent(self, parent_pid): ''' Kill this process when the parent died. ''' while True: time.sleep(5) try: # Check pid alive os.kill(parent_pid, 0) except OSError: # Forcibly exit ...
Kill this process when the parent died.
Below is the the instruction that describes the task: ### Input: Kill this process when the parent died. ### Response: def _suicide_when_without_parent(self, parent_pid): ''' Kill this process when the parent died. ''' while True: time.sleep(5) try: ...
async def handle_post_request(self, environ): """Handle a long-polling POST request from the client.""" length = int(environ.get('CONTENT_LENGTH', '0')) if length > self.server.max_http_buffer_size: raise exceptions.ContentTooLongError() else: body = await environ...
Handle a long-polling POST request from the client.
Below is the the instruction that describes the task: ### Input: Handle a long-polling POST request from the client. ### Response: async def handle_post_request(self, environ): """Handle a long-polling POST request from the client.""" length = int(environ.get('CONTENT_LENGTH', '0')) if leng...
def first_location_of_maximum(x): """ Returns the first location of the maximum value of x. The position is calculated relatively to the length of x. :param x: the time series to calculate the feature of :type x: numpy.ndarray :return: the value of this feature :return type: float """ ...
Returns the first location of the maximum value of x. The position is calculated relatively to the length of x. :param x: the time series to calculate the feature of :type x: numpy.ndarray :return: the value of this feature :return type: float
Below is the the instruction that describes the task: ### Input: Returns the first location of the maximum value of x. The position is calculated relatively to the length of x. :param x: the time series to calculate the feature of :type x: numpy.ndarray :return: the value of this feature :retur...
def seed_url(self): """A URL that can be used to open the page. The URL is formatted from :py:attr:`URL_TEMPLATE`, which is then appended to :py:attr:`base_url` unless the template results in an absolute URL. :return: URL that can be used to open the page. :rtype: str ...
A URL that can be used to open the page. The URL is formatted from :py:attr:`URL_TEMPLATE`, which is then appended to :py:attr:`base_url` unless the template results in an absolute URL. :return: URL that can be used to open the page. :rtype: str
Below is the the instruction that describes the task: ### Input: A URL that can be used to open the page. The URL is formatted from :py:attr:`URL_TEMPLATE`, which is then appended to :py:attr:`base_url` unless the template results in an absolute URL. :return: URL that can be used t...
def _find_references(model_name, references=None): """ Iterate over model references for `model_name` and return a list of parent model specifications (including those of `model_name`, ordered from parent to child). """ references = references or [] references.append(model_name) ref = M...
Iterate over model references for `model_name` and return a list of parent model specifications (including those of `model_name`, ordered from parent to child).
Below is the the instruction that describes the task: ### Input: Iterate over model references for `model_name` and return a list of parent model specifications (including those of `model_name`, ordered from parent to child). ### Response: def _find_references(model_name, references=None): """ Iter...
def update_reserved_vlan_range(self, id_or_uri, vlan_pool, force=False): """ Updates the reserved vlan ID range for the fabric. Note: This method is only available on HPE Synergy. Args: id_or_uri: ID or URI of fabric. vlan_pool (dict): vlan-pool data...
Updates the reserved vlan ID range for the fabric. Note: This method is only available on HPE Synergy. Args: id_or_uri: ID or URI of fabric. vlan_pool (dict): vlan-pool data to update. force: If set to true, the operation completes despite any problems ...
Below is the the instruction that describes the task: ### Input: Updates the reserved vlan ID range for the fabric. Note: This method is only available on HPE Synergy. Args: id_or_uri: ID or URI of fabric. vlan_pool (dict): vlan-pool data to update. ...
def __add_prop(self, key, admin=False): """Add gettable and settable room config property during runtime""" def getter(self): return self.config[key] def setter(self, val): if admin and not self.admin: raise RuntimeError( f"You can't ...
Add gettable and settable room config property during runtime
Below is the the instruction that describes the task: ### Input: Add gettable and settable room config property during runtime ### Response: def __add_prop(self, key, admin=False): """Add gettable and settable room config property during runtime""" def getter(self): return self.config[...
def add_object(self, name, mesh, transform=None): """ Add an object to the collision manager. If an object with the given name is already in the manager, replace it. Parameters ---------- name : str ...
Add an object to the collision manager. If an object with the given name is already in the manager, replace it. Parameters ---------- name : str An identifier for the object mesh : Trimesh object The geometry of the collision object transform...
Below is the the instruction that describes the task: ### Input: Add an object to the collision manager. If an object with the given name is already in the manager, replace it. Parameters ---------- name : str An identifier for the object mesh : Trimesh ob...
def anchor(self, value): """ Setter for **self.__anchor** attribute. :param value: Attribute value. :type value: int """ if value is not None: assert type(value) is int, "'{0}' attribute: '{1}' type is not 'int'!".format("anchor", value) assert v...
Setter for **self.__anchor** attribute. :param value: Attribute value. :type value: int
Below is the the instruction that describes the task: ### Input: Setter for **self.__anchor** attribute. :param value: Attribute value. :type value: int ### Response: def anchor(self, value): """ Setter for **self.__anchor** attribute. :param value: Attribute value. ...
def bcbio_variation_comparison(config_file, base_dir, data): """Run a variant comparison using the bcbio.variation toolkit, given an input configuration. """ tmp_dir = utils.safe_makedir(os.path.join(base_dir, "tmp")) resources = config_utils.get_resources("bcbio_variation", data["config"]) jvm_opts...
Run a variant comparison using the bcbio.variation toolkit, given an input configuration.
Below is the the instruction that describes the task: ### Input: Run a variant comparison using the bcbio.variation toolkit, given an input configuration. ### Response: def bcbio_variation_comparison(config_file, base_dir, data): """Run a variant comparison using the bcbio.variation toolkit, given an input con...
def gap_sizes(self): """Return gap sizes per chromosome. Returns ------- gap_sizes : dict a dictionary with chromosomes as key and the total number of Ns as values """ if not self._gap_sizes: gap_file = self.props["gaps"]["gap...
Return gap sizes per chromosome. Returns ------- gap_sizes : dict a dictionary with chromosomes as key and the total number of Ns as values
Below is the the instruction that describes the task: ### Input: Return gap sizes per chromosome. Returns ------- gap_sizes : dict a dictionary with chromosomes as key and the total number of Ns as values ### Response: def gap_sizes(self): """Return ...
def gapfill( model, core, blocked, exclude, solver, epsilon=0.001, v_max=1000, weights={}, implicit_sinks=True, allow_bounds_expansion=False): """Find a set of reactions to add such that no compounds are blocked. Returns two iterators: first an iterator of reactions not in core, that were a...
Find a set of reactions to add such that no compounds are blocked. Returns two iterators: first an iterator of reactions not in core, that were added to resolve the model. Second, an iterator of reactions in core that had flux bounds expanded (i.e. irreversible reactions become reversible). Similarly t...
Below is the the instruction that describes the task: ### Input: Find a set of reactions to add such that no compounds are blocked. Returns two iterators: first an iterator of reactions not in core, that were added to resolve the model. Second, an iterator of reactions in core that had flux bounds expa...
def _match_cubes(ccube_clean, ccube_dirty, bexpcube_clean, bexpcube_dirty, hpx_order): """ Match the HEALPIX scheme and order of all the input cubes return a dictionary of cubes with the same HEALPIX scheme and order """ if hpx_order == ccube_cl...
Match the HEALPIX scheme and order of all the input cubes return a dictionary of cubes with the same HEALPIX scheme and order
Below is the the instruction that describes the task: ### Input: Match the HEALPIX scheme and order of all the input cubes return a dictionary of cubes with the same HEALPIX scheme and order ### Response: def _match_cubes(ccube_clean, ccube_dirty, bexpcube_clean, bexpcube_dirty, ...
def application(environ, start_response): """ The main WSGI application. Dispatch the current request to the functions from above and store the regular expression captures in the WSGI environment as `myapp.url_args` so that the functions from above can access the url placeholders. If nothing m...
The main WSGI application. Dispatch the current request to the functions from above and store the regular expression captures in the WSGI environment as `myapp.url_args` so that the functions from above can access the url placeholders. If nothing matches, call the `not_found` function. :param env...
Below is the the instruction that describes the task: ### Input: The main WSGI application. Dispatch the current request to the functions from above and store the regular expression captures in the WSGI environment as `myapp.url_args` so that the functions from above can access the url placeholders. ...
def choose_parsimonious_states(tree, ps_feature, out_feature): """ Converts the content of the get_personalized_feature_name(feature, PARS_STATES) node feature to the predicted states and stores them in the `feature` feature to each node. The get_personalized_feature_name(feature, PARS_STATES) is delete...
Converts the content of the get_personalized_feature_name(feature, PARS_STATES) node feature to the predicted states and stores them in the `feature` feature to each node. The get_personalized_feature_name(feature, PARS_STATES) is deleted. :param feature: str, character for which the parsimonious states ar...
Below is the the instruction that describes the task: ### Input: Converts the content of the get_personalized_feature_name(feature, PARS_STATES) node feature to the predicted states and stores them in the `feature` feature to each node. The get_personalized_feature_name(feature, PARS_STATES) is deleted. ...
def shutdownFileStore(workflowDir, workflowID): """ Run the deferred functions from any prematurely terminated jobs still lingering on the system and carry out any necessary filestore-specific cleanup. This is a destructive operation and it is important to ensure that there are no other running pro...
Run the deferred functions from any prematurely terminated jobs still lingering on the system and carry out any necessary filestore-specific cleanup. This is a destructive operation and it is important to ensure that there are no other running processes on the system that are modifying or using the file st...
Below is the the instruction that describes the task: ### Input: Run the deferred functions from any prematurely terminated jobs still lingering on the system and carry out any necessary filestore-specific cleanup. This is a destructive operation and it is important to ensure that there are no other runnin...
def _update_belief(self, belief_prop, clique, clique_potential, message=None): """ Method for updating the belief. Parameters: ---------- belief_prop: Belief Propagation Belief Propagation which needs to be updated. in_clique: clique The factor w...
Method for updating the belief. Parameters: ---------- belief_prop: Belief Propagation Belief Propagation which needs to be updated. in_clique: clique The factor which needs to be updated corresponding to the input clique. out_clique_potential: factor ...
Below is the the instruction that describes the task: ### Input: Method for updating the belief. Parameters: ---------- belief_prop: Belief Propagation Belief Propagation which needs to be updated. in_clique: clique The factor which needs to be updated corre...
def tag_audio_file(audio_file, tracklisting): """ Adds tracklisting as list to lyrics tag of audio file if not present. Returns True if successful or not needed, False if tagging fails. """ try: save_tag_to_audio_file(audio_file, tracklisting) # TODO: is IOError required now or would the...
Adds tracklisting as list to lyrics tag of audio file if not present. Returns True if successful or not needed, False if tagging fails.
Below is the the instruction that describes the task: ### Input: Adds tracklisting as list to lyrics tag of audio file if not present. Returns True if successful or not needed, False if tagging fails. ### Response: def tag_audio_file(audio_file, tracklisting): """ Adds tracklisting as list to lyrics ta...
def isochone_ratio(e, rd, r_hyp): """ Get the isochone ratio as described in Spudich et al. (2013) PEER report, page 88. :param e: a float defining the E-path length, which is the distance from Pd(direction) point to hypocentre. In km. :param rd: float, distance from the sit...
Get the isochone ratio as described in Spudich et al. (2013) PEER report, page 88. :param e: a float defining the E-path length, which is the distance from Pd(direction) point to hypocentre. In km. :param rd: float, distance from the site to the direct point. :param r_hyp: ...
Below is the the instruction that describes the task: ### Input: Get the isochone ratio as described in Spudich et al. (2013) PEER report, page 88. :param e: a float defining the E-path length, which is the distance from Pd(direction) point to hypocentre. In km. :param rd: float...
def sentiment(self): """ Returns average sentiment of document. Must have sentiment enabled in XML output. :getter: returns average sentiment of the document :type: float """ if self._sentiment is None: results = self._xml.xpath('/root/document/sentences') ...
Returns average sentiment of document. Must have sentiment enabled in XML output. :getter: returns average sentiment of the document :type: float
Below is the the instruction that describes the task: ### Input: Returns average sentiment of document. Must have sentiment enabled in XML output. :getter: returns average sentiment of the document :type: float ### Response: def sentiment(self): """ Returns average sentiment of doc...
def _build(self, inputs, is_training): """Connects the module to some inputs. Args: inputs: Tensor, final dimension must be equal to embedding_dim. All other leading dimensions will be flattened and treated as a large batch. is_training: boolean, whether this connection is to training data....
Connects the module to some inputs. Args: inputs: Tensor, final dimension must be equal to embedding_dim. All other leading dimensions will be flattened and treated as a large batch. is_training: boolean, whether this connection is to training data. When this is set to False, the intern...
Below is the the instruction that describes the task: ### Input: Connects the module to some inputs. Args: inputs: Tensor, final dimension must be equal to embedding_dim. All other leading dimensions will be flattened and treated as a large batch. is_training: boolean, whether this connecti...
def filter_unbound_ports(query): """Filter ports not bound to a host or network""" # hack for pep8 E711: comparison to None should be # 'if cond is not None' none = None port_model = models_v2.Port binding_level_model = ml2_models.PortBindingLevel query = (query .join_if_necessa...
Filter ports not bound to a host or network
Below is the the instruction that describes the task: ### Input: Filter ports not bound to a host or network ### Response: def filter_unbound_ports(query): """Filter ports not bound to a host or network""" # hack for pep8 E711: comparison to None should be # 'if cond is not None' none = None po...
def downsample_bottleneck(x, output_channels, dim='2d', stride=1, scope='h'): """Downsamples 'x' by `stride` using a 1x1 convolution filter. Args: x: input tensor of size [N, H, W, C] output_channels: Desired number of output channels. dim: '2d' if 2-dimensional, '3d' if 3-dimensional. stride: What...
Downsamples 'x' by `stride` using a 1x1 convolution filter. Args: x: input tensor of size [N, H, W, C] output_channels: Desired number of output channels. dim: '2d' if 2-dimensional, '3d' if 3-dimensional. stride: What stride to use. Usually 1 or 2. scope: Optional variable scope. Returns: ...
Below is the the instruction that describes the task: ### Input: Downsamples 'x' by `stride` using a 1x1 convolution filter. Args: x: input tensor of size [N, H, W, C] output_channels: Desired number of output channels. dim: '2d' if 2-dimensional, '3d' if 3-dimensional. stride: What stride to use...
def __make_security_group_api_request(server_context, api, user_ids, group_id, container_path): """ Execute a request against the LabKey Security Controller Group Membership apis :param server_context: A LabKey server context. See utils.create_server_context. :param api: Action to execute :param use...
Execute a request against the LabKey Security Controller Group Membership apis :param server_context: A LabKey server context. See utils.create_server_context. :param api: Action to execute :param user_ids: user ids to apply action to :param group_id: group id to apply action to :param container_pat...
Below is the the instruction that describes the task: ### Input: Execute a request against the LabKey Security Controller Group Membership apis :param server_context: A LabKey server context. See utils.create_server_context. :param api: Action to execute :param user_ids: user ids to apply action to ...
def p_sens_all_paren(self, p): 'senslist : AT LPAREN TIMES RPAREN' p[0] = SensList( (Sens(None, 'all', lineno=p.lineno(1)),), lineno=p.lineno(1)) p.set_lineno(0, p.lineno(1))
senslist : AT LPAREN TIMES RPAREN
Below is the the instruction that describes the task: ### Input: senslist : AT LPAREN TIMES RPAREN ### Response: def p_sens_all_paren(self, p): 'senslist : AT LPAREN TIMES RPAREN' p[0] = SensList( (Sens(None, 'all', lineno=p.lineno(1)),), lineno=p.lineno(1)) p.set_lineno(0, p.li...
def task_id_str(task_family, params): """ Returns a canonical string used to identify a particular task :param task_family: The task family (class name) of the task :param params: a dict mapping parameter names to their serialized values :return: A unique, shortened identifier corresponding to the ...
Returns a canonical string used to identify a particular task :param task_family: The task family (class name) of the task :param params: a dict mapping parameter names to their serialized values :return: A unique, shortened identifier corresponding to the family and params
Below is the the instruction that describes the task: ### Input: Returns a canonical string used to identify a particular task :param task_family: The task family (class name) of the task :param params: a dict mapping parameter names to their serialized values :return: A unique, shortened identifier co...
def CharacterData(self, data): ''' Expat character data event handler ''' if data.strip(): data = data.encode() if not self.data: self.data = data else: self.data += data
Expat character data event handler
Below is the the instruction that describes the task: ### Input: Expat character data event handler ### Response: def CharacterData(self, data): ''' Expat character data event handler ''' if data.strip(): data = data.encode() if not self.data: ...
def _handle_exception(self, exc): """Common exception handling behavior across all exceptions. .. note:: This for internal use and should not be extended or used directly. """ exc_info = sys.exc_info() self.logger.exception( '%s while processing message ...
Common exception handling behavior across all exceptions. .. note:: This for internal use and should not be extended or used directly.
Below is the the instruction that describes the task: ### Input: Common exception handling behavior across all exceptions. .. note:: This for internal use and should not be extended or used directly. ### Response: def _handle_exception(self, exc): """Common exception handling behavior ...
def _updateVariantAnnotationSets(self, variantFile, dataUrl): """ Updates the variant annotation set associated with this variant using information in the specified pysam variantFile. """ # TODO check the consistency of this between VCF files. if not self.isAnnotated(): ...
Updates the variant annotation set associated with this variant using information in the specified pysam variantFile.
Below is the the instruction that describes the task: ### Input: Updates the variant annotation set associated with this variant using information in the specified pysam variantFile. ### Response: def _updateVariantAnnotationSets(self, variantFile, dataUrl): """ Updates the variant annotati...
def get_server_url(self): """Return the configured server url :returns: server url """ server_host = self.driver_wrapper.config.get('Server', 'host') server_port = self.driver_wrapper.config.get('Server', 'port') server_username = self.driver_wrapper.config.get_optional(...
Return the configured server url :returns: server url
Below is the the instruction that describes the task: ### Input: Return the configured server url :returns: server url ### Response: def get_server_url(self): """Return the configured server url :returns: server url """ server_host = self.driver_wrapper.config.get('Server'...
def combine_with(self, additional_constraints): """Combines two sets of constraints into a coherent single set.""" x = additional_constraints if not isinstance(additional_constraints, AffineWarpConstraints): x = AffineWarpConstraints(additional_constraints) new_constraints = [] for left, right...
Combines two sets of constraints into a coherent single set.
Below is the the instruction that describes the task: ### Input: Combines two sets of constraints into a coherent single set. ### Response: def combine_with(self, additional_constraints): """Combines two sets of constraints into a coherent single set.""" x = additional_constraints if not isinstance(add...
def backbone(self): """Returns a new `Residue` containing only the backbone atoms. Returns ------- bb_monomer : Residue `Residue` containing only the backbone atoms of the original `Monomer`. Raises ------ IndexError Raise if ...
Returns a new `Residue` containing only the backbone atoms. Returns ------- bb_monomer : Residue `Residue` containing only the backbone atoms of the original `Monomer`. Raises ------ IndexError Raise if the `atoms` dict does not conta...
Below is the the instruction that describes the task: ### Input: Returns a new `Residue` containing only the backbone atoms. Returns ------- bb_monomer : Residue `Residue` containing only the backbone atoms of the original `Monomer`. Raises ------ ...
def inner(self, x1, x2): """Calculate the constant-weighted inner product of two elements. Parameters ---------- x1, x2 : `ProductSpaceElement` Elements whose inner product is calculated. Returns ------- inner : float or complex The inner...
Calculate the constant-weighted inner product of two elements. Parameters ---------- x1, x2 : `ProductSpaceElement` Elements whose inner product is calculated. Returns ------- inner : float or complex The inner product of the two provided element...
Below is the the instruction that describes the task: ### Input: Calculate the constant-weighted inner product of two elements. Parameters ---------- x1, x2 : `ProductSpaceElement` Elements whose inner product is calculated. Returns ------- inner : float...
def get_decision_tree(self, agent_id, timestamp=None, version=DEFAULT_DECISION_TREE_VERSION): """Get decision tree. :param str agent_id: the id of the agent to get the tree. It must be an str containing only characters in "a-zA-Z0-9_-" and must be between 1 and 36 characters. :param int timestamp: ...
Get decision tree. :param str agent_id: the id of the agent to get the tree. It must be an str containing only characters in "a-zA-Z0-9_-" and must be between 1 and 36 characters. :param int timestamp: Optional. The decision tree is comptuted at this timestamp. :default timestamp: None, means t...
Below is the the instruction that describes the task: ### Input: Get decision tree. :param str agent_id: the id of the agent to get the tree. It must be an str containing only characters in "a-zA-Z0-9_-" and must be between 1 and 36 characters. :param int timestamp: Optional. The decision tree is c...
def documentation(self): """Return the documentation, from the documentation.md file, with template substitutions""" # Return the documentation as a scalar term, which has .text() and .html methods to do # metadata substitution using Jinja s = '' rc = self.build_source_files.d...
Return the documentation, from the documentation.md file, with template substitutions
Below is the the instruction that describes the task: ### Input: Return the documentation, from the documentation.md file, with template substitutions ### Response: def documentation(self): """Return the documentation, from the documentation.md file, with template substitutions""" # Return the doc...
def decr(self, conn, key, decrement=1): """Command is used to change data for some item in-place, decrementing it. The data for the item is treated as decimal representation of a 64-bit unsigned integer. :param key: ``bytes``, is the key of the item the client wishes to change ...
Command is used to change data for some item in-place, decrementing it. The data for the item is treated as decimal representation of a 64-bit unsigned integer. :param key: ``bytes``, is the key of the item the client wishes to change :param decrement: ``int``, is the amount by ...
Below is the the instruction that describes the task: ### Input: Command is used to change data for some item in-place, decrementing it. The data for the item is treated as decimal representation of a 64-bit unsigned integer. :param key: ``bytes``, is the key of the item the client wishes ...
def to_dict(self, nested=False): """Return dict object with model's data. :param nested: flag to return nested relationships' data if true :type: bool :return: dict """ result = dict() for key in self.columns: result[key] = getattr(self, key) ...
Return dict object with model's data. :param nested: flag to return nested relationships' data if true :type: bool :return: dict
Below is the the instruction that describes the task: ### Input: Return dict object with model's data. :param nested: flag to return nested relationships' data if true :type: bool :return: dict ### Response: def to_dict(self, nested=False): """Return dict object with model's data. ...
def _calculate_gain(self, cost_base, y_true, X, cost_mat, split): """ Private function to calculate the gain in cost of using split in the current node. Parameters ---------- cost_base : float Cost of the naive prediction y_true : array indicator matrix ...
Private function to calculate the gain in cost of using split in the current node. Parameters ---------- cost_base : float Cost of the naive prediction y_true : array indicator matrix Ground truth (correct) labels. X : array-like of shape = [n_...
Below is the the instruction that describes the task: ### Input: Private function to calculate the gain in cost of using split in the current node. Parameters ---------- cost_base : float Cost of the naive prediction y_true : array indicator matrix ...
def host(self): # pylint: disable=too-many-branches """Get a passive checks for an host and its services This function builds the external commands corresponding to the host and services provided information :param host_name: host name :param data: dictionary of the hos...
Get a passive checks for an host and its services This function builds the external commands corresponding to the host and services provided information :param host_name: host name :param data: dictionary of the host properties to be modified :return: command line
Below is the the instruction that describes the task: ### Input: Get a passive checks for an host and its services This function builds the external commands corresponding to the host and services provided information :param host_name: host name :param data: dictionary of the host ...
def sample_slice(args): """ Return a new live point proposed by a series of random slices away from an existing live point. Standard "Gibs-like" implementation where a single multivariate "slice" is a combination of `ndim` univariate slices through each axis. Parameters ---------- u : `...
Return a new live point proposed by a series of random slices away from an existing live point. Standard "Gibs-like" implementation where a single multivariate "slice" is a combination of `ndim` univariate slices through each axis. Parameters ---------- u : `~numpy.ndarray` with shape (npdim,) ...
Below is the the instruction that describes the task: ### Input: Return a new live point proposed by a series of random slices away from an existing live point. Standard "Gibs-like" implementation where a single multivariate "slice" is a combination of `ndim` univariate slices through each axis. Pa...
def disconnect(self): """Disconnect from the Graphite server if connected.""" if self.sock is not None: try: self.sock.close() except socket.error: pass finally: self.sock = None
Disconnect from the Graphite server if connected.
Below is the the instruction that describes the task: ### Input: Disconnect from the Graphite server if connected. ### Response: def disconnect(self): """Disconnect from the Graphite server if connected.""" if self.sock is not None: try: self.sock.close() except socket.error: pa...
def standard_input(): """Generator that yields lines from standard input.""" with click.get_text_stream("stdin") as stdin: while stdin.readable(): line = stdin.readline() if line: yield line.strip().encode("utf-8")
Generator that yields lines from standard input.
Below is the the instruction that describes the task: ### Input: Generator that yields lines from standard input. ### Response: def standard_input(): """Generator that yields lines from standard input.""" with click.get_text_stream("stdin") as stdin: while stdin.readable(): line = stdin...
def make_random_histogram(length=100, num_bins=10): "Returns a sequence of histogram density values that sum to 1.0" hist, bin_edges = np.histogram(np.random.random(length), bins=num_bins, density=True) # to ensure they sum to 1.0 hist = hist / sum(hist) if len(...
Returns a sequence of histogram density values that sum to 1.0
Below is the the instruction that describes the task: ### Input: Returns a sequence of histogram density values that sum to 1.0 ### Response: def make_random_histogram(length=100, num_bins=10): "Returns a sequence of histogram density values that sum to 1.0" hist, bin_edges = np.histogram(np.random.random...
def _config_parser_constrained(self, read_only): """:return: Config Parser constrained to our submodule in read or write mode""" try: pc = self.parent_commit except ValueError: pc = None # end handle empty parent repository parser = self._config_parser(sel...
:return: Config Parser constrained to our submodule in read or write mode
Below is the the instruction that describes the task: ### Input: :return: Config Parser constrained to our submodule in read or write mode ### Response: def _config_parser_constrained(self, read_only): """:return: Config Parser constrained to our submodule in read or write mode""" try: ...
def argument(self, argument_dest, arg_type=None, **kwargs): """ Register an argument for the given command scope using a knack.arguments.CLIArgumentType :param argument_dest: The destination argument to add this argument type to :type argument_dest: str :param arg_type: Predefined CLIAr...
Register an argument for the given command scope using a knack.arguments.CLIArgumentType :param argument_dest: The destination argument to add this argument type to :type argument_dest: str :param arg_type: Predefined CLIArgumentType definition to register, as modified by any provided kwargs. ...
Below is the the instruction that describes the task: ### Input: Register an argument for the given command scope using a knack.arguments.CLIArgumentType :param argument_dest: The destination argument to add this argument type to :type argument_dest: str :param arg_type: Predefined CLIArgum...
def link(self, content, link, title=''): """ Emit a link, potentially remapped based on our embed or static rules """ link = links.resolve(link, self._search_path, self._config.get('absolute')) return '{}{}</a>'.format( utils.make_tag('a', { ...
Emit a link, potentially remapped based on our embed or static rules
Below is the the instruction that describes the task: ### Input: Emit a link, potentially remapped based on our embed or static rules ### Response: def link(self, content, link, title=''): """ Emit a link, potentially remapped based on our embed or static rules """ link = links.resolve(link, self....
def post_user_login(sender, request, user, **kwargs): """ Create a profile for the user, when missing. Make sure that all neccessary user groups exist and have the right permissions. We need that automatism for people not calling the configure tool, admin rights for admins after the ...
Create a profile for the user, when missing. Make sure that all neccessary user groups exist and have the right permissions. We need that automatism for people not calling the configure tool, admin rights for admins after the first login, and similar cases.
Below is the the instruction that describes the task: ### Input: Create a profile for the user, when missing. Make sure that all neccessary user groups exist and have the right permissions. We need that automatism for people not calling the configure tool, admin rights for admins after the f...
def _append_plain_text(self, text, before_prompt=False): """ Appends plain text, processing ANSI codes if enabled. """ self._append_custom(self._insert_plain_text, text, before_prompt)
Appends plain text, processing ANSI codes if enabled.
Below is the the instruction that describes the task: ### Input: Appends plain text, processing ANSI codes if enabled. ### Response: def _append_plain_text(self, text, before_prompt=False): """ Appends plain text, processing ANSI codes if enabled. """ self._append_custom(self._insert_plain_...
def _pad_arrays(t, arrays, indices, span, period): """Internal routine to pad arrays for periodic models.""" N = len(t) if indices is None: indices = np.arange(N) pad_left = max(0, 0 - np.min(indices - span // 2)) pad_right = max(0, np.max(indices + span - span // 2) - (N - 1)) if pad_...
Internal routine to pad arrays for periodic models.
Below is the the instruction that describes the task: ### Input: Internal routine to pad arrays for periodic models. ### Response: def _pad_arrays(t, arrays, indices, span, period): """Internal routine to pad arrays for periodic models.""" N = len(t) if indices is None: indices = np.arange(N) ...
def multiply(self, number): """Return a Vector as the product of the vector and a real number.""" return self.from_list([x * number for x in self.to_list()])
Return a Vector as the product of the vector and a real number.
Below is the the instruction that describes the task: ### Input: Return a Vector as the product of the vector and a real number. ### Response: def multiply(self, number): """Return a Vector as the product of the vector and a real number.""" return self.from_list([x * number for x in self.to_list()]...
def environmentvip_step(self, finality='', client='', environmentp44=''): """ List finality, client or environment vip list. Param finality: finality of environment(optional) Param client: client of environment(optional) Param environmentp44: environmentp44(optional) Retu...
List finality, client or environment vip list. Param finality: finality of environment(optional) Param client: client of environment(optional) Param environmentp44: environmentp44(optional) Return finality list: when request has no finality and client. Return client list: when re...
Below is the the instruction that describes the task: ### Input: List finality, client or environment vip list. Param finality: finality of environment(optional) Param client: client of environment(optional) Param environmentp44: environmentp44(optional) Return finality list: when re...
def valid_station(station: str): """ Checks the validity of a station ident This function doesn't return anything. It merely raises a BadStation error if needed """ station = station.strip() if len(station) != 4: raise BadStation('ICAO station idents must be four characters long') u...
Checks the validity of a station ident This function doesn't return anything. It merely raises a BadStation error if needed
Below is the the instruction that describes the task: ### Input: Checks the validity of a station ident This function doesn't return anything. It merely raises a BadStation error if needed ### Response: def valid_station(station: str): """ Checks the validity of a station ident This function does...
def _setbin_unsafe(self, binstring): """Same as _setbin_safe, but input isn't sanity checked. binstring mustn't start with '0b'.""" length = len(binstring) # pad with zeros up to byte boundary if needed boundary = ((length + 7) // 8) * 8 padded_binstring = binstring + '0' * (boun...
Same as _setbin_safe, but input isn't sanity checked. binstring mustn't start with '0b'.
Below is the the instruction that describes the task: ### Input: Same as _setbin_safe, but input isn't sanity checked. binstring mustn't start with '0b'. ### Response: def _setbin_unsafe(self, binstring): """Same as _setbin_safe, but input isn't sanity checked. binstring mustn't start with '0b'.""" ...
def refresh(self): """Refresh the server and it's child objects. This method removes all the cache information in the server and it's child objects, and fetches the information again from the server using hpssacli/ssacli command. :raises: HPSSAOperationError, if hpssacli/ssacli...
Refresh the server and it's child objects. This method removes all the cache information in the server and it's child objects, and fetches the information again from the server using hpssacli/ssacli command. :raises: HPSSAOperationError, if hpssacli/ssacli operation failed.
Below is the the instruction that describes the task: ### Input: Refresh the server and it's child objects. This method removes all the cache information in the server and it's child objects, and fetches the information again from the server using hpssacli/ssacli command. :raises: ...
def write(self, filename=None): """Save exif data to file.""" if filename is None: filename = self._filename exif_bytes = piexif.dump(self._ef) with open(self._filename, "rb") as fin: img = fin.read() try: piexif.insert(exif_bytes, img, filen...
Save exif data to file.
Below is the the instruction that describes the task: ### Input: Save exif data to file. ### Response: def write(self, filename=None): """Save exif data to file.""" if filename is None: filename = self._filename exif_bytes = piexif.dump(self._ef) with open(self._filena...
def wstatus_to_str(status): """ Parse and format a :func:`os.waitpid` exit status. """ if os.WIFEXITED(status): return 'exited with return code %d' % (os.WEXITSTATUS(status),) if os.WIFSIGNALED(status): n = os.WTERMSIG(status) return 'exited due to signal %d (%s)' % (n, SIGNA...
Parse and format a :func:`os.waitpid` exit status.
Below is the the instruction that describes the task: ### Input: Parse and format a :func:`os.waitpid` exit status. ### Response: def wstatus_to_str(status): """ Parse and format a :func:`os.waitpid` exit status. """ if os.WIFEXITED(status): return 'exited with return code %d' % (os.WEXITST...
def metadata_and_language_from_option_line(self, line): """Parse code options on the given line. When a start of a code cell is found, self.metadata is set to a dictionary.""" if self.start_code_re.match(line): self.language, self.metadata = self.options_to_metadata(line[line.find('%...
Parse code options on the given line. When a start of a code cell is found, self.metadata is set to a dictionary.
Below is the the instruction that describes the task: ### Input: Parse code options on the given line. When a start of a code cell is found, self.metadata is set to a dictionary. ### Response: def metadata_and_language_from_option_line(self, line): """Parse code options on the given line. When a st...
def overlay(self, matchers, force=False): """ Given a list of matchers create overlays based on them. Normally I will remember what overlays were run this way and will avoid re-running them but you can `force` me to. This is the recommended way of running overlays.c """ ...
Given a list of matchers create overlays based on them. Normally I will remember what overlays were run this way and will avoid re-running them but you can `force` me to. This is the recommended way of running overlays.c
Below is the the instruction that describes the task: ### Input: Given a list of matchers create overlays based on them. Normally I will remember what overlays were run this way and will avoid re-running them but you can `force` me to. This is the recommended way of running overlays.c ### Re...
def action_notify(self, action): """ Notify all subscribers of an action status change. action -- the action whose status changed """ message = json.dumps({ 'messageType': 'actionStatus', 'data': action.as_action_description(), }) for sub...
Notify all subscribers of an action status change. action -- the action whose status changed
Below is the the instruction that describes the task: ### Input: Notify all subscribers of an action status change. action -- the action whose status changed ### Response: def action_notify(self, action): """ Notify all subscribers of an action status change. action -- the action ...
def sky(input=None,outExt=None,configObj=None, group=None, editpars=False, **inputDict): """ Perform sky subtraction on input list of images Parameters ---------- input : str or list of str a python list of image filenames, or just a single filename configObj : configObject an i...
Perform sky subtraction on input list of images Parameters ---------- input : str or list of str a python list of image filenames, or just a single filename configObj : configObject an instance of configObject inputDict : dict, optional an optional list of parameters specifi...
Below is the the instruction that describes the task: ### Input: Perform sky subtraction on input list of images Parameters ---------- input : str or list of str a python list of image filenames, or just a single filename configObj : configObject an instance of configObject inpu...
def main(self): """ python -m utool SetupRepo.main --modname=sklearn --repo=scikit-learn --codedir=~/code -w python -m utool SetupRepo.main --repo=ubelt --codedir=~/code --modname=ubelt -w Example: >>> # DISABLE_DOCTEST >>> # SCRIPT >>> from utool.util_pr...
python -m utool SetupRepo.main --modname=sklearn --repo=scikit-learn --codedir=~/code -w python -m utool SetupRepo.main --repo=ubelt --codedir=~/code --modname=ubelt -w Example: >>> # DISABLE_DOCTEST >>> # SCRIPT >>> from utool.util_project import * # NOQA >...
Below is the the instruction that describes the task: ### Input: python -m utool SetupRepo.main --modname=sklearn --repo=scikit-learn --codedir=~/code -w python -m utool SetupRepo.main --repo=ubelt --codedir=~/code --modname=ubelt -w Example: >>> # DISABLE_DOCTEST >>> # SCRIPT ...
def bbox_to_slices(bbox): r""" Given a tuple containing bounding box coordinates, return a tuple of slice objects. A bounding box in the form of a straight list is returned by several functions in skimage, but these cannot be used to direct index into an image. This function returns a tuples o...
r""" Given a tuple containing bounding box coordinates, return a tuple of slice objects. A bounding box in the form of a straight list is returned by several functions in skimage, but these cannot be used to direct index into an image. This function returns a tuples of slices can be, such as: ...
Below is the the instruction that describes the task: ### Input: r""" Given a tuple containing bounding box coordinates, return a tuple of slice objects. A bounding box in the form of a straight list is returned by several functions in skimage, but these cannot be used to direct index into an i...
def handle_privmsg(self, params): """ Handle sending a private message to a user or channel. """ target, sep, msg = params.partition(' ') if not msg: raise IRCError.from_name( 'needmoreparams', 'PRIVMSG :Not enough parameters') ...
Handle sending a private message to a user or channel.
Below is the the instruction that describes the task: ### Input: Handle sending a private message to a user or channel. ### Response: def handle_privmsg(self, params): """ Handle sending a private message to a user or channel. """ target, sep, msg = params.partition(' ') if ...
def nsmap(self): """ Returns the current namespace mapping as a dictionary there are several problems with the map and we try to guess a few things here: 1) a URI can be mapped by many prefixes, so it is to decide which one to take 2) a prefix might map to an empty stri...
Returns the current namespace mapping as a dictionary there are several problems with the map and we try to guess a few things here: 1) a URI can be mapped by many prefixes, so it is to decide which one to take 2) a prefix might map to an empty string (some packers) 3) uri+pref...
Below is the the instruction that describes the task: ### Input: Returns the current namespace mapping as a dictionary there are several problems with the map and we try to guess a few things here: 1) a URI can be mapped by many prefixes, so it is to decide which one to take 2) a p...
def __output_thread(self): "Output thread" while self.alive: instructions = self.__get_instructions() self.__process_instructions(instructions)
Output thread
Below is the the instruction that describes the task: ### Input: Output thread ### Response: def __output_thread(self): "Output thread" while self.alive: instructions = self.__get_instructions() self.__process_instructions(instructions)
def return_hdr(self): """Return the header for further use. Returns ------- subj_id : str subject identification code start_time : datetime start time of the dataset s_freq : float sampling frequency chan_name : list of str ...
Return the header for further use. Returns ------- subj_id : str subject identification code start_time : datetime start time of the dataset s_freq : float sampling frequency chan_name : list of str list of all the channels...
Below is the the instruction that describes the task: ### Input: Return the header for further use. Returns ------- subj_id : str subject identification code start_time : datetime start time of the dataset s_freq : float sampling frequency...
def wait_for_task_property(service, task, prop, timeout_sec=120): """Waits for a task to have the specified property""" return time_wait(lambda: task_property_present_predicate(service, task, prop), timeout_seconds=timeout_sec)
Waits for a task to have the specified property
Below is the the instruction that describes the task: ### Input: Waits for a task to have the specified property ### Response: def wait_for_task_property(service, task, prop, timeout_sec=120): """Waits for a task to have the specified property""" return time_wait(lambda: task_property_present_predicate(ser...
def updateArgs(self, namespace, updates): """Set multiple key/value pairs in one call @param updates: The values to set @type updates: {unicode:unicode} """ namespace = self._fixNS(namespace) for k, v in updates.iteritems(): self.setArg(namespace, k, v)
Set multiple key/value pairs in one call @param updates: The values to set @type updates: {unicode:unicode}
Below is the the instruction that describes the task: ### Input: Set multiple key/value pairs in one call @param updates: The values to set @type updates: {unicode:unicode} ### Response: def updateArgs(self, namespace, updates): """Set multiple key/value pairs in one call @param u...
def decode(self, encoded, parentFieldName=""): """See the function description in base.py""" if parentFieldName != "": fieldName = "%s.%s" % (parentFieldName, self.name) else: fieldName = self.name return ({fieldName: ([[0, 0]], "input")}, [fieldName])
See the function description in base.py
Below is the the instruction that describes the task: ### Input: See the function description in base.py ### Response: def decode(self, encoded, parentFieldName=""): """See the function description in base.py""" if parentFieldName != "": fieldName = "%s.%s" % (parentFieldName, self.name) else: ...
def delete_source_map(srcmap_file, names, logger=None): """Delete a map from a binned analysis source map file if it exists. Parameters ---------- srcmap_file : str Path to the source map file. names : list List of HDU keys of source maps to be deleted. """ with fits.open(sr...
Delete a map from a binned analysis source map file if it exists. Parameters ---------- srcmap_file : str Path to the source map file. names : list List of HDU keys of source maps to be deleted.
Below is the the instruction that describes the task: ### Input: Delete a map from a binned analysis source map file if it exists. Parameters ---------- srcmap_file : str Path to the source map file. names : list List of HDU keys of source maps to be deleted. ### Response: def delet...
def get_msd_plot(self, plt=None, mode="specie"): """ Get the plot of the smoothed msd vs time graph. Useful for checking convergence. This can be written to an image file. Args: plt: A plot object. Defaults to None, which means one will be generated. ...
Get the plot of the smoothed msd vs time graph. Useful for checking convergence. This can be written to an image file. Args: plt: A plot object. Defaults to None, which means one will be generated. mode (str): Determines type of msd plot. By "species", "sites", ...
Below is the the instruction that describes the task: ### Input: Get the plot of the smoothed msd vs time graph. Useful for checking convergence. This can be written to an image file. Args: plt: A plot object. Defaults to None, which means one will be generated. ...
def eventize(self, granularity): """ This splits the JSON information found at self.events into the several events. For this there are three different levels of time consuming actions: 1-soft, 2-medium and 3-hard. Level 1 provides events about emails Level 2 not implemented ...
This splits the JSON information found at self.events into the several events. For this there are three different levels of time consuming actions: 1-soft, 2-medium and 3-hard. Level 1 provides events about emails Level 2 not implemented Level 3 not implemented :param g...
Below is the the instruction that describes the task: ### Input: This splits the JSON information found at self.events into the several events. For this there are three different levels of time consuming actions: 1-soft, 2-medium and 3-hard. Level 1 provides events about emails Leve...
def get_outcome(self, outcome): """ Returns the details of the outcome with the given id. :calls: `GET /api/v1/outcomes/:id \ <https://canvas.instructure.com/doc/api/outcomes.html#method.outcomes_api.show>`_ :param outcome: The outcome object or ID to return. :type outc...
Returns the details of the outcome with the given id. :calls: `GET /api/v1/outcomes/:id \ <https://canvas.instructure.com/doc/api/outcomes.html#method.outcomes_api.show>`_ :param outcome: The outcome object or ID to return. :type outcome: :class:`canvasapi.outcome.Outcome` or int ...
Below is the the instruction that describes the task: ### Input: Returns the details of the outcome with the given id. :calls: `GET /api/v1/outcomes/:id \ <https://canvas.instructure.com/doc/api/outcomes.html#method.outcomes_api.show>`_ :param outcome: The outcome object or ID to return. ...
def data_json(self, pretty=False): """Returns the data as a valid JSON string.""" if pretty: return json.dumps(self.data, sort_keys=True, indent=4, separators=(',', ': ')) else: return json.dumps(self.data)
Returns the data as a valid JSON string.
Below is the the instruction that describes the task: ### Input: Returns the data as a valid JSON string. ### Response: def data_json(self, pretty=False): """Returns the data as a valid JSON string.""" if pretty: return json.dumps(self.data, sort_keys=True, indent=4, separators=(',', ':...
def header_encode(self, string): """Header-encode a string by converting it first to bytes. The type of encoding (base64 or quoted-printable) will be based on this charset's `header_encoding`. :param string: A unicode string for the header. It must be possible to encode th...
Header-encode a string by converting it first to bytes. The type of encoding (base64 or quoted-printable) will be based on this charset's `header_encoding`. :param string: A unicode string for the header. It must be possible to encode this string to bytes using the character set's...
Below is the the instruction that describes the task: ### Input: Header-encode a string by converting it first to bytes. The type of encoding (base64 or quoted-printable) will be based on this charset's `header_encoding`. :param string: A unicode string for the header. It must be possible...
def get_objective_objective_bank_session(self): """Gets the session for retrieving objective to objective bank mappings. return: (osid.learning.ObjectiveObjectiveBankSession) - an ``ObjectiveObjectiveBankSession`` raise: OperationFailed - unable to complete request rais...
Gets the session for retrieving objective to objective bank mappings. return: (osid.learning.ObjectiveObjectiveBankSession) - an ``ObjectiveObjectiveBankSession`` raise: OperationFailed - unable to complete request raise: Unimplemented - ``supports_objective_objective_bank()``...
Below is the the instruction that describes the task: ### Input: Gets the session for retrieving objective to objective bank mappings. return: (osid.learning.ObjectiveObjectiveBankSession) - an ``ObjectiveObjectiveBankSession`` raise: OperationFailed - unable to complete request ...
def buildSubscriptionList(self): """ Hits Google Reader for a users's alphabetically ordered list of feeds. Returns true if succesful. """ self._clearLists() unreadById = {} if not self.userId: self.getUserInfo() unreadJson = self.httpGet(Re...
Hits Google Reader for a users's alphabetically ordered list of feeds. Returns true if succesful.
Below is the the instruction that describes the task: ### Input: Hits Google Reader for a users's alphabetically ordered list of feeds. Returns true if succesful. ### Response: def buildSubscriptionList(self): """ Hits Google Reader for a users's alphabetically ordered list of feeds. ...
def main(): '''Main routine.''' # Load Azure app defaults try: with open('azurermconfig.json') as config_file: config_data = json.load(config_file) except FileNotFoundError: sys.exit("Error: Expecting azurermconfig.json in current folder") tenant_id = config_data['tenant...
Main routine.
Below is the the instruction that describes the task: ### Input: Main routine. ### Response: def main(): '''Main routine.''' # Load Azure app defaults try: with open('azurermconfig.json') as config_file: config_data = json.load(config_file) except FileNotFoundError: sys....
def scalar(value): """ Take return a value[0] if `value` is a list of length 1 """ if isinstance(value, (list, tuple)) and len(value) == 1: return value[0] return value
Take return a value[0] if `value` is a list of length 1
Below is the the instruction that describes the task: ### Input: Take return a value[0] if `value` is a list of length 1 ### Response: def scalar(value): """ Take return a value[0] if `value` is a list of length 1 """ if isinstance(value, (list, tuple)) and len(value) == 1: return value[0] ...
def save(self, replace=True): """ Saves this item to SDB. :param bool replace: If ``True``, delete any attributes on the remote SDB item that have a ``None`` value on this object. """ self.domain.put_attributes(self.name, self, replace) # Delete any a...
Saves this item to SDB. :param bool replace: If ``True``, delete any attributes on the remote SDB item that have a ``None`` value on this object.
Below is the the instruction that describes the task: ### Input: Saves this item to SDB. :param bool replace: If ``True``, delete any attributes on the remote SDB item that have a ``None`` value on this object. ### Response: def save(self, replace=True): """ Saves this ...
def shouldContinue(self): """ Decide whether to start generating features or return early. Returns a boolean: True to proceed, False to skip. Sublcasses may override this to skip generation based on the presence or lack of other required pieces of font data. """ if not s...
Decide whether to start generating features or return early. Returns a boolean: True to proceed, False to skip. Sublcasses may override this to skip generation based on the presence or lack of other required pieces of font data.
Below is the the instruction that describes the task: ### Input: Decide whether to start generating features or return early. Returns a boolean: True to proceed, False to skip. Sublcasses may override this to skip generation based on the presence or lack of other required pieces of font dat...
def md5_checksum(file_path, chunk_bytes=4194304): """Return the MD5 checksum (hex digest) of the file""" with open(file_path, "rb") as infile: checksum = hashlib.md5() while 1: data = infile.read(chunk_bytes) if not data: break checksum.update...
Return the MD5 checksum (hex digest) of the file
Below is the the instruction that describes the task: ### Input: Return the MD5 checksum (hex digest) of the file ### Response: def md5_checksum(file_path, chunk_bytes=4194304): """Return the MD5 checksum (hex digest) of the file""" with open(file_path, "rb") as infile: checksum = hashlib.md5() ...
def on_press(self, window, key, scancode, action, mods): """ Key handler for key presses. """ # controls for moving position if key == glfw.KEY_W: self.pos[0] -= self._pos_step # dec x elif key == glfw.KEY_S: self.pos[0] += self._pos_step # inc ...
Key handler for key presses.
Below is the the instruction that describes the task: ### Input: Key handler for key presses. ### Response: def on_press(self, window, key, scancode, action, mods): """ Key handler for key presses. """ # controls for moving position if key == glfw.KEY_W: self.po...
def ParseFileObject(self, parser_mediator, file_object): """Parses a Systemd journal file-like object. Args: parser_mediator (ParserMediator): parser mediator. file_object (dfvfs.FileIO): a file-like object. Raises: UnableToParseFile: when the header cannot be parsed. """ file_he...
Parses a Systemd journal file-like object. Args: parser_mediator (ParserMediator): parser mediator. file_object (dfvfs.FileIO): a file-like object. Raises: UnableToParseFile: when the header cannot be parsed.
Below is the the instruction that describes the task: ### Input: Parses a Systemd journal file-like object. Args: parser_mediator (ParserMediator): parser mediator. file_object (dfvfs.FileIO): a file-like object. Raises: UnableToParseFile: when the header cannot be parsed. ### Response: ...
def best_item_from_list(item,options,fuzzy=90,fname_match=True,fuzzy_fragment=None,guess=False): '''Returns just the best item, or ``None``''' match = best_match_from_list(item,options,fuzzy,fname_match,fuzzy_fragment,guess) if match: return match[0] return None
Returns just the best item, or ``None``
Below is the the instruction that describes the task: ### Input: Returns just the best item, or ``None`` ### Response: def best_item_from_list(item,options,fuzzy=90,fname_match=True,fuzzy_fragment=None,guess=False): '''Returns just the best item, or ``None``''' match = best_match_from_list(item,options,fuz...
def debug(self): '''Retrieve the debug information from the charmstore.''' url = '{}/debug/status'.format(self.url) data = self._get(url) return data.json()
Retrieve the debug information from the charmstore.
Below is the the instruction that describes the task: ### Input: Retrieve the debug information from the charmstore. ### Response: def debug(self): '''Retrieve the debug information from the charmstore.''' url = '{}/debug/status'.format(self.url) data = self._get(url) return data.js...
def query_int_attribute(self, target, display_mask, attr): """Return the value of an integer attribute""" reply = NVCtrlQueryAttributeReplyRequest(display=self.display, opcode=self.display.get_extension_major(extname), tar...
Return the value of an integer attribute
Below is the the instruction that describes the task: ### Input: Return the value of an integer attribute ### Response: def query_int_attribute(self, target, display_mask, attr): """Return the value of an integer attribute""" reply = NVCtrlQueryAttributeReplyRequest(display=self.display, ...
def predict_encoding(file_path, n_lines=20): '''Get file encoding of a text file''' import chardet # Open the file as binary data with open(file_path, 'rb') as f: # Join binary lines for specified number of lines rawdata = b''.join([f.readline() for _ in range(n_lines)]) return cha...
Get file encoding of a text file
Below is the the instruction that describes the task: ### Input: Get file encoding of a text file ### Response: def predict_encoding(file_path, n_lines=20): '''Get file encoding of a text file''' import chardet # Open the file as binary data with open(file_path, 'rb') as f: # Join binary l...
def normalize_layout(l): """Make sure all the spots in a layout are where you can click. Returns a copy of the layout with all spot coordinates are normalized to within (0.0, 0.98). """ xs = [] ys = [] ks = [] for (k, (x, y)) in l.items(): xs.append(x) ys.append(y) ...
Make sure all the spots in a layout are where you can click. Returns a copy of the layout with all spot coordinates are normalized to within (0.0, 0.98).
Below is the the instruction that describes the task: ### Input: Make sure all the spots in a layout are where you can click. Returns a copy of the layout with all spot coordinates are normalized to within (0.0, 0.98). ### Response: def normalize_layout(l): """Make sure all the spots in a layout are w...
def create_assignment( # pylint: disable=too-many-arguments self, name, short_name, weight, max_points, due_date_str, gradebook_id='', **kwargs ): """Create a new assignment. Create a new assignment. By...
Create a new assignment. Create a new assignment. By default, assignments are created under the `Uncategorized` category. Args: name (str): descriptive assignment name, i.e. ``new NUMERIC SIMPLE ASSIGNMENT`` short_name (str): short name of assignment, on...
Below is the the instruction that describes the task: ### Input: Create a new assignment. Create a new assignment. By default, assignments are created under the `Uncategorized` category. Args: name (str): descriptive assignment name, i.e. ``new NUMERIC SIMPLE AS...
def respond(request, code): """ Responds to the request with the given response code. If ``next`` is in the form, it will redirect instead. """ redirect = request.GET.get('next', request.POST.get('next')) if redirect: return HttpResponseRedirect(redirect) return type('Response%d' % c...
Responds to the request with the given response code. If ``next`` is in the form, it will redirect instead.
Below is the the instruction that describes the task: ### Input: Responds to the request with the given response code. If ``next`` is in the form, it will redirect instead. ### Response: def respond(request, code): """ Responds to the request with the given response code. If ``next`` is in the form...
def delete_target_group(name, region=None, key=None, keyid=None, profile=None): ''' Delete target group. name (string) - The Amazon Resource Name (ARN) of the resource. returns (bool) - True on success, False on failure. CLI example: .. code-block:: bash check-target...
Delete target group. name (string) - The Amazon Resource Name (ARN) of the resource. returns (bool) - True on success, False on failure. CLI example: .. code-block:: bash check-target: boto_elb2.delete_targets_group: - name: myALB - protocol...
Below is the the instruction that describes the task: ### Input: Delete target group. name (string) - The Amazon Resource Name (ARN) of the resource. returns (bool) - True on success, False on failure. CLI example: .. code-block:: bash check-target: boto_elb2.d...
def time_slides_vacuum(time_slides, verbose = False): """ Given a dictionary mapping time slide IDs to instrument-->offset mappings, for example as returned by the as_dict() method of the TimeSlideTable class in pycbc_glue.ligolw.lsctables or by the load_time_slides() function in this module, construct and return ...
Given a dictionary mapping time slide IDs to instrument-->offset mappings, for example as returned by the as_dict() method of the TimeSlideTable class in pycbc_glue.ligolw.lsctables or by the load_time_slides() function in this module, construct and return a mapping indicating time slide equivalences. This can be ...
Below is the the instruction that describes the task: ### Input: Given a dictionary mapping time slide IDs to instrument-->offset mappings, for example as returned by the as_dict() method of the TimeSlideTable class in pycbc_glue.ligolw.lsctables or by the load_time_slides() function in this module, construct an...
def storm_relative_helicity(u, v, heights, depth, bottom=0 * units.m, storm_u=0 * units('m/s'), storm_v=0 * units('m/s')): # Partially adapted from similar SharpPy code r"""Calculate storm relative helicity. Calculates storm relatively helicity following [Markowski2010] 230-231....
r"""Calculate storm relative helicity. Calculates storm relatively helicity following [Markowski2010] 230-231. .. math:: \int\limits_0^d (\bar v - c) \cdot \bar\omega_{h} \,dz This is applied to the data from a hodograph with the following summation: .. math:: \sum_{n = 1}^{N-1} [(u_{n+1} - c_{x})(v...
Below is the the instruction that describes the task: ### Input: r"""Calculate storm relative helicity. Calculates storm relatively helicity following [Markowski2010] 230-231. .. math:: \int\limits_0^d (\bar v - c) \cdot \bar\omega_{h} \,dz This is applied to the data from a hodograph with the follow...