code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
text
stringlengths
164
112k
def _masked_middle_begin_end(self): """ Return the begin and end indices w.r.t. ``self.__mfcc_mask_map``, corresponding to indices in the MIDDLE portion of the wave, that is, which fall between ``self.__middle_begin`` and ``self.__middle_end`` in ``self.__mfcc``. :rtype:...
Return the begin and end indices w.r.t. ``self.__mfcc_mask_map``, corresponding to indices in the MIDDLE portion of the wave, that is, which fall between ``self.__middle_begin`` and ``self.__middle_end`` in ``self.__mfcc``. :rtype: (int, int)
Below is the the instruction that describes the task: ### Input: Return the begin and end indices w.r.t. ``self.__mfcc_mask_map``, corresponding to indices in the MIDDLE portion of the wave, that is, which fall between ``self.__middle_begin`` and ``self.__middle_end`` in ``self.__mfcc``. ...
async def stop_async(self): """ Stop the EventHubClient and all its Sender/Receiver clients. """ log.info("%r: Stopping %r clients", self.container_id, len(self.clients)) self.stopped = True await self._close_clients_async()
Stop the EventHubClient and all its Sender/Receiver clients.
Below is the the instruction that describes the task: ### Input: Stop the EventHubClient and all its Sender/Receiver clients. ### Response: async def stop_async(self): """ Stop the EventHubClient and all its Sender/Receiver clients. """ log.info("%r: Stopping %r clients", self.conta...
def delete(self, id, attid): # pylint: disable=invalid-name,redefined-builtin """Delete a device's attachment. :param id: Device ID as an int. :param attid: Attachment ID as an int. """ return self.service.edit(self._base(id), attid)
Delete a device's attachment. :param id: Device ID as an int. :param attid: Attachment ID as an int.
Below is the the instruction that describes the task: ### Input: Delete a device's attachment. :param id: Device ID as an int. :param attid: Attachment ID as an int. ### Response: def delete(self, id, attid): # pylint: disable=invalid-name,redefined-builtin """Delete a device's attachment....
def create_condition(self, service_id, version_number, name, _type, statement, priority="10", comment=None): """Creates a new condition.""" body = self._formdata({ "name": name, "type": _type, "statement": statement, "priority": priority, "comment": comment, }, FastlyCondition.FIEL...
Creates a new condition.
Below is the the instruction that describes the task: ### Input: Creates a new condition. ### Response: def create_condition(self, service_id, version_number, name, _type, statement, priority="10", comment=None): """Creates a new condition.""" body = self._formdata({ "name": name, "type"...
def set_highest_api_version(db_aliases): """Set the highest version of Force.com API supported by all databases in db_aliases """ if not isinstance(db_aliases, (list, tuple)): db_aliases = [db_aliases] max_version = max(connections[db_alias].cursor().versions_request()[-1]['version'] ...
Set the highest version of Force.com API supported by all databases in db_aliases
Below is the the instruction that describes the task: ### Input: Set the highest version of Force.com API supported by all databases in db_aliases ### Response: def set_highest_api_version(db_aliases): """Set the highest version of Force.com API supported by all databases in db_aliases """ if not isins...
def exact_ipv4_match(self, field, values): """ An exact IPv4 address match on relevant address fields. :param str field: name of field to filter on. Taken from 'Show Filter Expression' within SMC. :param list values: value/s to add. If more than a single value is ...
An exact IPv4 address match on relevant address fields. :param str field: name of field to filter on. Taken from 'Show Filter Expression' within SMC. :param list values: value/s to add. If more than a single value is provided, the query is modified to use UNION vs. == ...
Below is the the instruction that describes the task: ### Input: An exact IPv4 address match on relevant address fields. :param str field: name of field to filter on. Taken from 'Show Filter Expression' within SMC. :param list values: value/s to add. If more than a single value ...
def __fill_buffer(self, size=0): """Fills the internal buffer. Args: size: Number of bytes to read. Will be clamped to [self.__buffer_size, MAX_BLOB_FETCH_SIZE]. """ read_size = min(max(size, self.__buffer_size), MAX_BLOB_FETCH_SIZE) self.__buffer = fetch_data(self.__blob_key, self._...
Fills the internal buffer. Args: size: Number of bytes to read. Will be clamped to [self.__buffer_size, MAX_BLOB_FETCH_SIZE].
Below is the the instruction that describes the task: ### Input: Fills the internal buffer. Args: size: Number of bytes to read. Will be clamped to [self.__buffer_size, MAX_BLOB_FETCH_SIZE]. ### Response: def __fill_buffer(self, size=0): """Fills the internal buffer. Args: size: N...
def main(): """Main entry.""" parser = argparse.ArgumentParser() parser.add_argument("--host", type=str, required=True) parser.add_argument("--user", type=str, required=True) parser.add_argument("--password", type=str) parser.add_argument("--token", type=str) args = parser.parse_args() i...
Main entry.
Below is the the instruction that describes the task: ### Input: Main entry. ### Response: def main(): """Main entry.""" parser = argparse.ArgumentParser() parser.add_argument("--host", type=str, required=True) parser.add_argument("--user", type=str, required=True) parser.add_argument("--passwo...
def save_file(db, user_id, path, content, encrypt_func, max_size_bytes): """ Save a file. TODO: Update-then-insert is probably cheaper than insert-then-update. """ content = preprocess_incoming_content( content, encrypt_func, max_size_bytes, ) directory, name = split...
Save a file. TODO: Update-then-insert is probably cheaper than insert-then-update.
Below is the the instruction that describes the task: ### Input: Save a file. TODO: Update-then-insert is probably cheaper than insert-then-update. ### Response: def save_file(db, user_id, path, content, encrypt_func, max_size_bytes): """ Save a file. TODO: Update-then-insert is probably cheaper ...
def add_template_global(self, f, name=None): """Register a custom template global function. Works exactly like the :meth:`template_global` decorator. .. versionadded:: 0.10 :param name: the optional name of the global function, otherwise the function name will be u...
Register a custom template global function. Works exactly like the :meth:`template_global` decorator. .. versionadded:: 0.10 :param name: the optional name of the global function, otherwise the function name will be used.
Below is the the instruction that describes the task: ### Input: Register a custom template global function. Works exactly like the :meth:`template_global` decorator. .. versionadded:: 0.10 :param name: the optional name of the global function, otherwise the function n...
def _login(self, username, password): '''login and update cached cookies''' self.logger.debug('login ...') res = self.session.http.get(self.login_url) input_list = self._input_re.findall(res.text) if not input_list: raise PluginError('Missing input data on login webs...
login and update cached cookies
Below is the the instruction that describes the task: ### Input: login and update cached cookies ### Response: def _login(self, username, password): '''login and update cached cookies''' self.logger.debug('login ...') res = self.session.http.get(self.login_url) input_list = self._i...
async def lookup(client: Client, search: str) -> dict: """ GET UID/Public key data :param client: Client to connect to the api :param search: UID or public key :return: """ return await client.get(MODULE + '/lookup/%s' % search, schema=LOOKUP_SCHEMA)
GET UID/Public key data :param client: Client to connect to the api :param search: UID or public key :return:
Below is the the instruction that describes the task: ### Input: GET UID/Public key data :param client: Client to connect to the api :param search: UID or public key :return: ### Response: async def lookup(client: Client, search: str) -> dict: """ GET UID/Public key data :param client: Cl...
def unix_ts(dtval): '''Convert datetime into a unix timestamp. This is the equivalent to Python 3's int(datetime.timestamp()). :param dt: datetime to convert ''' epoch = datetime(1970, 1, 1, 0, 0, tzinfo=tzutc()) delta = (dtval - epoch) return delta.days * 24 * 3600 + delta.seconds
Convert datetime into a unix timestamp. This is the equivalent to Python 3's int(datetime.timestamp()). :param dt: datetime to convert
Below is the the instruction that describes the task: ### Input: Convert datetime into a unix timestamp. This is the equivalent to Python 3's int(datetime.timestamp()). :param dt: datetime to convert ### Response: def unix_ts(dtval): '''Convert datetime into a unix timestamp. This is the equivalen...
def visit_Call(self, node): """ Function call depend on all function use in the call. >> a = foo(bar(c) or foobar(d)) Return type depend on [foo, bar] or [foo, foobar] """ args = [self.visit(arg) for arg in node.args] func = self.visit(node.func) params ...
Function call depend on all function use in the call. >> a = foo(bar(c) or foobar(d)) Return type depend on [foo, bar] or [foo, foobar]
Below is the the instruction that describes the task: ### Input: Function call depend on all function use in the call. >> a = foo(bar(c) or foobar(d)) Return type depend on [foo, bar] or [foo, foobar] ### Response: def visit_Call(self, node): """ Function call depend on all functi...
def jinja_env(template_path): """Sets up our Jinja environment, loading the few filters we have""" fs_loader = FileSystemLoader(os.path.dirname(template_path)) env = Environment(loader=fs_loader, autoescape=True, trim_blocks=True, lstrip_bloc...
Sets up our Jinja environment, loading the few filters we have
Below is the the instruction that describes the task: ### Input: Sets up our Jinja environment, loading the few filters we have ### Response: def jinja_env(template_path): """Sets up our Jinja environment, loading the few filters we have""" fs_loader = FileSystemLoader(os.path.dirname(template_path)) e...
def get_correlation(self, t1, t2): """ Computes the correlation coefficient for the specified periods. :param float t1: First period of interest. :param float t2: Second period of interest. :return float rho: The predicted correlation coeffi...
Computes the correlation coefficient for the specified periods. :param float t1: First period of interest. :param float t2: Second period of interest. :return float rho: The predicted correlation coefficient.
Below is the the instruction that describes the task: ### Input: Computes the correlation coefficient for the specified periods. :param float t1: First period of interest. :param float t2: Second period of interest. :return float rho: The predicted corr...
def angle(self): """Angle value.""" if self.use_global_light: return self._image_resources.get_data('global_angle', 30.0) return self.value.get(Key.LocalLightingAngle).value
Angle value.
Below is the the instruction that describes the task: ### Input: Angle value. ### Response: def angle(self): """Angle value.""" if self.use_global_light: return self._image_resources.get_data('global_angle', 30.0) return self.value.get(Key.LocalLightingAngle).value
def remember_order(self): """Verify that subsequent :func:`fudge.Fake.expects` are called in the right order. For example:: >>> import fudge >>> db = fudge.Fake('db').remember_order().expects('insert').expects('update') >>> db.update() Traceback (most re...
Verify that subsequent :func:`fudge.Fake.expects` are called in the right order. For example:: >>> import fudge >>> db = fudge.Fake('db').remember_order().expects('insert').expects('update') >>> db.update() Traceback (most recent call last): ... ...
Below is the the instruction that describes the task: ### Input: Verify that subsequent :func:`fudge.Fake.expects` are called in the right order. For example:: >>> import fudge >>> db = fudge.Fake('db').remember_order().expects('insert').expects('update') >>> db.update(...
def sonos_uri_from_id(self, item_id): """Get a uri which can be sent for playing. Args: item_id (str): The unique id of a playable item for this music service, such as that returned in the metadata from `get_metadata`, eg ``spotify:track:2qs5ZcLByNTctJKbhAZ9J...
Get a uri which can be sent for playing. Args: item_id (str): The unique id of a playable item for this music service, such as that returned in the metadata from `get_metadata`, eg ``spotify:track:2qs5ZcLByNTctJKbhAZ9JE`` Returns: str: A URI of t...
Below is the the instruction that describes the task: ### Input: Get a uri which can be sent for playing. Args: item_id (str): The unique id of a playable item for this music service, such as that returned in the metadata from `get_metadata`, eg ``spotify:track:2...
def find_by_id(self, project_status, params={}, **options): """Returns the complete record for a single status update. Parameters ---------- project-status : {Id} The project status update to get. [params] : {Object} Parameters for the request """ path = "/proje...
Returns the complete record for a single status update. Parameters ---------- project-status : {Id} The project status update to get. [params] : {Object} Parameters for the request
Below is the the instruction that describes the task: ### Input: Returns the complete record for a single status update. Parameters ---------- project-status : {Id} The project status update to get. [params] : {Object} Parameters for the request ### Response: def find_by_id(self, p...
def detect_nexson_version(blob): """Returns the nexml2json attribute or the default code for badgerfish""" n = get_nexml_el(blob) assert isinstance(n, dict) return n.get('@nexml2json', BADGER_FISH_NEXSON_VERSION)
Returns the nexml2json attribute or the default code for badgerfish
Below is the the instruction that describes the task: ### Input: Returns the nexml2json attribute or the default code for badgerfish ### Response: def detect_nexson_version(blob): """Returns the nexml2json attribute or the default code for badgerfish""" n = get_nexml_el(blob) assert isinstance(n, dict)...
def import_type(dest, src, name, api=None, filter_symbol=None): """Import Type `name` and its dependencies from Registry `src` to Registry `dest`. :param Registry dest: Destination Registry :param Registry src: Source Registry :param str name: Name of type to import :param str api: Prefer to im...
Import Type `name` and its dependencies from Registry `src` to Registry `dest`. :param Registry dest: Destination Registry :param Registry src: Source Registry :param str name: Name of type to import :param str api: Prefer to import Types with api Name `api`, or None to import T...
Below is the the instruction that describes the task: ### Input: Import Type `name` and its dependencies from Registry `src` to Registry `dest`. :param Registry dest: Destination Registry :param Registry src: Source Registry :param str name: Name of type to import :param str api: Prefer to impo...
def enabled(name, root=None, **kwargs): # pylint: disable=unused-argument ''' Return if the named service is enabled to start on boot root Enable/disable/mask unit files in the specified root directory CLI Example: .. code-block:: bash salt '*' service.enabled <service name> ...
Return if the named service is enabled to start on boot root Enable/disable/mask unit files in the specified root directory CLI Example: .. code-block:: bash salt '*' service.enabled <service name>
Below is the the instruction that describes the task: ### Input: Return if the named service is enabled to start on boot root Enable/disable/mask unit files in the specified root directory CLI Example: .. code-block:: bash salt '*' service.enabled <service name> ### Response: def en...
def validate(self): '''Validate all the entries in the environment cache.''' for env in list(self): if not env.exists: self.remove(env)
Validate all the entries in the environment cache.
Below is the the instruction that describes the task: ### Input: Validate all the entries in the environment cache. ### Response: def validate(self): '''Validate all the entries in the environment cache.''' for env in list(self): if not env.exists: self.remove(env)
def copy(self, new_fn): """copy the file to the new_fn, preserving atime and mtime""" new_file = self.__class__(fn=str(new_fn)) new_file.write(data=self.read()) new_file.utime(self.atime, self.mtime) return new_file
copy the file to the new_fn, preserving atime and mtime
Below is the the instruction that describes the task: ### Input: copy the file to the new_fn, preserving atime and mtime ### Response: def copy(self, new_fn): """copy the file to the new_fn, preserving atime and mtime""" new_file = self.__class__(fn=str(new_fn)) new_file.write(data=self.rea...
def zip(self, second_iterable, result_selector=lambda x, y: (x, y)): '''Elementwise combination of two sequences. The source sequence and the second iterable are merged element-by- element using a function to combine them into the single corresponding element of the result sequence. The...
Elementwise combination of two sequences. The source sequence and the second iterable are merged element-by- element using a function to combine them into the single corresponding element of the result sequence. The length of the result sequence is equal to the length of the shorter of ...
Below is the the instruction that describes the task: ### Input: Elementwise combination of two sequences. The source sequence and the second iterable are merged element-by- element using a function to combine them into the single corresponding element of the result sequence. The length of ...
def render(self, template=None): """Render the plot using a template. Once the plot is complete, it needs to be rendered. Artist uses the Jinja2 templating engine. The default template results in a LaTeX file which can be included in your document. :param template: a user-sup...
Render the plot using a template. Once the plot is complete, it needs to be rendered. Artist uses the Jinja2 templating engine. The default template results in a LaTeX file which can be included in your document. :param template: a user-supplied template or None. :type templa...
Below is the the instruction that describes the task: ### Input: Render the plot using a template. Once the plot is complete, it needs to be rendered. Artist uses the Jinja2 templating engine. The default template results in a LaTeX file which can be included in your document. :p...
def hook(module): """ Hook method to install the Instana middleware into Flask """ if "INSTANA_DEV" in os.environ: print("==============================================================") print("Instana: Running flask hook") print("=========================================================...
Hook method to install the Instana middleware into Flask
Below is the the instruction that describes the task: ### Input: Hook method to install the Instana middleware into Flask ### Response: def hook(module): """ Hook method to install the Instana middleware into Flask """ if "INSTANA_DEV" in os.environ: print("=========================================...
def p12d_local(vertices, lame, mu): """Local stiffness matrix for P1 elements in 2d.""" assert(vertices.shape == (3, 2)) A = np.vstack((np.ones((1, 3)), vertices.T)) PhiGrad = inv(A)[:, 1:] # gradients of basis functions R = np.zeros((3, 6)) R[[[0], [2]], [0, 2, 4]] = PhiGrad.T R[[[2], [1]...
Local stiffness matrix for P1 elements in 2d.
Below is the the instruction that describes the task: ### Input: Local stiffness matrix for P1 elements in 2d. ### Response: def p12d_local(vertices, lame, mu): """Local stiffness matrix for P1 elements in 2d.""" assert(vertices.shape == (3, 2)) A = np.vstack((np.ones((1, 3)), vertices.T)) PhiGrad...
def run(cmd, cwd=None, env=None, timeout=None, stream=False, warn_only=False): """ :param cmd: command to run :param cwd: change dir into before execute, default is current dir :param env: environments to pass to subprocess :param timeout: timeout :param stream: stream output, default is False, ...
:param cmd: command to run :param cwd: change dir into before execute, default is current dir :param env: environments to pass to subprocess :param timeout: timeout :param stream: stream output, default is False, block until finished :param warn_only: default False, set to True to allow unsuccessful...
Below is the the instruction that describes the task: ### Input: :param cmd: command to run :param cwd: change dir into before execute, default is current dir :param env: environments to pass to subprocess :param timeout: timeout :param stream: stream output, default is False, block until finished ...
def fire_running(self, running): ''' Pass in a state "running" dict, this is the return dict from a state call. The dict will be processed and fire events. By default yellows and reds fire events on the master and minion, but this can be configured. ''' load = {'...
Pass in a state "running" dict, this is the return dict from a state call. The dict will be processed and fire events. By default yellows and reds fire events on the master and minion, but this can be configured.
Below is the the instruction that describes the task: ### Input: Pass in a state "running" dict, this is the return dict from a state call. The dict will be processed and fire events. By default yellows and reds fire events on the master and minion, but this can be configured. ### Response:...
def has_variantcalls(data): """ returns True if the data dictionary is configured for variant calling """ analysis = get_analysis(data).lower() variant_pipeline = analysis.startswith(("standard", "variant", "variant2")) variantcaller = get_variantcaller(data) return variant_pipeline or varia...
returns True if the data dictionary is configured for variant calling
Below is the the instruction that describes the task: ### Input: returns True if the data dictionary is configured for variant calling ### Response: def has_variantcalls(data): """ returns True if the data dictionary is configured for variant calling """ analysis = get_analysis(data).lower() va...
def write(self, filename, encoding='utf-8'): """Write the list of entries to a file. :param filename: :param encoding: :return: """ with io.open(str(filename), 'w', encoding=encoding) as fp: for entry in self: fp.write(entry.__unicode__()) ...
Write the list of entries to a file. :param filename: :param encoding: :return:
Below is the the instruction that describes the task: ### Input: Write the list of entries to a file. :param filename: :param encoding: :return: ### Response: def write(self, filename, encoding='utf-8'): """Write the list of entries to a file. :param filename: :par...
def on_selection_changed(self): """ Callback invoked one the selection has changed. """ d = self.declaration selection = self.scene.selectedItems() self._guards |= 0x01 try: d.selected_items = [item.ref().declaration for item in selection ...
Callback invoked one the selection has changed.
Below is the the instruction that describes the task: ### Input: Callback invoked one the selection has changed. ### Response: def on_selection_changed(self): """ Callback invoked one the selection has changed. """ d = self.declaration selection = self.scene.selectedItems()...
def get_reminder(self, reminder_key): '''Gets one reminder Args: reminder_key key for the reminder to get return (status code, reminder dict) ''' #required sanity check if reminder_key: return requests.codes.bad_request, None uri = '/'.join([ self.api_uri, self.reminders_suffix, ...
Gets one reminder Args: reminder_key key for the reminder to get return (status code, reminder dict)
Below is the the instruction that describes the task: ### Input: Gets one reminder Args: reminder_key key for the reminder to get return (status code, reminder dict) ### Response: def get_reminder(self, reminder_key): '''Gets one reminder Args: reminder_key key for the reminder to get return ...
def output(self, _filename): """ _filename is not used Args: _filename(string) """ for contract in self.contracts: txt = "\nContract %s\n"%contract.name table = PrettyTable(["Function", "State variables written", "Conditions on msg...
_filename is not used Args: _filename(string)
Below is the the instruction that describes the task: ### Input: _filename is not used Args: _filename(string) ### Response: def output(self, _filename): """ _filename is not used Args: _filename(string) """ for contract i...
def verify_state(self): """ Verify if session was not yet opened. If it is, open it and call connection's C{connectionMade} """ if self.state == SESSION_STATE.CONNECTING: self.state = SESSION_STATE.OPEN self.conn.connectionMade(self.conn_info)
Verify if session was not yet opened. If it is, open it and call connection's C{connectionMade}
Below is the the instruction that describes the task: ### Input: Verify if session was not yet opened. If it is, open it and call connection's C{connectionMade} ### Response: def verify_state(self): """ Verify if session was not yet opened. If it is, open it and call connection's C{connecti...
def calc_level_runs(storage): """Split the storage to run of char types at the same level. Applies X10. See http://unicode.org/reports/tr9/#X10 """ # run level depends on the higher of the two levels on either side of # the boundary If the higher level is odd, the type is R; otherwise, # it is ...
Split the storage to run of char types at the same level. Applies X10. See http://unicode.org/reports/tr9/#X10
Below is the the instruction that describes the task: ### Input: Split the storage to run of char types at the same level. Applies X10. See http://unicode.org/reports/tr9/#X10 ### Response: def calc_level_runs(storage): """Split the storage to run of char types at the same level. Applies X10. See htt...
def get_url(self, url, fields=None, **urlopen_kw): """ .. deprecated:: 1.0 Use :meth:`request` instead. """ return self.request_encode_url('GET', url, fields=fields, **urlopen_kw)
.. deprecated:: 1.0 Use :meth:`request` instead.
Below is the the instruction that describes the task: ### Input: .. deprecated:: 1.0 Use :meth:`request` instead. ### Response: def get_url(self, url, fields=None, **urlopen_kw): """ .. deprecated:: 1.0 Use :meth:`request` instead. """ return self.request_encod...
def mask_right(self, n_seq_bases, mask="S"): """ Return a new cigar with cigar string where the last `n_seq_bases` are soft-masked unless they are already hard-masked. """ return Cigar(Cigar(self._reverse_cigar()).mask_left(n_seq_bases, mask)._reverse_cigar())
Return a new cigar with cigar string where the last `n_seq_bases` are soft-masked unless they are already hard-masked.
Below is the the instruction that describes the task: ### Input: Return a new cigar with cigar string where the last `n_seq_bases` are soft-masked unless they are already hard-masked. ### Response: def mask_right(self, n_seq_bases, mask="S"): """ Return a new cigar with cigar string where t...
def project(num=None, *args, **kwargs): """ Create a new main project Parameters ---------- num: int The number of the project %(Project.parameters.no_num)s Returns ------- Project The with the given `num` (if it does not already exist, it is created) See Also ...
Create a new main project Parameters ---------- num: int The number of the project %(Project.parameters.no_num)s Returns ------- Project The with the given `num` (if it does not already exist, it is created) See Also -------- scp: Sets the current project g...
Below is the the instruction that describes the task: ### Input: Create a new main project Parameters ---------- num: int The number of the project %(Project.parameters.no_num)s Returns ------- Project The with the given `num` (if it does not already exist, it is create...
def raise_event_handler_log_entry(self, command): """Raise SERVICE EVENT HANDLER entry (critical level) Format is : "SERVICE EVENT HANDLER: *host_name*;*self.get_name()*;*state*;*state_type* ;*attempt*;*command.get_name()*" Example : "SERVICE EVENT HANDLER: server;Load;UP;HAR...
Raise SERVICE EVENT HANDLER entry (critical level) Format is : "SERVICE EVENT HANDLER: *host_name*;*self.get_name()*;*state*;*state_type* ;*attempt*;*command.get_name()*" Example : "SERVICE EVENT HANDLER: server;Load;UP;HARD;1;notify-by-rss" :param command: Handler launched ...
Below is the the instruction that describes the task: ### Input: Raise SERVICE EVENT HANDLER entry (critical level) Format is : "SERVICE EVENT HANDLER: *host_name*;*self.get_name()*;*state*;*state_type* ;*attempt*;*command.get_name()*" Example : "SERVICE EVENT HANDLER: server;Loa...
def run_application_generator(self, coroutine, render_cli_done=False): """ EXPERIMENTAL Like `run_in_terminal`, but takes a generator that can yield Application instances. Example: def f(): yield Application1(...) print('...') ...
EXPERIMENTAL Like `run_in_terminal`, but takes a generator that can yield Application instances. Example: def f(): yield Application1(...) print('...') yield Application2(...) cli.run_in_terminal_async(f) The values which...
Below is the the instruction that describes the task: ### Input: EXPERIMENTAL Like `run_in_terminal`, but takes a generator that can yield Application instances. Example: def f(): yield Application1(...) print('...') yield Application2(.....
def sample(self, samples=[], bounds=None, **sample_values): """Samples element values at supplied coordinates. Allows sampling of element with a list of coordinates matching the key dimensions, returning a new object containing just the selected samples. Supports multiple signatures: ...
Samples element values at supplied coordinates. Allows sampling of element with a list of coordinates matching the key dimensions, returning a new object containing just the selected samples. Supports multiple signatures: Sampling with a list of coordinates, e.g.: ds.sampl...
Below is the the instruction that describes the task: ### Input: Samples element values at supplied coordinates. Allows sampling of element with a list of coordinates matching the key dimensions, returning a new object containing just the selected samples. Supports multiple signatures: ...
def _trace_filename(self): """ Creates trace filename. """ dir_stub = '' if self.output_directory is not None: dir_stub = self.output_directory if self.each_time: filename = '{0}_{1}.json'.format( self.output_file_name, self.counter...
Creates trace filename.
Below is the the instruction that describes the task: ### Input: Creates trace filename. ### Response: def _trace_filename(self): """ Creates trace filename. """ dir_stub = '' if self.output_directory is not None: dir_stub = self.output_directory if self....
def rectangle(bounds, **kwargs): """ Create a Path2D containing a single or multiple rectangles with the specified bounds. Parameters -------------- bounds : (2, 2) float, or (m, 2, 2) float Minimum XY, Maximum XY Returns ------------- rect : Path2D Path containing spec...
Create a Path2D containing a single or multiple rectangles with the specified bounds. Parameters -------------- bounds : (2, 2) float, or (m, 2, 2) float Minimum XY, Maximum XY Returns ------------- rect : Path2D Path containing specified rectangles
Below is the the instruction that describes the task: ### Input: Create a Path2D containing a single or multiple rectangles with the specified bounds. Parameters -------------- bounds : (2, 2) float, or (m, 2, 2) float Minimum XY, Maximum XY Returns ------------- rect : Path2D ...
def _rc_mset(self, mapping): "Sets each key in the ``mapping`` dict to its corresponding value" result = True for k, v in iteritems(mapping): result = result and self.set(k, v) return result
Sets each key in the ``mapping`` dict to its corresponding value
Below is the the instruction that describes the task: ### Input: Sets each key in the ``mapping`` dict to its corresponding value ### Response: def _rc_mset(self, mapping): "Sets each key in the ``mapping`` dict to its corresponding value" result = True for k, v in iteritems(mapping): ...
def addElement(self, parent, tag, value): """Add an RSS item.""" elem = self.rss.createElement(tag) node = self.rss.createTextNode(value) return parent.appendChild(elem).appendChild(node)
Add an RSS item.
Below is the the instruction that describes the task: ### Input: Add an RSS item. ### Response: def addElement(self, parent, tag, value): """Add an RSS item.""" elem = self.rss.createElement(tag) node = self.rss.createTextNode(value) return parent.appendChild(elem).appendChild(node)
def set_axis_labels(self, x_var=None, y_var=None): """Set axis labels on the left column and bottom row of the grid.""" if x_var is not None: if x_var in self.data.coords: self._x_var = x_var self.set_xlabels(label_from_attrs(self.data[x_var])) els...
Set axis labels on the left column and bottom row of the grid.
Below is the the instruction that describes the task: ### Input: Set axis labels on the left column and bottom row of the grid. ### Response: def set_axis_labels(self, x_var=None, y_var=None): """Set axis labels on the left column and bottom row of the grid.""" if x_var is not None: if ...
def ReadCronJobRuns(self, job_id, cursor=None): """Reads all cron job runs for a given job id.""" query = """ SELECT run, UNIX_TIMESTAMP(write_time) FROM cron_job_runs WHERE job_id = %s """ cursor.execute(query, [job_id]) runs = [self._CronJobRunFromRow(row) for row in cursor.fetchall...
Reads all cron job runs for a given job id.
Below is the the instruction that describes the task: ### Input: Reads all cron job runs for a given job id. ### Response: def ReadCronJobRuns(self, job_id, cursor=None): """Reads all cron job runs for a given job id.""" query = """ SELECT run, UNIX_TIMESTAMP(write_time) FROM cron_job_runs W...
def active_inactive(self): """The indexes of the active and the inactive cell vectors""" active_indices = [] inactive_indices = [] for index, active in enumerate(self.active): if active: active_indices.append(index) else: inactive_i...
The indexes of the active and the inactive cell vectors
Below is the the instruction that describes the task: ### Input: The indexes of the active and the inactive cell vectors ### Response: def active_inactive(self): """The indexes of the active and the inactive cell vectors""" active_indices = [] inactive_indices = [] for index, active...
def post_id_backpage_groups(): """ Get a dictionary of Backpage city names mapped to their posting ID group (ex: groups['buffalo']: 'upstateny') Returns: dictionary of Backpage city names mapped to their posting ID group """ city_bp_groups = {} with open('dataFiles/city_bp_groups.csv', 'rU') as csvfile...
Get a dictionary of Backpage city names mapped to their posting ID group (ex: groups['buffalo']: 'upstateny') Returns: dictionary of Backpage city names mapped to their posting ID group
Below is the the instruction that describes the task: ### Input: Get a dictionary of Backpage city names mapped to their posting ID group (ex: groups['buffalo']: 'upstateny') Returns: dictionary of Backpage city names mapped to their posting ID group ### Response: def post_id_backpage_groups(): """ Get ...
def wait_for_redis_to_start(redis_ip_address, redis_port, password=None, num_retries=5): """Wait for a Redis server to be available. This is accomplished by creating a Redis client and sending a random command to the server...
Wait for a Redis server to be available. This is accomplished by creating a Redis client and sending a random command to the server until the command gets through. Args: redis_ip_address (str): The IP address of the redis server. redis_port (int): The port of the redis server. pass...
Below is the the instruction that describes the task: ### Input: Wait for a Redis server to be available. This is accomplished by creating a Redis client and sending a random command to the server until the command gets through. Args: redis_ip_address (str): The IP address of the redis server....
def refresh(self, timeout=3, wait_for_finish=False, **kw): """ Refresh existing policy on specified device. This is an asynchronous call that will return a 'follower' link that can be queried to determine the status of the task. :: poller = engine.refresh() ...
Refresh existing policy on specified device. This is an asynchronous call that will return a 'follower' link that can be queried to determine the status of the task. :: poller = engine.refresh() while not poller.done(): poller.wait(5) prin...
Below is the the instruction that describes the task: ### Input: Refresh existing policy on specified device. This is an asynchronous call that will return a 'follower' link that can be queried to determine the status of the task. :: poller = engine.refresh() while n...
def trigger_all_callbacks(self, callbacks=None): """Trigger callbacks for all keys on all or a subset of subscribers. :param Iterable callbacks: list of callbacks or none for all subscribed :rtype: Iterable[tornado.concurrent.Future] """ return [ret for key in se...
Trigger callbacks for all keys on all or a subset of subscribers. :param Iterable callbacks: list of callbacks or none for all subscribed :rtype: Iterable[tornado.concurrent.Future]
Below is the the instruction that describes the task: ### Input: Trigger callbacks for all keys on all or a subset of subscribers. :param Iterable callbacks: list of callbacks or none for all subscribed :rtype: Iterable[tornado.concurrent.Future] ### Response: def trigger_all_callbacks(self, callb...
def next_id(self, channel): """Get the next sequence number for a named channel or topic If channel has not been sent to next_id before, 0 is returned otherwise next_id returns the last id returned + 1. Args: channel (string): The name of the channel to get a sequential ...
Get the next sequence number for a named channel or topic If channel has not been sent to next_id before, 0 is returned otherwise next_id returns the last id returned + 1. Args: channel (string): The name of the channel to get a sequential id for. Returns: ...
Below is the the instruction that describes the task: ### Input: Get the next sequence number for a named channel or topic If channel has not been sent to next_id before, 0 is returned otherwise next_id returns the last id returned + 1. Args: channel (string): The name of the c...
def plot_moc(moc, order=None, antialias=0, filename=None, projection='cart', color='blue', title='', coord_sys='C', graticule=True, **kwargs): """Plot a MOC using Healpy. This generates a plot of the MOC at the specified order, or the MOC's current order if this is not specified. ...
Plot a MOC using Healpy. This generates a plot of the MOC at the specified order, or the MOC's current order if this is not specified. The MOC is flattened at an order of `order + antialias` to generate intermediate color levels. :param order: HEALPix order at which to generate the plot. :param ...
Below is the the instruction that describes the task: ### Input: Plot a MOC using Healpy. This generates a plot of the MOC at the specified order, or the MOC's current order if this is not specified. The MOC is flattened at an order of `order + antialias` to generate intermediate color levels. :p...
def _generate_api_gateway(self): """ Generate the full configuration for the API Gateway, and add to self.tf_conf """ self.tf_conf['resource']['aws_api_gateway_rest_api']['rest_api'] = { 'name': self.resource_name, 'description': self.description }...
Generate the full configuration for the API Gateway, and add to self.tf_conf
Below is the the instruction that describes the task: ### Input: Generate the full configuration for the API Gateway, and add to self.tf_conf ### Response: def _generate_api_gateway(self): """ Generate the full configuration for the API Gateway, and add to self.tf_conf """ ...
def build(self): """Build single DNA strand along z-axis, starting with P on x-axis""" ang_per_res = (2 * numpy.pi) / self.nucleotides_per_turn atom_offset_coords = _backbone_properties[self.helix_type]['atoms'] if self.handedness == 'l': handedness = -1 else: ...
Build single DNA strand along z-axis, starting with P on x-axis
Below is the the instruction that describes the task: ### Input: Build single DNA strand along z-axis, starting with P on x-axis ### Response: def build(self): """Build single DNA strand along z-axis, starting with P on x-axis""" ang_per_res = (2 * numpy.pi) / self.nucleotides_per_turn atom...
def combine_slices(slice_datasets, rescale=None): ''' Given a list of pydicom datasets for an image series, stitch them together into a three-dimensional numpy array. Also calculate a 4x4 affine transformation matrix that converts the ijk-pixel-indices into the xyz-coordinates in the DICOM patient'...
Given a list of pydicom datasets for an image series, stitch them together into a three-dimensional numpy array. Also calculate a 4x4 affine transformation matrix that converts the ijk-pixel-indices into the xyz-coordinates in the DICOM patient's coordinate system. Returns a two-tuple containing the 3...
Below is the the instruction that describes the task: ### Input: Given a list of pydicom datasets for an image series, stitch them together into a three-dimensional numpy array. Also calculate a 4x4 affine transformation matrix that converts the ijk-pixel-indices into the xyz-coordinates in the DICOM p...
def send_command(self, command): """ Sends a given command to the HAProxy control socket. Returns the response from the socket as a string. If a known error response (e.g. "Permission denied.") is given then the appropriate exception is raised. """ logger.debug(...
Sends a given command to the HAProxy control socket. Returns the response from the socket as a string. If a known error response (e.g. "Permission denied.") is given then the appropriate exception is raised.
Below is the the instruction that describes the task: ### Input: Sends a given command to the HAProxy control socket. Returns the response from the socket as a string. If a known error response (e.g. "Permission denied.") is given then the appropriate exception is raised. ### Response: de...
def set_pragmas(self, pragmas): """ Set pragmas for the current database connection. Parameters ---------- pragmas : dict Dictionary of pragmas; see constants.default_pragmas for a template and http://www.sqlite.org/pragma.html for a full list. ""...
Set pragmas for the current database connection. Parameters ---------- pragmas : dict Dictionary of pragmas; see constants.default_pragmas for a template and http://www.sqlite.org/pragma.html for a full list.
Below is the the instruction that describes the task: ### Input: Set pragmas for the current database connection. Parameters ---------- pragmas : dict Dictionary of pragmas; see constants.default_pragmas for a template and http://www.sqlite.org/pragma.html for a full...
def striptags(self): r"""Unescape markup into an unicode string and strip all tags. This also resolves known HTML4 and XHTML entities. Whitespace is normalized to one: >>> Markup("Main &raquo; <em>About</em>").striptags() u'Main \xbb About' """ stripped = u' '...
r"""Unescape markup into an unicode string and strip all tags. This also resolves known HTML4 and XHTML entities. Whitespace is normalized to one: >>> Markup("Main &raquo; <em>About</em>").striptags() u'Main \xbb About'
Below is the the instruction that describes the task: ### Input: r"""Unescape markup into an unicode string and strip all tags. This also resolves known HTML4 and XHTML entities. Whitespace is normalized to one: >>> Markup("Main &raquo; <em>About</em>").striptags() u'Main \xbb Ab...
def has_all_nonzero_neurite_radii(neuron, threshold=0.0): '''Check presence of neurite points with radius not above threshold Arguments: neuron(Neuron): The neuron object to test threshold: value above which a radius is considered to be non-zero Returns: CheckResult with result inc...
Check presence of neurite points with radius not above threshold Arguments: neuron(Neuron): The neuron object to test threshold: value above which a radius is considered to be non-zero Returns: CheckResult with result including list of (section ID, point ID) pairs of zero-radiu...
Below is the the instruction that describes the task: ### Input: Check presence of neurite points with radius not above threshold Arguments: neuron(Neuron): The neuron object to test threshold: value above which a radius is considered to be non-zero Returns: CheckResult with result...
def color_as_heatmap(self, weights, max_weight=1.0, color=DEFAULT_COLORMAP): ''' Truncate weights to the range [0, max_weight] and rescale, as you would want for a heatmap with known scale. ''' import numpy as np adjusted_weights = np.clip(weights, 0., max_weight) / max_w...
Truncate weights to the range [0, max_weight] and rescale, as you would want for a heatmap with known scale.
Below is the the instruction that describes the task: ### Input: Truncate weights to the range [0, max_weight] and rescale, as you would want for a heatmap with known scale. ### Response: def color_as_heatmap(self, weights, max_weight=1.0, color=DEFAULT_COLORMAP): ''' Truncate weights to th...
def calls(self, truncate=False): """ Show 10 most frequently called queries. Requires the pg_stat_statements Postgres module to be installed. Record( query='BEGIN;', exec_time=datetime.timedelta(0, 0, 288174), prop_exec_time='0.0%', ncalls...
Show 10 most frequently called queries. Requires the pg_stat_statements Postgres module to be installed. Record( query='BEGIN;', exec_time=datetime.timedelta(0, 0, 288174), prop_exec_time='0.0%', ncalls='845590', sync_io_time=datetime.timedelt...
Below is the the instruction that describes the task: ### Input: Show 10 most frequently called queries. Requires the pg_stat_statements Postgres module to be installed. Record( query='BEGIN;', exec_time=datetime.timedelta(0, 0, 288174), prop_exec_time='0.0%', ...
def a1_to_rowcol(label): """Translates a cell's address in A1 notation to a tuple of integers. :param label: A cell label in A1 notation, e.g. 'B1'. Letter case is ignored. :type label: str :returns: a tuple containing `row` and `column` numbers. Both indexed from 1 (on...
Translates a cell's address in A1 notation to a tuple of integers. :param label: A cell label in A1 notation, e.g. 'B1'. Letter case is ignored. :type label: str :returns: a tuple containing `row` and `column` numbers. Both indexed from 1 (one). Example: >>> a1_to...
Below is the the instruction that describes the task: ### Input: Translates a cell's address in A1 notation to a tuple of integers. :param label: A cell label in A1 notation, e.g. 'B1'. Letter case is ignored. :type label: str :returns: a tuple containing `row` and `column` numbers. ...
def get_all_knoreq_user_objects(self, include_machine = False): """ Fetches all user objects with useraccountcontrol DONT_REQ_PREAUTH flag set from the AD, and returns MSADUser object. """ logger.debug('Polling AD for all user objects, machine accounts included: %s'% include_machine) if include_machine == ...
Fetches all user objects with useraccountcontrol DONT_REQ_PREAUTH flag set from the AD, and returns MSADUser object.
Below is the the instruction that describes the task: ### Input: Fetches all user objects with useraccountcontrol DONT_REQ_PREAUTH flag set from the AD, and returns MSADUser object. ### Response: def get_all_knoreq_user_objects(self, include_machine = False): """ Fetches all user objects with useraccountcontro...
def get_authn_header(self, request, authn_method, **kwargs): """ Construct an authorization specification to be sent in the HTTP header. :param request: The service request :param authn_method: Which authentication/authorization method to use :param kwargs: Extra keyword...
Construct an authorization specification to be sent in the HTTP header. :param request: The service request :param authn_method: Which authentication/authorization method to use :param kwargs: Extra keyword arguments :return: A set of keyword arguments to be sent in the HTTP hea...
Below is the the instruction that describes the task: ### Input: Construct an authorization specification to be sent in the HTTP header. :param request: The service request :param authn_method: Which authentication/authorization method to use :param kwargs: Extra keyword arguments ...
def visualize_cloud_of_words(dictionary, image_path=None): """ Renders the cloud of words representation for a given dictionary of frequencies :param dictionary: the dictionary object that contains key-frequency pairs :param image_path: the path to the image mask, None if no masking is ...
Renders the cloud of words representation for a given dictionary of frequencies :param dictionary: the dictionary object that contains key-frequency pairs :param image_path: the path to the image mask, None if no masking is needed
Below is the the instruction that describes the task: ### Input: Renders the cloud of words representation for a given dictionary of frequencies :param dictionary: the dictionary object that contains key-frequency pairs :param image_path: the path to the image mask, None if no masking is needed ###...
def append(self, item): """Appends a `Monomer to the `Polymer`. Notes ----- Does not update labelling. """ if isinstance(item, Monomer): self._monomers.append(item) else: raise TypeError( 'Only Monomer objects can be append...
Appends a `Monomer to the `Polymer`. Notes ----- Does not update labelling.
Below is the the instruction that describes the task: ### Input: Appends a `Monomer to the `Polymer`. Notes ----- Does not update labelling. ### Response: def append(self, item): """Appends a `Monomer to the `Polymer`. Notes ----- Does not update labelling....
def render_noderef(self, ontol, n, query_ids=None, **args): """ Render a node object """ if query_ids is None: query_ids = [] marker = "" if n in query_ids: marker = " * " label = ontol.label(n) s = None if label is not None...
Render a node object
Below is the the instruction that describes the task: ### Input: Render a node object ### Response: def render_noderef(self, ontol, n, query_ids=None, **args): """ Render a node object """ if query_ids is None: query_ids = [] marker = "" if n in query_ids...
def ifetch_single(iterable, key, default=EMPTY, getter=None): """ getter() g(item, key):pass """ def _getter(item): if getter: custom_getter = partial(getter, key=key) return custom_getter(item) else: return partial(bget, key=key, default=default)(ite...
getter() g(item, key):pass
Below is the the instruction that describes the task: ### Input: getter() g(item, key):pass ### Response: def ifetch_single(iterable, key, default=EMPTY, getter=None): """ getter() g(item, key):pass """ def _getter(item): if getter: custom_getter = partial(getter, key=key) ...
def main(self): """Main arbiter function:: * Set logger * Init daemon * Launch modules * Endless main process loop :return: None """ try: # Start the daemon if not self.verify_only and not self.do_daemon_init_and_start(): ...
Main arbiter function:: * Set logger * Init daemon * Launch modules * Endless main process loop :return: None
Below is the the instruction that describes the task: ### Input: Main arbiter function:: * Set logger * Init daemon * Launch modules * Endless main process loop :return: None ### Response: def main(self): """Main arbiter function:: * Set logger * I...
def get_snapshot_policies(self, view=None): """ Retrieve a list of snapshot policies. @param view: View to materialize. Valid values are 'full', 'summary', 'export', 'export_redacted'. @return: A list of snapshot policies. @since: API v6 """ return self._get("snapshots/policies", ApiSnapsho...
Retrieve a list of snapshot policies. @param view: View to materialize. Valid values are 'full', 'summary', 'export', 'export_redacted'. @return: A list of snapshot policies. @since: API v6
Below is the the instruction that describes the task: ### Input: Retrieve a list of snapshot policies. @param view: View to materialize. Valid values are 'full', 'summary', 'export', 'export_redacted'. @return: A list of snapshot policies. @since: API v6 ### Response: def get_snapshot_policies(self, v...
def run(self, force=False, quiet=False, ipyclient=None): """ Parameters ---------- force (bool): Overwrite existing results for object with the same name and workdir as this one. verbose (int): 0=primt nothing; 1=print progress bars; 2=print pr...
Parameters ---------- force (bool): Overwrite existing results for object with the same name and workdir as this one. verbose (int): 0=primt nothing; 1=print progress bars; 2=print pringress bars and cluster information. ipyclient (ipyparal...
Below is the the instruction that describes the task: ### Input: Parameters ---------- force (bool): Overwrite existing results for object with the same name and workdir as this one. verbose (int): 0=primt nothing; 1=print progress bars; 2=print pringress ...
def build_arch(self, arch): '''Run any build tasks for the Recipe. By default, this checks if any build_archname methods exist for the archname of the current architecture, and runs them if so.''' build = "build_{}".format(arch.arch) if hasattr(self, build): getattr(s...
Run any build tasks for the Recipe. By default, this checks if any build_archname methods exist for the archname of the current architecture, and runs them if so.
Below is the the instruction that describes the task: ### Input: Run any build tasks for the Recipe. By default, this checks if any build_archname methods exist for the archname of the current architecture, and runs them if so. ### Response: def build_arch(self, arch): '''Run any build task...
def fill_cache(self): """Fill the cache with new data from the sensor.""" _LOGGER.debug('Filling cache with new sensor data.') try: self.firmware_version() except BluetoothBackendException: # If a sensor doesn't work, wait 5 minutes before retrying sel...
Fill the cache with new data from the sensor.
Below is the the instruction that describes the task: ### Input: Fill the cache with new data from the sensor. ### Response: def fill_cache(self): """Fill the cache with new data from the sensor.""" _LOGGER.debug('Filling cache with new sensor data.') try: self.firmware_version(...
def inc(self, *args, **kwargs): ''' Atomically increment ``qfield`` by ``value`` ''' pairs = [] if len(args) == 1: pairs.append((args[0], 1)) elif len(args) == 2: pairs.append(args) elif len(kwargs) != 0: pairs.extend([(k, v) for k, v in kwargs...
Atomically increment ``qfield`` by ``value``
Below is the the instruction that describes the task: ### Input: Atomically increment ``qfield`` by ``value`` ### Response: def inc(self, *args, **kwargs): ''' Atomically increment ``qfield`` by ``value`` ''' pairs = [] if len(args) == 1: pairs.append((args[0], 1)) elif ...
def get_resource_value(self, device_id, resource_path, fix_path=True, timeout=None): """Get a resource value for a given device and resource path by blocking thread. Example usage: .. code-block:: python try: v = api.get_resource_value(device_id, path) ...
Get a resource value for a given device and resource path by blocking thread. Example usage: .. code-block:: python try: v = api.get_resource_value(device_id, path) print("Current value", v) except CloudAsyncError, e: print("Erro...
Below is the the instruction that describes the task: ### Input: Get a resource value for a given device and resource path by blocking thread. Example usage: .. code-block:: python try: v = api.get_resource_value(device_id, path) print("Current value", ...
def init_structure(self, total_num_bonds, total_num_atoms, total_num_groups, total_num_chains, total_num_models, structure_id): """Initialise the structure object. :param total_num_bonds: the number of bonds in the structure :param total_num_atoms: t...
Initialise the structure object. :param total_num_bonds: the number of bonds in the structure :param total_num_atoms: the number of atoms in the structure :param total_num_groups: the number of groups in the structure :param total_num_chains: the number of chains in the structure ...
Below is the the instruction that describes the task: ### Input: Initialise the structure object. :param total_num_bonds: the number of bonds in the structure :param total_num_atoms: the number of atoms in the structure :param total_num_groups: the number of groups in the structure :...
def connect(self): """Connects to the given host""" self.socket = socket.create_connection(self.address, self.timeout)
Connects to the given host
Below is the the instruction that describes the task: ### Input: Connects to the given host ### Response: def connect(self): """Connects to the given host""" self.socket = socket.create_connection(self.address, self.timeout)
def arsh(self, num): """Arithmetically right shift the farray by *num* places. The *num* argument must be a non-negative ``int``. The carry-in will be the value of the most significant bit. Returns a new farray. """ if num < 0 or num > self.size: raise Valu...
Arithmetically right shift the farray by *num* places. The *num* argument must be a non-negative ``int``. The carry-in will be the value of the most significant bit. Returns a new farray.
Below is the the instruction that describes the task: ### Input: Arithmetically right shift the farray by *num* places. The *num* argument must be a non-negative ``int``. The carry-in will be the value of the most significant bit. Returns a new farray. ### Response: def arsh(self, num): ...
def interpret(self, msg): """ Load input """ slides = msg.get('slides', []) result = [] for slide in slides: image = self.layout(slide) result.append(image) return result
Load input
Below is the the instruction that describes the task: ### Input: Load input ### Response: def interpret(self, msg): """ Load input """ slides = msg.get('slides', []) result = [] for slide in slides: image = self.layout(slide) result.append(image) r...
def gsignal(name, *args, **kwargs): """Add a GObject signal to the current object. It current supports the following types: - str, int, float, long, object, enum :param name: name of the signal :param args: types for signal parameters, if the first one is a string 'override', the signa...
Add a GObject signal to the current object. It current supports the following types: - str, int, float, long, object, enum :param name: name of the signal :param args: types for signal parameters, if the first one is a string 'override', the signal will be overridden and must there...
Below is the the instruction that describes the task: ### Input: Add a GObject signal to the current object. It current supports the following types: - str, int, float, long, object, enum :param name: name of the signal :param args: types for signal parameters, if the first one is a st...
def cut(self, bits, start=None, end=None, count=None): """Return bitstring generator by cutting into bits sized chunks. bits -- The size in bits of the bitstring chunks to generate. start -- The bit position to start the first cut. Defaults to 0. end -- The bit position one past the las...
Return bitstring generator by cutting into bits sized chunks. bits -- The size in bits of the bitstring chunks to generate. start -- The bit position to start the first cut. Defaults to 0. end -- The bit position one past the last bit to use in the cut. Defaults to self.len. ...
Below is the the instruction that describes the task: ### Input: Return bitstring generator by cutting into bits sized chunks. bits -- The size in bits of the bitstring chunks to generate. start -- The bit position to start the first cut. Defaults to 0. end -- The bit position one past the ...
def add(self, name, value, showkey=None, before=None, preserve_spacing=True): """Add a parameter to the template with a given *name* and *value*. *name* and *value* can be anything parsable by :func:`.utils.parse_anything`; pipes and equal signs are automatically escaped fro...
Add a parameter to the template with a given *name* and *value*. *name* and *value* can be anything parsable by :func:`.utils.parse_anything`; pipes and equal signs are automatically escaped from *value* when appropriate. If *name* is already a parameter in the template, we'll replace ...
Below is the the instruction that describes the task: ### Input: Add a parameter to the template with a given *name* and *value*. *name* and *value* can be anything parsable by :func:`.utils.parse_anything`; pipes and equal signs are automatically escaped from *value* when appropriate. ...
def findUselessCheckers(self, allowedMessages): """ Find checkers which generate no allowed messages. @param allowedMessages: allowed messages @return: useless checkers, remove them from pylint """ uselessCheckers = [] for checkerName in self.linter._checkers: ...
Find checkers which generate no allowed messages. @param allowedMessages: allowed messages @return: useless checkers, remove them from pylint
Below is the the instruction that describes the task: ### Input: Find checkers which generate no allowed messages. @param allowedMessages: allowed messages @return: useless checkers, remove them from pylint ### Response: def findUselessCheckers(self, allowedMessages): """ Find chec...
def _handle_result(self, result): """Mark the result as completed, insert the `CompiledResultNode` into the manifest, and mark any descendants (potentially with a 'cause' if the result was an ephemeral model) as skipped. """ is_ephemeral = result.node.is_ephemeral_model i...
Mark the result as completed, insert the `CompiledResultNode` into the manifest, and mark any descendants (potentially with a 'cause' if the result was an ephemeral model) as skipped.
Below is the the instruction that describes the task: ### Input: Mark the result as completed, insert the `CompiledResultNode` into the manifest, and mark any descendants (potentially with a 'cause' if the result was an ephemeral model) as skipped. ### Response: def _handle_result(self, result): ...
def _get_filter_indices(seg, start_as_yes, prob_raw_yes, ms_per_input, model, transition_matrix, model_stats): """ Runs a Markov Decision Process over the given `seg` in chunks of `ms_per_input`, yielding `True` if this `ms_per_input` chunk has been classified as positive (1) and `False` if this chunk has b...
Runs a Markov Decision Process over the given `seg` in chunks of `ms_per_input`, yielding `True` if this `ms_per_input` chunk has been classified as positive (1) and `False` if this chunk has been classified as negative (0). :param seg: The AudioSegment to apply this algorithm to. :para...
Below is the the instruction that describes the task: ### Input: Runs a Markov Decision Process over the given `seg` in chunks of `ms_per_input`, yielding `True` if this `ms_per_input` chunk has been classified as positive (1) and `False` if this chunk has been classified as negative (0). :param seg: ...
def get_followers(self, first_user_id=None): """ 获取一页用户列表(当关注用户过多的情况下,这个接口只会返回一部分用户) 详情请参考 https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421140840 :param first_user_id: 可选。第一个拉取的 OPENID,不填默认从头开始拉取 :return: 返回的 JSON 数据包 使用示例:: from wechatp...
获取一页用户列表(当关注用户过多的情况下,这个接口只会返回一部分用户) 详情请参考 https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421140840 :param first_user_id: 可选。第一个拉取的 OPENID,不填默认从头开始拉取 :return: 返回的 JSON 数据包 使用示例:: from wechatpy import WeChatClient client = WeChatClient('appid',...
Below is the the instruction that describes the task: ### Input: 获取一页用户列表(当关注用户过多的情况下,这个接口只会返回一部分用户) 详情请参考 https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421140840 :param first_user_id: 可选。第一个拉取的 OPENID,不填默认从头开始拉取 :return: 返回的 JSON 数据包 使用示例:: from wec...
def _get_config_dirs(): """Return a list of directories where config files may be located. The following directories are returned:: $XDG_CONFIG_HOME/rapport/ ($XDG_CONFIG_HOME defaults to ~/.config) /etc/rapport/ """ config_dirs = [ USER_CONFIG_DIR, os.path.join("/", "etc",...
Return a list of directories where config files may be located. The following directories are returned:: $XDG_CONFIG_HOME/rapport/ ($XDG_CONFIG_HOME defaults to ~/.config) /etc/rapport/
Below is the the instruction that describes the task: ### Input: Return a list of directories where config files may be located. The following directories are returned:: $XDG_CONFIG_HOME/rapport/ ($XDG_CONFIG_HOME defaults to ~/.config) /etc/rapport/ ### Response: def _get_config_dirs(): """R...
def _to_bstr(l): """Convert to byte string.""" if isinstance(l, str): l = l.encode('ascii', 'backslashreplace') elif not isinstance(l, bytes): l = str(l).encode('ascii', 'backslashreplace') return l
Convert to byte string.
Below is the the instruction that describes the task: ### Input: Convert to byte string. ### Response: def _to_bstr(l): """Convert to byte string.""" if isinstance(l, str): l = l.encode('ascii', 'backslashreplace') elif not isinstance(l, bytes): l = str(l).encode('ascii', 'backslashrep...
def _getAppStoreResource(self, ctx, name): """ Customize child lookup such that all installed offerings on the site store that this page is viewing are given an opportunity to display their own page. """ offer = self.frontPageItem.store.findFirst( offering.Ins...
Customize child lookup such that all installed offerings on the site store that this page is viewing are given an opportunity to display their own page.
Below is the the instruction that describes the task: ### Input: Customize child lookup such that all installed offerings on the site store that this page is viewing are given an opportunity to display their own page. ### Response: def _getAppStoreResource(self, ctx, name): """ Cust...
def get_config(self, budget): """ Function to sample a new configuration This function is called inside Hyperband to query a new configuration Parameters: ----------- budget: float the budget for which this configuration is scheduled returns: config should return a valid configuration ...
Function to sample a new configuration This function is called inside Hyperband to query a new configuration Parameters: ----------- budget: float the budget for which this configuration is scheduled returns: config should return a valid configuration
Below is the the instruction that describes the task: ### Input: Function to sample a new configuration This function is called inside Hyperband to query a new configuration Parameters: ----------- budget: float the budget for which this configuration is scheduled returns: config should r...
def load_config(self, conf): """ Load configurations from an rc file Parameters ---------- rc: str path to the rc file Returns ------- None """ section = self.__class__.__name__ if section not in conf.sections(): ...
Load configurations from an rc file Parameters ---------- rc: str path to the rc file Returns ------- None
Below is the the instruction that describes the task: ### Input: Load configurations from an rc file Parameters ---------- rc: str path to the rc file Returns ------- None ### Response: def load_config(self, conf): """ Load configuration...
def scroll_to_bottom(self): """ Scoll to the very bottom of the page TODO: add increment & delay options to scoll slowly down the whole page to let each section load in """ if self.driver.selenium is not None: try: self.driver.selenium.execute_script("...
Scoll to the very bottom of the page TODO: add increment & delay options to scoll slowly down the whole page to let each section load in
Below is the the instruction that describes the task: ### Input: Scoll to the very bottom of the page TODO: add increment & delay options to scoll slowly down the whole page to let each section load in ### Response: def scroll_to_bottom(self): """ Scoll to the very bottom of the page ...
def from_cookie(self, param_name, field): """ A decorator that converts a request cookie into a function parameter based on the specified field. :param str param_name: The parameter which receives the argument. :param Field field: The field class or instance used to deserialize the requ...
A decorator that converts a request cookie into a function parameter based on the specified field. :param str param_name: The parameter which receives the argument. :param Field field: The field class or instance used to deserialize the request cookie to a Python object. :return: A function
Below is the the instruction that describes the task: ### Input: A decorator that converts a request cookie into a function parameter based on the specified field. :param str param_name: The parameter which receives the argument. :param Field field: The field class or instance used to deserialize t...
def parse_build_file(self, build_file): """Capture Addressable instances from parsing `build_file`. Prepare a context for parsing, read a BUILD file from the filesystem, and return the Addressable instances generated by executing the code. """ def _format_context_msg(lineno, offset, error_type, mes...
Capture Addressable instances from parsing `build_file`. Prepare a context for parsing, read a BUILD file from the filesystem, and return the Addressable instances generated by executing the code.
Below is the the instruction that describes the task: ### Input: Capture Addressable instances from parsing `build_file`. Prepare a context for parsing, read a BUILD file from the filesystem, and return the Addressable instances generated by executing the code. ### Response: def parse_build_file(self, buil...
def use_sequestered_assessment_part_view(self): """Pass through to provider AssessmentPartLookupSession.use_sequestered_assessment_part_view""" # Does this need to be re-implemented to match the other non-sub-package view setters? self._containable_views['assessment_part'] = SEQUESTERED ...
Pass through to provider AssessmentPartLookupSession.use_sequestered_assessment_part_view
Below is the the instruction that describes the task: ### Input: Pass through to provider AssessmentPartLookupSession.use_sequestered_assessment_part_view ### Response: def use_sequestered_assessment_part_view(self): """Pass through to provider AssessmentPartLookupSession.use_sequestered_assessment_part_vi...