code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
text
stringlengths
164
112k
def delete_kubernetes_role(self, role, mount_point='kubernetes'): """DELETE /auth/<mount_point>/role/:role :type role: Name of the role. :param role: str. :param mount_point: The "path" the k8s auth backend was mounted on. Vault currently defaults to "kubernetes". :type mount_po...
DELETE /auth/<mount_point>/role/:role :type role: Name of the role. :param role: str. :param mount_point: The "path" the k8s auth backend was mounted on. Vault currently defaults to "kubernetes". :type mount_point: str. :return: Will be an empty body with a 204 status code upon ...
Below is the the instruction that describes the task: ### Input: DELETE /auth/<mount_point>/role/:role :type role: Name of the role. :param role: str. :param mount_point: The "path" the k8s auth backend was mounted on. Vault currently defaults to "kubernetes". :type mount_point: str...
def _TSat_P(P): """Define the saturated line, T=f(P) Parameters ---------- P : float Pressure, [MPa] Returns ------- T : float Temperature, [K] Notes ------ Raise :class:`NotImplementedError` if input isn't in limit: * 0.00061121 ≤ P ≤ 22.064 Refe...
Define the saturated line, T=f(P) Parameters ---------- P : float Pressure, [MPa] Returns ------- T : float Temperature, [K] Notes ------ Raise :class:`NotImplementedError` if input isn't in limit: * 0.00061121 ≤ P ≤ 22.064 References ---------- ...
Below is the the instruction that describes the task: ### Input: Define the saturated line, T=f(P) Parameters ---------- P : float Pressure, [MPa] Returns ------- T : float Temperature, [K] Notes ------ Raise :class:`NotImplementedError` if input isn't in limit...
def _get_team_results(self, team_result_html): """ Extract the winning or losing team's name and abbreviation. Depending on which team's data field is passed (either the winner or loser), return the name and abbreviation of that team to denote which team won and which lost the g...
Extract the winning or losing team's name and abbreviation. Depending on which team's data field is passed (either the winner or loser), return the name and abbreviation of that team to denote which team won and which lost the game. Parameters ---------- team_result_htm...
Below is the the instruction that describes the task: ### Input: Extract the winning or losing team's name and abbreviation. Depending on which team's data field is passed (either the winner or loser), return the name and abbreviation of that team to denote which team won and which lost the...
def create_client(self, client_id=None, client_secret=None, uaa=None): """ Create a client and add it to the manifest. :param client_id: The client id used to authenticate as a client in UAA. :param client_secret: The secret password used by a client to authenti...
Create a client and add it to the manifest. :param client_id: The client id used to authenticate as a client in UAA. :param client_secret: The secret password used by a client to authenticate and generate a UAA token. :param uaa: The UAA to create client with
Below is the the instruction that describes the task: ### Input: Create a client and add it to the manifest. :param client_id: The client id used to authenticate as a client in UAA. :param client_secret: The secret password used by a client to authenticate and generate a UA...
def add_failure(self): """ Add a failure event with the current timestamp. """ failure_time = time.time() if not self.first_failure_time: self.first_failure_time = failure_time self.failures.append(failure_time)
Add a failure event with the current timestamp.
Below is the the instruction that describes the task: ### Input: Add a failure event with the current timestamp. ### Response: def add_failure(self): """ Add a failure event with the current timestamp. """ failure_time = time.time() if not self.first_failure_time: ...
def apply_mask(matrix, mask_pattern, matrix_size, is_encoding_region): """\ Applies the provided mask pattern on the `matrix`. ISO/IEC 18004:2015(E) -- 7.8.2 Data mask patterns (page 50) :param tuple matrix: A tuple of bytearrays :param mask_pattern: A mask pattern (a function) :param int matr...
\ Applies the provided mask pattern on the `matrix`. ISO/IEC 18004:2015(E) -- 7.8.2 Data mask patterns (page 50) :param tuple matrix: A tuple of bytearrays :param mask_pattern: A mask pattern (a function) :param int matrix_size: width or height of the matrix :param is_encoding_region: A functi...
Below is the the instruction that describes the task: ### Input: \ Applies the provided mask pattern on the `matrix`. ISO/IEC 18004:2015(E) -- 7.8.2 Data mask patterns (page 50) :param tuple matrix: A tuple of bytearrays :param mask_pattern: A mask pattern (a function) :param int matrix_size: ...
def expand_python_version(version): """ Expand Python versions to all identifiers used on PyPI. >>> expand_python_version('3.5') ['3.5', 'py3', 'py2.py3', 'cp35'] """ if not re.match(r"^\d\.\d$", version): return [version] major, minor = version.split(".") patterns = [ ...
Expand Python versions to all identifiers used on PyPI. >>> expand_python_version('3.5') ['3.5', 'py3', 'py2.py3', 'cp35']
Below is the the instruction that describes the task: ### Input: Expand Python versions to all identifiers used on PyPI. >>> expand_python_version('3.5') ['3.5', 'py3', 'py2.py3', 'cp35'] ### Response: def expand_python_version(version): """ Expand Python versions to all identifiers used on PyPI. ...
def rgb_to_sv(rgb): '''Convert an RGB image or array of RGB colors to saturation and value, returning each one as a separate 32-bit floating point array or value. ''' if not isinstance(rgb, np.ndarray): rgb = np.array(rgb) axis = len(rgb.shape)-1 cmax = rgb.max(axis=axis).astype(np.float...
Convert an RGB image or array of RGB colors to saturation and value, returning each one as a separate 32-bit floating point array or value.
Below is the the instruction that describes the task: ### Input: Convert an RGB image or array of RGB colors to saturation and value, returning each one as a separate 32-bit floating point array or value. ### Response: def rgb_to_sv(rgb): '''Convert an RGB image or array of RGB colors to saturation and value,...
def imap_async(self, func, iterable, chunksize=None, callback=None): """A variant of the imap() method which returns an ApplyResult object that provides an iterator (next method(timeout) available). If callback is specified then it should be a callable which accepts a single arg...
A variant of the imap() method which returns an ApplyResult object that provides an iterator (next method(timeout) available). If callback is specified then it should be a callable which accepts a single argument. When the resulting iterator becomes ready, callback is applied to...
Below is the the instruction that describes the task: ### Input: A variant of the imap() method which returns an ApplyResult object that provides an iterator (next method(timeout) available). If callback is specified then it should be a callable which accepts a single argument. When...
def uint16_gt(a: int, b: int) -> bool: """ Return a > b. """ half_mod = 0x8000 return (((a < b) and ((b - a) > half_mod)) or ((a > b) and ((a - b) < half_mod)))
Return a > b.
Below is the the instruction that describes the task: ### Input: Return a > b. ### Response: def uint16_gt(a: int, b: int) -> bool: """ Return a > b. """ half_mod = 0x8000 return (((a < b) and ((b - a) > half_mod)) or ((a > b) and ((a - b) < half_mod)))
def render_html_tree(tree): """ Renders the given HTML tree, and strips any wrapping that was applied in get_html_tree(). You should avoid further processing of the given tree after calling this method because we modify namespaced tags here. """ # Restore any tag names that were changed in...
Renders the given HTML tree, and strips any wrapping that was applied in get_html_tree(). You should avoid further processing of the given tree after calling this method because we modify namespaced tags here.
Below is the the instruction that describes the task: ### Input: Renders the given HTML tree, and strips any wrapping that was applied in get_html_tree(). You should avoid further processing of the given tree after calling this method because we modify namespaced tags here. ### Response: def render_ht...
def is_pathogenic(pvs, ps_terms, pm_terms, pp_terms): """Check if the criterias for Pathogenic is fullfilled The following are descriptions of Pathogenic clasification from ACMG paper: Pathogenic (i) 1 Very strong (PVS1) AND (a) ≥1 Strong (PS1–PS4) OR (b) ≥2 Moderate (PM1–PM6) OR ...
Check if the criterias for Pathogenic is fullfilled The following are descriptions of Pathogenic clasification from ACMG paper: Pathogenic (i) 1 Very strong (PVS1) AND (a) ≥1 Strong (PS1–PS4) OR (b) ≥2 Moderate (PM1–PM6) OR (c) 1 Moderate (PM1–PM6) and 1 supporting (PP1–PP5) OR ...
Below is the the instruction that describes the task: ### Input: Check if the criterias for Pathogenic is fullfilled The following are descriptions of Pathogenic clasification from ACMG paper: Pathogenic (i) 1 Very strong (PVS1) AND (a) ≥1 Strong (PS1–PS4) OR (b) ≥2 Moderate (PM1–PM6...
def handle_markdown(value): md = markdown( value, extensions=[ 'markdown.extensions.fenced_code', 'codehilite', ] ) """ For some unknown reason markdown wraps the value in <p> tags. Currently there doesn't seem to be an extension to turn this off. ...
For some unknown reason markdown wraps the value in <p> tags. Currently there doesn't seem to be an extension to turn this off.
Below is the the instruction that describes the task: ### Input: For some unknown reason markdown wraps the value in <p> tags. Currently there doesn't seem to be an extension to turn this off. ### Response: def handle_markdown(value): md = markdown( value, extensions=[ 'mark...
def continuous(self, *args): """ Set fields to be continuous. :rtype: DataFrame :Example: >>> # Table schema is create table test(f1 double, f2 string) >>> # Original continuity: f1=DISCRETE, f2=DISCRETE >>> # Now we want to set ``f1`` and ``f2`` into continuou...
Set fields to be continuous. :rtype: DataFrame :Example: >>> # Table schema is create table test(f1 double, f2 string) >>> # Original continuity: f1=DISCRETE, f2=DISCRETE >>> # Now we want to set ``f1`` and ``f2`` into continuous >>> new_ds = df.continuous('f1 f2')
Below is the the instruction that describes the task: ### Input: Set fields to be continuous. :rtype: DataFrame :Example: >>> # Table schema is create table test(f1 double, f2 string) >>> # Original continuity: f1=DISCRETE, f2=DISCRETE >>> # Now we want to set ``f1`` and `...
def weighted_average_to_nodes(x1, x2, data, interpolator ): """ Weighted average of scattered data to the nodal points of a triangulation using the barycentric coordinates as weightings. Parameters ---------- x1, x2 : 1D arrays arrays of x,y or lon, lat (radians) data : 1D array of data...
Weighted average of scattered data to the nodal points of a triangulation using the barycentric coordinates as weightings. Parameters ---------- x1, x2 : 1D arrays arrays of x,y or lon, lat (radians) data : 1D array of data to be lumped to the node locations interpolator : a stripy.Tri...
Below is the the instruction that describes the task: ### Input: Weighted average of scattered data to the nodal points of a triangulation using the barycentric coordinates as weightings. Parameters ---------- x1, x2 : 1D arrays arrays of x,y or lon, lat (radians) data : 1D array of dat...
def drive(self) -> DriveChannel: """Return the primary drive channel of this qubit.""" if self._drives: return self._drives[0] else: raise PulseError("No drive channels in q[%d]" % self._index)
Return the primary drive channel of this qubit.
Below is the the instruction that describes the task: ### Input: Return the primary drive channel of this qubit. ### Response: def drive(self) -> DriveChannel: """Return the primary drive channel of this qubit.""" if self._drives: return self._drives[0] else: raise P...
def get_extent(self, filename, locations): """Obtain a SourceRange from this translation unit. The bounds of the SourceRange must ultimately be defined by a start and end SourceLocation. For the locations argument, you can pass: - 2 SourceLocation instances in a 2-tuple or list. ...
Obtain a SourceRange from this translation unit. The bounds of the SourceRange must ultimately be defined by a start and end SourceLocation. For the locations argument, you can pass: - 2 SourceLocation instances in a 2-tuple or list. - 2 int file offsets via a 2-tuple or list. ...
Below is the the instruction that describes the task: ### Input: Obtain a SourceRange from this translation unit. The bounds of the SourceRange must ultimately be defined by a start and end SourceLocation. For the locations argument, you can pass: - 2 SourceLocation instances in a 2-tupl...
async def add_alternative(self, alt, timeout=OTGW_DEFAULT_TIMEOUT): """ Add the specified Data-ID to the list of alternative commands to send to the boiler instead of a Data-ID that is known to be unsupported by the boiler. Alternative Data-IDs will always be sent to the boiler i...
Add the specified Data-ID to the list of alternative commands to send to the boiler instead of a Data-ID that is known to be unsupported by the boiler. Alternative Data-IDs will always be sent to the boiler in a Read-Data request message with the data-value set to zero. The table of alte...
Below is the the instruction that describes the task: ### Input: Add the specified Data-ID to the list of alternative commands to send to the boiler instead of a Data-ID that is known to be unsupported by the boiler. Alternative Data-IDs will always be sent to the boiler in a Read-Data reque...
def delete(self): """ Adds a check to make sure that the snapshot is able to be deleted. """ if self.status not in ("available", "error"): raise exc.SnapshotNotAvailable("Snapshot must be in 'available' " "or 'error' status before deleting. Current status:...
Adds a check to make sure that the snapshot is able to be deleted.
Below is the the instruction that describes the task: ### Input: Adds a check to make sure that the snapshot is able to be deleted. ### Response: def delete(self): """ Adds a check to make sure that the snapshot is able to be deleted. """ if self.status not in ("available", "error")...
def build(self): """Builds the barcode pattern from `self.ean`. :returns: The pattern as string :rtype: String """ code = _ean.EDGE[:] pattern = _ean.LEFT_PATTERN[int(self.ean[0])] for i, number in enumerate(self.ean[1:7]): code += _ean.CODES[pattern[...
Builds the barcode pattern from `self.ean`. :returns: The pattern as string :rtype: String
Below is the the instruction that describes the task: ### Input: Builds the barcode pattern from `self.ean`. :returns: The pattern as string :rtype: String ### Response: def build(self): """Builds the barcode pattern from `self.ean`. :returns: The pattern as string :rtype:...
def has_option(self, section, option): """Check for the existence of a given option in a given section. If the specified `section' is None or an empty string, DEFAULT is assumed. If the specified `section' does not exist, returns False.""" if not section or section == self.default_sectio...
Check for the existence of a given option in a given section. If the specified `section' is None or an empty string, DEFAULT is assumed. If the specified `section' does not exist, returns False.
Below is the the instruction that describes the task: ### Input: Check for the existence of a given option in a given section. If the specified `section' is None or an empty string, DEFAULT is assumed. If the specified `section' does not exist, returns False. ### Response: def has_option(self, sect...
def start(self): """Start the game.""" # For old-fashioned players, accept five-letter truncations like # "inven" instead of insisting on full words like "inventory". for key, value in list(self.vocabulary.items()): if isinstance(key, str) and len(key) > 5: ...
Start the game.
Below is the the instruction that describes the task: ### Input: Start the game. ### Response: def start(self): """Start the game.""" # For old-fashioned players, accept five-letter truncations like # "inven" instead of insisting on full words like "inventory". for key, value in l...
def IsRunning(self): """Returns True if there's a currently running iteration of this job.""" current_urn = self.Get(self.Schema.CURRENT_FLOW_URN) if not current_urn: return False try: current_flow = aff4.FACTORY.Open( urn=current_urn, aff4_type=flow.GRRFlow, token=self.token, mod...
Returns True if there's a currently running iteration of this job.
Below is the the instruction that describes the task: ### Input: Returns True if there's a currently running iteration of this job. ### Response: def IsRunning(self): """Returns True if there's a currently running iteration of this job.""" current_urn = self.Get(self.Schema.CURRENT_FLOW_URN) if not cur...
def _load_results(self, container_id): """ load results from recent build :return: BuildResults """ if self.temp_dir: dt = DockerTasker() # FIXME: load results only when requested # results_path = os.path.join(self.temp_dir, RESULTS_JSON) ...
load results from recent build :return: BuildResults
Below is the the instruction that describes the task: ### Input: load results from recent build :return: BuildResults ### Response: def _load_results(self, container_id): """ load results from recent build :return: BuildResults """ if self.temp_dir: dt ...
def national_significant_number(numobj): """Gets the national significant number of a phone number. Note that a national significant number doesn't contain a national prefix or any formatting. Arguments: numobj -- The PhoneNumber object for which the national significant number is ne...
Gets the national significant number of a phone number. Note that a national significant number doesn't contain a national prefix or any formatting. Arguments: numobj -- The PhoneNumber object for which the national significant number is needed. Returns the national significant numb...
Below is the the instruction that describes the task: ### Input: Gets the national significant number of a phone number. Note that a national significant number doesn't contain a national prefix or any formatting. Arguments: numobj -- The PhoneNumber object for which the national significant numbe...
async def get_vm(self, vm_id): ''' Get VM :arg vm_id: string :returns vm: object ''' result = await self.nova.servers.get(vm_id) return self._map_vm_structure(result["server"])
Get VM :arg vm_id: string :returns vm: object
Below is the the instruction that describes the task: ### Input: Get VM :arg vm_id: string :returns vm: object ### Response: async def get_vm(self, vm_id): ''' Get VM :arg vm_id: string :returns vm: object ''' result = await self.nova.servers.get(vm_i...
def flatten(it): """ Flattens any iterable From: http://stackoverflow.com/questions/11503065/python-function-to-flatten-generator-containing-another-generator :param it: Iterator, iterator to flatten :return: Generator, A generator of the flattened values """ for x in it: if...
Flattens any iterable From: http://stackoverflow.com/questions/11503065/python-function-to-flatten-generator-containing-another-generator :param it: Iterator, iterator to flatten :return: Generator, A generator of the flattened values
Below is the the instruction that describes the task: ### Input: Flattens any iterable From: http://stackoverflow.com/questions/11503065/python-function-to-flatten-generator-containing-another-generator :param it: Iterator, iterator to flatten :return: Generator, A generator of the flattene...
def delete(self, infohash_list): """ Delete torrents. :param infohash_list: Single or list() of infohashes. """ data = self._process_infohash_list(infohash_list) return self._post('command/delete', data=data)
Delete torrents. :param infohash_list: Single or list() of infohashes.
Below is the the instruction that describes the task: ### Input: Delete torrents. :param infohash_list: Single or list() of infohashes. ### Response: def delete(self, infohash_list): """ Delete torrents. :param infohash_list: Single or list() of infohashes. """ dat...
def AddVSSProcessingOptions(self, argument_group): """Adds the VSS processing options to the argument group. Args: argument_group (argparse._ArgumentGroup): argparse argument group. """ argument_group.add_argument( '--no_vss', '--no-vss', dest='no_vss', action='store_true', defaul...
Adds the VSS processing options to the argument group. Args: argument_group (argparse._ArgumentGroup): argparse argument group.
Below is the the instruction that describes the task: ### Input: Adds the VSS processing options to the argument group. Args: argument_group (argparse._ArgumentGroup): argparse argument group. ### Response: def AddVSSProcessingOptions(self, argument_group): """Adds the VSS processing options to the ...
def _request_login(self, login, password): """Sends Login request""" return self._request_internal("Login", login=login, password=password)
Sends Login request
Below is the the instruction that describes the task: ### Input: Sends Login request ### Response: def _request_login(self, login, password): """Sends Login request""" return self._request_internal("Login", login=login, pas...
def _send_stream_features(self): """Send stream <features/>. [receiving entity only]""" self.features = self._make_stream_features() self._write_element(self.features)
Send stream <features/>. [receiving entity only]
Below is the the instruction that describes the task: ### Input: Send stream <features/>. [receiving entity only] ### Response: def _send_stream_features(self): """Send stream <features/>. [receiving entity only]""" self.features = self._make_stream_features() self._write_...
def bounds_at_zoom(self, zoom=None): """ Return process bounds for zoom level. Parameters ---------- zoom : integer or list Returns ------- process bounds : tuple left, bottom, right, top """ return () if self.area_at_zoom(zoo...
Return process bounds for zoom level. Parameters ---------- zoom : integer or list Returns ------- process bounds : tuple left, bottom, right, top
Below is the the instruction that describes the task: ### Input: Return process bounds for zoom level. Parameters ---------- zoom : integer or list Returns ------- process bounds : tuple left, bottom, right, top ### Response: def bounds_at_zoom(self, zo...
def private_key_to_address(private_key: Union[str, bytes]) -> ChecksumAddress: """ Converts a private key to an Ethereum address. """ if isinstance(private_key, str): private_key_bytes = to_bytes(hexstr=private_key) else: private_key_bytes = private_key pk = PrivateKey(private_key_bytes)...
Converts a private key to an Ethereum address.
Below is the the instruction that describes the task: ### Input: Converts a private key to an Ethereum address. ### Response: def private_key_to_address(private_key: Union[str, bytes]) -> ChecksumAddress: """ Converts a private key to an Ethereum address. """ if isinstance(private_key, str): privat...
def help(self, message, plugin=None): """help: the normal help you're reading.""" # help_data = self.load("help_files") selected_modules = help_modules = self.load("help_modules") self.say("Sure thing, %s." % message.sender.handle) help_text = "Here's what I know how to do:" ...
help: the normal help you're reading.
Below is the the instruction that describes the task: ### Input: help: the normal help you're reading. ### Response: def help(self, message, plugin=None): """help: the normal help you're reading.""" # help_data = self.load("help_files") selected_modules = help_modules = self.load("help_modu...
def _init_client(self, from_archive=False): """Init client""" return ConduitClient(self.url, self.api_token, self.max_retries, self.sleep_time, self.archive, from_archive)
Init client
Below is the the instruction that describes the task: ### Input: Init client ### Response: def _init_client(self, from_archive=False): """Init client""" return ConduitClient(self.url, self.api_token, self.max_retries, self.sleep_time, self....
def wrap(cls, value): ''' Some property types need to wrap their values in special containers, etc. ''' if isinstance(value, list): if isinstance(value, PropertyValueList): return value else: return PropertyValueList(value) else: ...
Some property types need to wrap their values in special containers, etc.
Below is the the instruction that describes the task: ### Input: Some property types need to wrap their values in special containers, etc. ### Response: def wrap(cls, value): ''' Some property types need to wrap their values in special containers, etc. ''' if isinstance(value, list): ...
def _get_stddevs(self, stddev_types, rrup): """ Return standard deviations as defined in equation 3.5.5-2 page 151 """ assert all(stddev_type in self.DEFINED_FOR_STANDARD_DEVIATION_TYPES for stddev_type in stddev_types) std = np.zeros_like(rrup) std[rru...
Return standard deviations as defined in equation 3.5.5-2 page 151
Below is the the instruction that describes the task: ### Input: Return standard deviations as defined in equation 3.5.5-2 page 151 ### Response: def _get_stddevs(self, stddev_types, rrup): """ Return standard deviations as defined in equation 3.5.5-2 page 151 """ assert all(stddev_...
def add_eager_constraints(self, models): """ Set the constraints for an eager load of the relation. :type models: list """ key = "%s.%s" % (self._related.get_table(), self._other_key) self._query.where_in(key, self._get_eager_model_keys(models))
Set the constraints for an eager load of the relation. :type models: list
Below is the the instruction that describes the task: ### Input: Set the constraints for an eager load of the relation. :type models: list ### Response: def add_eager_constraints(self, models): """ Set the constraints for an eager load of the relation. :type models: list "...
def getMyPlexAccount(opts=None): # pragma: no cover """ Helper function tries to get a MyPlex Account instance by checking the the following locations for a username and password. This is useful to create user-friendly command line tools. 1. command-line options (opts). 2. environme...
Helper function tries to get a MyPlex Account instance by checking the the following locations for a username and password. This is useful to create user-friendly command line tools. 1. command-line options (opts). 2. environment variables and config.ini 3. Prompt on the command ...
Below is the the instruction that describes the task: ### Input: Helper function tries to get a MyPlex Account instance by checking the the following locations for a username and password. This is useful to create user-friendly command line tools. 1. command-line options (opts). 2. e...
def extract_code(end_mark, current_str, str_array, line_num): '''Extract a multi-line string from a string array, up to a specified end marker. Args: end_mark (str): The end mark string to match for. current_str (str): The first line of the string array. str_array (list)...
Extract a multi-line string from a string array, up to a specified end marker. Args: end_mark (str): The end mark string to match for. current_str (str): The first line of the string array. str_array (list): An array of strings (lines). line_num (int): The curren...
Below is the the instruction that describes the task: ### Input: Extract a multi-line string from a string array, up to a specified end marker. Args: end_mark (str): The end mark string to match for. current_str (str): The first line of the string array. str_array (list)...
def _prm_read_table(self, table_or_group, full_name): """Reads a non-nested PyTables table column by column and created a new ObjectTable for the loaded data. :param table_or_group: PyTables table to read from or a group containing subtables. :param full_name: ...
Reads a non-nested PyTables table column by column and created a new ObjectTable for the loaded data. :param table_or_group: PyTables table to read from or a group containing subtables. :param full_name: Full name of the parameter or result whose data is to be loaded ...
Below is the the instruction that describes the task: ### Input: Reads a non-nested PyTables table column by column and created a new ObjectTable for the loaded data. :param table_or_group: PyTables table to read from or a group containing subtables. :param full_name: ...
def save(self): """Update or insert a Todo item.""" req = datastore.CommitRequest() req.mode = datastore.CommitRequest.NON_TRANSACTIONAL req.mutations.add().upsert.CopyFrom(self.to_proto()) resp = datastore.commit(req) if not self.id: self.id = resp.mutation_results[0].key.path[-1].id ...
Update or insert a Todo item.
Below is the the instruction that describes the task: ### Input: Update or insert a Todo item. ### Response: def save(self): """Update or insert a Todo item.""" req = datastore.CommitRequest() req.mode = datastore.CommitRequest.NON_TRANSACTIONAL req.mutations.add().upsert.CopyFrom(self.to_proto()) ...
def tabulate(self, restricted_predicted_column_indices = [], restricted_predicted_column_names = [], dataset_name = None): '''Returns summary analysis from the dataframe as a DataTable object. DataTables are wrapped pandas dataframes which can be combined if the have the same width. This is useful fo...
Returns summary analysis from the dataframe as a DataTable object. DataTables are wrapped pandas dataframes which can be combined if the have the same width. This is useful for combining multiple analyses. DataTables can be printed to terminal as a tabular string using their representation functio...
Below is the the instruction that describes the task: ### Input: Returns summary analysis from the dataframe as a DataTable object. DataTables are wrapped pandas dataframes which can be combined if the have the same width. This is useful for combining multiple analyses. DataTables can be print...
def aws(client, path, opt): """Renders a shell environment snippet with AWS information""" try: creds = client.read(path) except (hvac.exceptions.InternalServerError) as vault_exception: # this is how old vault behaves if vault_exception.errors[0].find('unsupported path') > 0: ...
Renders a shell environment snippet with AWS information
Below is the the instruction that describes the task: ### Input: Renders a shell environment snippet with AWS information ### Response: def aws(client, path, opt): """Renders a shell environment snippet with AWS information""" try: creds = client.read(path) except (hvac.exceptions.InternalServ...
def split(cls, dataset, start, end, datatype, **kwargs): """ Splits a multi-interface Dataset into regular Datasets using regular tabular interfaces. """ objs = [] if datatype is None: for d in dataset.data[start: end]: objs.append(dataset.clon...
Splits a multi-interface Dataset into regular Datasets using regular tabular interfaces.
Below is the the instruction that describes the task: ### Input: Splits a multi-interface Dataset into regular Datasets using regular tabular interfaces. ### Response: def split(cls, dataset, start, end, datatype, **kwargs): """ Splits a multi-interface Dataset into regular Datasets using ...
def fuzzy_get_value(obj, approximate_key, default=None, **kwargs): """ Like fuzzy_get, but assume the obj is dict-like and return the value without the key Notes: Argument order is in reverse order relative to `fuzzywuzzy.process.extractOne()` but in the same order as get(self, key) method on dic...
Like fuzzy_get, but assume the obj is dict-like and return the value without the key Notes: Argument order is in reverse order relative to `fuzzywuzzy.process.extractOne()` but in the same order as get(self, key) method on dicts Arguments: obj (dict-like): object to run the get method on u...
Below is the the instruction that describes the task: ### Input: Like fuzzy_get, but assume the obj is dict-like and return the value without the key Notes: Argument order is in reverse order relative to `fuzzywuzzy.process.extractOne()` but in the same order as get(self, key) method on dicts ...
def _calculate_cluster_distance(end_iter): """Compute allowed distance for clustering based on end confidence intervals. """ out = [] sizes = [] for x in end_iter: out.append(x) sizes.append(x.end1 - x.start1) sizes.append(x.end2 - x.start2) distance = sum(sizes) // len(s...
Compute allowed distance for clustering based on end confidence intervals.
Below is the the instruction that describes the task: ### Input: Compute allowed distance for clustering based on end confidence intervals. ### Response: def _calculate_cluster_distance(end_iter): """Compute allowed distance for clustering based on end confidence intervals. """ out = [] sizes = [] ...
def create_new_address_for_user(self, user_id): """Create a new bitcoin address to accept payments for a User. This is a convenience wrapper around `get_child` that helps you do the right thing. This method always creates a public, non-prime address that can be generated from a BIP32 pu...
Create a new bitcoin address to accept payments for a User. This is a convenience wrapper around `get_child` that helps you do the right thing. This method always creates a public, non-prime address that can be generated from a BIP32 public key on an insecure server.
Below is the the instruction that describes the task: ### Input: Create a new bitcoin address to accept payments for a User. This is a convenience wrapper around `get_child` that helps you do the right thing. This method always creates a public, non-prime address that can be generated from ...
def add_rect(img, box, color=None, thickness=1): """ Draws a bounding box inside the image. :param img: Input image :param box: Box object that defines the bounding box. :param color: Color of the box :param thickness: Thickness of line :return: Rectangle added image """ if color is...
Draws a bounding box inside the image. :param img: Input image :param box: Box object that defines the bounding box. :param color: Color of the box :param thickness: Thickness of line :return: Rectangle added image
Below is the the instruction that describes the task: ### Input: Draws a bounding box inside the image. :param img: Input image :param box: Box object that defines the bounding box. :param color: Color of the box :param thickness: Thickness of line :return: Rectangle added image ### Response: ...
def create_namespaced_config_map(self, namespace, body, **kwargs): # noqa: E501 """create_namespaced_config_map # noqa: E501 create a ConfigMap # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True ...
create_namespaced_config_map # noqa: E501 create a ConfigMap # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.create_namespaced_config_map(namespace, body, async_req=True) >>...
Below is the the instruction that describes the task: ### Input: create_namespaced_config_map # noqa: E501 create a ConfigMap # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.cre...
def remove(self, item): """ Transactional implementation of :func:`Set.remove(item) <hazelcast.proxy.set.Set.remove>` :param item: (object), the specified item to be deleted. :return: (bool), ``true`` if item is remove successfully, ``false`` otherwise. """ check_not_non...
Transactional implementation of :func:`Set.remove(item) <hazelcast.proxy.set.Set.remove>` :param item: (object), the specified item to be deleted. :return: (bool), ``true`` if item is remove successfully, ``false`` otherwise.
Below is the the instruction that describes the task: ### Input: Transactional implementation of :func:`Set.remove(item) <hazelcast.proxy.set.Set.remove>` :param item: (object), the specified item to be deleted. :return: (bool), ``true`` if item is remove successfully, ``false`` otherwise. ### Resp...
def sgt(self, other): """Compares two equal-sized BinWords, treating them as signed integers, and returning True if the first is bigger. """ self._check_match(other) return self.to_sint() > other.to_sint()
Compares two equal-sized BinWords, treating them as signed integers, and returning True if the first is bigger.
Below is the the instruction that describes the task: ### Input: Compares two equal-sized BinWords, treating them as signed integers, and returning True if the first is bigger. ### Response: def sgt(self, other): """Compares two equal-sized BinWords, treating them as signed integers, and re...
def get_authorisation_url(self, reset=False): """ Initialises the OAuth2 Process by asking the auth server for a login URL. Once called, the user can login by being redirected to the url returned by this function. If there is an error during authorisation, None is returned.""...
Initialises the OAuth2 Process by asking the auth server for a login URL. Once called, the user can login by being redirected to the url returned by this function. If there is an error during authorisation, None is returned.
Below is the the instruction that describes the task: ### Input: Initialises the OAuth2 Process by asking the auth server for a login URL. Once called, the user can login by being redirected to the url returned by this function. If there is an error during authorisation, None is ...
def Search(self, text): """Search the text for our value.""" if isinstance(text, rdfvalue.RDFString): text = str(text) return self._regex.search(text)
Search the text for our value.
Below is the the instruction that describes the task: ### Input: Search the text for our value. ### Response: def Search(self, text): """Search the text for our value.""" if isinstance(text, rdfvalue.RDFString): text = str(text) return self._regex.search(text)
def upper_underscore(string, prefix='', suffix=''): """ Generate an underscore-separated upper-case identifier. Useful for constants. Takes a string, prefix, and optional suffix. `prefix` can be set to `''`, though be careful - without a prefix, the function will throw `InvalidIdentifier` when...
Generate an underscore-separated upper-case identifier. Useful for constants. Takes a string, prefix, and optional suffix. `prefix` can be set to `''`, though be careful - without a prefix, the function will throw `InvalidIdentifier` when your string starts with a number. Example: >>>...
Below is the the instruction that describes the task: ### Input: Generate an underscore-separated upper-case identifier. Useful for constants. Takes a string, prefix, and optional suffix. `prefix` can be set to `''`, though be careful - without a prefix, the function will throw `InvalidIdentifier`...
def remove_repo_from_team(self, auth, team_id, repo_name): """ Remove repo from team. :param auth.Authentication auth: authentication object, must be admin-level :param str team_id: Team's id :param str repo_name: Name of the repo to be removed from the team :raises Netw...
Remove repo from team. :param auth.Authentication auth: authentication object, must be admin-level :param str team_id: Team's id :param str repo_name: Name of the repo to be removed from the team :raises NetworkFailure: if there is an error communicating with the server :raises ...
Below is the the instruction that describes the task: ### Input: Remove repo from team. :param auth.Authentication auth: authentication object, must be admin-level :param str team_id: Team's id :param str repo_name: Name of the repo to be removed from the team :raises NetworkFailure...
def sweep(ABF,sweep=None,rainbow=True,alpha=None,protocol=False,color='b', continuous=False,offsetX=0,offsetY=0,minutes=False, decimate=None,newFigure=False): """ Load a particular sweep then plot it. If sweep is None or False, just plot current dataX/dataY. If rainbow, it'...
Load a particular sweep then plot it. If sweep is None or False, just plot current dataX/dataY. If rainbow, it'll make it color coded prettily.
Below is the the instruction that describes the task: ### Input: Load a particular sweep then plot it. If sweep is None or False, just plot current dataX/dataY. If rainbow, it'll make it color coded prettily. ### Response: def sweep(ABF,sweep=None,rainbow=True,alpha=None,protocol=False,color='b', ...
def _read_header(self, header_str): """Reads metadata from the header.""" # regular expressions re_float = '[-+]?(\d+(\.\d*)?|\.\d+)([eE][-+]?\d+)?' re_uint = '\d+' re_binning = '{d} in (?P<nbins>' + re_uint + ') bin[ s] ' re_binning += 'of (?P<binwidth>' + re_float + ')...
Reads metadata from the header.
Below is the the instruction that describes the task: ### Input: Reads metadata from the header. ### Response: def _read_header(self, header_str): """Reads metadata from the header.""" # regular expressions re_float = '[-+]?(\d+(\.\d*)?|\.\d+)([eE][-+]?\d+)?' re_uint = '\d+' ...
def csv_to_numpy(string_like, dtype=None): # type: (str) -> np.array """Convert a CSV object to a numpy array. Args: string_like (str): CSV string. dtype (dtype, optional): Data type of the resulting array. If None, the dtypes will be determined by the ...
Convert a CSV object to a numpy array. Args: string_like (str): CSV string. dtype (dtype, optional): Data type of the resulting array. If None, the dtypes will be determined by the contents of each column, individually. This argument can only be used to ...
Below is the the instruction that describes the task: ### Input: Convert a CSV object to a numpy array. Args: string_like (str): CSV string. dtype (dtype, optional): Data type of the resulting array. If None, the dtypes will be determined by the contents...
def paga_expression_entropies(adata) -> List[float]: """Compute the median expression entropy for each node-group. Parameters ---------- adata : AnnData Annotated data matrix. Returns ------- Entropies of median expressions for each node. """ from scipy.stats import entropy...
Compute the median expression entropy for each node-group. Parameters ---------- adata : AnnData Annotated data matrix. Returns ------- Entropies of median expressions for each node.
Below is the the instruction that describes the task: ### Input: Compute the median expression entropy for each node-group. Parameters ---------- adata : AnnData Annotated data matrix. Returns ------- Entropies of median expressions for each node. ### Response: def paga_expression...
def get_pixel(framebuf, x, y): """Get the color of a given pixel""" index = (y >> 3) * framebuf.stride + x offset = y & 0x07 return (framebuf.buf[index] >> offset) & 0x01
Get the color of a given pixel
Below is the the instruction that describes the task: ### Input: Get the color of a given pixel ### Response: def get_pixel(framebuf, x, y): """Get the color of a given pixel""" index = (y >> 3) * framebuf.stride + x offset = y & 0x07 return (framebuf.buf[index] >> offset) & 0x01
def sg_arg(): r"""Gets current command line options Returns: tf.sg_opt instance that is updated with current commandd line options. """ if not tf.app.flags.FLAGS.__dict__['__parsed']: tf.app.flags.FLAGS._parse_flags() return tf.sg_opt(tf.app.flags.FLAGS.__dict__['__flags'])
r"""Gets current command line options Returns: tf.sg_opt instance that is updated with current commandd line options.
Below is the the instruction that describes the task: ### Input: r"""Gets current command line options Returns: tf.sg_opt instance that is updated with current commandd line options. ### Response: def sg_arg(): r"""Gets current command line options Returns: tf.sg_opt instance that is upda...
def do_gate(self, gate: Gate) -> 'AbstractQuantumSimulator': """ Perform a gate. :return: ``self`` to support method chaining. """ unitary = lifted_gate(gate=gate, n_qubits=self.n_qubits) self.density = unitary.dot(self.density).dot(np.conj(unitary).T) return sel...
Perform a gate. :return: ``self`` to support method chaining.
Below is the the instruction that describes the task: ### Input: Perform a gate. :return: ``self`` to support method chaining. ### Response: def do_gate(self, gate: Gate) -> 'AbstractQuantumSimulator': """ Perform a gate. :return: ``self`` to support method chaining. """ ...
def filter_hidden_frames(self): """Remove the frames according to the paste spec.""" for group in self.groups: group.filter_hidden_frames() self.frames[:] = [frame for group in self.groups for frame in group.frames]
Remove the frames according to the paste spec.
Below is the the instruction that describes the task: ### Input: Remove the frames according to the paste spec. ### Response: def filter_hidden_frames(self): """Remove the frames according to the paste spec.""" for group in self.groups: group.filter_hidden_frames() self.frames[...
def plan_tr(p, *args, **kwargs): ''' plan_tr(p, ...) yields a copy of plan p in which the afferent and efferent values of its functions have been translated. The translation is found from merging the list of 0 or more dictionary arguments given left-to-right followed by the keyword arguments. If the...
plan_tr(p, ...) yields a copy of plan p in which the afferent and efferent values of its functions have been translated. The translation is found from merging the list of 0 or more dictionary arguments given left-to-right followed by the keyword arguments. If the plan that is given is not a plan objec...
Below is the the instruction that describes the task: ### Input: plan_tr(p, ...) yields a copy of plan p in which the afferent and efferent values of its functions have been translated. The translation is found from merging the list of 0 or more dictionary arguments given left-to-right followed by the k...
def match_note_onsets(ref_intervals, est_intervals, onset_tolerance=0.05, strict=False): """Compute a maximum matching between reference and estimated notes, only taking note onsets into account. Given two note sequences represented by ``ref_intervals`` and ``est_intervals`` (see ...
Compute a maximum matching between reference and estimated notes, only taking note onsets into account. Given two note sequences represented by ``ref_intervals`` and ``est_intervals`` (see :func:`mir_eval.io.load_valued_intervals`), we see the largest set of correspondences ``(i,j)`` such that the onse...
Below is the the instruction that describes the task: ### Input: Compute a maximum matching between reference and estimated notes, only taking note onsets into account. Given two note sequences represented by ``ref_intervals`` and ``est_intervals`` (see :func:`mir_eval.io.load_valued_intervals`), we se...
def clear(self): """Clear all keys from the comment.""" for i in list(self._internal): self._internal.remove(i)
Clear all keys from the comment.
Below is the the instruction that describes the task: ### Input: Clear all keys from the comment. ### Response: def clear(self): """Clear all keys from the comment.""" for i in list(self._internal): self._internal.remove(i)
def decode_jwt(encoded_token, secret, algorithm, identity_claim_key, user_claims_key): """ Decodes an encoded JWT :param encoded_token: The encoded JWT string to decode :param secret: Secret key used to encode the JWT :param algorithm: Algorithm used to encode the JWT :param iden...
Decodes an encoded JWT :param encoded_token: The encoded JWT string to decode :param secret: Secret key used to encode the JWT :param algorithm: Algorithm used to encode the JWT :param identity_claim_key: expected key that contains the identity :param user_claims_key: expected key that contains the...
Below is the the instruction that describes the task: ### Input: Decodes an encoded JWT :param encoded_token: The encoded JWT string to decode :param secret: Secret key used to encode the JWT :param algorithm: Algorithm used to encode the JWT :param identity_claim_key: expected key that contains th...
def setup_smp(self): """ setup observations from PEST-style SMP file pairs """ if self.obssim_smp_pairs is None: return if len(self.obssim_smp_pairs) == 2: if isinstance(self.obssim_smp_pairs[0],str): self.obssim_smp_pairs = [self.obssim_smp_pairs...
setup observations from PEST-style SMP file pairs
Below is the the instruction that describes the task: ### Input: setup observations from PEST-style SMP file pairs ### Response: def setup_smp(self): """ setup observations from PEST-style SMP file pairs """ if self.obssim_smp_pairs is None: return if len(self.obssim_sm...
def from_ashrae_revised_clear_sky(cls, location, monthly_tau_beam, monthly_tau_diffuse, timestep=1, is_leap_year=False): """Create a wea object representing an ASHRAE Revised Clear Sky ("Tau Model") ASHRAE Revised Clear Skies a...
Create a wea object representing an ASHRAE Revised Clear Sky ("Tau Model") ASHRAE Revised Clear Skies are intended to determine peak solar load and sizing parmeters for HVAC systems. The revised clear sky is currently the default recommended sky model used to autosize HVAC systems in E...
Below is the the instruction that describes the task: ### Input: Create a wea object representing an ASHRAE Revised Clear Sky ("Tau Model") ASHRAE Revised Clear Skies are intended to determine peak solar load and sizing parmeters for HVAC systems. The revised clear sky is currently the def...
def create_dispatcher(self): """ Return a dispatcher for configured channels. """ before_context = max(self.args.before_context, self.args.context) after_context = max(self.args.after_context, self.args.context) if self.args.files_with_match is not None or self.args.coun...
Return a dispatcher for configured channels.
Below is the the instruction that describes the task: ### Input: Return a dispatcher for configured channels. ### Response: def create_dispatcher(self): """ Return a dispatcher for configured channels. """ before_context = max(self.args.before_context, self.args.context) aft...
def _num_players(self): """Compute number of players, both human and computer.""" self._player_num = 0 self._computer_num = 0 for player in self._header.scenario.game_settings.player_info: if player.type == 'human': self._player_num += 1 elif playe...
Compute number of players, both human and computer.
Below is the the instruction that describes the task: ### Input: Compute number of players, both human and computer. ### Response: def _num_players(self): """Compute number of players, both human and computer.""" self._player_num = 0 self._computer_num = 0 for player in self._header...
def validate_plugin(self, plugin_class, experimental=False): """ Verifies that the plugin_class should execute under this policy """ valid_subclasses = [IndependentPlugin] + self.valid_subclasses if experimental: valid_subclasses += [ExperimentalPlugin] return...
Verifies that the plugin_class should execute under this policy
Below is the the instruction that describes the task: ### Input: Verifies that the plugin_class should execute under this policy ### Response: def validate_plugin(self, plugin_class, experimental=False): """ Verifies that the plugin_class should execute under this policy """ valid_s...
def get_mac_acl_for_intf_input_interface_name(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") get_mac_acl_for_intf = ET.Element("get_mac_acl_for_intf") config = get_mac_acl_for_intf input = ET.SubElement(get_mac_acl_for_intf, "input") int...
Auto Generated Code
Below is the the instruction that describes the task: ### Input: Auto Generated Code ### Response: def get_mac_acl_for_intf_input_interface_name(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") get_mac_acl_for_intf = ET.Element("get_mac_acl_for_intf") ...
def write_message(self, msg, timeout=None): """Write an arbitrary message (of one of the types above). For the host side implementation, this will only ever be a DataMessage, but it's implemented generically enough here that you could use FilesyncTransport to implement the device side if you wanted. ...
Write an arbitrary message (of one of the types above). For the host side implementation, this will only ever be a DataMessage, but it's implemented generically enough here that you could use FilesyncTransport to implement the device side if you wanted. Args: msg: The message to send, must be o...
Below is the the instruction that describes the task: ### Input: Write an arbitrary message (of one of the types above). For the host side implementation, this will only ever be a DataMessage, but it's implemented generically enough here that you could use FilesyncTransport to implement the device side...
def get(self): """Return current profiler statistics.""" sort = self.get_argument('sort', 'cum_time') count = self.get_argument('count', 20) strip_dirs = self.get_argument('strip_dirs', True) error = '' sorts = ('num_calls', 'cum_time', 'total_time', 'cu...
Return current profiler statistics.
Below is the the instruction that describes the task: ### Input: Return current profiler statistics. ### Response: def get(self): """Return current profiler statistics.""" sort = self.get_argument('sort', 'cum_time') count = self.get_argument('count', 20) strip_dirs = self.get_argu...
def scores_to_preds(self, threshold, use_probs = True): """ use_probs : boolean, default True if True, use probabilities for predictions, else use scores. """ self.threshold = threshold if use_probs: if self.probs is None: raise DataError(...
use_probs : boolean, default True if True, use probabilities for predictions, else use scores.
Below is the the instruction that describes the task: ### Input: use_probs : boolean, default True if True, use probabilities for predictions, else use scores. ### Response: def scores_to_preds(self, threshold, use_probs = True): """ use_probs : boolean, default True if True...
def post_comments(self, post_id, after='', order="chronological", filter="stream", fields=None, **params): """ :param post_id: :param after: :param order: Can be 'ranked', 'chronological', 'reverse_chronological' :param filter: Can be 'stream', 'to...
:param post_id: :param after: :param order: Can be 'ranked', 'chronological', 'reverse_chronological' :param filter: Can be 'stream', 'toplevel' :param fields: Can be 'id', 'application', 'attachment', 'can_comment', 'can_remove', 'can_hide', 'can_like', 'can_reply_privately...
Below is the the instruction that describes the task: ### Input: :param post_id: :param after: :param order: Can be 'ranked', 'chronological', 'reverse_chronological' :param filter: Can be 'stream', 'toplevel' :param fields: Can be 'id', 'application', 'attachment', 'can_comment'...
def OnTogglePlay(self, event): """Toggles the video status between play and hold""" if self.player.get_state() == vlc.State.Playing: self.player.pause() else: self.player.play() event.Skip()
Toggles the video status between play and hold
Below is the the instruction that describes the task: ### Input: Toggles the video status between play and hold ### Response: def OnTogglePlay(self, event): """Toggles the video status between play and hold""" if self.player.get_state() == vlc.State.Playing: self.player.pause() ...
def keys(self): """Keys Returns a list of the node names in the parent Returns: list """ if hasattr(self._nodes, 'iterkeys'): return self._nodes.keys() else: return tuple(self._nodes.keys())
Keys Returns a list of the node names in the parent Returns: list
Below is the the instruction that describes the task: ### Input: Keys Returns a list of the node names in the parent Returns: list ### Response: def keys(self): """Keys Returns a list of the node names in the parent Returns: list """ if hasattr(self._nodes, 'iterkeys'): return self._node...
def computed_fitting_parameters(self): """ A list identical to what is set with `scipy_data_fitting.Fit.fitting_parameters`, but in each dictionary, the key `value` is added with the fitted value of the quantity. The reported value is scaled by the inverse prefix. """ fit...
A list identical to what is set with `scipy_data_fitting.Fit.fitting_parameters`, but in each dictionary, the key `value` is added with the fitted value of the quantity. The reported value is scaled by the inverse prefix.
Below is the the instruction that describes the task: ### Input: A list identical to what is set with `scipy_data_fitting.Fit.fitting_parameters`, but in each dictionary, the key `value` is added with the fitted value of the quantity. The reported value is scaled by the inverse prefix. ### Response:...
def getdict(self, crop=True): """Get final dictionary. If ``crop`` is ``True``, apply :func:`.cnvrep.bcrop` to returned array. """ global mp_D_Y0 D = mp_D_Y0 if crop: D = cr.bcrop(D, self.dstep.cri.dsz, self.dstep.cri.dimN) return D
Get final dictionary. If ``crop`` is ``True``, apply :func:`.cnvrep.bcrop` to returned array.
Below is the the instruction that describes the task: ### Input: Get final dictionary. If ``crop`` is ``True``, apply :func:`.cnvrep.bcrop` to returned array. ### Response: def getdict(self, crop=True): """Get final dictionary. If ``crop`` is ``True``, apply :func:`.cnvrep.bcrop` to returne...
def allocated_chunks(self): """ Returns an iterator over all the allocated chunks in the heap. """ raise NotImplementedError("%s not implemented for %s" % (self.allocated_chunks.__func__.__name__, self.__class__.__name__))
Returns an iterator over all the allocated chunks in the heap.
Below is the the instruction that describes the task: ### Input: Returns an iterator over all the allocated chunks in the heap. ### Response: def allocated_chunks(self): """ Returns an iterator over all the allocated chunks in the heap. """ raise NotImplementedError("%s not implemen...
def import_txt(cls, txt_file, feed, filter_func=None): '''Import from the GTFS text file''' # Setup the conversion from GTFS to Django Format # Conversion functions def no_convert(value): return value def date_convert(value): return datetime.strptime(value, '%Y%m%d') d...
Import from the GTFS text file
Below is the the instruction that describes the task: ### Input: Import from the GTFS text file ### Response: def import_txt(cls, txt_file, feed, filter_func=None): '''Import from the GTFS text file''' # Setup the conversion from GTFS to Django Format # Conversion functions def no_...
def set_ev_cls(ev_cls, dispatchers=None): """ A decorator for Ryu application to declare an event handler. Decorated method will become an event handler. ev_cls is an event class whose instances this RyuApp wants to receive. dispatchers argument specifies one of the following negotiation phases ...
A decorator for Ryu application to declare an event handler. Decorated method will become an event handler. ev_cls is an event class whose instances this RyuApp wants to receive. dispatchers argument specifies one of the following negotiation phases (or a list of them) for which events should be genera...
Below is the the instruction that describes the task: ### Input: A decorator for Ryu application to declare an event handler. Decorated method will become an event handler. ev_cls is an event class whose instances this RyuApp wants to receive. dispatchers argument specifies one of the following negotia...
def get_child_for_path(self, path): """Get a child for a given path. Rather than repeated calls to get_child, children can be found by a derivation path. Paths look like: m/0/1'/10 Which is the same as self.get_child(0).get_child(-1).get_child(10) Or,...
Get a child for a given path. Rather than repeated calls to get_child, children can be found by a derivation path. Paths look like: m/0/1'/10 Which is the same as self.get_child(0).get_child(-1).get_child(10) Or, in other words, the 10th publicly derived chil...
Below is the the instruction that describes the task: ### Input: Get a child for a given path. Rather than repeated calls to get_child, children can be found by a derivation path. Paths look like: m/0/1'/10 Which is the same as self.get_child(0).get_child(-1).get_...
def scourUnitlessLength(length, renderer_workaround=False, is_control_point=False): # length is of a numeric type """ Scours the numeric part of a length only. Does not accept units. This is faster than scourLength on elements guaranteed not to contain units. """ if not isinstance(length, Deci...
Scours the numeric part of a length only. Does not accept units. This is faster than scourLength on elements guaranteed not to contain units.
Below is the the instruction that describes the task: ### Input: Scours the numeric part of a length only. Does not accept units. This is faster than scourLength on elements guaranteed not to contain units. ### Response: def scourUnitlessLength(length, renderer_workaround=False, is_control_point=False): ...
def is_in(allowed_values # type: Set ): """ 'Values in' validation_function generator. Returns a validation_function to check that x is in the provided set of allowed values :param allowed_values: a set of allowed values :return: """ def is_in_allowed_values(x): if x in a...
'Values in' validation_function generator. Returns a validation_function to check that x is in the provided set of allowed values :param allowed_values: a set of allowed values :return:
Below is the the instruction that describes the task: ### Input: 'Values in' validation_function generator. Returns a validation_function to check that x is in the provided set of allowed values :param allowed_values: a set of allowed values :return: ### Response: def is_in(allowed_values # type: Set...
def QueueQueryAndOwn(self, queue, lease_seconds, limit, timestamp): """Returns a list of Tasks leased for a certain time. Args: queue: The queue to query from. lease_seconds: The tasks will be leased for this long. limit: Number of values to fetch. timestamp: Range of times for consider...
Returns a list of Tasks leased for a certain time. Args: queue: The queue to query from. lease_seconds: The tasks will be leased for this long. limit: Number of values to fetch. timestamp: Range of times for consideration. Returns: A list of GrrMessage() objects leased.
Below is the the instruction that describes the task: ### Input: Returns a list of Tasks leased for a certain time. Args: queue: The queue to query from. lease_seconds: The tasks will be leased for this long. limit: Number of values to fetch. timestamp: Range of times for consideration....
def _rand_init(x_bounds, x_types, selection_num_starting_points): ''' Random sample some init seed within bounds. ''' return [lib_data.rand(x_bounds, x_types) for i \ in range(0, selection_num_starting_points)]
Random sample some init seed within bounds.
Below is the the instruction that describes the task: ### Input: Random sample some init seed within bounds. ### Response: def _rand_init(x_bounds, x_types, selection_num_starting_points): ''' Random sample some init seed within bounds. ''' return [lib_data.rand(x_bounds, x_types) for i \ ...
def _get_option(target_obj, key): """ Given a target object and option key, get that option from the target object, either through a get_{key} method or from an attribute directly. """ getter_name = 'get_{key}'.format(**locals()) by_attribute = functools.partial(getattr, target_obj, key) ...
Given a target object and option key, get that option from the target object, either through a get_{key} method or from an attribute directly.
Below is the the instruction that describes the task: ### Input: Given a target object and option key, get that option from the target object, either through a get_{key} method or from an attribute directly. ### Response: def _get_option(target_obj, key): """ Given a target object and option key, g...
def folderitem(self, obj, item, index): """Service triggered each time an item is iterated in folderitems. The use of this service prevents the extra-loops in child objects. :obj: the instance of the class to be foldered :item: dict containing the properties of the object to be used by...
Service triggered each time an item is iterated in folderitems. The use of this service prevents the extra-loops in child objects. :obj: the instance of the class to be foldered :item: dict containing the properties of the object to be used by the template :index: current i...
Below is the the instruction that describes the task: ### Input: Service triggered each time an item is iterated in folderitems. The use of this service prevents the extra-loops in child objects. :obj: the instance of the class to be foldered :item: dict containing the properties of the ob...
def add_attachment(message, attachment, rfc2231=True): '''Attach an attachment to a message as a side effect. Arguments: message: MIMEMultipart instance. attachment: Attachment instance. ''' data = attachment.read() part = MIMEBase('application', 'octet-stream') part.set_payloa...
Attach an attachment to a message as a side effect. Arguments: message: MIMEMultipart instance. attachment: Attachment instance.
Below is the the instruction that describes the task: ### Input: Attach an attachment to a message as a side effect. Arguments: message: MIMEMultipart instance. attachment: Attachment instance. ### Response: def add_attachment(message, attachment, rfc2231=True): '''Attach an attachment to ...
def dynamodb_autoscaling_policy(tables): """Policy to allow AutoScaling a list of DynamoDB tables.""" return Policy( Statement=[ Statement( Effect=Allow, Resource=dynamodb_arns(tables), Action=[ dynamodb.DescribeTable, ...
Policy to allow AutoScaling a list of DynamoDB tables.
Below is the the instruction that describes the task: ### Input: Policy to allow AutoScaling a list of DynamoDB tables. ### Response: def dynamodb_autoscaling_policy(tables): """Policy to allow AutoScaling a list of DynamoDB tables.""" return Policy( Statement=[ Statement( ...
def process_request(self, request): """Called on each request, before Django decides which view to execute. :type request: :class:`~django.http.request.HttpRequest` :param request: Django http request. """ # Do not trace if the url is blacklisted if utils.disable_tracing...
Called on each request, before Django decides which view to execute. :type request: :class:`~django.http.request.HttpRequest` :param request: Django http request.
Below is the the instruction that describes the task: ### Input: Called on each request, before Django decides which view to execute. :type request: :class:`~django.http.request.HttpRequest` :param request: Django http request. ### Response: def process_request(self, request): """Called on...
def competition_submissions(self, competition): """ get the list of Submission for a particular competition Parameters ========== competition: the name of the competition """ submissions_result = self.process_response( self.competitions_submission...
get the list of Submission for a particular competition Parameters ========== competition: the name of the competition
Below is the the instruction that describes the task: ### Input: get the list of Submission for a particular competition Parameters ========== competition: the name of the competition ### Response: def competition_submissions(self, competition): """ get the list of Subm...
def get_zcta_ids(state=None): """ Get ids of all supported ZCTAs, optionally by state. Parameters ---------- state : str, optional Select zipcodes only from this state or territory, given as 2-letter abbreviation (e.g., ``'CA'``, ``'PR'``). Returns ------- results : list of...
Get ids of all supported ZCTAs, optionally by state. Parameters ---------- state : str, optional Select zipcodes only from this state or territory, given as 2-letter abbreviation (e.g., ``'CA'``, ``'PR'``). Returns ------- results : list of str List of all supported sel...
Below is the the instruction that describes the task: ### Input: Get ids of all supported ZCTAs, optionally by state. Parameters ---------- state : str, optional Select zipcodes only from this state or territory, given as 2-letter abbreviation (e.g., ``'CA'``, ``'PR'``). Returns ...
def get_body(self, environ=None): """Get the request body.""" body = dict( status=self.code, message=self.description, ) errors = self.get_errors() if self.errors: body['errors'] = errors return json.dumps(body)
Get the request body.
Below is the the instruction that describes the task: ### Input: Get the request body. ### Response: def get_body(self, environ=None): """Get the request body.""" body = dict( status=self.code, message=self.description, ) errors = self.get_errors() i...
def expand_cmd_labels(self): """Expand make-style variables in cmd parameters. Currently: $(location <foo>) Location of one dependency or output file. $(locations <foo>) Space-delimited list of foo's output files. $(SRCS) Space-delimited list of this rule's ...
Expand make-style variables in cmd parameters. Currently: $(location <foo>) Location of one dependency or output file. $(locations <foo>) Space-delimited list of foo's output files. $(SRCS) Space-delimited list of this rule's source files. $(OUTS) ...
Below is the the instruction that describes the task: ### Input: Expand make-style variables in cmd parameters. Currently: $(location <foo>) Location of one dependency or output file. $(locations <foo>) Space-delimited list of foo's output files. $(SRCS) Space-d...
def _set_base(self): '''set the API base or default to use Docker Hub. The user is able to set the base, api version, and protocol via a settings file of environment variables: SREGISTRY_NVIDIA_BASE: defaults to nvcr.io SREGISTRY_NVIDIA_TOKEN: defaults to $oauthtoke...
set the API base or default to use Docker Hub. The user is able to set the base, api version, and protocol via a settings file of environment variables: SREGISTRY_NVIDIA_BASE: defaults to nvcr.io SREGISTRY_NVIDIA_TOKEN: defaults to $oauthtoken SREGISTRY_NVIDIA_VE...
Below is the the instruction that describes the task: ### Input: set the API base or default to use Docker Hub. The user is able to set the base, api version, and protocol via a settings file of environment variables: SREGISTRY_NVIDIA_BASE: defaults to nvcr.io SREGISTRY...