code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
text
stringlengths
164
112k
def command_show(self): """ Show metadata """ self.parser = argparse.ArgumentParser( description="Show metadata of available objects") self.options_select() self.options_formatting() self.options_utils() self.options = self.parser.parse_args(self.arguments[2:]...
Show metadata
Below is the the instruction that describes the task: ### Input: Show metadata ### Response: def command_show(self): """ Show metadata """ self.parser = argparse.ArgumentParser( description="Show metadata of available objects") self.options_select() self.options_formatti...
def _calculate(self, startingPercentage, endPercentage, startDate, endDate): """This is the error calculation function that gets called by :py:meth:`BaseErrorMeasure.get_error`. Both parameters will be correct at this time. :param float startingPercentage: Defines the start of the interval. Th...
This is the error calculation function that gets called by :py:meth:`BaseErrorMeasure.get_error`. Both parameters will be correct at this time. :param float startingPercentage: Defines the start of the interval. This has to be a value in [0.0, 100.0]. It represents the value, where the err...
Below is the the instruction that describes the task: ### Input: This is the error calculation function that gets called by :py:meth:`BaseErrorMeasure.get_error`. Both parameters will be correct at this time. :param float startingPercentage: Defines the start of the interval. This has to be a valu...
def get_address(): """ Get one or more existing address(es) owned by your user. --- parameters: - name: address in: body description: The address you'd like to get info about. required: false schema: $ref: '#/definitions/Address' responses: '200'...
Get one or more existing address(es) owned by your user. --- parameters: - name: address in: body description: The address you'd like to get info about. required: false schema: $ref: '#/definitions/Address' responses: '200': description: Your new...
Below is the the instruction that describes the task: ### Input: Get one or more existing address(es) owned by your user. --- parameters: - name: address in: body description: The address you'd like to get info about. required: false schema: $ref: '#/definitio...
def modified(self): """Union[datetime.datetime, None]: Datetime at which the dataset was last modified (:data:`None` until set from the server). """ modified_time = self._properties.get("lastModifiedTime") if modified_time is not None: # modified_time will be in milli...
Union[datetime.datetime, None]: Datetime at which the dataset was last modified (:data:`None` until set from the server).
Below is the the instruction that describes the task: ### Input: Union[datetime.datetime, None]: Datetime at which the dataset was last modified (:data:`None` until set from the server). ### Response: def modified(self): """Union[datetime.datetime, None]: Datetime at which the dataset was l...
def _typelist(x): """Helper function converting all items of x to instances.""" if isinstance(x, collections.Sequence): return list(map(_to_instance, x)) elif isinstance(x, collections.Iterable): return x return None if x is None else [_to_instance(x)]
Helper function converting all items of x to instances.
Below is the the instruction that describes the task: ### Input: Helper function converting all items of x to instances. ### Response: def _typelist(x): """Helper function converting all items of x to instances.""" if isinstance(x, collections.Sequence): return list(map(_to_instance, x)) elif i...
def find_related_modules(package, related_name_re='.+', ignore_exceptions=False): """Find matching modules using a package and a module name pattern.""" warnings.warn('find_related_modules has been deprecated.', DeprecationWarning) package_elements = package.rsplit...
Find matching modules using a package and a module name pattern.
Below is the the instruction that describes the task: ### Input: Find matching modules using a package and a module name pattern. ### Response: def find_related_modules(package, related_name_re='.+', ignore_exceptions=False): """Find matching modules using a package and a module name p...
def close(self): """End the report.""" endpoint = self.endpoint.replace("/api/v1/spans", "") logger.debug("Zipkin trace may be located at this URL {}/traces/{}".format(endpoint, self.trace_id))
End the report.
Below is the the instruction that describes the task: ### Input: End the report. ### Response: def close(self): """End the report.""" endpoint = self.endpoint.replace("/api/v1/spans", "") logger.debug("Zipkin trace may be located at this URL {}/traces/{}".format(endpoint, self.trace_id))
def loadable_modules(self): '''The list of loadable module profile dictionaries.''' with self._mutex: if not self._loadable_modules: self._loadable_modules = [] for mp in self._obj.get_loadable_modules(): self._loadable_modules.append(utils...
The list of loadable module profile dictionaries.
Below is the the instruction that describes the task: ### Input: The list of loadable module profile dictionaries. ### Response: def loadable_modules(self): '''The list of loadable module profile dictionaries.''' with self._mutex: if not self._loadable_modules: self._loa...
def refill_main_wallet(self, from_address, to_address, nfees, ntokens, password, min_confirmations=6, sync=False): """ Refill the Federation wallet with tokens and fees. This keeps the federation wallet clean. Dealing with exact values simplifies the transactions. No need to calculate change. Ea...
Refill the Federation wallet with tokens and fees. This keeps the federation wallet clean. Dealing with exact values simplifies the transactions. No need to calculate change. Easier to keep track of the unspents and prevent double spends that would result in transactions being rejected by the bitcoin ne...
Below is the the instruction that describes the task: ### Input: Refill the Federation wallet with tokens and fees. This keeps the federation wallet clean. Dealing with exact values simplifies the transactions. No need to calculate change. Easier to keep track of the unspents and prevent double spen...
def skesa_assemble(self): """ Run skesa to assemble genomes """ with progressbar(self.metadata) as bar: for sample in bar: # Initialise the assembly command sample.commands.assemble = str() try: if sample.gen...
Run skesa to assemble genomes
Below is the the instruction that describes the task: ### Input: Run skesa to assemble genomes ### Response: def skesa_assemble(self): """ Run skesa to assemble genomes """ with progressbar(self.metadata) as bar: for sample in bar: # Initialise the assemb...
def get_attached_container_host_config_kwargs(self, action, container_name, kwargs=None): """ Generates keyword arguments for the Docker client to set up the HostConfig or start an attached container. :param action: Action configuration. :type action: ActionConfig :param contain...
Generates keyword arguments for the Docker client to set up the HostConfig or start an attached container. :param action: Action configuration. :type action: ActionConfig :param container_name: Container name or id. Set ``None`` when included in kwargs for ``create_container``. :type co...
Below is the the instruction that describes the task: ### Input: Generates keyword arguments for the Docker client to set up the HostConfig or start an attached container. :param action: Action configuration. :type action: ActionConfig :param container_name: Container name or id. Set ``None...
def altitudes(self): ''' A list of the altitudes of each vertex [AltA, AltB, AltC], list of floats. An altitude is the shortest distance from a vertex to the side opposite of it. ''' a = self.area * 2 return [a / self.a, a / self.b, a / self.c]
A list of the altitudes of each vertex [AltA, AltB, AltC], list of floats. An altitude is the shortest distance from a vertex to the side opposite of it.
Below is the the instruction that describes the task: ### Input: A list of the altitudes of each vertex [AltA, AltB, AltC], list of floats. An altitude is the shortest distance from a vertex to the side opposite of it. ### Response: def altitudes(self): ''' A list of the al...
def user(self, extra_params=None): """ The User currently assigned to the Ticket """ if self.get('assigned_to_id', None): users = self.space.users( id=self['assigned_to_id'], extra_params=extra_params ) if users: ...
The User currently assigned to the Ticket
Below is the the instruction that describes the task: ### Input: The User currently assigned to the Ticket ### Response: def user(self, extra_params=None): """ The User currently assigned to the Ticket """ if self.get('assigned_to_id', None): users = self.space.users( ...
def get_port_channel_detail_output_lacp_aggr_member_sync(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") get_port_channel_detail = ET.Element("get_port_channel_detail") config = get_port_channel_detail output = ET.SubElement(get_port_channel_deta...
Auto Generated Code
Below is the the instruction that describes the task: ### Input: Auto Generated Code ### Response: def get_port_channel_detail_output_lacp_aggr_member_sync(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") get_port_channel_detail = ET.Element("get_port_channe...
def get_pickle_protocol(): """ Allow configuration of the pickle protocol on a per-machine basis. This way, if you use multiple platforms with different versions of pickle, you can configure each of them to use the highest protocol supported by all of the machines that you want to be able to com...
Allow configuration of the pickle protocol on a per-machine basis. This way, if you use multiple platforms with different versions of pickle, you can configure each of them to use the highest protocol supported by all of the machines that you want to be able to communicate.
Below is the the instruction that describes the task: ### Input: Allow configuration of the pickle protocol on a per-machine basis. This way, if you use multiple platforms with different versions of pickle, you can configure each of them to use the highest protocol supported by all of the machines that ...
def extract_agg_curves(dstore, what): """ Aggregate loss curves of the given loss type and tags for event based risk calculations. Use it as /extract/agg_curves/structural?taxonomy=RC&zipcode=20126 :returns: array of shape (S, P), being P the number of return periods and S the number...
Aggregate loss curves of the given loss type and tags for event based risk calculations. Use it as /extract/agg_curves/structural?taxonomy=RC&zipcode=20126 :returns: array of shape (S, P), being P the number of return periods and S the number of statistics
Below is the the instruction that describes the task: ### Input: Aggregate loss curves of the given loss type and tags for event based risk calculations. Use it as /extract/agg_curves/structural?taxonomy=RC&zipcode=20126 :returns: array of shape (S, P), being P the number of return periods ...
def update_forward_refs(cls, **localns: Any) -> None: """ Try to update ForwardRefs on fields based on this Model, globalns and localns. """ globalns = sys.modules[cls.__module__].__dict__ globalns.setdefault(cls.__name__, cls) for f in cls.__fields__.values(): ...
Try to update ForwardRefs on fields based on this Model, globalns and localns.
Below is the the instruction that describes the task: ### Input: Try to update ForwardRefs on fields based on this Model, globalns and localns. ### Response: def update_forward_refs(cls, **localns: Any) -> None: """ Try to update ForwardRefs on fields based on this Model, globalns and localns. ...
def show_banner(ctx, param, value): """Shows dynaconf awesome banner""" if not value or ctx.resilient_parsing: return set_settings() click.echo(settings.dynaconf_banner) click.echo("Learn more at: http://github.com/rochacbruno/dynaconf") ctx.exit()
Shows dynaconf awesome banner
Below is the the instruction that describes the task: ### Input: Shows dynaconf awesome banner ### Response: def show_banner(ctx, param, value): """Shows dynaconf awesome banner""" if not value or ctx.resilient_parsing: return set_settings() click.echo(settings.dynaconf_banner) click.ec...
def _parse_text(self, text): """Parse text (string) and return list of parsed sentences (strings). Each sentence consists of space separated token elements and the token format returned by the PatternParser is WORD/TAG/PHRASE/ROLE/(LEMMA) (separated by a forward slash '/') :par...
Parse text (string) and return list of parsed sentences (strings). Each sentence consists of space separated token elements and the token format returned by the PatternParser is WORD/TAG/PHRASE/ROLE/(LEMMA) (separated by a forward slash '/') :param str text: A string.
Below is the the instruction that describes the task: ### Input: Parse text (string) and return list of parsed sentences (strings). Each sentence consists of space separated token elements and the token format returned by the PatternParser is WORD/TAG/PHRASE/ROLE/(LEMMA) (separated by a for...
def get(self, path='', page=False, retry=3, **options): """ Get an item from the Graph API. :param path: A string describing the path to the item. :param page: A boolean describing whether to return a generator that iterates over each page of results. :param...
Get an item from the Graph API. :param path: A string describing the path to the item. :param page: A boolean describing whether to return a generator that iterates over each page of results. :param retry: An integer describing how many times the request may be retried. ...
Below is the the instruction that describes the task: ### Input: Get an item from the Graph API. :param path: A string describing the path to the item. :param page: A boolean describing whether to return a generator that iterates over each page of results. :param retry:...
async def mark_fixed(self, *, comment: str = None): """Mark fixes. :param comment: Reason machine is fixed. :type comment: `str` """ params = { "system_id": self.system_id } if comment: params["comment"] = comment self._data = awai...
Mark fixes. :param comment: Reason machine is fixed. :type comment: `str`
Below is the the instruction that describes the task: ### Input: Mark fixes. :param comment: Reason machine is fixed. :type comment: `str` ### Response: async def mark_fixed(self, *, comment: str = None): """Mark fixes. :param comment: Reason machine is fixed. :type commen...
def get_n_cluster_in_events(event_numbers): '''Calculates the number of cluster in every given event. An external C++ library is used since there is no sufficient solution in python possible. Because of np.bincount # BUG #225 for values > int32 and the different handling under 32/64 bit operating systems. ...
Calculates the number of cluster in every given event. An external C++ library is used since there is no sufficient solution in python possible. Because of np.bincount # BUG #225 for values > int32 and the different handling under 32/64 bit operating systems. Parameters ---------- event_numbers : n...
Below is the the instruction that describes the task: ### Input: Calculates the number of cluster in every given event. An external C++ library is used since there is no sufficient solution in python possible. Because of np.bincount # BUG #225 for values > int32 and the different handling under 32/64 bit op...
def logger(): """Configure program logger.""" scriptlogger = logging.getLogger(__program__) # ensure logger is not reconfigured if not scriptlogger.hasHandlers(): # set log level scriptlogger.setLevel(logging.INFO) fmt = '%(name)s:%(levelname)s: %(message)s' # config...
Configure program logger.
Below is the the instruction that describes the task: ### Input: Configure program logger. ### Response: def logger(): """Configure program logger.""" scriptlogger = logging.getLogger(__program__) # ensure logger is not reconfigured if not scriptlogger.hasHandlers(): # set log level ...
def looks_like_gene(self): '''Returns true iff: length >=6, length is a multiple of 3, first codon is start, last codon is a stop and has no other stop codons''' return self.is_complete_orf() \ and len(self) >= 6 \ and len(self) %3 == 0 \ and self.seq[0:3].upper() in geneti...
Returns true iff: length >=6, length is a multiple of 3, first codon is start, last codon is a stop and has no other stop codons
Below is the the instruction that describes the task: ### Input: Returns true iff: length >=6, length is a multiple of 3, first codon is start, last codon is a stop and has no other stop codons ### Response: def looks_like_gene(self): '''Returns true iff: length >=6, length is a multiple of 3, first codon ...
def PrepareMergeTaskStorage(self, task): """Prepares a task storage for merging. Args: task (Task): task. Raises: IOError: if the task storage does not exist. OSError: if the task storage does not exist. """ if task.identifier not in self._task_storage_writers: raise IOErro...
Prepares a task storage for merging. Args: task (Task): task. Raises: IOError: if the task storage does not exist. OSError: if the task storage does not exist.
Below is the the instruction that describes the task: ### Input: Prepares a task storage for merging. Args: task (Task): task. Raises: IOError: if the task storage does not exist. OSError: if the task storage does not exist. ### Response: def PrepareMergeTaskStorage(self, task): """...
def read_single_knmi_file(filename): """reads a single file of KNMI's meteorological time series data availability: www.knmi.nl/nederland-nu/klimatologie/uurgegevens Args: filename: the file to be opened Returns: pandas data frame including time series """ hourly_data_obs_raw ...
reads a single file of KNMI's meteorological time series data availability: www.knmi.nl/nederland-nu/klimatologie/uurgegevens Args: filename: the file to be opened Returns: pandas data frame including time series
Below is the the instruction that describes the task: ### Input: reads a single file of KNMI's meteorological time series data availability: www.knmi.nl/nederland-nu/klimatologie/uurgegevens Args: filename: the file to be opened Returns: pandas data frame including time series ### Res...
def spmt(t, peak_delay=6, under_delay=16, peak_disp=1, under_disp=1, p_u_ratio=6): """Normalized SPM HRF function from sum of two gamma PDFs Parameters ---------- t : array-like vector of times at which to sample HRF Returns ------- hrf : array vector length ``len(...
Normalized SPM HRF function from sum of two gamma PDFs Parameters ---------- t : array-like vector of times at which to sample HRF Returns ------- hrf : array vector length ``len(t)`` of samples from HRF at times `t` Notes ----- [1] This is the canonical HRF functi...
Below is the the instruction that describes the task: ### Input: Normalized SPM HRF function from sum of two gamma PDFs Parameters ---------- t : array-like vector of times at which to sample HRF Returns ------- hrf : array vector length ``len(t)`` of samples from HRF at ti...
def get_country_short(self, ip): ''' Get country_short ''' rec = self.get_all(ip) return rec and rec.country_short
Get country_short
Below is the the instruction that describes the task: ### Input: Get country_short ### Response: def get_country_short(self, ip): ''' Get country_short ''' rec = self.get_all(ip) return rec and rec.country_short
def refresh(self): """Do a full refresh of all devices and automations.""" self.get_devices(refresh=True) self.get_automations(refresh=True)
Do a full refresh of all devices and automations.
Below is the the instruction that describes the task: ### Input: Do a full refresh of all devices and automations. ### Response: def refresh(self): """Do a full refresh of all devices and automations.""" self.get_devices(refresh=True) self.get_automations(refresh=True)
def get_qpimage_raw(self, idx=0): """Return QPImage without background correction""" qpi = qpimage.QPImage(h5file=self.path, h5mode="r", h5dtype=self.as_type, ).copy() # Remove previously performed backgrou...
Return QPImage without background correction
Below is the the instruction that describes the task: ### Input: Return QPImage without background correction ### Response: def get_qpimage_raw(self, idx=0): """Return QPImage without background correction""" qpi = qpimage.QPImage(h5file=self.path, h5mode="r", ...
async def spop(self, name, count=None): """ Remove and return a random member of set ``name`` ``count`` should be type of int and default set to 1. If ``count`` is supplied, pops a list of ``count`` random + members of set ``name`` """ if count and isinstance(count...
Remove and return a random member of set ``name`` ``count`` should be type of int and default set to 1. If ``count`` is supplied, pops a list of ``count`` random + members of set ``name``
Below is the the instruction that describes the task: ### Input: Remove and return a random member of set ``name`` ``count`` should be type of int and default set to 1. If ``count`` is supplied, pops a list of ``count`` random + members of set ``name`` ### Response: async def spop(self, name...
def _walk_polyline(tid, intersect, T, mesh, plane, dist_tol): """ Given an intersection, walk through the mesh triangles, computing intersection with the cut plane for each visited triangle and adding those intersection to a polyline. """ T = set(T) p = [] # Loop until we have explored a...
Given an intersection, walk through the mesh triangles, computing intersection with the cut plane for each visited triangle and adding those intersection to a polyline.
Below is the the instruction that describes the task: ### Input: Given an intersection, walk through the mesh triangles, computing intersection with the cut plane for each visited triangle and adding those intersection to a polyline. ### Response: def _walk_polyline(tid, intersect, T, mesh, plane, dist_tol...
def create_record(destination, file_ids, width=None, height=None): """ Creates a master record for the HTML report; this doesn't contain contain the actual HTML, but reports are required to be records rather than files and we can link more than one HTML file to a report """ [project, path, name] = p...
Creates a master record for the HTML report; this doesn't contain contain the actual HTML, but reports are required to be records rather than files and we can link more than one HTML file to a report
Below is the the instruction that describes the task: ### Input: Creates a master record for the HTML report; this doesn't contain contain the actual HTML, but reports are required to be records rather than files and we can link more than one HTML file to a report ### Response: def create_record(destination, f...
def start(self): """Indicate that we are performing work in a thread. :returns: multiprocessing job object """ if self.run is True: self.job = multiprocessing.Process(target=self.indicator) self.job.start() return self.job
Indicate that we are performing work in a thread. :returns: multiprocessing job object
Below is the the instruction that describes the task: ### Input: Indicate that we are performing work in a thread. :returns: multiprocessing job object ### Response: def start(self): """Indicate that we are performing work in a thread. :returns: multiprocessing job object """ ...
def prod(self, values, axis=0, dtype=None): """compute the product over each group Parameters ---------- values : array_like, [keys, ...] values to multiply per group axis : int, optional alternative reduction axis for values dtype : output dtype ...
compute the product over each group Parameters ---------- values : array_like, [keys, ...] values to multiply per group axis : int, optional alternative reduction axis for values dtype : output dtype Returns ------- unique: ndarra...
Below is the the instruction that describes the task: ### Input: compute the product over each group Parameters ---------- values : array_like, [keys, ...] values to multiply per group axis : int, optional alternative reduction axis for values dtype :...
def _make_links_absolute(html, base_url): """ Make all links absolute. """ url_changes = [] soup = BeautifulSoup(html) for tag in soup.find_all('a', href=True): old = tag['href'] fixed = urljoin(base_url, old) if old != fixed: url_changes.append((old, fixed))...
Make all links absolute.
Below is the the instruction that describes the task: ### Input: Make all links absolute. ### Response: def _make_links_absolute(html, base_url): """ Make all links absolute. """ url_changes = [] soup = BeautifulSoup(html) for tag in soup.find_all('a', href=True): old = tag['href']...
def check_type(self, value): """Hook for type-checking, invoked during assignment. Allows size 1 numpy arrays and lists, but raises TypeError if value can not be cast to a scalar. """ try: scalar = asscalar(value) except ValueError as e: raise Typ...
Hook for type-checking, invoked during assignment. Allows size 1 numpy arrays and lists, but raises TypeError if value can not be cast to a scalar.
Below is the the instruction that describes the task: ### Input: Hook for type-checking, invoked during assignment. Allows size 1 numpy arrays and lists, but raises TypeError if value can not be cast to a scalar. ### Response: def check_type(self, value): """Hook for type-checking, invoked ...
def client_file(self): """Specify path to the ipcontroller-client.json file. This file is stored in in the ipython_dir/profile folders. Returns : - str, File path to client file """ return os.path.join(self.ipython_dir, 'profile_{0}'.fo...
Specify path to the ipcontroller-client.json file. This file is stored in in the ipython_dir/profile folders. Returns : - str, File path to client file
Below is the the instruction that describes the task: ### Input: Specify path to the ipcontroller-client.json file. This file is stored in in the ipython_dir/profile folders. Returns : - str, File path to client file ### Response: def client_file(self): """Specify path to th...
def block_process_call(self, addr, cmd, vals): """block_process_call(addr, cmd, vals) -> results Perform SMBus Block Process Call transaction. """ self._set_addr(addr) data = ffi.new("union i2c_smbus_data *") list_to_smbus_data(data, vals) if SMBUS.i2c_smbus_acce...
block_process_call(addr, cmd, vals) -> results Perform SMBus Block Process Call transaction.
Below is the the instruction that describes the task: ### Input: block_process_call(addr, cmd, vals) -> results Perform SMBus Block Process Call transaction. ### Response: def block_process_call(self, addr, cmd, vals): """block_process_call(addr, cmd, vals) -> results Perform SMBus Block ...
def end_parallel(self): """ Ends a parallel region by merging the channels into a single stream. Returns: Stream: Stream for which subsequent transformations are no longer parallelized. .. seealso:: :py:meth:`set_parallel`, :py:meth:`parallel` """ outport = ...
Ends a parallel region by merging the channels into a single stream. Returns: Stream: Stream for which subsequent transformations are no longer parallelized. .. seealso:: :py:meth:`set_parallel`, :py:meth:`parallel`
Below is the the instruction that describes the task: ### Input: Ends a parallel region by merging the channels into a single stream. Returns: Stream: Stream for which subsequent transformations are no longer parallelized. .. seealso:: :py:meth:`set_parallel`, :py:meth:`parallel` ### R...
def from_hdf5(cls, f): """ Load an object from an HDF5 file. Requires ``h5py``. Parameters ---------- f : str, :class:`h5py.File` Either the filename or an open HDF5 file. """ if isinstance(f, str): import h5py f = h5p...
Load an object from an HDF5 file. Requires ``h5py``. Parameters ---------- f : str, :class:`h5py.File` Either the filename or an open HDF5 file.
Below is the the instruction that describes the task: ### Input: Load an object from an HDF5 file. Requires ``h5py``. Parameters ---------- f : str, :class:`h5py.File` Either the filename or an open HDF5 file. ### Response: def from_hdf5(cls, f): """ Lo...
def open_book(self, for_writing=False) -> piecash.Book: """ Opens the database. Call this using 'with'. If database file is not found, an in-memory database will be created. """ filename = None # check if the file path is already a URL. file_url = urllib.parse.ur...
Opens the database. Call this using 'with'. If database file is not found, an in-memory database will be created.
Below is the the instruction that describes the task: ### Input: Opens the database. Call this using 'with'. If database file is not found, an in-memory database will be created. ### Response: def open_book(self, for_writing=False) -> piecash.Book: """ Opens the database. Call this using 'w...
def threw(self, error_type=None): """ Determining whether the exception is thrown Args: error_type: None: checking without specified exception Specified Exception Return: Boolean """ if not error_type: return True if...
Determining whether the exception is thrown Args: error_type: None: checking without specified exception Specified Exception Return: Boolean
Below is the the instruction that describes the task: ### Input: Determining whether the exception is thrown Args: error_type: None: checking without specified exception Specified Exception Return: Boolean ### Response: def threw(self, error_type=None): ...
def binom(n, k): """Binomial coefficients for :math:`n \choose k` :param n,k: non-negative integers :complexity: O(k) """ prod = 1 for i in range(k): prod = (prod * (n - i)) // (i + 1) return prod
Binomial coefficients for :math:`n \choose k` :param n,k: non-negative integers :complexity: O(k)
Below is the the instruction that describes the task: ### Input: Binomial coefficients for :math:`n \choose k` :param n,k: non-negative integers :complexity: O(k) ### Response: def binom(n, k): """Binomial coefficients for :math:`n \choose k` :param n,k: non-negative integers :complexity: O(k...
def _handle_status(self, key, value): """Parse a status code from the attached GnuPG process. :raises: :exc:`~exceptions.ValueError` if the status message is unknown. """ if key in ("GOOD_PASSPHRASE"): pass elif key == "KEY_CONSIDERED": self.status = key....
Parse a status code from the attached GnuPG process. :raises: :exc:`~exceptions.ValueError` if the status message is unknown.
Below is the the instruction that describes the task: ### Input: Parse a status code from the attached GnuPG process. :raises: :exc:`~exceptions.ValueError` if the status message is unknown. ### Response: def _handle_status(self, key, value): """Parse a status code from the attached GnuPG process....
def check_latitude(self, ds): ''' Check variable(s) that define latitude and are defined correctly according to CF. CF §4.1 Variables representing latitude must always explicitly include the units attribute; there is no default value. The recommended unit of latitude is degrees...
Check variable(s) that define latitude and are defined correctly according to CF. CF §4.1 Variables representing latitude must always explicitly include the units attribute; there is no default value. The recommended unit of latitude is degrees_north. Also acceptable are degree_north, ...
Below is the the instruction that describes the task: ### Input: Check variable(s) that define latitude and are defined correctly according to CF. CF §4.1 Variables representing latitude must always explicitly include the units attribute; there is no default value. The recommended unit of ...
def add_scripts_to_package(): """ Update the "scripts" parameter of the setup_arguments with any scripts found in the "scripts" directory. :return: """ global setup_arguments if os.path.isdir('scripts'): setup_arguments['scripts'] = [ os.path.join('scripts', f) for f in ...
Update the "scripts" parameter of the setup_arguments with any scripts found in the "scripts" directory. :return:
Below is the the instruction that describes the task: ### Input: Update the "scripts" parameter of the setup_arguments with any scripts found in the "scripts" directory. :return: ### Response: def add_scripts_to_package(): """ Update the "scripts" parameter of the setup_arguments with any scripts ...
def _prepare_read(self, start, stop, frames): """Seek to start frame and calculate length.""" if start != 0 and not self.seekable(): raise ValueError("start is only allowed for seekable files") if frames >= 0 and stop is not None: raise TypeError("Only one of {frames, sto...
Seek to start frame and calculate length.
Below is the the instruction that describes the task: ### Input: Seek to start frame and calculate length. ### Response: def _prepare_read(self, start, stop, frames): """Seek to start frame and calculate length.""" if start != 0 and not self.seekable(): raise ValueError("start is only a...
def list_running_zones(self): """ Returns the currently active relay. :returns: Returns the running relay number or None if no relays are active. :rtype: string """ self.update_controller_info() if self.running is None or not self.running: ...
Returns the currently active relay. :returns: Returns the running relay number or None if no relays are active. :rtype: string
Below is the the instruction that describes the task: ### Input: Returns the currently active relay. :returns: Returns the running relay number or None if no relays are active. :rtype: string ### Response: def list_running_zones(self): """ Returns the currently ac...
def ori(ip, rc=None, r=None, iq=None, ico=None, pl=None, fl=None, fs=None, ot=None, coe=None, moc=None): # pylint: disable=too-many-arguments, redefined-outer-name, invalid-name """ This function is a wrapper for :meth:`~pywbem.WBEMConnection.OpenReferenceInstances`. Open an enumeration ses...
This function is a wrapper for :meth:`~pywbem.WBEMConnection.OpenReferenceInstances`. Open an enumeration session to retrieve the association instances that reference a source instance. Use the :func:`~wbemcli.piwp` function to retrieve the next set of instances or the :func:`~wbcmeli.ce` function...
Below is the the instruction that describes the task: ### Input: This function is a wrapper for :meth:`~pywbem.WBEMConnection.OpenReferenceInstances`. Open an enumeration session to retrieve the association instances that reference a source instance. Use the :func:`~wbemcli.piwp` function to retri...
def clock(self, interval, basis="system"): """Return a NodeInput tuple for triggering an event every interval. Args: interval (int): The interval at which this input should trigger. If basis == system (the default), this interval must be in seconds. Otherwis...
Return a NodeInput tuple for triggering an event every interval. Args: interval (int): The interval at which this input should trigger. If basis == system (the default), this interval must be in seconds. Otherwise it will be in units of whatever the ...
Below is the the instruction that describes the task: ### Input: Return a NodeInput tuple for triggering an event every interval. Args: interval (int): The interval at which this input should trigger. If basis == system (the default), this interval must be in sec...
def _quoteattr(self, attr): """Escape an XML attribute. Value can be unicode.""" attr = xml_safe(attr) if isinstance(attr, unicode) and not UNICODE_STRINGS: attr = attr.encode(self.encoding) return saxutils.quoteattr(attr)
Escape an XML attribute. Value can be unicode.
Below is the the instruction that describes the task: ### Input: Escape an XML attribute. Value can be unicode. ### Response: def _quoteattr(self, attr): """Escape an XML attribute. Value can be unicode.""" attr = xml_safe(attr) if isinstance(attr, unicode) and not UNICODE_STRINGS: ...
def make_coord_dict(subs, subscript_dict, terse=True): """ This is for assisting with the lookup of a particular element, such that the output of this function would take the place of %s in this expression `variable.loc[%s]` Parameters ---------- subs: list of strings coordinates, ...
This is for assisting with the lookup of a particular element, such that the output of this function would take the place of %s in this expression `variable.loc[%s]` Parameters ---------- subs: list of strings coordinates, either as names of dimensions, or positions within a dimension ...
Below is the the instruction that describes the task: ### Input: This is for assisting with the lookup of a particular element, such that the output of this function would take the place of %s in this expression `variable.loc[%s]` Parameters ---------- subs: list of strings coordinates...
def get_changed_devices(self, timestamp): """Get data since last timestamp. This is done via a blocking call, pass NONE for initial state. """ if timestamp is None: payload = {} else: payload = { 'timeout': SUBSCRIPTION_WAIT, ...
Get data since last timestamp. This is done via a blocking call, pass NONE for initial state.
Below is the the instruction that describes the task: ### Input: Get data since last timestamp. This is done via a blocking call, pass NONE for initial state. ### Response: def get_changed_devices(self, timestamp): """Get data since last timestamp. This is done via a blocking call, pass N...
def _get_struct_shapewithstyle(self, shape_number): """Get the values for the SHAPEWITHSTYLE record.""" obj = _make_object("ShapeWithStyle") obj.FillStyles = self._get_struct_fillstylearray(shape_number) obj.LineStyles = self._get_struct_linestylearray(shape_number) bc = BitConsu...
Get the values for the SHAPEWITHSTYLE record.
Below is the the instruction that describes the task: ### Input: Get the values for the SHAPEWITHSTYLE record. ### Response: def _get_struct_shapewithstyle(self, shape_number): """Get the values for the SHAPEWITHSTYLE record.""" obj = _make_object("ShapeWithStyle") obj.FillStyles = self._ge...
def set_index(self, field, value): """ set_index(field, value) Works like :meth:`add_index`, but ensures that there is only one index on given field. If other found, then removes it first. :param field: The index field. :type field: string :param value: ...
set_index(field, value) Works like :meth:`add_index`, but ensures that there is only one index on given field. If other found, then removes it first. :param field: The index field. :type field: string :param value: The index value. :type value: string or integer...
Below is the the instruction that describes the task: ### Input: set_index(field, value) Works like :meth:`add_index`, but ensures that there is only one index on given field. If other found, then removes it first. :param field: The index field. :type field: string ...
def make_inputs(input_file: Optional[str], translator: inference.Translator, input_is_json: bool, input_factors: Optional[List[str]] = None) -> Generator[inference.TranslatorInput, None, None]: """ Generates TranslatorInput instances from input. If input is None, ...
Generates TranslatorInput instances from input. If input is None, reads from stdin. If num_input_factors > 1, the function will look for factors attached to each token, separated by '|'. If source is not None, reads from the source file. If num_source_factors > 1, num_source_factors source factor filenames ...
Below is the the instruction that describes the task: ### Input: Generates TranslatorInput instances from input. If input is None, reads from stdin. If num_input_factors > 1, the function will look for factors attached to each token, separated by '|'. If source is not None, reads from the source file. If nu...
def memoize(func): """ Decorator for unerasable memoization based on function arguments, for functions without keyword arguments. """ class Memoizer(dict): def __missing__(self, args): val = func(*args) self[args] = val return val memory = Memoizer() @wraps(func) def wrapper(*args)...
Decorator for unerasable memoization based on function arguments, for functions without keyword arguments.
Below is the the instruction that describes the task: ### Input: Decorator for unerasable memoization based on function arguments, for functions without keyword arguments. ### Response: def memoize(func): """ Decorator for unerasable memoization based on function arguments, for functions without keyword ar...
def webui(ctx, host, port, cdn, scheduler_rpc, fetcher_rpc, max_rate, max_burst, username, password, need_auth, webui_instance, process_time_limit, get_object=False): """ Run WebUI """ app = load_cls(None, None, webui_instance) g = ctx.obj app.config['taskdb'] = g.taskdb app.confi...
Run WebUI
Below is the the instruction that describes the task: ### Input: Run WebUI ### Response: def webui(ctx, host, port, cdn, scheduler_rpc, fetcher_rpc, max_rate, max_burst, username, password, need_auth, webui_instance, process_time_limit, get_object=False): """ Run WebUI """ app = load_cls(...
def find_vmrun(self): """ Searches for vmrun. :returns: path to vmrun """ # look for vmrun vmrun_path = self.config.get_section_config("VMware").get("vmrun_path") if not vmrun_path: if sys.platform.startswith("win"): vmrun_path = shut...
Searches for vmrun. :returns: path to vmrun
Below is the the instruction that describes the task: ### Input: Searches for vmrun. :returns: path to vmrun ### Response: def find_vmrun(self): """ Searches for vmrun. :returns: path to vmrun """ # look for vmrun vmrun_path = self.config.get_section_confi...
def train_async(train_dataset, eval_dataset, analysis_dir, output_dir, features, model_type, max_steps=5000, num_epochs=None, train_batch_size=100, eval_batch_size=16, ...
Train model locally or in the cloud. Local Training: Args: train_dataset: CsvDataSet eval_dataset: CsvDataSet analysis_dir: The output directory from local_analysis output_dir: Output directory of training. features: file path or features object. Example: { "col_A": {"trans...
Below is the the instruction that describes the task: ### Input: Train model locally or in the cloud. Local Training: Args: train_dataset: CsvDataSet eval_dataset: CsvDataSet analysis_dir: The output directory from local_analysis output_dir: Output directory of training. features: file p...
def commit_input_confirm_timeout(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") commit = ET.Element("commit") config = commit input = ET.SubElement(commit, "input") confirm_timeout = ET.SubElement(input, "confirm-timeout") confir...
Auto Generated Code
Below is the the instruction that describes the task: ### Input: Auto Generated Code ### Response: def commit_input_confirm_timeout(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") commit = ET.Element("commit") config = commit input = ET.SubE...
def encrypt(self, plaintext, nonce, encoder=encoding.RawEncoder): """ Encrypts the plaintext message using the given `nonce` and returns the ciphertext encoded with the encoder. .. warning:: It is **VITALLY** important that the nonce is a nonce, i.e. it is a number used only...
Encrypts the plaintext message using the given `nonce` and returns the ciphertext encoded with the encoder. .. warning:: It is **VITALLY** important that the nonce is a nonce, i.e. it is a number used only once for any given key. If you fail to do this, you compromise the privac...
Below is the the instruction that describes the task: ### Input: Encrypts the plaintext message using the given `nonce` and returns the ciphertext encoded with the encoder. .. warning:: It is **VITALLY** important that the nonce is a nonce, i.e. it is a number used only once for any giv...
def iter_up(self, include_self=True): """Iterates up the tree to the root.""" if include_self: yield self parent = self.parent while parent is not None: yield parent try: parent = parent.parent except AttributeError: ret...
Iterates up the tree to the root.
Below is the the instruction that describes the task: ### Input: Iterates up the tree to the root. ### Response: def iter_up(self, include_self=True): """Iterates up the tree to the root.""" if include_self: yield self parent = self.parent while parent is not None: yield...
async def flush(self, request: Request, stacks: List[Stack]): """ Add a typing stack after each stack. """ ns: List[Stack] = [] for stack in stacks: ns.extend(self.typify(stack)) if len(ns) > 1 and ns[-1] == Stack([lyr.Typing()]): ns[-1].get_lay...
Add a typing stack after each stack.
Below is the the instruction that describes the task: ### Input: Add a typing stack after each stack. ### Response: async def flush(self, request: Request, stacks: List[Stack]): """ Add a typing stack after each stack. """ ns: List[Stack] = [] for stack in stacks: ...
def reduce(self, colors): """Converts color codes into optimized text This optimizer works by merging adjacent colors so we don't have to repeat the same escape codes for each pixel. There is no loss of information. :param colors: Iterable yielding an xterm color code for each...
Converts color codes into optimized text This optimizer works by merging adjacent colors so we don't have to repeat the same escape codes for each pixel. There is no loss of information. :param colors: Iterable yielding an xterm color code for each pixel, None t...
Below is the the instruction that describes the task: ### Input: Converts color codes into optimized text This optimizer works by merging adjacent colors so we don't have to repeat the same escape codes for each pixel. There is no loss of information. :param colors: Iterable yield...
def is_valid_file(path): ''' Returns True if provided file exists and is a file, or False otherwise. ''' return os.path.exists(path) and os.path.isfile(path)
Returns True if provided file exists and is a file, or False otherwise.
Below is the the instruction that describes the task: ### Input: Returns True if provided file exists and is a file, or False otherwise. ### Response: def is_valid_file(path): ''' Returns True if provided file exists and is a file, or False otherwise. ''' return os.path.exists(path) and os.path.isfile(path...
def add_text_mask(self, start, method_str, text_producer): """Adds a handler that produces a plain text response. Parameters ---------- start : string The URL prefix that must be matched to perform this request. method_str : string The HTTP method for wh...
Adds a handler that produces a plain text response. Parameters ---------- start : string The URL prefix that must be matched to perform this request. method_str : string The HTTP method for which to trigger the request. text_producer : function(esrh, ar...
Below is the the instruction that describes the task: ### Input: Adds a handler that produces a plain text response. Parameters ---------- start : string The URL prefix that must be matched to perform this request. method_str : string The HTTP method for whi...
def _check_registry_type(folder=None): """Check if the user has placed a registry_type.txt file to choose the registry type If a default registry type file is found, the DefaultBackingType and DefaultBackingFile class parameters in ComponentRegistry are updated accordingly. Args: folder (strin...
Check if the user has placed a registry_type.txt file to choose the registry type If a default registry type file is found, the DefaultBackingType and DefaultBackingFile class parameters in ComponentRegistry are updated accordingly. Args: folder (string): The folder that we should check for a defa...
Below is the the instruction that describes the task: ### Input: Check if the user has placed a registry_type.txt file to choose the registry type If a default registry type file is found, the DefaultBackingType and DefaultBackingFile class parameters in ComponentRegistry are updated accordingly. Args...
def rolling_update(config=None, name=None, image=None, container_name=None, rc_new=None): """ Performs a simple rolling update of a ReplicationController. See https://github.com/kubernetes/kubernetes/blob/master/docs/design/simple-rolling-update.md for algorithm details. We have modifie...
Performs a simple rolling update of a ReplicationController. See https://github.com/kubernetes/kubernetes/blob/master/docs/design/simple-rolling-update.md for algorithm details. We have modified it slightly to allow for keeping the same RC name between updates, which is not supported by default...
Below is the the instruction that describes the task: ### Input: Performs a simple rolling update of a ReplicationController. See https://github.com/kubernetes/kubernetes/blob/master/docs/design/simple-rolling-update.md for algorithm details. We have modified it slightly to allow for keeping the sa...
def pmtm(x, NW=None, k=None, NFFT=None, e=None, v=None, method='adapt', show=False): """Multitapering spectral estimation :param array x: the data :param float NW: The time half bandwidth parameter (typical values are 2.5,3,3.5,4). Must be provided otherwise the tapering windows and eigen v...
Multitapering spectral estimation :param array x: the data :param float NW: The time half bandwidth parameter (typical values are 2.5,3,3.5,4). Must be provided otherwise the tapering windows and eigen values (outputs of dpss) must be provided :param int k: uses the first k Slepian sequence...
Below is the the instruction that describes the task: ### Input: Multitapering spectral estimation :param array x: the data :param float NW: The time half bandwidth parameter (typical values are 2.5,3,3.5,4). Must be provided otherwise the tapering windows and eigen values (outputs of dpss)...
def _from_dict(cls, _dict): """Initialize a Environment object from a json dictionary.""" args = {} if 'environment_id' in _dict: args['environment_id'] = _dict.get('environment_id') if 'name' in _dict: args['name'] = _dict.get('name') if 'description' in ...
Initialize a Environment object from a json dictionary.
Below is the the instruction that describes the task: ### Input: Initialize a Environment object from a json dictionary. ### Response: def _from_dict(cls, _dict): """Initialize a Environment object from a json dictionary.""" args = {} if 'environment_id' in _dict: args['environm...
def sow(self): ''' Distributes attrributes named in sow_vars from self to each AgentType in the market, storing them in respectively named attributes. Parameters ---------- none Returns ------- none ''' for var_name in self.sow_va...
Distributes attrributes named in sow_vars from self to each AgentType in the market, storing them in respectively named attributes. Parameters ---------- none Returns ------- none
Below is the the instruction that describes the task: ### Input: Distributes attrributes named in sow_vars from self to each AgentType in the market, storing them in respectively named attributes. Parameters ---------- none Returns ------- none ### Response:...
def sha256_file(path): """Calculate sha256 hex digest of a file. :param path: The path of the file you are calculating the digest of. :type path: str :returns: The sha256 hex digest of the specified file. :rtype: builtin_function_or_method """ h = hashlib.sha256() with open(path, 'rb')...
Calculate sha256 hex digest of a file. :param path: The path of the file you are calculating the digest of. :type path: str :returns: The sha256 hex digest of the specified file. :rtype: builtin_function_or_method
Below is the the instruction that describes the task: ### Input: Calculate sha256 hex digest of a file. :param path: The path of the file you are calculating the digest of. :type path: str :returns: The sha256 hex digest of the specified file. :rtype: builtin_function_or_method ### Response: def s...
def nbytes(self): """The number of bytes required to encode this command. Encoded commands are comprised of a two byte opcode, followed by a one byte size, and then the command argument bytes. The size indicates the number of bytes required to represent command arguments. ...
The number of bytes required to encode this command. Encoded commands are comprised of a two byte opcode, followed by a one byte size, and then the command argument bytes. The size indicates the number of bytes required to represent command arguments.
Below is the the instruction that describes the task: ### Input: The number of bytes required to encode this command. Encoded commands are comprised of a two byte opcode, followed by a one byte size, and then the command argument bytes. The size indicates the number of bytes required to re...
def GetMessages(self, formatter_mediator, event): """Determines the formatted message strings for an event object. Args: formatter_mediator (FormatterMediator): mediates the interactions between formatters and other components, such as storage and Windows EventLog resources. eve...
Determines the formatted message strings for an event object. Args: formatter_mediator (FormatterMediator): mediates the interactions between formatters and other components, such as storage and Windows EventLog resources. event (EventObject): event. Returns: tuple(str, s...
Below is the the instruction that describes the task: ### Input: Determines the formatted message strings for an event object. Args: formatter_mediator (FormatterMediator): mediates the interactions between formatters and other components, such as storage and Windows EventLog resource...
def solve_map(expr, vars): """Solves the map-form, by recursively calling its RHS with new vars. let-forms are binary expressions. The LHS should evaluate to an IAssociative that can be used as new vars with which to solve a new query, of which the RHS is the root. In most cases, the LHS will be a Var ...
Solves the map-form, by recursively calling its RHS with new vars. let-forms are binary expressions. The LHS should evaluate to an IAssociative that can be used as new vars with which to solve a new query, of which the RHS is the root. In most cases, the LHS will be a Var (var). Typically, map-forms r...
Below is the the instruction that describes the task: ### Input: Solves the map-form, by recursively calling its RHS with new vars. let-forms are binary expressions. The LHS should evaluate to an IAssociative that can be used as new vars with which to solve a new query, of which the RHS is the root. In...
def set_properties(self, properties, **kwargs): """ :param properties: Property names and values given as key-value pairs of strings :type properties: dict Given key-value pairs in *properties* for property names and values, the properties are set on the project for the given ...
:param properties: Property names and values given as key-value pairs of strings :type properties: dict Given key-value pairs in *properties* for property names and values, the properties are set on the project for the given property names. Any property with a value of :const:`None` ...
Below is the the instruction that describes the task: ### Input: :param properties: Property names and values given as key-value pairs of strings :type properties: dict Given key-value pairs in *properties* for property names and values, the properties are set on the project for the given ...
def augassign_handle(self, tokens): """Process assignments.""" internal_assert(len(tokens) == 3, "invalid assignment tokens", tokens) name, op, item = tokens out = "" if op == "|>=": out += name + " = (" + item + ")(" + name + ")" elif op == "|*>=": ...
Process assignments.
Below is the the instruction that describes the task: ### Input: Process assignments. ### Response: def augassign_handle(self, tokens): """Process assignments.""" internal_assert(len(tokens) == 3, "invalid assignment tokens", tokens) name, op, item = tokens out = "" if op ==...
def add_extra_urls(self, item_session: ItemSession): '''Add additional URLs such as robots.txt, favicon.ico.''' if item_session.url_record.level == 0 and self._sitemaps: extra_url_infos = ( self.parse_url( '{0}://{1}/robots.txt'.format( ...
Add additional URLs such as robots.txt, favicon.ico.
Below is the the instruction that describes the task: ### Input: Add additional URLs such as robots.txt, favicon.ico. ### Response: def add_extra_urls(self, item_session: ItemSession): '''Add additional URLs such as robots.txt, favicon.ico.''' if item_session.url_record.level == 0 and self._sitema...
def get_parent_aligned_annotation(self, ref_id): """" Give the aligment annotation that a reference annotation belongs to directly, or indirectly through other reference annotations. :param str ref_id: Id of a reference annotation. :raises KeyError: If no annotation exists with the id or...
Give the aligment annotation that a reference annotation belongs to directly, or indirectly through other reference annotations. :param str ref_id: Id of a reference annotation. :raises KeyError: If no annotation exists with the id or if it belongs to an alignment annotation. :returns: T...
Below is the the instruction that describes the task: ### Input: Give the aligment annotation that a reference annotation belongs to directly, or indirectly through other reference annotations. :param str ref_id: Id of a reference annotation. :raises KeyError: If no annotation exists with th...
def setup_authentication_methods(authn_config, template_env): """Add all authentication methods specified in the configuration.""" routing = {} ac = AuthnBroker() for authn_method in authn_config: cls = make_cls_from_name(authn_method["class"]) instance = cls(template_env=template_env, *...
Add all authentication methods specified in the configuration.
Below is the the instruction that describes the task: ### Input: Add all authentication methods specified in the configuration. ### Response: def setup_authentication_methods(authn_config, template_env): """Add all authentication methods specified in the configuration.""" routing = {} ac = AuthnBroker(...
def translate(self, instruction): """Return IR representation of an instruction. """ try: trans_instrs = self.__translate(instruction) except NotImplementedError: unkn_instr = self._builder.gen_unkn() unkn_instr.address = instruction.address << 8 | (0x...
Return IR representation of an instruction.
Below is the the instruction that describes the task: ### Input: Return IR representation of an instruction. ### Response: def translate(self, instruction): """Return IR representation of an instruction. """ try: trans_instrs = self.__translate(instruction) except NotImp...
def SetActiveBreakpoints(self, breakpoints_data): """Adds new breakpoints and removes missing ones. Args: breakpoints_data: updated list of active breakpoints. """ with self._lock: ids = set([x['id'] for x in breakpoints_data]) # Clear breakpoints that no longer show up in active bre...
Adds new breakpoints and removes missing ones. Args: breakpoints_data: updated list of active breakpoints.
Below is the the instruction that describes the task: ### Input: Adds new breakpoints and removes missing ones. Args: breakpoints_data: updated list of active breakpoints. ### Response: def SetActiveBreakpoints(self, breakpoints_data): """Adds new breakpoints and removes missing ones. Args: ...
def as_ipywidget(self): """ Provides an IPywidgets player that can be used in a notebook. """ from IPython.display import Audio return Audio(data=self.y, rate=self.sr)
Provides an IPywidgets player that can be used in a notebook.
Below is the the instruction that describes the task: ### Input: Provides an IPywidgets player that can be used in a notebook. ### Response: def as_ipywidget(self): """ Provides an IPywidgets player that can be used in a notebook. """ from IPython.display import Audio return Audio(data=sel...
def del_from_groups(self, username, groups): """Delete user from groups""" # it follows the same logic than add_to_groups # but with MOD_DELETE ldap_client = self._bind() tmp = self._get_user(self._byte_p2(username), ALL_ATTRS) if tmp is None: raise UserDoesnt...
Delete user from groups
Below is the the instruction that describes the task: ### Input: Delete user from groups ### Response: def del_from_groups(self, username, groups): """Delete user from groups""" # it follows the same logic than add_to_groups # but with MOD_DELETE ldap_client = self._bind() t...
def _get_mtime(): """ Get the modified time of the RPM Database. Returns: Unix ticks """ return os.path.exists(RPM_PATH) and int(os.path.getmtime(RPM_PATH)) or 0
Get the modified time of the RPM Database. Returns: Unix ticks
Below is the the instruction that describes the task: ### Input: Get the modified time of the RPM Database. Returns: Unix ticks ### Response: def _get_mtime(): """ Get the modified time of the RPM Database. Returns: Unix ticks """ return os.path.exists(RPM_PATH) and int(os...
def get_list_of_paths(self): """ return a list of unique paths in the file list """ all_paths = [] for p in self.fl_metadata: try: all_paths.append(p['path']) except: try: print('cls_filelist - ...
return a list of unique paths in the file list
Below is the the instruction that describes the task: ### Input: return a list of unique paths in the file list ### Response: def get_list_of_paths(self): """ return a list of unique paths in the file list """ all_paths = [] for p in self.fl_metadata: try: ...
def get_transformed_feature_info(features, schema): """Returns information about the transformed features. Returns: Dict in the from {transformed_feature_name: {dtype: tf type, size: int or None}}. If the size is None, then the tensor is a sparse tensor. """ info = collections.defaultdict(dict) ...
Returns information about the transformed features. Returns: Dict in the from {transformed_feature_name: {dtype: tf type, size: int or None}}. If the size is None, then the tensor is a sparse tensor.
Below is the the instruction that describes the task: ### Input: Returns information about the transformed features. Returns: Dict in the from {transformed_feature_name: {dtype: tf type, size: int or None}}. If the size is None, then the tensor is a sparse tensor. ### Response: def get_transformed_f...
def reset(self, dim): """ Resets / Initializes the hash for the specified dimension. """ if self.dim != dim: self.dim = dim self.normals = self.rand.randn(self.projection_count, dim) self.tree_root = RandomBinaryProjectionTreeNode()
Resets / Initializes the hash for the specified dimension.
Below is the the instruction that describes the task: ### Input: Resets / Initializes the hash for the specified dimension. ### Response: def reset(self, dim): """ Resets / Initializes the hash for the specified dimension. """ if self.dim != dim: self.dim = dim self.normals ...
def show_subnetpool(self, subnetpool, **_params): """Fetches information of a certain subnetpool.""" return self.get(self.subnetpool_path % (subnetpool), params=_params)
Fetches information of a certain subnetpool.
Below is the the instruction that describes the task: ### Input: Fetches information of a certain subnetpool. ### Response: def show_subnetpool(self, subnetpool, **_params): """Fetches information of a certain subnetpool.""" return self.get(self.subnetpool_path % (subnetpool), params=_params)
def wigner_d_small(J, beta): u"""Return the small Wigner d matrix for angular momentum J. We use the general formula from [Edmonds74]_, equation 4.1.15. Some examples form [Edmonds74]_: >>> from sympy import Integer, symbols, pi >>> half = 1/Integer(2) >>> beta = symbols("beta", real=True) ...
u"""Return the small Wigner d matrix for angular momentum J. We use the general formula from [Edmonds74]_, equation 4.1.15. Some examples form [Edmonds74]_: >>> from sympy import Integer, symbols, pi >>> half = 1/Integer(2) >>> beta = symbols("beta", real=True) >>> wigner_d_small(half, beta) ...
Below is the the instruction that describes the task: ### Input: u"""Return the small Wigner d matrix for angular momentum J. We use the general formula from [Edmonds74]_, equation 4.1.15. Some examples form [Edmonds74]_: >>> from sympy import Integer, symbols, pi >>> half = 1/Integer(2) >>> ...
def cmd_iter( self, tgt, fun, arg=(), timeout=None, tgt_type='glob', ret='', kwarg=None, **kwargs): ''' Execute a single command via the salt-ssh subsystem and return a generator ...
Execute a single command via the salt-ssh subsystem and return a generator .. versionadded:: 2015.5.0
Below is the the instruction that describes the task: ### Input: Execute a single command via the salt-ssh subsystem and return a generator .. versionadded:: 2015.5.0 ### Response: def cmd_iter( self, tgt, fun, arg=(), timeout=None, ...
def push_header(self, filename): """ Push the header to a given filename :param filename: the file path to push into. """ # open file and read it all with open(filename, "r") as infile: content = infile.read() # push header content = self.__he...
Push the header to a given filename :param filename: the file path to push into.
Below is the the instruction that describes the task: ### Input: Push the header to a given filename :param filename: the file path to push into. ### Response: def push_header(self, filename): """ Push the header to a given filename :param filename: the file path to push into. ...
def add_object_file(self, obj_file): """ Add object file to the jit. object_file can be instance of :class:ObjectFile or a string representing file system path """ if isinstance(obj_file, str): obj_file = object_file.ObjectFileRef.from_path(obj_file) ffi.lib....
Add object file to the jit. object_file can be instance of :class:ObjectFile or a string representing file system path
Below is the the instruction that describes the task: ### Input: Add object file to the jit. object_file can be instance of :class:ObjectFile or a string representing file system path ### Response: def add_object_file(self, obj_file): """ Add object file to the jit. object_file can be insta...
def validate_properties(self, model, context=None): """ Validate simple properties Performs validation on simple properties to return a result object. :param model: object or dict :param context: object, dict or None :return: shiftschema.result.Result """ ...
Validate simple properties Performs validation on simple properties to return a result object. :param model: object or dict :param context: object, dict or None :return: shiftschema.result.Result
Below is the the instruction that describes the task: ### Input: Validate simple properties Performs validation on simple properties to return a result object. :param model: object or dict :param context: object, dict or None :return: shiftschema.result.Result ### Response: def val...
def report(self, req): """Adds a report request to the cache. Returns ``None`` if it could not be aggregated, and callers need to send the request to the server, otherwise it returns ``CACHED_OK``. Args: req (:class:`sc_messages.ReportRequest`): the request to b...
Adds a report request to the cache. Returns ``None`` if it could not be aggregated, and callers need to send the request to the server, otherwise it returns ``CACHED_OK``. Args: req (:class:`sc_messages.ReportRequest`): the request to be aggregated Result: ...
Below is the the instruction that describes the task: ### Input: Adds a report request to the cache. Returns ``None`` if it could not be aggregated, and callers need to send the request to the server, otherwise it returns ``CACHED_OK``. Args: req (:class:`sc_messages.ReportReque...
def save(yaml_dict, filepath): ''' Save YAML settings to the specified file path. ''' yamldict.dump(yaml_dict, open(filepath, 'w'), default_flow_style=False)
Save YAML settings to the specified file path.
Below is the the instruction that describes the task: ### Input: Save YAML settings to the specified file path. ### Response: def save(yaml_dict, filepath): ''' Save YAML settings to the specified file path. ''' yamldict.dump(yaml_dict, open(filepath, 'w'), default_flow_style=False)
def put(self, file_path, upload_path = ''): """PUT Args: file_path: Full path for a file you want to upload upload_path: Ndrive path where you want to upload file ex) /Picture/ Returns: True: Upload success False: Upload failed ...
PUT Args: file_path: Full path for a file you want to upload upload_path: Ndrive path where you want to upload file ex) /Picture/ Returns: True: Upload success False: Upload failed
Below is the the instruction that describes the task: ### Input: PUT Args: file_path: Full path for a file you want to upload upload_path: Ndrive path where you want to upload file ex) /Picture/ Returns: True: Upload success False: Up...
def once(dispatcher, event, handle, *args): """ Used to do a mapping like event -> handle but handle is called just once upon event. """ def shell(dispatcher, *args): try: handle(dispatcher, *args) except Exception as e: raise e finally: d...
Used to do a mapping like event -> handle but handle is called just once upon event.
Below is the the instruction that describes the task: ### Input: Used to do a mapping like event -> handle but handle is called just once upon event. ### Response: def once(dispatcher, event, handle, *args): """ Used to do a mapping like event -> handle but handle is called just once upon event. ...