code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
text
stringlengths
164
112k
def debug(self, msg, indent=0, **kwargs): """invoke ``self.logger.debug``""" return self.logger.debug(self._indent(msg, indent), **kwargs)
invoke ``self.logger.debug``
Below is the the instruction that describes the task: ### Input: invoke ``self.logger.debug`` ### Response: def debug(self, msg, indent=0, **kwargs): """invoke ``self.logger.debug``""" return self.logger.debug(self._indent(msg, indent), **kwargs)
def parse(to_parse, ignore_whitespace_text_nodes=True, adapter=None): """ Parse an XML document into an *xml4h*-wrapped DOM representation using an underlying XML library implementation. :param to_parse: an XML document file, document string, or the path to an XML file. If a string value is giv...
Parse an XML document into an *xml4h*-wrapped DOM representation using an underlying XML library implementation. :param to_parse: an XML document file, document string, or the path to an XML file. If a string value is given that contains a ``<`` character it is treated as literal XML data, othe...
Below is the the instruction that describes the task: ### Input: Parse an XML document into an *xml4h*-wrapped DOM representation using an underlying XML library implementation. :param to_parse: an XML document file, document string, or the path to an XML file. If a string value is given that conta...
def select_rows(cols, rows, mode='list', cast=True): """ Yield data selected from rows. It is sometimes useful to select a subset of data from a profile. This function selects the data in *cols* from *rows* and yields it in a form specified by *mode*. Possible values of *mode* are: ===========...
Yield data selected from rows. It is sometimes useful to select a subset of data from a profile. This function selects the data in *cols* from *rows* and yields it in a form specified by *mode*. Possible values of *mode* are: ================== ================= ========================== mode ...
Below is the the instruction that describes the task: ### Input: Yield data selected from rows. It is sometimes useful to select a subset of data from a profile. This function selects the data in *cols* from *rows* and yields it in a form specified by *mode*. Possible values of *mode* are: =======...
def _fsic_queuing_calc(fsic1, fsic2): """ We set the lower counter between two same instance ids. If an instance_id exists in one fsic but not the other we want to give that counter a value of 0. :param fsic1: dictionary containing (instance_id, counter) pairs :param fsic2: dictionary containing (i...
We set the lower counter between two same instance ids. If an instance_id exists in one fsic but not the other we want to give that counter a value of 0. :param fsic1: dictionary containing (instance_id, counter) pairs :param fsic2: dictionary containing (instance_id, counter) pairs :return ``dict`` of...
Below is the the instruction that describes the task: ### Input: We set the lower counter between two same instance ids. If an instance_id exists in one fsic but not the other we want to give that counter a value of 0. :param fsic1: dictionary containing (instance_id, counter) pairs :param fsic2: dicti...
def get_service_categories(self, restricted=True): """Return all service categories in the right order :param restricted: Client settings restrict categories :type restricted: bool :returns: Category catalog results :rtype: brains """ bsc = api.get_tool("bika_set...
Return all service categories in the right order :param restricted: Client settings restrict categories :type restricted: bool :returns: Category catalog results :rtype: brains
Below is the the instruction that describes the task: ### Input: Return all service categories in the right order :param restricted: Client settings restrict categories :type restricted: bool :returns: Category catalog results :rtype: brains ### Response: def get_service_categories...
def registerSimulator(self, name=None, hdl=None, analyze_cmd=None, elaborate_cmd=None, simulate_cmd=None): ''' Registers an HDL _simulator name - str, user defined name, used to identify this _simulator record hdl - str, case insensitive, (verilog, vhdl), the HDL to which the sim...
Registers an HDL _simulator name - str, user defined name, used to identify this _simulator record hdl - str, case insensitive, (verilog, vhdl), the HDL to which the simulated MyHDL code will be converted analyze_cmd - str, system command that will be run to analyze the g...
Below is the the instruction that describes the task: ### Input: Registers an HDL _simulator name - str, user defined name, used to identify this _simulator record hdl - str, case insensitive, (verilog, vhdl), the HDL to which the simulated MyHDL code will be converted ...
def suck_out_variations_only(reporters): """Builds a dictionary of variations to canonical reporters. The dictionary takes the form of: { "A. 2d": ["A.2d"], ... "P.R.": ["Pen. & W.", "P.R.R.", "P."], } In other words, it's a dictionary that maps each variation to...
Builds a dictionary of variations to canonical reporters. The dictionary takes the form of: { "A. 2d": ["A.2d"], ... "P.R.": ["Pen. & W.", "P.R.R.", "P."], } In other words, it's a dictionary that maps each variation to a list of reporters that it could be possib...
Below is the the instruction that describes the task: ### Input: Builds a dictionary of variations to canonical reporters. The dictionary takes the form of: { "A. 2d": ["A.2d"], ... "P.R.": ["Pen. & W.", "P.R.R.", "P."], } In other words, it's a dictionary that m...
def file_response(data: Union[bytes, str], # HttpResponse encodes str if req'd content_type: str, filename: str) -> HttpResponse: """ Returns an ``HttpResponse`` with an attachment containing the specified data with the specified filename as an attachment. """ re...
Returns an ``HttpResponse`` with an attachment containing the specified data with the specified filename as an attachment.
Below is the the instruction that describes the task: ### Input: Returns an ``HttpResponse`` with an attachment containing the specified data with the specified filename as an attachment. ### Response: def file_response(data: Union[bytes, str], # HttpResponse encodes str if req'd content_typ...
def advReplace(document, search, replace, bs=3): """ Replace all occurences of string with a different string, return updated document This is a modified version of python-docx.replace() that takes into account blocks of <bs> elements at a time. The replace element can also be a string or an xm...
Replace all occurences of string with a different string, return updated document This is a modified version of python-docx.replace() that takes into account blocks of <bs> elements at a time. The replace element can also be a string or an xml etree element. What it does: It searches the entir...
Below is the the instruction that describes the task: ### Input: Replace all occurences of string with a different string, return updated document This is a modified version of python-docx.replace() that takes into account blocks of <bs> elements at a time. The replace element can also be a string ...
def _construct_update(self, outgoing_route): """Construct update message with Outgoing-routes path attribute appropriately cloned/copied/updated. """ update = None path = outgoing_route.path # Get copy of path's path attributes. pathattr_map = path.pathattr_map ...
Construct update message with Outgoing-routes path attribute appropriately cloned/copied/updated.
Below is the the instruction that describes the task: ### Input: Construct update message with Outgoing-routes path attribute appropriately cloned/copied/updated. ### Response: def _construct_update(self, outgoing_route): """Construct update message with Outgoing-routes path attribute appro...
def mtx_refl(nv, reps=1): """ Generate block-diagonal reflection matrix about nv. reps must be >=1 and indicates the number of times the reflection matrix should be repeated along the block diagonal. Typically this will be the number of atoms in a geometry. .. todo:: Complete mtx_refl docstring ...
Generate block-diagonal reflection matrix about nv. reps must be >=1 and indicates the number of times the reflection matrix should be repeated along the block diagonal. Typically this will be the number of atoms in a geometry. .. todo:: Complete mtx_refl docstring
Below is the the instruction that describes the task: ### Input: Generate block-diagonal reflection matrix about nv. reps must be >=1 and indicates the number of times the reflection matrix should be repeated along the block diagonal. Typically this will be the number of atoms in a geometry. .. t...
async def _update_firmware(filename, loop): """ Currently uses the robot singleton from the API server to connect to Smoothie. Those calls should be separated out from the singleton so it can be used directly without requiring a full initialization of the API robot. """ try: from opentro...
Currently uses the robot singleton from the API server to connect to Smoothie. Those calls should be separated out from the singleton so it can be used directly without requiring a full initialization of the API robot.
Below is the the instruction that describes the task: ### Input: Currently uses the robot singleton from the API server to connect to Smoothie. Those calls should be separated out from the singleton so it can be used directly without requiring a full initialization of the API robot. ### Response: async def...
def revert_unordered_batches(self): """ Revert changes to ledger (uncommitted) and state made by any requests that have not been ordered. """ i = 0 for key in sorted(self.batches.keys(), reverse=True): if compare_3PC_keys(self.last_ordered_3pc, key) > 0: ...
Revert changes to ledger (uncommitted) and state made by any requests that have not been ordered.
Below is the the instruction that describes the task: ### Input: Revert changes to ledger (uncommitted) and state made by any requests that have not been ordered. ### Response: def revert_unordered_batches(self): """ Revert changes to ledger (uncommitted) and state made by any requests ...
def _get_queries(self, migration, method): """ Get all of the queries that would be run for a migration. :param migration: The migration :type migration: orator.migrations.migration.Migration :param method: The method to execute :type method: str :rtype: list ...
Get all of the queries that would be run for a migration. :param migration: The migration :type migration: orator.migrations.migration.Migration :param method: The method to execute :type method: str :rtype: list
Below is the the instruction that describes the task: ### Input: Get all of the queries that would be run for a migration. :param migration: The migration :type migration: orator.migrations.migration.Migration :param method: The method to execute :type method: str :rtype: ...
def encode(self, source_path, target_path, params): # NOQA: C901 """ Encodes a video to a specified file. All encoder specific options are passed in using `params`. """ total_time = self.get_media_info(source_path)['duration'] cmds = [self.ffmpeg_path, '-i', source_path...
Encodes a video to a specified file. All encoder specific options are passed in using `params`.
Below is the the instruction that describes the task: ### Input: Encodes a video to a specified file. All encoder specific options are passed in using `params`. ### Response: def encode(self, source_path, target_path, params): # NOQA: C901 """ Encodes a video to a specified file. All encod...
def _make_connection(self, bind_user=None, bind_password=None, contextualise=True, **kwargs): """ Make a connection. Args: bind_user (str): User to bind with. If `None`, AUTH_ANONYMOUS is used, otherwise authentication specified with ...
Make a connection. Args: bind_user (str): User to bind with. If `None`, AUTH_ANONYMOUS is used, otherwise authentication specified with config['LDAP_BIND_AUTHENTICATION_TYPE'] is used. bind_password (str): Password to bind to the directory with ...
Below is the the instruction that describes the task: ### Input: Make a connection. Args: bind_user (str): User to bind with. If `None`, AUTH_ANONYMOUS is used, otherwise authentication specified with config['LDAP_BIND_AUTHENTICATION_TYPE'] is used. b...
def lines(self, lines): """ Fill Dockerfile content with specified lines :param lines: list of lines to be written to Dockerfile """ if self.cache_content: self.cached_content = ''.join([b2u(l) for l in lines]) try: with self._open_dockerfile('wb'...
Fill Dockerfile content with specified lines :param lines: list of lines to be written to Dockerfile
Below is the the instruction that describes the task: ### Input: Fill Dockerfile content with specified lines :param lines: list of lines to be written to Dockerfile ### Response: def lines(self, lines): """ Fill Dockerfile content with specified lines :param lines: list of lines to...
def source_group_receiver(self, sender, source, signal, **kwargs): """ Relay source group signals to the appropriate spec strategy. """ from imagekit.cachefiles import ImageCacheFile source_group = sender instance = kwargs['instance'] # Ignore signals from unre...
Relay source group signals to the appropriate spec strategy.
Below is the the instruction that describes the task: ### Input: Relay source group signals to the appropriate spec strategy. ### Response: def source_group_receiver(self, sender, source, signal, **kwargs): """ Relay source group signals to the appropriate spec strategy. """ from i...
def _get_resource_access_state(self, request): """ Returns the FeinCMS resource's access_state, following any INHERITed values. Will return None if the resource has an access state that should never be protected. It should not be possible to protect a resource with an access_state ...
Returns the FeinCMS resource's access_state, following any INHERITed values. Will return None if the resource has an access state that should never be protected. It should not be possible to protect a resource with an access_state of STATE_ALL_ALLOWED, or an access_state of STATE_INHERIT and no...
Below is the the instruction that describes the task: ### Input: Returns the FeinCMS resource's access_state, following any INHERITed values. Will return None if the resource has an access state that should never be protected. It should not be possible to protect a resource with an access_state ...
def trim_variant_sequences(variant_sequences, min_variant_sequence_coverage): """ Trim VariantSequences to desired coverage and then combine any subsequences which get generated. """ n_total = len(variant_sequences) trimmed_variant_sequences = [ variant_sequence.trim_by_coverage(min_vari...
Trim VariantSequences to desired coverage and then combine any subsequences which get generated.
Below is the the instruction that describes the task: ### Input: Trim VariantSequences to desired coverage and then combine any subsequences which get generated. ### Response: def trim_variant_sequences(variant_sequences, min_variant_sequence_coverage): """ Trim VariantSequences to desired coverage and...
def start(controller_class): """Start the Helper controller either in the foreground or as a daemon process. :param controller_class: The controller class handle to create and run :type controller_class: callable """ args = parser.parse() obj = controller_class(args, platform.operating_sys...
Start the Helper controller either in the foreground or as a daemon process. :param controller_class: The controller class handle to create and run :type controller_class: callable
Below is the the instruction that describes the task: ### Input: Start the Helper controller either in the foreground or as a daemon process. :param controller_class: The controller class handle to create and run :type controller_class: callable ### Response: def start(controller_class): """Start ...
def show_diff(original, modified, prefix='', suffix='', prefix_unchanged=' ', suffix_unchanged='', prefix_removed='-', suffix_removed='', prefix_added='+', suffix_added=''): """Return the diff view between original and modified stri...
Return the diff view between original and modified strings. Function checks both arguments line by line and returns a string with a: - prefix_unchanged when line is common to both sequences - prefix_removed when line is unique to sequence 1 - prefix_added when line is unique to sequence 2 and a...
Below is the the instruction that describes the task: ### Input: Return the diff view between original and modified strings. Function checks both arguments line by line and returns a string with a: - prefix_unchanged when line is common to both sequences - prefix_removed when line is unique to sequ...
def main(): """ Program main. """ options = parse_options() output, code = create_output(get_status(options), options) sys.stdout.write(output) sys.exit(code)
Program main.
Below is the the instruction that describes the task: ### Input: Program main. ### Response: def main(): """ Program main. """ options = parse_options() output, code = create_output(get_status(options), options) sys.stdout.write(output) sys.exit(code)
def upload(training_dir, algorithm_id=None, writeup=None, api_key=None, ignore_open_monitors=False): """Upload the results of training (as automatically recorded by your env's monitor) to OpenAI Gym. Args: training_dir (Optional[str]): A directory containing the results of a training run. a...
Upload the results of training (as automatically recorded by your env's monitor) to OpenAI Gym. Args: training_dir (Optional[str]): A directory containing the results of a training run. algorithm_id (Optional[str]): An algorithm id indicating the particular version of the algorithm (including c...
Below is the the instruction that describes the task: ### Input: Upload the results of training (as automatically recorded by your env's monitor) to OpenAI Gym. Args: training_dir (Optional[str]): A directory containing the results of a training run. algorithm_id (Optional[str]): An algorit...
def set_permissions(obj_name, principal, permissions, access_mode='grant', applies_to=None, obj_type='file', reset_perms=False, protected=None): ''' Set the permissions of ...
Set the permissions of an object. This can be a file, folder, registry key, printer, service, etc... Args: obj_name (str): The object for which to set permissions. This can be the path to a file or folder, a registry key, printer, etc. For more information about how...
Below is the the instruction that describes the task: ### Input: Set the permissions of an object. This can be a file, folder, registry key, printer, service, etc... Args: obj_name (str): The object for which to set permissions. This can be the path to a file or folder, a r...
def split_command_line(command_line): '''This splits a command line into a list of arguments. It splits arguments on spaces, but handles embedded quotes, doublequotes, and escaped characters. It's impossible to do this with a regular expression, so I wrote a little state machine to parse the command li...
This splits a command line into a list of arguments. It splits arguments on spaces, but handles embedded quotes, doublequotes, and escaped characters. It's impossible to do this with a regular expression, so I wrote a little state machine to parse the command line.
Below is the the instruction that describes the task: ### Input: This splits a command line into a list of arguments. It splits arguments on spaces, but handles embedded quotes, doublequotes, and escaped characters. It's impossible to do this with a regular expression, so I wrote a little state machine ...
def setData(self, wordBeforeCursor, wholeWord): """Set model information """ self._typedText = wordBeforeCursor self.words = self._makeListOfCompletions(wordBeforeCursor, wholeWord) commonStart = self._commonWordStart(self.words) self.canCompleteText = commonStart[len(wor...
Set model information
Below is the the instruction that describes the task: ### Input: Set model information ### Response: def setData(self, wordBeforeCursor, wholeWord): """Set model information """ self._typedText = wordBeforeCursor self.words = self._makeListOfCompletions(wordBeforeCursor, wholeWord) ...
def write_async(name, values, tags={}, timestamp=None, database=None): """ write metrics """ thread = Thread(target=write, args=(name, values, tags, timestamp, database)) thread.start()
write metrics
Below is the the instruction that describes the task: ### Input: write metrics ### Response: def write_async(name, values, tags={}, timestamp=None, database=None): """ write metrics """ thread = Thread(target=write, args=(name, values, tags, timestamp, database)) thread.start()
def create_zipfile(context): """This is the actual zest.releaser entry point Relevant items in the context dict: name Name of the project being released tagdir Directory where the tag checkout is placed (*if* a tag checkout has been made) version Version we're rel...
This is the actual zest.releaser entry point Relevant items in the context dict: name Name of the project being released tagdir Directory where the tag checkout is placed (*if* a tag checkout has been made) version Version we're releasing workingdir Origi...
Below is the the instruction that describes the task: ### Input: This is the actual zest.releaser entry point Relevant items in the context dict: name Name of the project being released tagdir Directory where the tag checkout is placed (*if* a tag checkout has been made) ...
def stop(self, container, **kwargs): """ Identical to :meth:`dockermap.client.base.DockerClientWrapper.stop` with additional logging. """ self.push_log("Stopping container '{0}'.".format(container)) super(DockerFabricClient, self).stop(container, **kwargs)
Identical to :meth:`dockermap.client.base.DockerClientWrapper.stop` with additional logging.
Below is the the instruction that describes the task: ### Input: Identical to :meth:`dockermap.client.base.DockerClientWrapper.stop` with additional logging. ### Response: def stop(self, container, **kwargs): """ Identical to :meth:`dockermap.client.base.DockerClientWrapper.stop` with additional lo...
def dump(val, humanread = True, dumpextra = False, typeinfo = DUMPTYPE_FLAT, ordered=True, tostr=False, encoding='utf-8'): ''' Convert a parsed NamedStruct (probably with additional NamedStruct as fields) into a JSON-friendly format, with only Python primitives (dictionaries, lists, bytes, integers...
Convert a parsed NamedStruct (probably with additional NamedStruct as fields) into a JSON-friendly format, with only Python primitives (dictionaries, lists, bytes, integers etc.) Then you may use json.dumps, or pprint to further process the result. :param val: parsed result, may contain NamedStruct ...
Below is the the instruction that describes the task: ### Input: Convert a parsed NamedStruct (probably with additional NamedStruct as fields) into a JSON-friendly format, with only Python primitives (dictionaries, lists, bytes, integers etc.) Then you may use json.dumps, or pprint to further process the re...
def close(self): """Close all active poll instances and remove all callbacks.""" if self._mpoll is None: return for mpoll in self._mpoll.values(): mpoll.close() self._mpoll.clear() self._mpoll = None
Close all active poll instances and remove all callbacks.
Below is the the instruction that describes the task: ### Input: Close all active poll instances and remove all callbacks. ### Response: def close(self): """Close all active poll instances and remove all callbacks.""" if self._mpoll is None: return for mpoll in self._mpoll.value...
def set_bug(self, bug_number): """ Set the bug number of this Classified Failure If an existing ClassifiedFailure exists with the same bug number replace this instance with the existing one. """ if bug_number == self.bug_number: return self other = C...
Set the bug number of this Classified Failure If an existing ClassifiedFailure exists with the same bug number replace this instance with the existing one.
Below is the the instruction that describes the task: ### Input: Set the bug number of this Classified Failure If an existing ClassifiedFailure exists with the same bug number replace this instance with the existing one. ### Response: def set_bug(self, bug_number): """ Set the bug ...
def set_power(self, power): """Send Power command.""" req_url = ENDPOINTS["setPower"].format(self.ip_address, self.zone_id) params = {"power": "on" if power else "standby"} return request(req_url, params=params)
Send Power command.
Below is the the instruction that describes the task: ### Input: Send Power command. ### Response: def set_power(self, power): """Send Power command.""" req_url = ENDPOINTS["setPower"].format(self.ip_address, self.zone_id) params = {"power": "on" if power else "standby"} return requ...
def chunks(l,n): '''chunk l in n sized bits''' #http://stackoverflow.com/a/3226719 #...not that this is hard to understand. return [l[x:x+n] for x in range(0, len(l), n)];
chunk l in n sized bits
Below is the the instruction that describes the task: ### Input: chunk l in n sized bits ### Response: def chunks(l,n): '''chunk l in n sized bits''' #http://stackoverflow.com/a/3226719 #...not that this is hard to understand. return [l[x:x+n] for x in range(0, len(l), n)];
def change_password(): """ Changes the standard password from neo4j to testing to be able to run the test suite. """ basic_auth = '%s:%s' % (DEFAULT_USERNAME, DEFAULT_PASSWORD) try: # Python 2 auth = base64.encodestring(basic_auth) except TypeError: # Python 3 auth = base64.enc...
Changes the standard password from neo4j to testing to be able to run the test suite.
Below is the the instruction that describes the task: ### Input: Changes the standard password from neo4j to testing to be able to run the test suite. ### Response: def change_password(): """ Changes the standard password from neo4j to testing to be able to run the test suite. """ basic_auth = '%s:...
def set_dependencies(ctx, archive_name, dependency=None): ''' Set the dependencies of an archive ''' _generate_api(ctx) kwargs = _parse_dependencies(dependency) var = ctx.obj.api.get_archive(archive_name) var.set_dependencies(dependencies=kwargs)
Set the dependencies of an archive
Below is the the instruction that describes the task: ### Input: Set the dependencies of an archive ### Response: def set_dependencies(ctx, archive_name, dependency=None): ''' Set the dependencies of an archive ''' _generate_api(ctx) kwargs = _parse_dependencies(dependency) var = ctx.obj....
def add(name, gid=None, system=False, root=None): ''' Add the specified group name Name of the new group gid Use GID for the new group system Create a system account root Directory to chroot into CLI Example: .. code-block:: bash salt '*' gr...
Add the specified group name Name of the new group gid Use GID for the new group system Create a system account root Directory to chroot into CLI Example: .. code-block:: bash salt '*' group.add foo 3456
Below is the the instruction that describes the task: ### Input: Add the specified group name Name of the new group gid Use GID for the new group system Create a system account root Directory to chroot into CLI Example: .. code-block:: bash salt...
def output_file_name(self): """Name of the file where plugin's output should be written to.""" safe_path = re.sub(r":|/", "_", self.source_urn.Path().lstrip("/")) return "results_%s%s" % (safe_path, self.output_file_extension)
Name of the file where plugin's output should be written to.
Below is the the instruction that describes the task: ### Input: Name of the file where plugin's output should be written to. ### Response: def output_file_name(self): """Name of the file where plugin's output should be written to.""" safe_path = re.sub(r":|/", "_", self.source_urn.Path().lstrip("/")) ...
def make_function_value_private(self, value, value_type, function): """ Wraps converted value so that it is hidden in logs etc. Note this is not secure just reduces leaking info Allows base 64 encode stuff using base64() or plain hide() in the config """ # remove...
Wraps converted value so that it is hidden in logs etc. Note this is not secure just reduces leaking info Allows base 64 encode stuff using base64() or plain hide() in the config
Below is the the instruction that describes the task: ### Input: Wraps converted value so that it is hidden in logs etc. Note this is not secure just reduces leaking info Allows base 64 encode stuff using base64() or plain hide() in the config ### Response: def make_function_value_private(...
def get_sqlproxy_runner(self): """ Retrieve Cloud SQL Proxy runner. It is used to manage the proxy lifecycle per task. :return: The Cloud SQL Proxy runner. :rtype: CloudSqlProxyRunner """ if not self.use_proxy: raise AirflowException("Proxy runner can...
Retrieve Cloud SQL Proxy runner. It is used to manage the proxy lifecycle per task. :return: The Cloud SQL Proxy runner. :rtype: CloudSqlProxyRunner
Below is the the instruction that describes the task: ### Input: Retrieve Cloud SQL Proxy runner. It is used to manage the proxy lifecycle per task. :return: The Cloud SQL Proxy runner. :rtype: CloudSqlProxyRunner ### Response: def get_sqlproxy_runner(self): """ Retrieve Cl...
def volume_detach(self, name, timeout=300): ''' Detach a block device ''' try: volume = self.volume_show(name) except KeyError as exc: raise SaltCloudSystemExit('Unable to find {0} volume: {1}'.format(name, exc))...
Detach a block device
Below is the the instruction that describes the task: ### Input: Detach a block device ### Response: def volume_detach(self, name, timeout=300): ''' Detach a block device ''' try: volume = self.volume_show(name) except ...
def retrieve(func): """ Decorator for Zotero read API methods; calls _retrieve_data() and passes the result to the correct processor, based on a lookup """ def wrapped_f(self, *args, **kwargs): """ Returns result of _retrieve_data() func's return value is part of a URI, and...
Decorator for Zotero read API methods; calls _retrieve_data() and passes the result to the correct processor, based on a lookup
Below is the the instruction that describes the task: ### Input: Decorator for Zotero read API methods; calls _retrieve_data() and passes the result to the correct processor, based on a lookup ### Response: def retrieve(func): """ Decorator for Zotero read API methods; calls _retrieve_data() and passes...
def get_service_resources(cls, model): """ Get resource models by service model """ key = cls.get_model_key(model) return cls.get_service_name_resources(key)
Get resource models by service model
Below is the the instruction that describes the task: ### Input: Get resource models by service model ### Response: def get_service_resources(cls, model): """ Get resource models by service model """ key = cls.get_model_key(model) return cls.get_service_name_resources(key)
def job_data(cls, job_id=dummy_job_id, status=None, code=None, error=None, **kwargs): """ Returns a dictionary containing default job status information such as the *job_id*, a job *status* string, a job return code, and an *error* message. """ return dict(job_id=job_id, status=s...
Returns a dictionary containing default job status information such as the *job_id*, a job *status* string, a job return code, and an *error* message.
Below is the the instruction that describes the task: ### Input: Returns a dictionary containing default job status information such as the *job_id*, a job *status* string, a job return code, and an *error* message. ### Response: def job_data(cls, job_id=dummy_job_id, status=None, code=None, error=None, **...
def do_put(endpoint, body, access_token): '''Do an HTTP PUT request and return JSON. Args: endpoint (str): Azure Resource Manager management endpoint. body (str): JSON body of information to put. access_token (str): A valid Azure authentication token. Returns: HTTP response...
Do an HTTP PUT request and return JSON. Args: endpoint (str): Azure Resource Manager management endpoint. body (str): JSON body of information to put. access_token (str): A valid Azure authentication token. Returns: HTTP response. JSON body.
Below is the the instruction that describes the task: ### Input: Do an HTTP PUT request and return JSON. Args: endpoint (str): Azure Resource Manager management endpoint. body (str): JSON body of information to put. access_token (str): A valid Azure authentication token. Returns: ...
def GetNetworks(alias=None,location=None): """Gets the list of Networks mapped to the account in the specified datacenter. https://t3n.zendesk.com/entries/21024721-Get-Networks :param alias: short code for a particular account. If none will use account's default alias :param location: datacenter where group ...
Gets the list of Networks mapped to the account in the specified datacenter. https://t3n.zendesk.com/entries/21024721-Get-Networks :param alias: short code for a particular account. If none will use account's default alias :param location: datacenter where group resides. If none will use account's primary dat...
Below is the the instruction that describes the task: ### Input: Gets the list of Networks mapped to the account in the specified datacenter. https://t3n.zendesk.com/entries/21024721-Get-Networks :param alias: short code for a particular account. If none will use account's default alias :param location: da...
def init(ctx, client, directory, name, force, use_external_storage): """Initialize a project.""" if not client.use_external_storage: use_external_storage = False ctx.obj = client = attr.evolve( client, path=directory, use_external_storage=use_external_storage, ) msg...
Initialize a project.
Below is the the instruction that describes the task: ### Input: Initialize a project. ### Response: def init(ctx, client, directory, name, force, use_external_storage): """Initialize a project.""" if not client.use_external_storage: use_external_storage = False ctx.obj = client = attr.evolve(...
def create_exchange(self): """ Creates user's private exchange Actually user's private channel needed to be defined only once, and this should be happened when user first created. But since this has a little performance cost, to be safe we always call it before binding t...
Creates user's private exchange Actually user's private channel needed to be defined only once, and this should be happened when user first created. But since this has a little performance cost, to be safe we always call it before binding to the channel we currently subscribe
Below is the the instruction that describes the task: ### Input: Creates user's private exchange Actually user's private channel needed to be defined only once, and this should be happened when user first created. But since this has a little performance cost, to be safe we always ca...
def make_signed_jwt(signer, payload, key_id=None): """Make a signed JWT. See http://self-issued.info/docs/draft-jones-json-web-token.html. Args: signer: crypt.Signer, Cryptographic signer. payload: dict, Dictionary of data to convert to JSON and then sign. key_id: string, (Optional...
Make a signed JWT. See http://self-issued.info/docs/draft-jones-json-web-token.html. Args: signer: crypt.Signer, Cryptographic signer. payload: dict, Dictionary of data to convert to JSON and then sign. key_id: string, (Optional) Key ID header. Returns: string, The JWT for...
Below is the the instruction that describes the task: ### Input: Make a signed JWT. See http://self-issued.info/docs/draft-jones-json-web-token.html. Args: signer: crypt.Signer, Cryptographic signer. payload: dict, Dictionary of data to convert to JSON and then sign. key_id: string...
def do_for_dir(inws, begin): ''' do something in the directory. ''' inws = os.path.abspath(inws) for wroot, wdirs, wfiles in os.walk(inws): for wfile in wfiles: if wfile.endswith('.html'): if 'autogen' in wroot: continue check_h...
do something in the directory.
Below is the the instruction that describes the task: ### Input: do something in the directory. ### Response: def do_for_dir(inws, begin): ''' do something in the directory. ''' inws = os.path.abspath(inws) for wroot, wdirs, wfiles in os.walk(inws): for wfile in wfiles: if w...
def get_meta(catid, sig): ''' Get metadata of dataset via ID. ''' meta_base = './static/dataset_list' if os.path.exists(meta_base): pass else: return False pp_data = {'logo': '', 'kind': '9'} for wroot, wdirs, wfiles in os.walk(meta_base): for wdir in wdirs: ...
Get metadata of dataset via ID.
Below is the the instruction that describes the task: ### Input: Get metadata of dataset via ID. ### Response: def get_meta(catid, sig): ''' Get metadata of dataset via ID. ''' meta_base = './static/dataset_list' if os.path.exists(meta_base): pass else: return False pp_...
def index(request, obj_id=None): """Handles a request based on method and calls the appropriate function""" if request.method == 'GET': return get(request, obj_id) elif request.method == 'POST': return post(request) elif request.method == 'PUT': getPutData(request) return...
Handles a request based on method and calls the appropriate function
Below is the the instruction that describes the task: ### Input: Handles a request based on method and calls the appropriate function ### Response: def index(request, obj_id=None): """Handles a request based on method and calls the appropriate function""" if request.method == 'GET': return get(requ...
def set_cache_dir(directory): """Set the directory to cache JSON responses from most API endpoints. """ global cache_dir if directory is None: cache_dir = None return if not os.path.exists(directory): os.makedirs(directory) if not os.path.isdir(directory): raise...
Set the directory to cache JSON responses from most API endpoints.
Below is the the instruction that describes the task: ### Input: Set the directory to cache JSON responses from most API endpoints. ### Response: def set_cache_dir(directory): """Set the directory to cache JSON responses from most API endpoints. """ global cache_dir if directory is None: c...
def _survives_exclude(self, matchstr, match_type): ''' Returns True if *matchstr* does not match patterns ``self.package_name`` removed from front of string if present Examples -------- >>> dw = ApiDocWriter('sphinx') >>> dw._survives_exclude('sphinx.okpkg', 'package') ...
Returns True if *matchstr* does not match patterns ``self.package_name`` removed from front of string if present Examples -------- >>> dw = ApiDocWriter('sphinx') >>> dw._survives_exclude('sphinx.okpkg', 'package') True >>> dw.package_skip_patterns.append('^\\.b...
Below is the the instruction that describes the task: ### Input: Returns True if *matchstr* does not match patterns ``self.package_name`` removed from front of string if present Examples -------- >>> dw = ApiDocWriter('sphinx') >>> dw._survives_exclude('sphinx.okpkg', 'pack...
def compat_string(value): """ Provide a python2/3 compatible string representation of the value :type value: :rtype : """ if isinstance(value, bytes): return value.decode(encoding='utf-8') return str(value)
Provide a python2/3 compatible string representation of the value :type value: :rtype :
Below is the the instruction that describes the task: ### Input: Provide a python2/3 compatible string representation of the value :type value: :rtype : ### Response: def compat_string(value): """ Provide a python2/3 compatible string representation of the value :type value:...
def __method_descriptor(self, service, method_info, rosy_method, protorpc_method_info): """Describes a method. Args: service: endpoints.Service, Implementation of the API as a service. method_info: _MethodInfo, Configuration for the method. rosy_method: string, Proto...
Describes a method. Args: service: endpoints.Service, Implementation of the API as a service. method_info: _MethodInfo, Configuration for the method. rosy_method: string, ProtoRPC method name prefixed with the name of the service. protorpc_method_info: protorpc.remote._RemoteMethodI...
Below is the the instruction that describes the task: ### Input: Describes a method. Args: service: endpoints.Service, Implementation of the API as a service. method_info: _MethodInfo, Configuration for the method. rosy_method: string, ProtoRPC method name prefixed with the name of th...
def numberOfConnectedProximalSynapses(self, cells=None): """ Returns the number of proximal connected synapses on these cells. Parameters: ---------------------------- @param cells (iterable) Indices of the cells. If None return count for all cells. """ if cells is None: ...
Returns the number of proximal connected synapses on these cells. Parameters: ---------------------------- @param cells (iterable) Indices of the cells. If None return count for all cells.
Below is the the instruction that describes the task: ### Input: Returns the number of proximal connected synapses on these cells. Parameters: ---------------------------- @param cells (iterable) Indices of the cells. If None return count for all cells. ### Response: def numberOfConnected...
def respond(self, output): """Generates server response.""" response = {'exit_code': output.code, 'command_output': output.log} self.send_response(200) self.send_header('Content-type', 'application/json') self.end_headers() self.wfile.write(bytes(js...
Generates server response.
Below is the the instruction that describes the task: ### Input: Generates server response. ### Response: def respond(self, output): """Generates server response.""" response = {'exit_code': output.code, 'command_output': output.log} self.send_response(200) sel...
def _parse_request(self, xml): """ Parse a request with metadata information :param xml: LXML Object :type xml: Union[lxml.etree._Element] """ for node in xml.xpath(".//ti:groupname", namespaces=XPATH_NAMESPACES): lang = node.get("xml:lang") or CtsText.DEFAULT_LANG ...
Parse a request with metadata information :param xml: LXML Object :type xml: Union[lxml.etree._Element]
Below is the the instruction that describes the task: ### Input: Parse a request with metadata information :param xml: LXML Object :type xml: Union[lxml.etree._Element] ### Response: def _parse_request(self, xml): """ Parse a request with metadata information :param xml: LXML Obje...
def get_heap(self, *args, **kwargs): """Return a new heap which contains all the new items and item descriptors since the last call. This is a convenience wrapper around :meth:`add_to_heap`. """ heap = Heap(self._flavour) self.add_to_heap(heap, *args, **kwargs) re...
Return a new heap which contains all the new items and item descriptors since the last call. This is a convenience wrapper around :meth:`add_to_heap`.
Below is the the instruction that describes the task: ### Input: Return a new heap which contains all the new items and item descriptors since the last call. This is a convenience wrapper around :meth:`add_to_heap`. ### Response: def get_heap(self, *args, **kwargs): """Return a new heap whi...
def check_event_coverage(patterns, event_list): """Calculate the ratio of patterns that were extracted.""" proportions = [] for pattern_list in patterns: proportion = 0 for pattern in pattern_list: for node in pattern.nodes(): if node in event_list: ...
Calculate the ratio of patterns that were extracted.
Below is the the instruction that describes the task: ### Input: Calculate the ratio of patterns that were extracted. ### Response: def check_event_coverage(patterns, event_list): """Calculate the ratio of patterns that were extracted.""" proportions = [] for pattern_list in patterns: proportio...
def get_coords(x, y, params): """ Transforms the given coordinates from plane-space to Mandelbrot-space (real and imaginary). :param x: X coordinate on the plane. :param y: Y coordinate on the plane. :param params: Current application parameters. :type params: params.Params :return: Tuple c...
Transforms the given coordinates from plane-space to Mandelbrot-space (real and imaginary). :param x: X coordinate on the plane. :param y: Y coordinate on the plane. :param params: Current application parameters. :type params: params.Params :return: Tuple containing the re-mapped coordinates in Man...
Below is the the instruction that describes the task: ### Input: Transforms the given coordinates from plane-space to Mandelbrot-space (real and imaginary). :param x: X coordinate on the plane. :param y: Y coordinate on the plane. :param params: Current application parameters. :type params: params....
def check_each_direction(n,angs,ifprint=True): """ returns a list of the index of elements of n which do not have adequate toy angle coverage. The criterion is that we must have at least one sample in each Nyquist box when we project the toy angles along the vector n """ checks = np.array([]) P = np...
returns a list of the index of elements of n which do not have adequate toy angle coverage. The criterion is that we must have at least one sample in each Nyquist box when we project the toy angles along the vector n
Below is the the instruction that describes the task: ### Input: returns a list of the index of elements of n which do not have adequate toy angle coverage. The criterion is that we must have at least one sample in each Nyquist box when we project the toy angles along the vector n ### Response: def check_e...
def node_vectors(node_id): """Get the vectors of a node. You must specify the node id in the url. You can pass direction (incoming/outgoing/all) and failed (True/False/all). """ exp = Experiment(session) # get the parameters direction = request_parameter(parameter="direction", default="...
Get the vectors of a node. You must specify the node id in the url. You can pass direction (incoming/outgoing/all) and failed (True/False/all).
Below is the the instruction that describes the task: ### Input: Get the vectors of a node. You must specify the node id in the url. You can pass direction (incoming/outgoing/all) and failed (True/False/all). ### Response: def node_vectors(node_id): """Get the vectors of a node. You must spec...
def populate_keys_tree(self): """Reads the HOTKEYS global variable and insert all data in the TreeStore used by the preferences window treeview. """ for group in HOTKEYS: parent = self.store.append(None, [None, group['label'], None, None]) for item in group['keys'...
Reads the HOTKEYS global variable and insert all data in the TreeStore used by the preferences window treeview.
Below is the the instruction that describes the task: ### Input: Reads the HOTKEYS global variable and insert all data in the TreeStore used by the preferences window treeview. ### Response: def populate_keys_tree(self): """Reads the HOTKEYS global variable and insert all data in the TreeSt...
def p_file_contrib_1(self, p): """file_contrib : FILE_CONTRIB LINE""" try: if six.PY2: value = p[2].decode(encoding='utf-8') else: value = p[2] self.builder.add_file_contribution(self.document, value) except OrderError: ...
file_contrib : FILE_CONTRIB LINE
Below is the the instruction that describes the task: ### Input: file_contrib : FILE_CONTRIB LINE ### Response: def p_file_contrib_1(self, p): """file_contrib : FILE_CONTRIB LINE""" try: if six.PY2: value = p[2].decode(encoding='utf-8') else: ...
def _json_request(self, req_type, url, **kwargs): """ Make a request of the specified type and expect a JSON object in response. If the result has an 'error' value, raise a LuminosoAPIError with its contents. Otherwise, return the contents of the 'result' value. """ ...
Make a request of the specified type and expect a JSON object in response. If the result has an 'error' value, raise a LuminosoAPIError with its contents. Otherwise, return the contents of the 'result' value.
Below is the the instruction that describes the task: ### Input: Make a request of the specified type and expect a JSON object in response. If the result has an 'error' value, raise a LuminosoAPIError with its contents. Otherwise, return the contents of the 'result' value. ### Response: de...
def CopyToString(self): """Copies the identifier to a string representation. Returns: str: unique identifier or None. """ if self.name is not None and self.row_identifier is not None: return '{0:s}.{1:d}'.format(self.name, self.row_identifier) return None
Copies the identifier to a string representation. Returns: str: unique identifier or None.
Below is the the instruction that describes the task: ### Input: Copies the identifier to a string representation. Returns: str: unique identifier or None. ### Response: def CopyToString(self): """Copies the identifier to a string representation. Returns: str: unique identifier or None. ...
def make_create_payload(**kwargs): """Create payload for upload/check-upload operations.""" payload = {} # Add non-empty arguments for k, v in six.iteritems(kwargs): if v is not None: payload[k] = v return payload
Create payload for upload/check-upload operations.
Below is the the instruction that describes the task: ### Input: Create payload for upload/check-upload operations. ### Response: def make_create_payload(**kwargs): """Create payload for upload/check-upload operations.""" payload = {} # Add non-empty arguments for k, v in six.iteritems(kwargs): ...
def graph_easy(self): """Draw ascii diagram. graph-easy perl module require """ if not os.path.isfile("/usr/bin/graph-easy"): print("Require 'graph-easy': Install with 'slpkg -s sbo " "graph-easy'") self.remove_dot() raise SystemExit() ...
Draw ascii diagram. graph-easy perl module require
Below is the the instruction that describes the task: ### Input: Draw ascii diagram. graph-easy perl module require ### Response: def graph_easy(self): """Draw ascii diagram. graph-easy perl module require """ if not os.path.isfile("/usr/bin/graph-easy"): print("Require 'graph-e...
def find_plugins(): """Locate and initialize all available plugins. """ plugin_dir = os.path.dirname(os.path.realpath(__file__)) plugin_dir = os.path.join(plugin_dir, "plugins") plugin_files = [x[:-3] for x in os.listdir(plugin_dir) if x.endswith(".py")] sys.path.insert(0, plugin_dir) for p...
Locate and initialize all available plugins.
Below is the the instruction that describes the task: ### Input: Locate and initialize all available plugins. ### Response: def find_plugins(): """Locate and initialize all available plugins. """ plugin_dir = os.path.dirname(os.path.realpath(__file__)) plugin_dir = os.path.join(plugin_dir, "plugin...
def parse_column_filters(*definitions): """Parse multiple compound column filter definitions Examples -------- >>> parse_column_filters('snr > 10', 'frequency < 1000') [('snr', <function operator.gt>, 10.), ('frequency', <function operator.lt>, 1000.)] >>> parse_column_filters('snr > 10 && freq...
Parse multiple compound column filter definitions Examples -------- >>> parse_column_filters('snr > 10', 'frequency < 1000') [('snr', <function operator.gt>, 10.), ('frequency', <function operator.lt>, 1000.)] >>> parse_column_filters('snr > 10 && frequency < 1000') [('snr', <function operator....
Below is the the instruction that describes the task: ### Input: Parse multiple compound column filter definitions Examples -------- >>> parse_column_filters('snr > 10', 'frequency < 1000') [('snr', <function operator.gt>, 10.), ('frequency', <function operator.lt>, 1000.)] >>> parse_column_fil...
def get_nodes_with_recipe(recipe_name, environment=None): """Get all nodes which include a given recipe, prefix-searches are also supported """ prefix_search = recipe_name.endswith("*") if prefix_search: recipe_name = recipe_name.rstrip("*") for n in get_nodes(environment): reci...
Get all nodes which include a given recipe, prefix-searches are also supported
Below is the the instruction that describes the task: ### Input: Get all nodes which include a given recipe, prefix-searches are also supported ### Response: def get_nodes_with_recipe(recipe_name, environment=None): """Get all nodes which include a given recipe, prefix-searches are also supported ...
def path(self): """ Returns the path to this table in HDFS. """ location = self.client.table_location(self.table, self.database) if not location: raise Exception("Couldn't find location for table: {0}".format(str(self))) return location
Returns the path to this table in HDFS.
Below is the the instruction that describes the task: ### Input: Returns the path to this table in HDFS. ### Response: def path(self): """ Returns the path to this table in HDFS. """ location = self.client.table_location(self.table, self.database) if not location: ...
def fit(self, conver=DEFAULT_CONVERGENCE, minit=DEFAULT_MINIT, maxit=DEFAULT_MAXIT, fflag=DEFAULT_FFLAG, maxgerr=DEFAULT_MAXGERR, going_inwards=False): """ Fit an elliptical isophote. Parameters ---------- conver : float, optional The main con...
Fit an elliptical isophote. Parameters ---------- conver : float, optional The main convergence criterion. Iterations stop when the largest harmonic amplitude becomes smaller (in absolute value) than ``conver`` times the harmonic fit rms. The def...
Below is the the instruction that describes the task: ### Input: Fit an elliptical isophote. Parameters ---------- conver : float, optional The main convergence criterion. Iterations stop when the largest harmonic amplitude becomes smaller (in absolute va...
def get_context_data(self, **kwargs): """This add in the context of list_type and returns this as whatever the crosstype was.""" context = super(CrossTypeAnimalList, self).get_context_data(**kwargs) context['list_type'] = self.kwargs['breeding_type'] return context
This add in the context of list_type and returns this as whatever the crosstype was.
Below is the the instruction that describes the task: ### Input: This add in the context of list_type and returns this as whatever the crosstype was. ### Response: def get_context_data(self, **kwargs): """This add in the context of list_type and returns this as whatever the crosstype was.""" ...
def __create_list_item_widget(self, ui, calibration_observable): """Called when an item (calibration_observable) is inserted into the list widget. Returns a widget.""" calibration_row = make_calibration_row_widget(ui, calibration_observable) column = ui.create_column_widget() column.add_...
Called when an item (calibration_observable) is inserted into the list widget. Returns a widget.
Below is the the instruction that describes the task: ### Input: Called when an item (calibration_observable) is inserted into the list widget. Returns a widget. ### Response: def __create_list_item_widget(self, ui, calibration_observable): """Called when an item (calibration_observable) is inserted into t...
def customize_form_field(self, name, field): """ Allows views to customize their form fields. By default, Smartmin replaces the plain textbox date input with it's own DatePicker implementation. """ if isinstance(field, forms.fields.DateField) and isinstance(field.widget, forms.w...
Allows views to customize their form fields. By default, Smartmin replaces the plain textbox date input with it's own DatePicker implementation.
Below is the the instruction that describes the task: ### Input: Allows views to customize their form fields. By default, Smartmin replaces the plain textbox date input with it's own DatePicker implementation. ### Response: def customize_form_field(self, name, field): """ Allows views to c...
def transformer_revnet_encoder(encoder_input, encoder_self_attention_bias, hparams, name="encoder"): """A stack of transformer layers. Args: encoder_input: a Tensor encoder_self_attention_bias: bias Tensor for self...
A stack of transformer layers. Args: encoder_input: a Tensor encoder_self_attention_bias: bias Tensor for self-attention (see common_attention.attention_bias()) hparams: hyperparameters for model name: a string Returns: y: a Tensors
Below is the the instruction that describes the task: ### Input: A stack of transformer layers. Args: encoder_input: a Tensor encoder_self_attention_bias: bias Tensor for self-attention (see common_attention.attention_bias()) hparams: hyperparameters for model name: a string Returns: ...
def is_connected(C, directed=True): r"""Return true, if the input count matrix is completely connected. Effectively checking if the number of connected components equals one. Parameters ---------- C : scipy.sparse matrix or numpy ndarray Count matrix specifying edge weights. directed : ...
r"""Return true, if the input count matrix is completely connected. Effectively checking if the number of connected components equals one. Parameters ---------- C : scipy.sparse matrix or numpy ndarray Count matrix specifying edge weights. directed : bool, optional Whether to compute...
Below is the the instruction that describes the task: ### Input: r"""Return true, if the input count matrix is completely connected. Effectively checking if the number of connected components equals one. Parameters ---------- C : scipy.sparse matrix or numpy ndarray Count matrix specifying ...
def _route(self): """Define route.""" # REST API self._app.route('/api/%s/config' % self.API_VERSION, method="GET", callback=self._api_config) self._app.route('/api/%s/config/<item>' % self.API_VERSION, method="GET", callback=self._api_conf...
Define route.
Below is the the instruction that describes the task: ### Input: Define route. ### Response: def _route(self): """Define route.""" # REST API self._app.route('/api/%s/config' % self.API_VERSION, method="GET", callback=self._api_config) self._app.route('/api/%...
def add(from_user, from_id, to_user, to_id, type): "adds a relation to the graph" if options.users and to_user: G.add_node(from_user, screen_name=from_user) G.add_node(to_user, screen_name=to_user) if G.has_edge(from_user, to_user): weight = G[from_user][to_user]['we...
adds a relation to the graph
Below is the the instruction that describes the task: ### Input: adds a relation to the graph ### Response: def add(from_user, from_id, to_user, to_id, type): "adds a relation to the graph" if options.users and to_user: G.add_node(from_user, screen_name=from_user) G.add_node(to_user, scree...
def clear(self, session): """Clears a device. Corresponds to viClear function of the VISA library. :param session: Unique logical identifier to a session. :return: return value of the library call. :rtype: :class:`pyvisa.constants.StatusCode` """ try: ...
Clears a device. Corresponds to viClear function of the VISA library. :param session: Unique logical identifier to a session. :return: return value of the library call. :rtype: :class:`pyvisa.constants.StatusCode`
Below is the the instruction that describes the task: ### Input: Clears a device. Corresponds to viClear function of the VISA library. :param session: Unique logical identifier to a session. :return: return value of the library call. :rtype: :class:`pyvisa.constants.StatusCode` ###...
def manage_async(self, command='', name='process', site=ALL, exclude_sites='', end_message='', recipients=''): """ Starts a Django management command in a screen. Parameters: command :- all arguments passed to `./manage` as a single string site :- the site to run the c...
Starts a Django management command in a screen. Parameters: command :- all arguments passed to `./manage` as a single string site :- the site to run the command for (default is all) Designed to be ran like: fab <role> dj.manage_async:"some_management_command --fo...
Below is the the instruction that describes the task: ### Input: Starts a Django management command in a screen. Parameters: command :- all arguments passed to `./manage` as a single string site :- the site to run the command for (default is all) Designed to be ran like: ...
def topology(struct=None, protein='protein', top='system.top', dirname='top', posres="posres.itp", ff="oplsaa", water="tip4p", **pdb2gmx_args): """Build Gromacs topology files from pdb. :Keywords: *struct* input structure (**required**) ...
Build Gromacs topology files from pdb. :Keywords: *struct* input structure (**required**) *protein* name of the output files *top* name of the topology file *dirname* directory in which the new topology will be stored *ff* fo...
Below is the the instruction that describes the task: ### Input: Build Gromacs topology files from pdb. :Keywords: *struct* input structure (**required**) *protein* name of the output files *top* name of the topology file *dirname* directo...
def _get_list_axis(self, key, axis=None): """ Return Series values by list or array of integers Parameters ---------- key : list-like positional indexer axis : int (can only be zero) Returns ------- Series object """ if axis is No...
Return Series values by list or array of integers Parameters ---------- key : list-like positional indexer axis : int (can only be zero) Returns ------- Series object
Below is the the instruction that describes the task: ### Input: Return Series values by list or array of integers Parameters ---------- key : list-like positional indexer axis : int (can only be zero) Returns ------- Series object ### Response: def _get_li...
def pause(profile_process='worker'): """Pause profiling. Parameters ---------- profile_process : string whether to profile kvstore `server` or `worker`. server can only be profiled when kvstore is of type dist. if this is not passed, defaults to `worker` """ profile_proc...
Pause profiling. Parameters ---------- profile_process : string whether to profile kvstore `server` or `worker`. server can only be profiled when kvstore is of type dist. if this is not passed, defaults to `worker`
Below is the the instruction that describes the task: ### Input: Pause profiling. Parameters ---------- profile_process : string whether to profile kvstore `server` or `worker`. server can only be profiled when kvstore is of type dist. if this is not passed, defaults to `worker`...
def decode_signature(sigb64): """ Decode a signature into r, s """ sig_bin = base64.b64decode(sigb64) if len(sig_bin) != 64: raise ValueError("Invalid base64 signature") sig_hex = sig_bin.encode('hex') sig_r = int(sig_hex[:64], 16) sig_s = int(sig_hex[64:], 16) return sig_r,...
Decode a signature into r, s
Below is the the instruction that describes the task: ### Input: Decode a signature into r, s ### Response: def decode_signature(sigb64): """ Decode a signature into r, s """ sig_bin = base64.b64decode(sigb64) if len(sig_bin) != 64: raise ValueError("Invalid base64 signature") sig_...
def path_only_contains_dirs(self, path): """Return boolean on whether a path only contains directories.""" pathlistdir = os.listdir(path) if pathlistdir == []: return True if any(os.path.isfile(os.path.join(path, i)) for i in pathlistdir): return False ret...
Return boolean on whether a path only contains directories.
Below is the the instruction that describes the task: ### Input: Return boolean on whether a path only contains directories. ### Response: def path_only_contains_dirs(self, path): """Return boolean on whether a path only contains directories.""" pathlistdir = os.listdir(path) if pathlistdir...
def arc_by_radian(x, y, height, radian_range, thickness, gaussian_width): """ Radial arc with Gaussian fall-off after the solid ring-shaped region with the given thickness, with shape specified by the (start,end) radian_range. """ # Create a circular ring (copied from the ring function) rad...
Radial arc with Gaussian fall-off after the solid ring-shaped region with the given thickness, with shape specified by the (start,end) radian_range.
Below is the the instruction that describes the task: ### Input: Radial arc with Gaussian fall-off after the solid ring-shaped region with the given thickness, with shape specified by the (start,end) radian_range. ### Response: def arc_by_radian(x, y, height, radian_range, thickness, gaussian_width): "...
def log(arg1, arg2=None): """Returns the first argument-based logarithm of the second argument. If there is only one argument, then this takes the natural logarithm of the argument. >>> df.select(log(10.0, df.age).alias('ten')).rdd.map(lambda l: str(l.ten)[:7]).collect() ['0.30102', '0.69897'] >>...
Returns the first argument-based logarithm of the second argument. If there is only one argument, then this takes the natural logarithm of the argument. >>> df.select(log(10.0, df.age).alias('ten')).rdd.map(lambda l: str(l.ten)[:7]).collect() ['0.30102', '0.69897'] >>> df.select(log(df.age).alias('e'...
Below is the the instruction that describes the task: ### Input: Returns the first argument-based logarithm of the second argument. If there is only one argument, then this takes the natural logarithm of the argument. >>> df.select(log(10.0, df.age).alias('ten')).rdd.map(lambda l: str(l.ten)[:7]).collect(...
def get_concept(self, conceptId, lang='en'): """ Fetch the concept from the Knowledge base Args: id (str): The concept id to be fetched, it can be Wikipedia page id or Wikiedata id. Returns: dict, int: A dict containing the concept information; an inte...
Fetch the concept from the Knowledge base Args: id (str): The concept id to be fetched, it can be Wikipedia page id or Wikiedata id. Returns: dict, int: A dict containing the concept information; an integer representing the response code.
Below is the the instruction that describes the task: ### Input: Fetch the concept from the Knowledge base Args: id (str): The concept id to be fetched, it can be Wikipedia page id or Wikiedata id. Returns: dict, int: A dict containing the concept informat...
def _attr_sort_func(model, iter1, iter2, attribute): """Internal helper """ attr1 = getattr(model[iter1][0], attribute, None) attr2 = getattr(model[iter2][0], attribute, None) return cmp(attr1, attr2)
Internal helper
Below is the the instruction that describes the task: ### Input: Internal helper ### Response: def _attr_sort_func(model, iter1, iter2, attribute): """Internal helper """ attr1 = getattr(model[iter1][0], attribute, None) attr2 = getattr(model[iter2][0], attribute, None) return cmp(attr1, attr2)
def min(self, key=None): """ Find the minimum item in this RDD. :param key: A function used to generate key for comparing >>> rdd = sc.parallelize([2.0, 5.0, 43.0, 10.0]) >>> rdd.min() 2.0 >>> rdd.min(key=str) 10.0 """ if key is None: ...
Find the minimum item in this RDD. :param key: A function used to generate key for comparing >>> rdd = sc.parallelize([2.0, 5.0, 43.0, 10.0]) >>> rdd.min() 2.0 >>> rdd.min(key=str) 10.0
Below is the the instruction that describes the task: ### Input: Find the minimum item in this RDD. :param key: A function used to generate key for comparing >>> rdd = sc.parallelize([2.0, 5.0, 43.0, 10.0]) >>> rdd.min() 2.0 >>> rdd.min(key=str) 10.0 ### Response: ...
def delete_state(self, state): """Delete a specified state from the LRS :param state: State document to be deleted :type state: :class:`tincan.documents.state_document.StateDocument` :return: LRS Response object :rtype: :class:`tincan.lrs_response.LRSResponse` """ ...
Delete a specified state from the LRS :param state: State document to be deleted :type state: :class:`tincan.documents.state_document.StateDocument` :return: LRS Response object :rtype: :class:`tincan.lrs_response.LRSResponse`
Below is the the instruction that describes the task: ### Input: Delete a specified state from the LRS :param state: State document to be deleted :type state: :class:`tincan.documents.state_document.StateDocument` :return: LRS Response object :rtype: :class:`tincan.lrs_response.LRSR...
def runs(self): """ Immutable sequence of |_Run| objects corresponding to the runs in this paragraph. """ return tuple(_Run(r, self) for r in self._element.r_lst)
Immutable sequence of |_Run| objects corresponding to the runs in this paragraph.
Below is the the instruction that describes the task: ### Input: Immutable sequence of |_Run| objects corresponding to the runs in this paragraph. ### Response: def runs(self): """ Immutable sequence of |_Run| objects corresponding to the runs in this paragraph. """ ...
def _serialize(self, value, attr, obj): """ Serialize value as a timestamp, either as a Unix timestamp (in float second) or a UTC isoformat string. """ if value is None: return None if self.use_isoformat: return datetime.utcfromtimestamp(value).isoformat...
Serialize value as a timestamp, either as a Unix timestamp (in float second) or a UTC isoformat string.
Below is the the instruction that describes the task: ### Input: Serialize value as a timestamp, either as a Unix timestamp (in float second) or a UTC isoformat string. ### Response: def _serialize(self, value, attr, obj): """ Serialize value as a timestamp, either as a Unix timestamp (in float sec...
def _add_parameterized_validator_internal(param_validator, base_tag): "with builtin tag prefixing" add_parameterized_validator(param_validator, base_tag, tag_prefix=u'!~~%s(' % param_validator.__name__)
with builtin tag prefixing
Below is the the instruction that describes the task: ### Input: with builtin tag prefixing ### Response: def _add_parameterized_validator_internal(param_validator, base_tag): "with builtin tag prefixing" add_parameterized_validator(param_validator, base_tag, tag_prefix=u'!~~%s(' % param_validator.__name__...
def format_datetime(self, value, format_): """ Format the datetime using Babel """ date_ = make_datetime(value) return dates.format_datetime(date_, format_, locale=self.lang)
Format the datetime using Babel
Below is the the instruction that describes the task: ### Input: Format the datetime using Babel ### Response: def format_datetime(self, value, format_): """ Format the datetime using Babel """ date_ = make_datetime(value) return dates.format_datetime(date_, format_, locale=...