code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
text
stringlengths
164
112k
def calcAbsSegCoords(self): ''' Calculate absolute seg coords by translating the relative seg coords -- used for LFP calc''' from .. import sim p3dsoma = self.getSomaPos() pop = self.tags['pop'] morphSegCoords = sim.net.pops[pop]._morphSegCoords # rotated coordinates ar...
Calculate absolute seg coords by translating the relative seg coords -- used for LFP calc
Below is the the instruction that describes the task: ### Input: Calculate absolute seg coords by translating the relative seg coords -- used for LFP calc ### Response: def calcAbsSegCoords(self): ''' Calculate absolute seg coords by translating the relative seg coords -- used for LFP calc''' from ...
def _set_pwm(self, raw_values): """ Set pwm values on the controlled pins. :param raw_values: Raw values to set (0-255). """ for i in range(len(self._pins)): self._pi.set_PWM_dutycycle(self._pins[i], raw_values[i])
Set pwm values on the controlled pins. :param raw_values: Raw values to set (0-255).
Below is the the instruction that describes the task: ### Input: Set pwm values on the controlled pins. :param raw_values: Raw values to set (0-255). ### Response: def _set_pwm(self, raw_values): """ Set pwm values on the controlled pins. :param raw_values: Raw values to set (0-25...
def _init_vocab(self, token_generator, add_reserved_tokens=True): """Initialize vocabulary with tokens from token_generator.""" self._id_to_token = {} non_reserved_start_index = 0 if add_reserved_tokens: self._id_to_token.update(enumerate(RESERVED_TOKENS)) non_reserved_start_index = len(RE...
Initialize vocabulary with tokens from token_generator.
Below is the the instruction that describes the task: ### Input: Initialize vocabulary with tokens from token_generator. ### Response: def _init_vocab(self, token_generator, add_reserved_tokens=True): """Initialize vocabulary with tokens from token_generator.""" self._id_to_token = {} non_reserved_sta...
def typewrite(message, interval=0.0, pause=None, _pause=True): """Performs a keyboard key press down, followed by a release, for each of the characters in message. The message argument can also be list of strings, in which case any valid keyboard name can be used. Since this performs a sequence of...
Performs a keyboard key press down, followed by a release, for each of the characters in message. The message argument can also be list of strings, in which case any valid keyboard name can be used. Since this performs a sequence of keyboard presses and does not hold down keys, it cannot be used t...
Below is the the instruction that describes the task: ### Input: Performs a keyboard key press down, followed by a release, for each of the characters in message. The message argument can also be list of strings, in which case any valid keyboard name can be used. Since this performs a sequence of ...
def plotConvergenceByDistantConnectionChance(results, featureRange, columnRange, longDistanceConnectionsRange, numTrials): """ Plots the convergence graph: iterations vs number of columns. Each curve shows the convergence for a given number of unique features. """ #############################################...
Plots the convergence graph: iterations vs number of columns. Each curve shows the convergence for a given number of unique features.
Below is the the instruction that describes the task: ### Input: Plots the convergence graph: iterations vs number of columns. Each curve shows the convergence for a given number of unique features. ### Response: def plotConvergenceByDistantConnectionChance(results, featureRange, columnRange, longDistanceConnect...
def divide_separate_words(string_matrix: List[List[str]]) -> List[List[str]]: """ As part of processing, some words obviously need to be separated. :param string_matrix: a data matrix: a list wrapping a list of strings, with each sublist being a sentence. :return: >>> divide_separate_words([['ita ve...
As part of processing, some words obviously need to be separated. :param string_matrix: a data matrix: a list wrapping a list of strings, with each sublist being a sentence. :return: >>> divide_separate_words([['ita vero'], ['quid', 'est', 'veritas']]) [['ita', 'vero'], ['quid', 'est', 'veritas']]
Below is the the instruction that describes the task: ### Input: As part of processing, some words obviously need to be separated. :param string_matrix: a data matrix: a list wrapping a list of strings, with each sublist being a sentence. :return: >>> divide_separate_words([['ita vero'], ['quid', 'est',...
def write_skills_data(self, data=None): """ Write skills data hash if it has been modified. """ data = data or self.skills_data if skills_data_hash(data) != self.skills_data_hash: write_skills_data(data) self.skills_data_hash = skills_data_hash(data)
Write skills data hash if it has been modified.
Below is the the instruction that describes the task: ### Input: Write skills data hash if it has been modified. ### Response: def write_skills_data(self, data=None): """ Write skills data hash if it has been modified. """ data = data or self.skills_data if skills_data_hash(data) != self.sk...
def _get_expanded_active_specs(specs): """ This function removes any unnecessary bundles, apps, libs, and services that aren't needed by the activated_bundles. It also expands inside specs.apps.depends.libs all libs that are needed indirectly by each app """ _filter_active(constants.CONFIG_BUND...
This function removes any unnecessary bundles, apps, libs, and services that aren't needed by the activated_bundles. It also expands inside specs.apps.depends.libs all libs that are needed indirectly by each app
Below is the the instruction that describes the task: ### Input: This function removes any unnecessary bundles, apps, libs, and services that aren't needed by the activated_bundles. It also expands inside specs.apps.depends.libs all libs that are needed indirectly by each app ### Response: def _get_expand...
def destroy(self, uuid): """ Destroy a kvm domain by uuid :param uuid: uuid of the kvm container (same as the used in create) :return: """ args = { 'uuid': uuid, } self._domain_action_chk.check(args) self._client.sync('kvm.destroy', ar...
Destroy a kvm domain by uuid :param uuid: uuid of the kvm container (same as the used in create) :return:
Below is the the instruction that describes the task: ### Input: Destroy a kvm domain by uuid :param uuid: uuid of the kvm container (same as the used in create) :return: ### Response: def destroy(self, uuid): """ Destroy a kvm domain by uuid :param uuid: uuid of the kvm con...
def remote_pdb_handler(signum, frame): """ Handler to drop us into a remote debugger upon receiving SIGUSR1 """ try: from remote_pdb import RemotePdb rdb = RemotePdb(host="127.0.0.1", port=0) rdb.set_trace(frame=frame) except ImportError: log.warning( "remote_pdb...
Handler to drop us into a remote debugger upon receiving SIGUSR1
Below is the the instruction that describes the task: ### Input: Handler to drop us into a remote debugger upon receiving SIGUSR1 ### Response: def remote_pdb_handler(signum, frame): """ Handler to drop us into a remote debugger upon receiving SIGUSR1 """ try: from remote_pdb import RemotePdb ...
def get_job_collection(self, cloud_service_id, job_collection_id): ''' The Get Job Collection operation gets the details of a job collection cloud_service_id: The cloud service id job_collection_id: Name of the hosted service. ''' _validate_not_no...
The Get Job Collection operation gets the details of a job collection cloud_service_id: The cloud service id job_collection_id: Name of the hosted service.
Below is the the instruction that describes the task: ### Input: The Get Job Collection operation gets the details of a job collection cloud_service_id: The cloud service id job_collection_id: Name of the hosted service. ### Response: def get_job_collection(self, cloud_serv...
def bpopmax(self, timeout=0): """ Atomically remove the highest-scoring item from the set, blocking until an item becomes available or timeout is reached (0 for no timeout, default). Returns a 2-tuple of (item, score). """ res = self.database.bzpopmax(self.key, t...
Atomically remove the highest-scoring item from the set, blocking until an item becomes available or timeout is reached (0 for no timeout, default). Returns a 2-tuple of (item, score).
Below is the the instruction that describes the task: ### Input: Atomically remove the highest-scoring item from the set, blocking until an item becomes available or timeout is reached (0 for no timeout, default). Returns a 2-tuple of (item, score). ### Response: def bpopmax(self, timeout=...
def from_http_status(status_code, message, **kwargs): """Create a :class:`GoogleAPICallError` from an HTTP status code. Args: status_code (int): The HTTP status code. message (str): The exception message. kwargs: Additional arguments passed to the :class:`GoogleAPICallError` ...
Create a :class:`GoogleAPICallError` from an HTTP status code. Args: status_code (int): The HTTP status code. message (str): The exception message. kwargs: Additional arguments passed to the :class:`GoogleAPICallError` constructor. Returns: GoogleAPICallError: An in...
Below is the the instruction that describes the task: ### Input: Create a :class:`GoogleAPICallError` from an HTTP status code. Args: status_code (int): The HTTP status code. message (str): The exception message. kwargs: Additional arguments passed to the :class:`GoogleAPICallError` ...
def sync_status(self): """Synchronize DOI status DataCite MDS. :returns: `True` if is sync successfully. """ status = None try: try: self.api.doi_get(self.pid.pid_value) status = PIDStatus.REGISTERED except DataCiteGoneErr...
Synchronize DOI status DataCite MDS. :returns: `True` if is sync successfully.
Below is the the instruction that describes the task: ### Input: Synchronize DOI status DataCite MDS. :returns: `True` if is sync successfully. ### Response: def sync_status(self): """Synchronize DOI status DataCite MDS. :returns: `True` if is sync successfully. """ status...
def setActions( self, actions ): """ Sets the list of actions that will be used for this shortcut dialog \ when editing. :param actions | [<QAction>, ..] """ self.uiActionTREE.blockSignals(True) self.uiActionTREE.setUpdatesEnabled(False) ...
Sets the list of actions that will be used for this shortcut dialog \ when editing. :param actions | [<QAction>, ..]
Below is the the instruction that describes the task: ### Input: Sets the list of actions that will be used for this shortcut dialog \ when editing. :param actions | [<QAction>, ..] ### Response: def setActions( self, actions ): """ Sets the list of actions that will b...
def set_fallback_resolution(self, x_pixels_per_inch, y_pixels_per_inch): """ Set the horizontal and vertical resolution for image fallbacks. When certain operations aren't supported natively by a backend, cairo will fallback by rendering operations to an image and then overlayin...
Set the horizontal and vertical resolution for image fallbacks. When certain operations aren't supported natively by a backend, cairo will fallback by rendering operations to an image and then overlaying that image onto the output. For backends that are natively vector-oriented, ...
Below is the the instruction that describes the task: ### Input: Set the horizontal and vertical resolution for image fallbacks. When certain operations aren't supported natively by a backend, cairo will fallback by rendering operations to an image and then overlaying that image onto the ou...
def sync_request(self, command, payload, retry=2): """Request data.""" loop = asyncio.get_event_loop() task = loop.create_task(self.request(command, payload, retry)) return loop.run_until_complete(task)
Request data.
Below is the the instruction that describes the task: ### Input: Request data. ### Response: def sync_request(self, command, payload, retry=2): """Request data.""" loop = asyncio.get_event_loop() task = loop.create_task(self.request(command, payload, retry)) return loop.run_until_co...
def _compute_vline_scores(self): """Does the hard work to prepare ``vline_score``. """ M, N, L = self.M, self.N, self.L vline_score = {} for x in range(M): laststart = [0 if (x, 0, 1, k) in self else None for k in range(L)] for y in range(N): ...
Does the hard work to prepare ``vline_score``.
Below is the the instruction that describes the task: ### Input: Does the hard work to prepare ``vline_score``. ### Response: def _compute_vline_scores(self): """Does the hard work to prepare ``vline_score``. """ M, N, L = self.M, self.N, self.L vline_score = {} for x in ran...
def put(self, filename, handle): """ Upload a distribution archive to the configured Amazon S3 bucket. If the :attr:`~.Config.s3_cache_readonly` configuration option is enabled this method does nothing. :param filename: The filename of the distribution archive (a string). ...
Upload a distribution archive to the configured Amazon S3 bucket. If the :attr:`~.Config.s3_cache_readonly` configuration option is enabled this method does nothing. :param filename: The filename of the distribution archive (a string). :param handle: A file-like object that provides ac...
Below is the the instruction that describes the task: ### Input: Upload a distribution archive to the configured Amazon S3 bucket. If the :attr:`~.Config.s3_cache_readonly` configuration option is enabled this method does nothing. :param filename: The filename of the distribution archive (...
async def _send_sleep(self, request: Request, stack: Stack): """ Sleep for the amount of time specified in the Sleep layer """ duration = stack.get_layer(lyr.Sleep).duration await sleep(duration)
Sleep for the amount of time specified in the Sleep layer
Below is the the instruction that describes the task: ### Input: Sleep for the amount of time specified in the Sleep layer ### Response: async def _send_sleep(self, request: Request, stack: Stack): """ Sleep for the amount of time specified in the Sleep layer """ duration = stack.g...
def load(self, shapefile=None): """Opens a shapefile from a filename or file-like object. Normally this method would be called by the constructor with the file name as an argument.""" if shapefile: (shapeName, ext) = os.path.splitext(shapefile) self.shapeNam...
Opens a shapefile from a filename or file-like object. Normally this method would be called by the constructor with the file name as an argument.
Below is the the instruction that describes the task: ### Input: Opens a shapefile from a filename or file-like object. Normally this method would be called by the constructor with the file name as an argument. ### Response: def load(self, shapefile=None): """Opens a shapefile from a fil...
def get_call_signature(fn: FunctionType, args: ArgsType, kwargs: KwargsType, debug_cache: bool = False) -> str: """ Takes a function and its args/kwargs, and produces a string description of the function call (the call signature) suitable ...
Takes a function and its args/kwargs, and produces a string description of the function call (the call signature) suitable for use indirectly as a cache key. The string is a JSON representation. See ``make_cache_key`` for a more suitable actual cache key.
Below is the the instruction that describes the task: ### Input: Takes a function and its args/kwargs, and produces a string description of the function call (the call signature) suitable for use indirectly as a cache key. The string is a JSON representation. See ``make_cache_key`` for a more suitable a...
def query(query, use_sudo=True, **kwargs): """ Run a MySQL query. """ func = use_sudo and run_as_root or run user = kwargs.get('mysql_user') or env.get('mysql_user') password = kwargs.get('mysql_password') or env.get('mysql_password') options = [ '--batch', '--raw', ...
Run a MySQL query.
Below is the the instruction that describes the task: ### Input: Run a MySQL query. ### Response: def query(query, use_sudo=True, **kwargs): """ Run a MySQL query. """ func = use_sudo and run_as_root or run user = kwargs.get('mysql_user') or env.get('mysql_user') password = kwargs.get('mys...
def generation_time(self): """ The generation time as set by Yamcs. :type: :class:`~datetime.datetime` """ entry = self._proto.commandQueueEntry if entry.HasField('generationTimeUTC'): return parse_isostring(entry.generationTimeUTC) return None
The generation time as set by Yamcs. :type: :class:`~datetime.datetime`
Below is the the instruction that describes the task: ### Input: The generation time as set by Yamcs. :type: :class:`~datetime.datetime` ### Response: def generation_time(self): """ The generation time as set by Yamcs. :type: :class:`~datetime.datetime` """ entry =...
def get_include_path(): """ Default include path using a tricky sys calls. """ f1 = os.path.basename(sys.argv[0]).lower() # script filename f2 = os.path.basename(sys.executable).lower() # Executable filename # If executable filename and script name are the same, we are if f1 == f2 or f2 =...
Default include path using a tricky sys calls.
Below is the the instruction that describes the task: ### Input: Default include path using a tricky sys calls. ### Response: def get_include_path(): """ Default include path using a tricky sys calls. """ f1 = os.path.basename(sys.argv[0]).lower() # script filename f2 = os.path.basename(sy...
async def post_data(self, path, data=None, headers=None, timeout=None): """Perform a POST request.""" url = self.base_url + path _LOGGER.debug('POST URL: %s', url) self._log_data(data, False) resp = None try: resp = await self._session.post( u...
Perform a POST request.
Below is the the instruction that describes the task: ### Input: Perform a POST request. ### Response: async def post_data(self, path, data=None, headers=None, timeout=None): """Perform a POST request.""" url = self.base_url + path _LOGGER.debug('POST URL: %s', url) self._log_data(d...
def fetch_replace_restriction(self, ): """Fetch whether unloading is restricted :returns: True, if unloading is restricted :rtype: :class:`bool` :raises: None """ inter = self.get_refobjinter() restricted = self.status() is None return restricted or inter...
Fetch whether unloading is restricted :returns: True, if unloading is restricted :rtype: :class:`bool` :raises: None
Below is the the instruction that describes the task: ### Input: Fetch whether unloading is restricted :returns: True, if unloading is restricted :rtype: :class:`bool` :raises: None ### Response: def fetch_replace_restriction(self, ): """Fetch whether unloading is restricted ...
def timestring(self, pattern="%Y-%m-%d %H:%M:%S", timezone=None): """Returns a time string. :param pattern = "%Y-%m-%d %H:%M:%S" The format used. By default, an ISO-type format is used. The syntax here is identical to the one used by time.strftime() and time.strptime...
Returns a time string. :param pattern = "%Y-%m-%d %H:%M:%S" The format used. By default, an ISO-type format is used. The syntax here is identical to the one used by time.strftime() and time.strptime(). :param timezone = self.timezone The timezone (in sec...
Below is the the instruction that describes the task: ### Input: Returns a time string. :param pattern = "%Y-%m-%d %H:%M:%S" The format used. By default, an ISO-type format is used. The syntax here is identical to the one used by time.strftime() and time.strptime(). ...
def from_html_one(html_code, **kwargs): """ Generates a PrettyTables from a string of HTML code which contains only a single <table> """ tables = from_html(html_code, **kwargs) try: assert len(tables) == 1 except AssertionError: raise Exception("More than one <table> in prov...
Generates a PrettyTables from a string of HTML code which contains only a single <table>
Below is the the instruction that describes the task: ### Input: Generates a PrettyTables from a string of HTML code which contains only a single <table> ### Response: def from_html_one(html_code, **kwargs): """ Generates a PrettyTables from a string of HTML code which contains only a single <table...
def get_corrections_dict(self, entry): """ Returns the corrections applied to a particular entry. Args: entry: A ComputedEntry object. Returns: ({correction_name: value}) """ corrections = {} for c in self.corrections: val = c...
Returns the corrections applied to a particular entry. Args: entry: A ComputedEntry object. Returns: ({correction_name: value})
Below is the the instruction that describes the task: ### Input: Returns the corrections applied to a particular entry. Args: entry: A ComputedEntry object. Returns: ({correction_name: value}) ### Response: def get_corrections_dict(self, entry): """ Returns...
def change_owner(self, new_owner): """ Changes ownership of an organization. """ old_owner = self.owner.organization_user self.owner.organization_user = new_owner self.owner.save() # Owner changed signal owner_changed.send(sender=self, old=old_owner, new=...
Changes ownership of an organization.
Below is the the instruction that describes the task: ### Input: Changes ownership of an organization. ### Response: def change_owner(self, new_owner): """ Changes ownership of an organization. """ old_owner = self.owner.organization_user self.owner.organization_user = new_o...
def add(self, pattern_txt): """Add a pattern to the list. Args: pattern_txt (str list): the pattern, as a list of lines. """ self.patterns[len(pattern_txt)] = pattern_txt low = 0 high = len(pattern_txt) - 1 while not pattern_txt[low]: lo...
Add a pattern to the list. Args: pattern_txt (str list): the pattern, as a list of lines.
Below is the the instruction that describes the task: ### Input: Add a pattern to the list. Args: pattern_txt (str list): the pattern, as a list of lines. ### Response: def add(self, pattern_txt): """Add a pattern to the list. Args: pattern_txt (str list): the patt...
def gt(self, other, axis="columns", level=None): """Checks element-wise that this is greater than other. Args: other: A DataFrame or Series or scalar to compare to. axis: The axis to perform the gt over. level: The Multilevel index level to apply gt over. ...
Checks element-wise that this is greater than other. Args: other: A DataFrame or Series or scalar to compare to. axis: The axis to perform the gt over. level: The Multilevel index level to apply gt over. Returns: A new DataFrame filled with Boole...
Below is the the instruction that describes the task: ### Input: Checks element-wise that this is greater than other. Args: other: A DataFrame or Series or scalar to compare to. axis: The axis to perform the gt over. level: The Multilevel index level to apply gt ove...
def save_figure(self,event=None, transparent=False, dpi=600): """ save figure image to file""" if self.panel is not None: self.panel.save_figure(event=event, transparent=transparent, dpi=dpi)
save figure image to file
Below is the the instruction that describes the task: ### Input: save figure image to file ### Response: def save_figure(self,event=None, transparent=False, dpi=600): """ save figure image to file""" if self.panel is not None: self.panel.save_figure(event=event, ...
def get_account(config, environment, stage=None): """Find environment name in config object and return AWS account.""" if environment is None and stage: environment = get_environment(config, stage) account = None for env in config.get('environments', []): if env.get('name') == environmen...
Find environment name in config object and return AWS account.
Below is the the instruction that describes the task: ### Input: Find environment name in config object and return AWS account. ### Response: def get_account(config, environment, stage=None): """Find environment name in config object and return AWS account.""" if environment is None and stage: envi...
def load_amazon(): """Amazon product co-purchasing network and ground-truth communities. Network was collected by crawling Amazon website. It is based on Customers Who Bought This Item Also Bought feature of the Amazon website. If a product i is frequently co-purchased with product j, the graph contain...
Amazon product co-purchasing network and ground-truth communities. Network was collected by crawling Amazon website. It is based on Customers Who Bought This Item Also Bought feature of the Amazon website. If a product i is frequently co-purchased with product j, the graph contains an undirected edge from ...
Below is the the instruction that describes the task: ### Input: Amazon product co-purchasing network and ground-truth communities. Network was collected by crawling Amazon website. It is based on Customers Who Bought This Item Also Bought feature of the Amazon website. If a product i is frequently co-...
def cofold(self, strand1, strand2, temp=37.0, dangles=2, nolp=False, nogu=False, noclosinggu=False, constraints=None, canonicalbponly=False, partition=-1, pfscale=None, gquad=False): '''Run the RNAcofold command and retrieve the result in a dictionary. :param strand1: Stra...
Run the RNAcofold command and retrieve the result in a dictionary. :param strand1: Strand 1 for running RNAcofold. :type strand1: coral.DNA or coral.RNA :param strand1: Strand 2 for running RNAcofold. :type strand2: coral.DNA or coral.RNA :param temp: Temperature at which to run...
Below is the the instruction that describes the task: ### Input: Run the RNAcofold command and retrieve the result in a dictionary. :param strand1: Strand 1 for running RNAcofold. :type strand1: coral.DNA or coral.RNA :param strand1: Strand 2 for running RNAcofold. :type strand2: co...
def add(self): """ Save the current :code.`PyFunceble.CONFIGURATION['to_test']` into the current timestamp. """ if PyFunceble.CONFIGURATION["inactive_database"]: # The database subsystem is activated. # We get the timestamp to use as index. t...
Save the current :code.`PyFunceble.CONFIGURATION['to_test']` into the current timestamp.
Below is the the instruction that describes the task: ### Input: Save the current :code.`PyFunceble.CONFIGURATION['to_test']` into the current timestamp. ### Response: def add(self): """ Save the current :code.`PyFunceble.CONFIGURATION['to_test']` into the current timestamp. ...
def _AbortJoin(self, timeout=None): """Aborts all registered processes by joining with the parent process. Args: timeout (int): number of seconds to wait for processes to join, where None represents no timeout. """ for pid, process in iter(self._processes_per_pid.items()): logger....
Aborts all registered processes by joining with the parent process. Args: timeout (int): number of seconds to wait for processes to join, where None represents no timeout.
Below is the the instruction that describes the task: ### Input: Aborts all registered processes by joining with the parent process. Args: timeout (int): number of seconds to wait for processes to join, where None represents no timeout. ### Response: def _AbortJoin(self, timeout=None): """...
def calc_inbag(n_samples, forest): """ Derive samples used to create trees in scikit-learn RandomForest objects. Recovers the samples in each tree from the random state of that tree using :func:`forest._generate_sample_indices`. Parameters ---------- n_samples : int The number of s...
Derive samples used to create trees in scikit-learn RandomForest objects. Recovers the samples in each tree from the random state of that tree using :func:`forest._generate_sample_indices`. Parameters ---------- n_samples : int The number of samples used to fit the scikit-learn RandomFores...
Below is the the instruction that describes the task: ### Input: Derive samples used to create trees in scikit-learn RandomForest objects. Recovers the samples in each tree from the random state of that tree using :func:`forest._generate_sample_indices`. Parameters ---------- n_samples : int ...
def _get_ID2position_mapper(self, position_mapper): ''' Defines a position parser that is used to map between sample IDs and positions. Parameters -------------- {_bases_position_mapper} TODO: Fix the name to work with more than 26 letters of the alphabe...
Defines a position parser that is used to map between sample IDs and positions. Parameters -------------- {_bases_position_mapper} TODO: Fix the name to work with more than 26 letters of the alphabet.
Below is the the instruction that describes the task: ### Input: Defines a position parser that is used to map between sample IDs and positions. Parameters -------------- {_bases_position_mapper} TODO: Fix the name to work with more than 26 letters of the alphabet. ...
def delete_snapshot(self, path, snapshotname, **kwargs): """Delete a snapshot of a directory""" response = self._delete(path, 'DELETESNAPSHOT', snapshotname=snapshotname, **kwargs) assert not response.content
Delete a snapshot of a directory
Below is the the instruction that describes the task: ### Input: Delete a snapshot of a directory ### Response: def delete_snapshot(self, path, snapshotname, **kwargs): """Delete a snapshot of a directory""" response = self._delete(path, 'DELETESNAPSHOT', snapshotname=snapshotname, **kwargs) ...
def list_containers(active=True, defined=True, as_object=False, config_path=None): """ List the containers on the system. """ if config_path: if not os.path.exists(config_path): return tuple() try: entries = _lxc.list_containers(active=act...
List the containers on the system.
Below is the the instruction that describes the task: ### Input: List the containers on the system. ### Response: def list_containers(active=True, defined=True, as_object=False, config_path=None): """ List the containers on the system. """ if config_path: if not os....
def transform_non_affine(self, x, mask_out_of_range=True): """ Transform a Nx1 numpy array. Parameters ---------- x : array Data to be transformed. mask_out_of_range : bool, optional Whether to mask input values out of range. Return ...
Transform a Nx1 numpy array. Parameters ---------- x : array Data to be transformed. mask_out_of_range : bool, optional Whether to mask input values out of range. Return ------ array or masked array Transformed data.
Below is the the instruction that describes the task: ### Input: Transform a Nx1 numpy array. Parameters ---------- x : array Data to be transformed. mask_out_of_range : bool, optional Whether to mask input values out of range. Return ------ ...
def search(self, template: str, first: bool = False) -> _Result: """Search the :class:`Element <Element>` for the given parse template. :param template: The Parse template to use. """ elements = [r for r in findall(template, self.xml)] return _get_first_or_list(elements...
Search the :class:`Element <Element>` for the given parse template. :param template: The Parse template to use.
Below is the the instruction that describes the task: ### Input: Search the :class:`Element <Element>` for the given parse template. :param template: The Parse template to use. ### Response: def search(self, template: str, first: bool = False) -> _Result: """Search the :class:`Element <Ele...
def retrieve(self, thing, thing_type=None): """ Retrieve a report from VirusTotal based on a hash, IP, domain, file or URL or ScanID. NOTE: URLs must include the scheme (e.g. http://)\n :param thing: a file name on the local system, a URL or list of URLs, an IP o...
Retrieve a report from VirusTotal based on a hash, IP, domain, file or URL or ScanID. NOTE: URLs must include the scheme (e.g. http://)\n :param thing: a file name on the local system, a URL or list of URLs, an IP or list of IPs, a domain or list of domains, a hash or list of ha...
Below is the the instruction that describes the task: ### Input: Retrieve a report from VirusTotal based on a hash, IP, domain, file or URL or ScanID. NOTE: URLs must include the scheme (e.g. http://)\n :param thing: a file name on the local system, a URL or list of URLs, an...
def __allocate_clusters(self): """! @brief Performs cluster allocation and builds ordering diagram that is based on reachability-distances. """ self.__initialize(self.__sample_pointer) for optic_object in self.__optics_objects: if o...
! @brief Performs cluster allocation and builds ordering diagram that is based on reachability-distances.
Below is the the instruction that describes the task: ### Input: ! @brief Performs cluster allocation and builds ordering diagram that is based on reachability-distances. ### Response: def __allocate_clusters(self): """! @brief Performs cluster allocation and builds ordering diagram that...
def _setup_images(directory, brightness, saturation, hue, preserve_transparency): """ Apply modifiers to the images of a theme Modifies the images using the PIL.ImageEnhance module. Using this function, theme images are modified to given them a unique look and feel. Works best w...
Apply modifiers to the images of a theme Modifies the images using the PIL.ImageEnhance module. Using this function, theme images are modified to given them a unique look and feel. Works best with PNG-based images.
Below is the the instruction that describes the task: ### Input: Apply modifiers to the images of a theme Modifies the images using the PIL.ImageEnhance module. Using this function, theme images are modified to given them a unique look and feel. Works best with PNG-based images. ### Respons...
def get_codon(seq, codon_no, start_offset): """ This function takes a sequece and a codon number and returns the codon found in the sequence at that position """ seq = seq.replace("-","") codon_start_pos = int(codon_no - 1)*3 - start_offset codon = seq[codon_start_pos:codon_start_pos + 3] ...
This function takes a sequece and a codon number and returns the codon found in the sequence at that position
Below is the the instruction that describes the task: ### Input: This function takes a sequece and a codon number and returns the codon found in the sequence at that position ### Response: def get_codon(seq, codon_no, start_offset): """ This function takes a sequece and a codon number and returns the c...
def actionAngleTorus_hessian_c(pot,jr,jphi,jz, tol=0.003,dJ=0.001): """ NAME: actionAngleTorus_hessian_c PURPOSE: compute dO/dJ on a single torus INPUT: pot - Potential object or list thereof jr - radial action (scalar) jphi - azimuthal a...
NAME: actionAngleTorus_hessian_c PURPOSE: compute dO/dJ on a single torus INPUT: pot - Potential object or list thereof jr - radial action (scalar) jphi - azimuthal action (scalar) jz - vertical action (scalar) tol= (0.003) goal for |dJ|/|J| along the torus ...
Below is the the instruction that describes the task: ### Input: NAME: actionAngleTorus_hessian_c PURPOSE: compute dO/dJ on a single torus INPUT: pot - Potential object or list thereof jr - radial action (scalar) jphi - azimuthal action (scalar) jz - vertical action...
def contains(self, stimtype): """Returns whether the specified stimlus type is a component in this stimulus :param stimtype: :class:`AbstractStimulusComponent<sparkle.stim.abstract_component.AbstractStimulusComponent>` subclass class name to test for membership in the components of this stimulus ...
Returns whether the specified stimlus type is a component in this stimulus :param stimtype: :class:`AbstractStimulusComponent<sparkle.stim.abstract_component.AbstractStimulusComponent>` subclass class name to test for membership in the components of this stimulus :type stimtype: str :returns: b...
Below is the the instruction that describes the task: ### Input: Returns whether the specified stimlus type is a component in this stimulus :param stimtype: :class:`AbstractStimulusComponent<sparkle.stim.abstract_component.AbstractStimulusComponent>` subclass class name to test for membership in the compon...
def iter_last_tour(tourfile, clm): """ Extract last tour from tourfile. The clm instance is also passed in to see if any contig is covered in the clm. """ row = open(tourfile).readlines()[-1] _tour, _tour_o = separate_tour_and_o(row) tour = [] tour_o = [] for tc, to in zip(_tour, _to...
Extract last tour from tourfile. The clm instance is also passed in to see if any contig is covered in the clm.
Below is the the instruction that describes the task: ### Input: Extract last tour from tourfile. The clm instance is also passed in to see if any contig is covered in the clm. ### Response: def iter_last_tour(tourfile, clm): """ Extract last tour from tourfile. The clm instance is also passed in to se...
def stats(self): """ Get the stats for the current :class:`Milestone` """ response = self.requester.get( '/{endpoint}/{id}/stats', endpoint=self.endpoint, id=self.id ) return response.json()
Get the stats for the current :class:`Milestone`
Below is the the instruction that describes the task: ### Input: Get the stats for the current :class:`Milestone` ### Response: def stats(self): """ Get the stats for the current :class:`Milestone` """ response = self.requester.get( '/{endpoint}/{id}/stats', ...
def retrieve(self, order_id, id) : """ Retrieve a single line item Returns a single line item of an order, according to the unique line item ID provided :calls: ``get /orders/{order_id}/line_items/{id}`` :param int order_id: Unique identifier of a Order. :param int id: ...
Retrieve a single line item Returns a single line item of an order, according to the unique line item ID provided :calls: ``get /orders/{order_id}/line_items/{id}`` :param int order_id: Unique identifier of a Order. :param int id: Unique identifier of a LineItem. :return: Dicti...
Below is the the instruction that describes the task: ### Input: Retrieve a single line item Returns a single line item of an order, according to the unique line item ID provided :calls: ``get /orders/{order_id}/line_items/{id}`` :param int order_id: Unique identifier of a Order. :...
def last_valid_index(self): """Returns index of last non-NaN/NULL value. Return: Scalar of index name. """ def last_valid_index_builder(df): df.index = pandas.RangeIndex(len(df.index)) return df.apply(lambda df: df.last_valid_index()) func =...
Returns index of last non-NaN/NULL value. Return: Scalar of index name.
Below is the the instruction that describes the task: ### Input: Returns index of last non-NaN/NULL value. Return: Scalar of index name. ### Response: def last_valid_index(self): """Returns index of last non-NaN/NULL value. Return: Scalar of index name. """...
def set_light_state_raw(self, hue, saturation, brightness, kelvin, bulb=ALL_BULBS, timeout=None): """ Sets the (low-level) light state of one or more bulbs. """ with _blocking(self.lock, self.light_state, self.light_state_event, timeout)...
Sets the (low-level) light state of one or more bulbs.
Below is the the instruction that describes the task: ### Input: Sets the (low-level) light state of one or more bulbs. ### Response: def set_light_state_raw(self, hue, saturation, brightness, kelvin, bulb=ALL_BULBS, timeout=None): """ Sets the (low-level) light state of...
def score(self, X, y=None, **kwargs): """ The score function is the hook for visual interaction. Pass in test data and the visualizer will create predictions on the data and evaluate them with respect to the test values. The evaluation will then be passed to draw() and the result...
The score function is the hook for visual interaction. Pass in test data and the visualizer will create predictions on the data and evaluate them with respect to the test values. The evaluation will then be passed to draw() and the result of the estimator score will be returned. ...
Below is the the instruction that describes the task: ### Input: The score function is the hook for visual interaction. Pass in test data and the visualizer will create predictions on the data and evaluate them with respect to the test values. The evaluation will then be passed to draw() and...
def replace_random_tokens_bow(self, n_samples, # type: int replacement='', # type: str random_state=None, min_replace=1, # type: Union[int, float] ...
Return a list of ``(text, replaced_words_count, mask)`` tuples with n_samples versions of text with some words replaced. If a word is replaced, all duplicate words are also replaced from the text. By default words are replaced with '', i.e. removed.
Below is the the instruction that describes the task: ### Input: Return a list of ``(text, replaced_words_count, mask)`` tuples with n_samples versions of text with some words replaced. If a word is replaced, all duplicate words are also replaced from the text. By default words are replaced ...
def write_data(self, data, response_required=None, timeout=5.0, raw=False): """Write data on the asyncio Protocol""" if self._transport is None: return if self._paused: return if self._waiting_for_response: LOG.debug("queueing write %s", data) ...
Write data on the asyncio Protocol
Below is the the instruction that describes the task: ### Input: Write data on the asyncio Protocol ### Response: def write_data(self, data, response_required=None, timeout=5.0, raw=False): """Write data on the asyncio Protocol""" if self._transport is None: return if self._pau...
def pemp(stat, stat0): """ Computes empirical values identically to bioconductor/qvalue empPvals """ assert len(stat0) > 0 assert len(stat) > 0 stat = np.array(stat) stat0 = np.array(stat0) m = len(stat) m0 = len(stat0) statc = np.concatenate((stat, stat0)) v = np.array([True] * ...
Computes empirical values identically to bioconductor/qvalue empPvals
Below is the the instruction that describes the task: ### Input: Computes empirical values identically to bioconductor/qvalue empPvals ### Response: def pemp(stat, stat0): """ Computes empirical values identically to bioconductor/qvalue empPvals """ assert len(stat0) > 0 assert len(stat) > 0 stat...
def diff_result_to_cell(item): '''diff.diff returns a dictionary with all the information we need, but we want to extract the cell and change its metadata.''' state = item['state'] if state == 'modified': new_cell = item['modifiedvalue'].data old_cell = item['originalvalue'].data ...
diff.diff returns a dictionary with all the information we need, but we want to extract the cell and change its metadata.
Below is the the instruction that describes the task: ### Input: diff.diff returns a dictionary with all the information we need, but we want to extract the cell and change its metadata. ### Response: def diff_result_to_cell(item): '''diff.diff returns a dictionary with all the information we need, but...
def ligolw_add(xmldoc, urls, non_lsc_tables_ok = False, verbose = False, contenthandler = DefaultContentHandler): """ An implementation of the LIGO LW add algorithm. urls is a list of URLs (or filenames) to load, xmldoc is the XML document tree to which they should be added. """ # Input for n, url in enumerate(...
An implementation of the LIGO LW add algorithm. urls is a list of URLs (or filenames) to load, xmldoc is the XML document tree to which they should be added.
Below is the the instruction that describes the task: ### Input: An implementation of the LIGO LW add algorithm. urls is a list of URLs (or filenames) to load, xmldoc is the XML document tree to which they should be added. ### Response: def ligolw_add(xmldoc, urls, non_lsc_tables_ok = False, verbose = False, co...
def present(name, pipeline_objects=None, pipeline_objects_from_pillars='boto_datapipeline_pipeline_objects', parameter_objects=None, parameter_objects_from_pillars='boto_datapipeline_parameter_objects', parameter_values=None, parameter_values_from_pillars='bot...
Ensure the data pipeline exists with matching definition. name Name of the service to ensure a data pipeline exists for. pipeline_objects Pipeline objects to use. Will override objects read from pillars. pipeline_objects_from_pillars The pillar key to use for lookup. paramete...
Below is the the instruction that describes the task: ### Input: Ensure the data pipeline exists with matching definition. name Name of the service to ensure a data pipeline exists for. pipeline_objects Pipeline objects to use. Will override objects read from pillars. pipeline_objects...
def parse_swf (url_data): """Parse a SWF file for URLs.""" linkfinder = linkparse.swf_url_re.finditer for mo in linkfinder(url_data.get_content()): url = mo.group() url_data.add_url(url)
Parse a SWF file for URLs.
Below is the the instruction that describes the task: ### Input: Parse a SWF file for URLs. ### Response: def parse_swf (url_data): """Parse a SWF file for URLs.""" linkfinder = linkparse.swf_url_re.finditer for mo in linkfinder(url_data.get_content()): url = mo.group() url_data.add_url...
def fetch(self, bank, key): ''' Fetch data using the specified module :param bank: The name of the location inside the cache which will hold the key and its associated data. :param key: The name of the key (or file inside a directory) which will hold...
Fetch data using the specified module :param bank: The name of the location inside the cache which will hold the key and its associated data. :param key: The name of the key (or file inside a directory) which will hold the data. File extensions should no...
Below is the the instruction that describes the task: ### Input: Fetch data using the specified module :param bank: The name of the location inside the cache which will hold the key and its associated data. :param key: The name of the key (or file inside a direc...
def process_raw_data(cls, raw_data): """Create a new model using raw API response.""" properties = raw_data.get("properties", {}) raw_content = properties.get("ipSecConfiguration", None) if raw_content is not None: ip_sec = IPSecConfiguration.from_raw_data(raw_content) ...
Create a new model using raw API response.
Below is the the instruction that describes the task: ### Input: Create a new model using raw API response. ### Response: def process_raw_data(cls, raw_data): """Create a new model using raw API response.""" properties = raw_data.get("properties", {}) raw_content = properties.get("ipSecCon...
def record_service_agreement(storage_path, service_agreement_id, did, service_definition_id, price, files, start_time, status='pending'): """ Records the given pending service agreement. :param storage_path: storage path for the internal db, str ...
Records the given pending service agreement. :param storage_path: storage path for the internal db, str :param service_agreement_id: :param did: DID, str :param service_definition_id: identifier of the service inside the asset DDO, str :param price: Asset price, int :param files: :param sta...
Below is the the instruction that describes the task: ### Input: Records the given pending service agreement. :param storage_path: storage path for the internal db, str :param service_agreement_id: :param did: DID, str :param service_definition_id: identifier of the service inside the asset DDO, st...
def get(self, *, kind: Type=None, tag: Hashable=None, **_) -> Iterator: """ Get an iterator of objects by kind or tag. kind: Any type. Pass to get a subset of contained items with the given type. tag: Any Hashable object. Pass to get a subset of contained items with ...
Get an iterator of objects by kind or tag. kind: Any type. Pass to get a subset of contained items with the given type. tag: Any Hashable object. Pass to get a subset of contained items with the given tag. Pass both kind and tag to get objects that are both that type...
Below is the the instruction that describes the task: ### Input: Get an iterator of objects by kind or tag. kind: Any type. Pass to get a subset of contained items with the given type. tag: Any Hashable object. Pass to get a subset of contained items with the given tag. ...
def subgroup(self, t, i): """Handle parenthesis.""" # (?flags) flags = self.get_flags(i, self.version == _regex.V0) if flags: self.flags(flags[2:-1]) return [flags] # (?#comment) comments = self.get_comments(i) if comments: re...
Handle parenthesis.
Below is the the instruction that describes the task: ### Input: Handle parenthesis. ### Response: def subgroup(self, t, i): """Handle parenthesis.""" # (?flags) flags = self.get_flags(i, self.version == _regex.V0) if flags: self.flags(flags[2:-1]) return [f...
def convert_to_btc(self, amount, currency): """ Convert X amount to Bit Coins """ if isinstance(amount, Decimal): use_decimal = True else: use_decimal = self._force_decimal url = 'https://api.coindesk.com/v1/bpi/currentprice/{}.json'.format(curren...
Convert X amount to Bit Coins
Below is the the instruction that describes the task: ### Input: Convert X amount to Bit Coins ### Response: def convert_to_btc(self, amount, currency): """ Convert X amount to Bit Coins """ if isinstance(amount, Decimal): use_decimal = True else: use...
def _grabContentFromUrl(self, url): """ Function that abstracts capturing a URL. This method rewrites the one from Wrapper. :param url: The URL to be processed. :return: The response in a Json format. """ # Defining an empty object for the res...
Function that abstracts capturing a URL. This method rewrites the one from Wrapper. :param url: The URL to be processed. :return: The response in a Json format.
Below is the the instruction that describes the task: ### Input: Function that abstracts capturing a URL. This method rewrites the one from Wrapper. :param url: The URL to be processed. :return: The response in a Json format. ### Response: def _grabContentFromUrl(self, url):...
def save_caption(self, filename: str, mtime: datetime, caption: str) -> None: """Updates picture caption / Post metadata info""" def _elliptify(caption): pcaption = caption.replace('\n', ' ').strip() return '[' + ((pcaption[:29] + u"\u2026") if len(pcaption) > 31 else pcaption) +...
Updates picture caption / Post metadata info
Below is the the instruction that describes the task: ### Input: Updates picture caption / Post metadata info ### Response: def save_caption(self, filename: str, mtime: datetime, caption: str) -> None: """Updates picture caption / Post metadata info""" def _elliptify(caption): pcaption ...
def get_controller_value(self, index_or_name, value_type): """ Returns current/min/max value of controller at given index or name. It is much more efficient to query using an integer index rather than string name. Name is fine for seldom updates but it's not advised to be used every sec...
Returns current/min/max value of controller at given index or name. It is much more efficient to query using an integer index rather than string name. Name is fine for seldom updates but it's not advised to be used every second or so. See `get_controller_list` for an example how to cache a dict...
Below is the the instruction that describes the task: ### Input: Returns current/min/max value of controller at given index or name. It is much more efficient to query using an integer index rather than string name. Name is fine for seldom updates but it's not advised to be used every second or so....
def default_config(level=logging.INFO, auto_init=True, new_formatter=False, **kwargs): """ Returns the default config dictionary and inits the logging system if requested Keyword arguments: level -- loglevel of the console handler (Default: logging.INFO) auto_init -- initialize the logging syst...
Returns the default config dictionary and inits the logging system if requested Keyword arguments: level -- loglevel of the console handler (Default: logging.INFO) auto_init -- initialize the logging system with the provided config (Default: True) **kwargs -- additional options for the logging syst...
Below is the the instruction that describes the task: ### Input: Returns the default config dictionary and inits the logging system if requested Keyword arguments: level -- loglevel of the console handler (Default: logging.INFO) auto_init -- initialize the logging system with the provided config (D...
def download_folder(project, destdir, folder="/", overwrite=False, chunksize=dxfile.DEFAULT_BUFFER_SIZE, show_progress=False, **kwargs): ''' :param project: Project ID to use as context for this download. :type project: string :param destdir: Local destination location :type dest...
:param project: Project ID to use as context for this download. :type project: string :param destdir: Local destination location :type destdir: string :param folder: Path to the remote folder to download :type folder: string :param overwrite: Overwrite existing files :type overwrite: boolean...
Below is the the instruction that describes the task: ### Input: :param project: Project ID to use as context for this download. :type project: string :param destdir: Local destination location :type destdir: string :param folder: Path to the remote folder to download :type folder: string :p...
def md5(self): """Return md5 from meta, or compute it if absent.""" md5 = self.meta.get("md5") if md5 is None: md5 = str(hashlib.md5(self.value).hexdigest()) return md5
Return md5 from meta, or compute it if absent.
Below is the the instruction that describes the task: ### Input: Return md5 from meta, or compute it if absent. ### Response: def md5(self): """Return md5 from meta, or compute it if absent.""" md5 = self.meta.get("md5") if md5 is None: md5 = str(hashlib.md5(self.value).hexdiges...
def read_header(filename, ext=0, extver=None, case_sensitive=False, **keys): """ Convenience function to read the header from the specified FITS HDU The FITSHDR allows access to the values and comments by name and number. parameters ---------- filename: string A filename. ext: ...
Convenience function to read the header from the specified FITS HDU The FITSHDR allows access to the values and comments by name and number. parameters ---------- filename: string A filename. ext: number or string, optional The extension. Either the numerical extension from ze...
Below is the the instruction that describes the task: ### Input: Convenience function to read the header from the specified FITS HDU The FITSHDR allows access to the values and comments by name and number. parameters ---------- filename: string A filename. ext: number or string, op...
def partition_dict(items, key): """ Given an ordered dictionary of items and a key in that dict, return an ordered dict of items before, the keyed item, and an ordered dict of items after. >>> od = collections.OrderedDict(zip(range(5), 'abcde')) >>> before, item, after = partition_dict(od, 3) >>> before Ordere...
Given an ordered dictionary of items and a key in that dict, return an ordered dict of items before, the keyed item, and an ordered dict of items after. >>> od = collections.OrderedDict(zip(range(5), 'abcde')) >>> before, item, after = partition_dict(od, 3) >>> before OrderedDict([(0, 'a'), (1, 'b'), (2, 'c')]) ...
Below is the the instruction that describes the task: ### Input: Given an ordered dictionary of items and a key in that dict, return an ordered dict of items before, the keyed item, and an ordered dict of items after. >>> od = collections.OrderedDict(zip(range(5), 'abcde')) >>> before, item, after = partition_...
def extend_hierarchy(levels, strength, aggregate, smooth, improve_candidates, diagonal_dominance=False, keep=True): """Extend the multigrid hierarchy. Service routine to implement the strength of connection, aggregation, tentative prolongation construction, and prolongation smoothing. ...
Extend the multigrid hierarchy. Service routine to implement the strength of connection, aggregation, tentative prolongation construction, and prolongation smoothing. Called by smoothed_aggregation_solver.
Below is the the instruction that describes the task: ### Input: Extend the multigrid hierarchy. Service routine to implement the strength of connection, aggregation, tentative prolongation construction, and prolongation smoothing. Called by smoothed_aggregation_solver. ### Response: def extend_hiera...
def gof_plot( simdata, trueval, name=None, bins=None, format='png', suffix='-gof', path='./', fontmap=None, verbose=0): """ Plots histogram of replicated data, indicating the location of the observed data :Arguments: simdata: array or PyMC object Trace of simulated data or t...
Plots histogram of replicated data, indicating the location of the observed data :Arguments: simdata: array or PyMC object Trace of simulated data or the PyMC stochastic object containing trace. trueval: numeric True (observed) value of the data bins: int or string...
Below is the the instruction that describes the task: ### Input: Plots histogram of replicated data, indicating the location of the observed data :Arguments: simdata: array or PyMC object Trace of simulated data or the PyMC stochastic object containing trace. trueval: numeric ...
async def timeRangeAsync( start: datetime.time, end: datetime.time, step: float) -> AsyncIterator[datetime.datetime]: """ Async version of :meth:`timeRange`. """ assert step > 0 start = _fillDate(start) end = _fillDate(end) delta = datetime.timedelta(seconds=step) t = sta...
Async version of :meth:`timeRange`.
Below is the the instruction that describes the task: ### Input: Async version of :meth:`timeRange`. ### Response: async def timeRangeAsync( start: datetime.time, end: datetime.time, step: float) -> AsyncIterator[datetime.datetime]: """ Async version of :meth:`timeRange`. """ assert...
def nonuniq(iterable): """ Yield the non-unique items of an iterable, preserving order. If an item occurs N > 0 times in the input sequence, it will occur N-1 times in the output sequence. Example: >>> x = nonuniq([0, 0, 2, 6, 2, 0, 5]) >>> list(x) [0, 2, 0] """ temp_dict = {} for e in iterable: if e in...
Yield the non-unique items of an iterable, preserving order. If an item occurs N > 0 times in the input sequence, it will occur N-1 times in the output sequence. Example: >>> x = nonuniq([0, 0, 2, 6, 2, 0, 5]) >>> list(x) [0, 2, 0]
Below is the the instruction that describes the task: ### Input: Yield the non-unique items of an iterable, preserving order. If an item occurs N > 0 times in the input sequence, it will occur N-1 times in the output sequence. Example: >>> x = nonuniq([0, 0, 2, 6, 2, 0, 5]) >>> list(x) [0, 2, 0] ### Respon...
def stop_host(self, config_file): """ Stops a managed host specified by `config_file`. """ res = self.send_json_request('host/stop', data={'config': config_file}) if res.status_code != 200: raise UnexpectedResponse( 'Attempted to stop a JSHost. Respon...
Stops a managed host specified by `config_file`.
Below is the the instruction that describes the task: ### Input: Stops a managed host specified by `config_file`. ### Response: def stop_host(self, config_file): """ Stops a managed host specified by `config_file`. """ res = self.send_json_request('host/stop', data={'config': config...
def create_station(name, latlonalt, parent_frame=WGS84, orientation='N', mask=None): """Create a ground station instance Args: name (str): Name of the station latlonalt (tuple of float): coordinates of the station, as follow: * Latitude in degrees * Longitude in degree...
Create a ground station instance Args: name (str): Name of the station latlonalt (tuple of float): coordinates of the station, as follow: * Latitude in degrees * Longitude in degrees * Altitude to sea level in meters parent_frame (Frame): Planetocentri...
Below is the the instruction that describes the task: ### Input: Create a ground station instance Args: name (str): Name of the station latlonalt (tuple of float): coordinates of the station, as follow: * Latitude in degrees * Longitude in degrees * Altitud...
def dispatch(self, receiver): ''' Dispatch handling of this event to a receiver. This method will invoke ``receiver._session_callback_removed`` if it exists. ''' super(SessionCallbackRemoved, self).dispatch(receiver) if hasattr(receiver, '_session_callback_removed'): ...
Dispatch handling of this event to a receiver. This method will invoke ``receiver._session_callback_removed`` if it exists.
Below is the the instruction that describes the task: ### Input: Dispatch handling of this event to a receiver. This method will invoke ``receiver._session_callback_removed`` if it exists. ### Response: def dispatch(self, receiver): ''' Dispatch handling of this event to a receiver. ...
def get_volumes(self): """Gets a list of all volumes in this disk, including volumes that are contained in other volumes.""" volumes = [] for v in self.volumes: volumes.extend(v.get_volumes()) return volumes
Gets a list of all volumes in this disk, including volumes that are contained in other volumes.
Below is the the instruction that describes the task: ### Input: Gets a list of all volumes in this disk, including volumes that are contained in other volumes. ### Response: def get_volumes(self): """Gets a list of all volumes in this disk, including volumes that are contained in other volumes.""" ...
def IsFile(self): """Determines if the file entry is a file. Returns: bool: True if the file entry is a file. """ if self._stat_object is None: self._stat_object = self._GetStat() if self._stat_object is not None: self.entry_type = self._stat_object.type return self.entry_type...
Determines if the file entry is a file. Returns: bool: True if the file entry is a file.
Below is the the instruction that describes the task: ### Input: Determines if the file entry is a file. Returns: bool: True if the file entry is a file. ### Response: def IsFile(self): """Determines if the file entry is a file. Returns: bool: True if the file entry is a file. """ ...
def run(self): """Reads data from disk and generates CSV files.""" # Try to create the directory if not os.path.exists(self.output): try: os.mkdir(self.output) except: print 'failed to create output directory %s' % self.output # Be...
Reads data from disk and generates CSV files.
Below is the the instruction that describes the task: ### Input: Reads data from disk and generates CSV files. ### Response: def run(self): """Reads data from disk and generates CSV files.""" # Try to create the directory if not os.path.exists(self.output): try: ...
def _StripCommonPathPrefix(paths): """Removes path common prefix from a list of path strings.""" # Find the longest common prefix in terms of characters. common_prefix = os.path.commonprefix(paths) # Truncate at last segment boundary. E.g. '/aa/bb1/x.py' and '/a/bb2/x.py' # have '/aa/bb' as the common prefix,...
Removes path common prefix from a list of path strings.
Below is the the instruction that describes the task: ### Input: Removes path common prefix from a list of path strings. ### Response: def _StripCommonPathPrefix(paths): """Removes path common prefix from a list of path strings.""" # Find the longest common prefix in terms of characters. common_prefix = os.p...
def brightness(self): """Return current brightness 0-255. For warm white return current led level. For RGB calculate the HSV and return the 'value'. """ if self.mode == "ww": return int(self.raw_state[9]) else: _, _, v = colorsys.rgb_to_hsv(*self....
Return current brightness 0-255. For warm white return current led level. For RGB calculate the HSV and return the 'value'.
Below is the the instruction that describes the task: ### Input: Return current brightness 0-255. For warm white return current led level. For RGB calculate the HSV and return the 'value'. ### Response: def brightness(self): """Return current brightness 0-255. For warm white retur...
def rmultivariate_hypergeometric(n, m, size=None): """ Random multivariate hypergeometric variates. Parameters: - `n` : Number of draws. - `m` : Number of items in each categoy. """ N = len(m) urn = np.repeat(np.arange(N), m) if size: draw = np.array([[urn[i] for i in ...
Random multivariate hypergeometric variates. Parameters: - `n` : Number of draws. - `m` : Number of items in each categoy.
Below is the the instruction that describes the task: ### Input: Random multivariate hypergeometric variates. Parameters: - `n` : Number of draws. - `m` : Number of items in each categoy. ### Response: def rmultivariate_hypergeometric(n, m, size=None): """ Random multivariate hypergeometri...
def convert_tags_to_dict(item): """ Convert AWS inconvenient tags model of a list of {"Key": <key>, "Value": <value>} pairs to a dict of {<key>: <value>} for easier querying. This returns a proxied object over given item to return a different tags format as the tags attribute is read-only and we ca...
Convert AWS inconvenient tags model of a list of {"Key": <key>, "Value": <value>} pairs to a dict of {<key>: <value>} for easier querying. This returns a proxied object over given item to return a different tags format as the tags attribute is read-only and we cannot modify it directly.
Below is the the instruction that describes the task: ### Input: Convert AWS inconvenient tags model of a list of {"Key": <key>, "Value": <value>} pairs to a dict of {<key>: <value>} for easier querying. This returns a proxied object over given item to return a different tags format as the tags attribu...
def add_data_point_xy(self, x, y): """Add a new data point to the data set to be smoothed.""" self.x.append(x) self.y.append(y)
Add a new data point to the data set to be smoothed.
Below is the the instruction that describes the task: ### Input: Add a new data point to the data set to be smoothed. ### Response: def add_data_point_xy(self, x, y): """Add a new data point to the data set to be smoothed.""" self.x.append(x) self.y.append(y)
def _try_import(module_name): """Try importing a module, with an informative error message on failure.""" try: mod = importlib.import_module(module_name) return mod except ImportError: err_msg = ("Tried importing %s but failed. See setup.py extras_require. " "The dataset you are trying ...
Try importing a module, with an informative error message on failure.
Below is the the instruction that describes the task: ### Input: Try importing a module, with an informative error message on failure. ### Response: def _try_import(module_name): """Try importing a module, with an informative error message on failure.""" try: mod = importlib.import_module(module_name) ...
def _load_data(self, band): """In-flight effective areas for the Swift UVOT, as obtained from the CALDB. See Breeveld+ 2011. XXX: confirm that these are equal-energy, not quantum-efficiency. """ d = bandpass_data_fits('sw' + self._band_map[band] + '_20041120v106.arf')[1].data ...
In-flight effective areas for the Swift UVOT, as obtained from the CALDB. See Breeveld+ 2011. XXX: confirm that these are equal-energy, not quantum-efficiency.
Below is the the instruction that describes the task: ### Input: In-flight effective areas for the Swift UVOT, as obtained from the CALDB. See Breeveld+ 2011. XXX: confirm that these are equal-energy, not quantum-efficiency. ### Response: def _load_data(self, band): """In-flight effective a...
def vdm_b(vdm, lat): """ Converts a virtual dipole moment (VDM) or a virtual axial dipole moment (VADM; input in units of Am^2) to a local magnetic field value (output in units of tesla) Parameters ---------- vdm : V(A)DM in units of Am^2 lat: latitude of site in degrees Returns ...
Converts a virtual dipole moment (VDM) or a virtual axial dipole moment (VADM; input in units of Am^2) to a local magnetic field value (output in units of tesla) Parameters ---------- vdm : V(A)DM in units of Am^2 lat: latitude of site in degrees Returns ------- B: local magnetic f...
Below is the the instruction that describes the task: ### Input: Converts a virtual dipole moment (VDM) or a virtual axial dipole moment (VADM; input in units of Am^2) to a local magnetic field value (output in units of tesla) Parameters ---------- vdm : V(A)DM in units of Am^2 lat: latitud...
def _rspiral(width, height): """Reversed spiral generator. Parameters ---------- width : `int` Spiral width. height : `int` Spiral height. Returns ------- `generator` of (`int`, `int`) Points. """ x0 =...
Reversed spiral generator. Parameters ---------- width : `int` Spiral width. height : `int` Spiral height. Returns ------- `generator` of (`int`, `int`) Points.
Below is the the instruction that describes the task: ### Input: Reversed spiral generator. Parameters ---------- width : `int` Spiral width. height : `int` Spiral height. Returns ------- `generator` of (`int`, `int`) Poin...
def outer_product(vec0: QubitVector, vec1: QubitVector) -> QubitVector: """Direct product of qubit vectors The tensor ranks must match and qubits must be disjoint. """ R = vec0.rank R1 = vec1.rank N0 = vec0.qubit_nb N1 = vec1.qubit_nb if R != R1: raise ValueError('Incompatibly...
Direct product of qubit vectors The tensor ranks must match and qubits must be disjoint.
Below is the the instruction that describes the task: ### Input: Direct product of qubit vectors The tensor ranks must match and qubits must be disjoint. ### Response: def outer_product(vec0: QubitVector, vec1: QubitVector) -> QubitVector: """Direct product of qubit vectors The tensor ranks must matc...
def _get_kws_plt(self, usrgos, **kws_usr): """Add go2color and go2bordercolor relevant to this grouping into plot.""" kws_plt = kws_usr.copy() kws_dag = {} hdrgo = kws_plt.get('hdrgo', None) objcolor = GrouperColors(self.grprobj) # GO term colors if 'go2color' not...
Add go2color and go2bordercolor relevant to this grouping into plot.
Below is the the instruction that describes the task: ### Input: Add go2color and go2bordercolor relevant to this grouping into plot. ### Response: def _get_kws_plt(self, usrgos, **kws_usr): """Add go2color and go2bordercolor relevant to this grouping into plot.""" kws_plt = kws_usr.copy() ...
def safe_input(prompt): """ Prompts user for input. Correctly handles prompt message encoding. """ if sys.version_info < (3,0): if isinstance(prompt, compat.text_type): # Python 2.x: unicode → bytes encoding = locale.getpreferredencoding() or 'utf-8' prompt ...
Prompts user for input. Correctly handles prompt message encoding.
Below is the the instruction that describes the task: ### Input: Prompts user for input. Correctly handles prompt message encoding. ### Response: def safe_input(prompt): """ Prompts user for input. Correctly handles prompt message encoding. """ if sys.version_info < (3,0): if isinstance(pr...