code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
text
stringlengths
164
112k
def get_sender(self, message_timeout=0, session=None, **kwargs): """Get a Sender for the Service Bus endpoint. A Sender represents a single open connection within which multiple send operations can be made. :param message_timeout: The period in seconds during which messages sent with ...
Get a Sender for the Service Bus endpoint. A Sender represents a single open connection within which multiple send operations can be made. :param message_timeout: The period in seconds during which messages sent with this Sender must be sent. If the send is not completed in this time it will ...
Below is the the instruction that describes the task: ### Input: Get a Sender for the Service Bus endpoint. A Sender represents a single open connection within which multiple send operations can be made. :param message_timeout: The period in seconds during which messages sent with this Se...
def main(net): ''' calculate pvalue of category closeness ''' # calculate the distance between the data points within the same category and # compare to null distribution for inst_rc in ['row', 'col']: inst_nodes = deepcopy(net.dat['nodes'][inst_rc]) inst_index = deepcopy(net.dat['node_info'][inst...
calculate pvalue of category closeness
Below is the the instruction that describes the task: ### Input: calculate pvalue of category closeness ### Response: def main(net): ''' calculate pvalue of category closeness ''' # calculate the distance between the data points within the same category and # compare to null distribution for inst_rc in...
def reloader_thread(softexit=False): """If ``soft_exit`` is True, we use sys.exit(); otherwise ``os_exit`` will be used to end the process. """ while RUN_RELOADER: if code_changed(): # force reload if softexit: sys.exit(3) else: ...
If ``soft_exit`` is True, we use sys.exit(); otherwise ``os_exit`` will be used to end the process.
Below is the the instruction that describes the task: ### Input: If ``soft_exit`` is True, we use sys.exit(); otherwise ``os_exit`` will be used to end the process. ### Response: def reloader_thread(softexit=False): """If ``soft_exit`` is True, we use sys.exit(); otherwise ``os_exit`` will be used to e...
def banner(): """ Display a product banner :return: a delightful Mesosphere logo rendered in unicode :rtype: str """ banner_dict = { 'a0': click.style(chr(9601), fg='magenta'), 'a1': click.style(chr(9601), fg='magenta', bold=True), 'b0': click.style(chr(9616), fg='m...
Display a product banner :return: a delightful Mesosphere logo rendered in unicode :rtype: str
Below is the the instruction that describes the task: ### Input: Display a product banner :return: a delightful Mesosphere logo rendered in unicode :rtype: str ### Response: def banner(): """ Display a product banner :return: a delightful Mesosphere logo rendered in unicode :r...
def main(): """Print the RedBaron syntax tree for a Python module.""" parser = argparse.ArgumentParser( description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter ) parser.add_argument("path", help="Python module path") args = parser.parse_args() r = d1_dev.util.redbaron_...
Print the RedBaron syntax tree for a Python module.
Below is the the instruction that describes the task: ### Input: Print the RedBaron syntax tree for a Python module. ### Response: def main(): """Print the RedBaron syntax tree for a Python module.""" parser = argparse.ArgumentParser( description=__doc__, formatter_class=argparse.RawDescriptionHelp...
def diag_ksl(A, y0, tau, verb=1, scheme='symm', space=8, rmax=2000): """ Dynamical tensor-train approximation based on projector splitting This function performs one step of dynamical tensor-train approximation with diagonal matrix, i.e. it solves the equation for the equation .. math :: ...
Dynamical tensor-train approximation based on projector splitting This function performs one step of dynamical tensor-train approximation with diagonal matrix, i.e. it solves the equation for the equation .. math :: \\frac{dy}{dt} = V y, \\quad y(0) = y_0 and outputs approx...
Below is the the instruction that describes the task: ### Input: Dynamical tensor-train approximation based on projector splitting This function performs one step of dynamical tensor-train approximation with diagonal matrix, i.e. it solves the equation for the equation .. math :: ...
def find_file(self, path, tgt_env): ''' Find the specified file in the specified environment ''' tree = self.get_tree(tgt_env) if not tree: # Branch/tag/SHA not found in repo return None, None, None blob = None depth = 0 while True:...
Find the specified file in the specified environment
Below is the the instruction that describes the task: ### Input: Find the specified file in the specified environment ### Response: def find_file(self, path, tgt_env): ''' Find the specified file in the specified environment ''' tree = self.get_tree(tgt_env) if not tree: ...
def initialize_model(self, root_node): """ Initializes the Model using given root node. :param root_node: Graph root node. :type root_node: DefaultNode :return: Method success :rtype: bool """ LOGGER.debug("> Initializing model with '{0}' root node.".for...
Initializes the Model using given root node. :param root_node: Graph root node. :type root_node: DefaultNode :return: Method success :rtype: bool
Below is the the instruction that describes the task: ### Input: Initializes the Model using given root node. :param root_node: Graph root node. :type root_node: DefaultNode :return: Method success :rtype: bool ### Response: def initialize_model(self, root_node): """ ...
def get_service_password(service, username, oracle=None, interactive=False): """ Retrieve the sensitive password for a service by: * retrieving password from a secure store (@oracle:use_keyring, default) * asking the password from the user (@oracle:ask_password, interactive) * executing a com...
Retrieve the sensitive password for a service by: * retrieving password from a secure store (@oracle:use_keyring, default) * asking the password from the user (@oracle:ask_password, interactive) * executing a command and use the output as password (@oracle:eval:<command>) Note that the k...
Below is the the instruction that describes the task: ### Input: Retrieve the sensitive password for a service by: * retrieving password from a secure store (@oracle:use_keyring, default) * asking the password from the user (@oracle:ask_password, interactive) * executing a command and use the out...
def debug_validator(validator: ValidatorType) -> ValidatorType: """ Use as a wrapper around a validator, e.g. .. code-block:: python self.validator = debug_validator(OneOf(["some", "values"])) If you do this, the log will show the thinking of the validator (what it's trying to validate, a...
Use as a wrapper around a validator, e.g. .. code-block:: python self.validator = debug_validator(OneOf(["some", "values"])) If you do this, the log will show the thinking of the validator (what it's trying to validate, and whether it accepted or rejected the value).
Below is the the instruction that describes the task: ### Input: Use as a wrapper around a validator, e.g. .. code-block:: python self.validator = debug_validator(OneOf(["some", "values"])) If you do this, the log will show the thinking of the validator (what it's trying to validate, and whet...
def launch_experiment(args, experiment_config, mode, config_file_name, experiment_id=None): '''follow steps to start rest server and start experiment''' nni_config = Config(config_file_name) # check packages for tuner if experiment_config.get('tuner') and experiment_config['tuner'].get('builtinTunerName...
follow steps to start rest server and start experiment
Below is the the instruction that describes the task: ### Input: follow steps to start rest server and start experiment ### Response: def launch_experiment(args, experiment_config, mode, config_file_name, experiment_id=None): '''follow steps to start rest server and start experiment''' nni_config = Config(...
def categories(self): ''' List of categories of a page. ''' if not getattr(self, '_categories', False): self._categories = [re.sub(r'^Category:', '', x) for x in [link['title'] for link in self.__continued_query({ 'prop': 'categories', 'cllimit': 'max' ...
List of categories of a page.
Below is the the instruction that describes the task: ### Input: List of categories of a page. ### Response: def categories(self): ''' List of categories of a page. ''' if not getattr(self, '_categories', False): self._categories = [re.sub(r'^Category:', '', x) for x in [link['title'...
def _fix_weights(weight_fun, *args): """Ensure random weight matrix is valid. TODO: The diagonally dominant tuning currently doesn't make sense. Our weight matrix has zeros along the diagonal, so multiplying by a diagonal matrix results in a zero-matrix. """ weights = weight_fun(...
Ensure random weight matrix is valid. TODO: The diagonally dominant tuning currently doesn't make sense. Our weight matrix has zeros along the diagonal, so multiplying by a diagonal matrix results in a zero-matrix.
Below is the the instruction that describes the task: ### Input: Ensure random weight matrix is valid. TODO: The diagonally dominant tuning currently doesn't make sense. Our weight matrix has zeros along the diagonal, so multiplying by a diagonal matrix results in a zero-matrix. ### Resp...
def safe_indicator(self, indicator, errors='strict'): """Indicator encode value for safe HTTP request. Args: indicator (string): Indicator to URL Encode errors (string): The error handler type. Returns: (string): The urlencoded string """ if ...
Indicator encode value for safe HTTP request. Args: indicator (string): Indicator to URL Encode errors (string): The error handler type. Returns: (string): The urlencoded string
Below is the the instruction that describes the task: ### Input: Indicator encode value for safe HTTP request. Args: indicator (string): Indicator to URL Encode errors (string): The error handler type. Returns: (string): The urlencoded string ### Response: def ...
def _effective_view_filter(self): """Returns the mongodb relationship filter for effective views""" if self._effective_view == EFFECTIVE: now = datetime.datetime.utcnow() return {'startDate': {'$$lte': now}, 'endDate': {'$$gte': now}} return {}
Returns the mongodb relationship filter for effective views
Below is the the instruction that describes the task: ### Input: Returns the mongodb relationship filter for effective views ### Response: def _effective_view_filter(self): """Returns the mongodb relationship filter for effective views""" if self._effective_view == EFFECTIVE: now = date...
def run(self, host: str = "0.0.0.0", port: int = 5000) -> None: """ debug run :param host: the hostname to listen on, default is ``'0.0.0.0'`` :param port: the port of the server, default id ``5000`` """ loop = cast(asyncio.AbstractEventLoop, self._loop) listen = ...
debug run :param host: the hostname to listen on, default is ``'0.0.0.0'`` :param port: the port of the server, default id ``5000``
Below is the the instruction that describes the task: ### Input: debug run :param host: the hostname to listen on, default is ``'0.0.0.0'`` :param port: the port of the server, default id ``5000`` ### Response: def run(self, host: str = "0.0.0.0", port: int = 5000) -> None: """ debu...
def could_scope_out(self): """ could bubble up from current scope :return: """ return not self.waiting_for or \ isinstance(self.waiting_for, callable.EndOfStory) or \ self.is_breaking_a_loop()
could bubble up from current scope :return:
Below is the the instruction that describes the task: ### Input: could bubble up from current scope :return: ### Response: def could_scope_out(self): """ could bubble up from current scope :return: """ return not self.waiting_for or \ isinstance(self...
def upath(path): """ Always return a unicode path. """ if six.PY2 and not isinstance(path, six.text_type): return path.decode(fs_encoding) return path
Always return a unicode path.
Below is the the instruction that describes the task: ### Input: Always return a unicode path. ### Response: def upath(path): """ Always return a unicode path. """ if six.PY2 and not isinstance(path, six.text_type): return path.decode(fs_encoding) return path
def _prepare_facet_field_spies(self, facets): """ Returns a list of spies based on the facets used to count frequencies. """ spies = [] for facet in facets: slot = self.column[facet] spy = xapian.ValueCountMatchSpy(slot) # add attribute...
Returns a list of spies based on the facets used to count frequencies.
Below is the the instruction that describes the task: ### Input: Returns a list of spies based on the facets used to count frequencies. ### Response: def _prepare_facet_field_spies(self, facets): """ Returns a list of spies based on the facets used to count frequencies. """ ...
def get_me(self, *args, **kwargs): """See :func:`get_me`""" return get_me(*args, **self._merge_overrides(**kwargs)).run()
See :func:`get_me`
Below is the the instruction that describes the task: ### Input: See :func:`get_me` ### Response: def get_me(self, *args, **kwargs): """See :func:`get_me`""" return get_me(*args, **self._merge_overrides(**kwargs)).run()
def create_or_update(ctx, model, xmlid, values): """ Create or update a record matching xmlid with values """ if isinstance(model, basestring): model = ctx.env[model] record = ctx.env.ref(xmlid, raise_if_not_found=False) if record: record.update(values) else: record = model....
Create or update a record matching xmlid with values
Below is the the instruction that describes the task: ### Input: Create or update a record matching xmlid with values ### Response: def create_or_update(ctx, model, xmlid, values): """ Create or update a record matching xmlid with values """ if isinstance(model, basestring): model = ctx.env[model] ...
def show_context_menu(self, item, mouse_pos=None): "Open a popup menu with options regarding the selected object" if item: d = self.tree.GetItemData(item) if d: obj = d.GetData() if obj: # highligh and store the selected object:...
Open a popup menu with options regarding the selected object
Below is the the instruction that describes the task: ### Input: Open a popup menu with options regarding the selected object ### Response: def show_context_menu(self, item, mouse_pos=None): "Open a popup menu with options regarding the selected object" if item: d = self.tree.GetItemDat...
def _get_dvportgroup_out_shaping(pg_name, pg_default_port_config): ''' Returns the out shaping policy of a distributed virtual portgroup pg_name The name of the portgroup pg_default_port_config The dafault port config of the portgroup ''' log.trace('Retrieving portgroup\'s \'%s...
Returns the out shaping policy of a distributed virtual portgroup pg_name The name of the portgroup pg_default_port_config The dafault port config of the portgroup
Below is the the instruction that describes the task: ### Input: Returns the out shaping policy of a distributed virtual portgroup pg_name The name of the portgroup pg_default_port_config The dafault port config of the portgroup ### Response: def _get_dvportgroup_out_shaping(pg_name, pg_d...
def set_params(self, arg_params, aux_params, allow_missing=False, force_init=True, allow_extra=False): """Assigns parameter and aux state values. Parameters ---------- arg_params : dict Dictionary of name to value (`NDArray`) mapping. aux_params : ...
Assigns parameter and aux state values. Parameters ---------- arg_params : dict Dictionary of name to value (`NDArray`) mapping. aux_params : dict Dictionary of name to value (`NDArray`) mapping. allow_missing : bool If ``True``, params could ...
Below is the the instruction that describes the task: ### Input: Assigns parameter and aux state values. Parameters ---------- arg_params : dict Dictionary of name to value (`NDArray`) mapping. aux_params : dict Dictionary of name to value (`NDArray`) mapping...
def folder_get(self, token, folder_id): """ Get the attributes of the specified folder. :param token: A valid token for the user in question. :type token: string :param folder_id: The id of the requested folder. :type folder_id: int | long :returns: Dictionary of...
Get the attributes of the specified folder. :param token: A valid token for the user in question. :type token: string :param folder_id: The id of the requested folder. :type folder_id: int | long :returns: Dictionary of the folder attributes. :rtype: dict
Below is the the instruction that describes the task: ### Input: Get the attributes of the specified folder. :param token: A valid token for the user in question. :type token: string :param folder_id: The id of the requested folder. :type folder_id: int | long :returns: Dict...
def logL(self, kwargs_lens, kwargs_ps, kwargs_cosmo): """ routine to compute the log likelihood of the time delay distance :param kwargs_lens: lens model kwargs list :param kwargs_ps: point source kwargs list :param kwargs_cosmo: cosmology and other kwargs :return: log li...
routine to compute the log likelihood of the time delay distance :param kwargs_lens: lens model kwargs list :param kwargs_ps: point source kwargs list :param kwargs_cosmo: cosmology and other kwargs :return: log likelihood of the model given the time delay data
Below is the the instruction that describes the task: ### Input: routine to compute the log likelihood of the time delay distance :param kwargs_lens: lens model kwargs list :param kwargs_ps: point source kwargs list :param kwargs_cosmo: cosmology and other kwargs :return: log likelih...
def shutdown(self, join=True, timeout=None): """ Clean shutdown of the node. :param join: optionally wait for the process to end (default : True) :return: last exitcode from update method """ if self.interface is not None: self.interface.stop() return...
Clean shutdown of the node. :param join: optionally wait for the process to end (default : True) :return: last exitcode from update method
Below is the the instruction that describes the task: ### Input: Clean shutdown of the node. :param join: optionally wait for the process to end (default : True) :return: last exitcode from update method ### Response: def shutdown(self, join=True, timeout=None): """ Clean shutdown o...
def install(name=None, refresh=False, skip_verify=False, pkgs=None, sources=None, downloadonly=False, reinstall=False, normalize=True, update_holds=False, saltenv='base', ignore_epoch=False, ...
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0 On minions running systemd>=205, `systemd-run(1)`_ is now used to isolate commands which modify installed packages from the ``salt-minion`` daemon's control group. This is done to keep systemd from killing any yum/dnf commands spawned by S...
Below is the the instruction that describes the task: ### Input: .. versionchanged:: 2015.8.12,2016.3.3,2016.11.0 On minions running systemd>=205, `systemd-run(1)`_ is now used to isolate commands which modify installed packages from the ``salt-minion`` daemon's control group. This is done t...
def compose(*funcs): """ chained function composition wrapper creates function f, where f(x) = arg0(arg1(arg2(...argN(x)))) if *funcs is empty, an identity function is returned. Args: *funcs: list of functions to chain Returns: a new function composed of chained calls to ...
chained function composition wrapper creates function f, where f(x) = arg0(arg1(arg2(...argN(x)))) if *funcs is empty, an identity function is returned. Args: *funcs: list of functions to chain Returns: a new function composed of chained calls to *args
Below is the the instruction that describes the task: ### Input: chained function composition wrapper creates function f, where f(x) = arg0(arg1(arg2(...argN(x)))) if *funcs is empty, an identity function is returned. Args: *funcs: list of functions to chain Returns: a new fu...
def encrypt_file(self, path, output_path=None, overwrite=False, enable_verbose=True): """ Encrypt a file using rsa. RSA for big file encryption is very slow. For big file, I recommend to use symmetric en...
Encrypt a file using rsa. RSA for big file encryption is very slow. For big file, I recommend to use symmetric encryption and use RSA to encrypt the password.
Below is the the instruction that describes the task: ### Input: Encrypt a file using rsa. RSA for big file encryption is very slow. For big file, I recommend to use symmetric encryption and use RSA to encrypt the password. ### Response: def encrypt_file(self, path, ...
def find_duplicates_in_dirs(directories, exclude_dirs=None, exclude_files=None, follow_dirlinks=False): """Recursively scan a list of directories, looking for duplicate files. `exclude_dirs`, if provided, should be a list of glob patterns. Subdirectories whose names match these patterns are exclude...
Recursively scan a list of directories, looking for duplicate files. `exclude_dirs`, if provided, should be a list of glob patterns. Subdirectories whose names match these patterns are excluded from the scan. `exclude_files`, if provided, should be a list of glob patterns. Files whose names match ...
Below is the the instruction that describes the task: ### Input: Recursively scan a list of directories, looking for duplicate files. `exclude_dirs`, if provided, should be a list of glob patterns. Subdirectories whose names match these patterns are excluded from the scan. `exclude_files`, if prov...
def GetServices(): """ Obtains all the connected eDNA services. :return: A pandas DataFrame of connected eDNA services in the form [Name, Description, Type, Status] """ # Define all required variables in the correct ctypes format pulKey = c_ulong(0) szType = c_char_p("".enc...
Obtains all the connected eDNA services. :return: A pandas DataFrame of connected eDNA services in the form [Name, Description, Type, Status]
Below is the the instruction that describes the task: ### Input: Obtains all the connected eDNA services. :return: A pandas DataFrame of connected eDNA services in the form [Name, Description, Type, Status] ### Response: def GetServices(): """ Obtains all the connected eDNA services. ...
def package_load_instructions(inst_distributions): """Load instructions, displayed in the package notes""" per_package_inst = '' for dist in inst_distributions: if dist.type == 'zip': per_package_inst += dedent( """ # Loading the ZIP Package ...
Load instructions, displayed in the package notes
Below is the the instruction that describes the task: ### Input: Load instructions, displayed in the package notes ### Response: def package_load_instructions(inst_distributions): """Load instructions, displayed in the package notes""" per_package_inst = '' for dist in inst_distributions: if...
def _req(self): """ List of required fields for each template. Format is [tmpl_idx, "all"|"any", [req_field_1, req_field_2, ...]]. Partial reimplementation of req computing logic from Anki. We use pystache instead of Anki's custom mustache implementation. The goal is to figure out which fields are...
List of required fields for each template. Format is [tmpl_idx, "all"|"any", [req_field_1, req_field_2, ...]]. Partial reimplementation of req computing logic from Anki. We use pystache instead of Anki's custom mustache implementation. The goal is to figure out which fields are "required", i.e. if they ar...
Below is the the instruction that describes the task: ### Input: List of required fields for each template. Format is [tmpl_idx, "all"|"any", [req_field_1, req_field_2, ...]]. Partial reimplementation of req computing logic from Anki. We use pystache instead of Anki's custom mustache implementation. T...
def stats(self, input_filepath): '''Display time domain statistical information about the audio channels. Audio is passed unmodified through the SoX processing chain. Statistics are calculated and displayed for each audio channel Unlike other Transformer methods, this does not modify th...
Display time domain statistical information about the audio channels. Audio is passed unmodified through the SoX processing chain. Statistics are calculated and displayed for each audio channel Unlike other Transformer methods, this does not modify the transformer effects chain. Instead...
Below is the the instruction that describes the task: ### Input: Display time domain statistical information about the audio channels. Audio is passed unmodified through the SoX processing chain. Statistics are calculated and displayed for each audio channel Unlike other Transformer methods...
def GetRosettaResidueMap(self, ConvertMSEToAtom = False, RemoveIncompleteFinalResidues = False, RemoveIncompleteResidues = False): '''Note: This function ignores any DNA.''' raise Exception('This code looks to be deprecated. Use construct_pdb_to_rosetta_residue_map instead.') chain = None ...
Note: This function ignores any DNA.
Below is the the instruction that describes the task: ### Input: Note: This function ignores any DNA. ### Response: def GetRosettaResidueMap(self, ConvertMSEToAtom = False, RemoveIncompleteFinalResidues = False, RemoveIncompleteResidues = False): '''Note: This function ignores any DNA.''' raise Exc...
async def on_connect(self): """ Initialize the connection, authenticate and select a database and send READONLY if it is set during object initialization. """ if self.db: warnings.warn('SELECT DB is not allowed in cluster mode') self.db = '' await ...
Initialize the connection, authenticate and select a database and send READONLY if it is set during object initialization.
Below is the the instruction that describes the task: ### Input: Initialize the connection, authenticate and select a database and send READONLY if it is set during object initialization. ### Response: async def on_connect(self): """ Initialize the connection, authenticate and select a data...
def get_summary_files(dirnames): """Gets the TeX summary files for each test. :param dirnames: the list of directories to merge data from. :type dirnames: list :returns: a list of summary file names. :rtype: list """ # A useful regular expression to get step number in the current directo...
Gets the TeX summary files for each test. :param dirnames: the list of directories to merge data from. :type dirnames: list :returns: a list of summary file names. :rtype: list
Below is the the instruction that describes the task: ### Input: Gets the TeX summary files for each test. :param dirnames: the list of directories to merge data from. :type dirnames: list :returns: a list of summary file names. :rtype: list ### Response: def get_summary_files(dirnames): """...
def write_branch_data(self, file): """ Writes branch data to an Excel spreadsheet. """ branch_sheet = self.book.add_sheet("Branches") for i, branch in enumerate(self.case.branches): for j, attr in enumerate(BRANCH_ATTRS): branch_sheet.write(i, j, getattr(bran...
Writes branch data to an Excel spreadsheet.
Below is the the instruction that describes the task: ### Input: Writes branch data to an Excel spreadsheet. ### Response: def write_branch_data(self, file): """ Writes branch data to an Excel spreadsheet. """ branch_sheet = self.book.add_sheet("Branches") for i, branch in enumerat...
def login(self, command='su -', user=None, password=None, prompt_prefix=None, expect=None, timeout=shutit_global.shutit_global_object.default_timeout, escape=False, echo=None, note=None, go_home=True, ...
Logs user in on default child.
Below is the the instruction that describes the task: ### Input: Logs user in on default child. ### Response: def login(self, command='su -', user=None, password=None, prompt_prefix=None, expect=None, timeout=shutit_global.shutit_global_object.defau...
def salience(S, freqs, h_range, weights=None, aggregate=None, filter_peaks=True, fill_value=np.nan, kind='linear', axis=0): """Harmonic salience function. Parameters ---------- S : np.ndarray [shape=(d, n)] input time frequency magnitude representation (stft, ifgram, etc). ...
Harmonic salience function. Parameters ---------- S : np.ndarray [shape=(d, n)] input time frequency magnitude representation (stft, ifgram, etc). Must be real-valued and non-negative. freqs : np.ndarray, shape=(S.shape[axis]) The frequency values corresponding to S's elements a...
Below is the the instruction that describes the task: ### Input: Harmonic salience function. Parameters ---------- S : np.ndarray [shape=(d, n)] input time frequency magnitude representation (stft, ifgram, etc). Must be real-valued and non-negative. freqs : np.ndarray, shape=(S.shap...
def do_forceescape(value): """Enforce HTML escaping. This will probably double escape variables.""" if hasattr(value, '__html__'): value = value.__html__() return escape(text_type(value))
Enforce HTML escaping. This will probably double escape variables.
Below is the the instruction that describes the task: ### Input: Enforce HTML escaping. This will probably double escape variables. ### Response: def do_forceescape(value): """Enforce HTML escaping. This will probably double escape variables.""" if hasattr(value, '__html__'): value = value.__html...
def list_nodes_full(call=None): ''' Return a list of the BareMetal servers that are on the provider. ''' if call == 'action': raise SaltCloudSystemExit( 'list_nodes_full must be called with -f or --function' ) items = query(method='servers') # For each server, iterate o...
Return a list of the BareMetal servers that are on the provider.
Below is the the instruction that describes the task: ### Input: Return a list of the BareMetal servers that are on the provider. ### Response: def list_nodes_full(call=None): ''' Return a list of the BareMetal servers that are on the provider. ''' if call == 'action': raise SaltCloudSystemExit...
def calcuate_bboxes(im_shape, patch_size): """Calculate bound boxes based on image shape and size of the bounding box given by `patch_size`""" h, w = im_shape ph, pw = patch_size steps_h = chain(range(0, h - ph, ph), [h - ph]) steps_w = chain(range(0, w - pw, pw), [w - pw]) return product(...
Calculate bound boxes based on image shape and size of the bounding box given by `patch_size`
Below is the the instruction that describes the task: ### Input: Calculate bound boxes based on image shape and size of the bounding box given by `patch_size` ### Response: def calcuate_bboxes(im_shape, patch_size): """Calculate bound boxes based on image shape and size of the bounding box given by `pa...
def drawHotspots(self, painter): """ Draws all the hotspots for the renderer. :param painter | <QPaint> """ # draw hotspots for hotspot in (self._hotspots + self._dropzones): hstyle = hotspot.style() if hstyle == XNode.HotspotStyle.In...
Draws all the hotspots for the renderer. :param painter | <QPaint>
Below is the the instruction that describes the task: ### Input: Draws all the hotspots for the renderer. :param painter | <QPaint> ### Response: def drawHotspots(self, painter): """ Draws all the hotspots for the renderer. :param painter | <QPaint> ...
def unpack(self, token): """ Unpack a received signed or signed and encrypted Json Web Token :param token: The Json Web Token :return: If decryption and signature verification work the payload will be returned as a Message instance if possible. """ if not tok...
Unpack a received signed or signed and encrypted Json Web Token :param token: The Json Web Token :return: If decryption and signature verification work the payload will be returned as a Message instance if possible.
Below is the the instruction that describes the task: ### Input: Unpack a received signed or signed and encrypted Json Web Token :param token: The Json Web Token :return: If decryption and signature verification work the payload will be returned as a Message instance if possible. ### Re...
def translate_alias(self, alias, namespace=None, target_namespaces=None, translate_ncbi_namespace=None): """given an alias and optional namespace, return a list of all other aliases for same sequence """ if translate_ncbi_namespace is None: translate_ncbi_namespace = self.t...
given an alias and optional namespace, return a list of all other aliases for same sequence
Below is the the instruction that describes the task: ### Input: given an alias and optional namespace, return a list of all other aliases for same sequence ### Response: def translate_alias(self, alias, namespace=None, target_namespaces=None, translate_ncbi_namespace=None): """given an alias and o...
def _make_unique_title(self, title): """Make the title unique. Adds a counter to the title to prevent duplicates. Prior to IDA 6.8, two graphs with the same title could crash IDA. This has been fixed (https://www.hex-rays.com/products/ida/6.8/index.shtml). The code will not cha...
Make the title unique. Adds a counter to the title to prevent duplicates. Prior to IDA 6.8, two graphs with the same title could crash IDA. This has been fixed (https://www.hex-rays.com/products/ida/6.8/index.shtml). The code will not change for support of older versions and as it is ...
Below is the the instruction that describes the task: ### Input: Make the title unique. Adds a counter to the title to prevent duplicates. Prior to IDA 6.8, two graphs with the same title could crash IDA. This has been fixed (https://www.hex-rays.com/products/ida/6.8/index.shtml). ...
def _env_runner(base_env, extra_batch_callback, policies, policy_mapping_fn, unroll_length, horizon, preprocessors, obs_filters, clip_rewards, clip_actions, pack, callbacks, tf_sess, perf_stats, soft_horizon): """This implements the common experience collection logic....
This implements the common experience collection logic. Args: base_env (BaseEnv): env implementing BaseEnv. extra_batch_callback (fn): function to send extra batch data to. policies (dict): Map of policy ids to PolicyGraph instances. policy_mapping_fn (func): Function that maps agen...
Below is the the instruction that describes the task: ### Input: This implements the common experience collection logic. Args: base_env (BaseEnv): env implementing BaseEnv. extra_batch_callback (fn): function to send extra batch data to. policies (dict): Map of policy ids to PolicyGraph...
def ScanForWindowsVolume(self, source_path): """Scans for a Windows volume. Args: source_path (str): source path. Returns: bool: True if a Windows volume was found. Raises: ScannerError: if the source path does not exists, or if the source path is not a file or directory, ...
Scans for a Windows volume. Args: source_path (str): source path. Returns: bool: True if a Windows volume was found. Raises: ScannerError: if the source path does not exists, or if the source path is not a file or directory, or if the format of or within the source f...
Below is the the instruction that describes the task: ### Input: Scans for a Windows volume. Args: source_path (str): source path. Returns: bool: True if a Windows volume was found. Raises: ScannerError: if the source path does not exists, or if the source path is not a fi...
def _fix_unsafe(shell_input): """Find characters used to escape from a string into a shell, and wrap them in quotes if they exist. Regex pilfered from Python3 :mod:`shlex` module. :param str shell_input: The input intended for the GnuPG process. """ _unsafe = re.compile(r'[^\w@%+=:,./-]', 256) ...
Find characters used to escape from a string into a shell, and wrap them in quotes if they exist. Regex pilfered from Python3 :mod:`shlex` module. :param str shell_input: The input intended for the GnuPG process.
Below is the the instruction that describes the task: ### Input: Find characters used to escape from a string into a shell, and wrap them in quotes if they exist. Regex pilfered from Python3 :mod:`shlex` module. :param str shell_input: The input intended for the GnuPG process. ### Response: def _fix_unsaf...
def verify(self, verify_locations: str) -> None: """Verify that the OCSP response is trusted. Args: verify_locations: The file path to a trust store containing pem-formatted certificates, to be used for validating the OCSP response. Raises OcspResponseNotTrustedError if...
Verify that the OCSP response is trusted. Args: verify_locations: The file path to a trust store containing pem-formatted certificates, to be used for validating the OCSP response. Raises OcspResponseNotTrustedError if the validation failed ie. the OCSP response is not trusted.
Below is the the instruction that describes the task: ### Input: Verify that the OCSP response is trusted. Args: verify_locations: The file path to a trust store containing pem-formatted certificates, to be used for validating the OCSP response. Raises OcspResponseNotTruste...
def get_url(cls, url, uid, **kwargs): """ Construct the URL for talking to an individual resource. http://myapi.com/api/resource/1 Args: url: The url for this resource uid: The unique identifier for an individual resource kwargs: Additional keyword a...
Construct the URL for talking to an individual resource. http://myapi.com/api/resource/1 Args: url: The url for this resource uid: The unique identifier for an individual resource kwargs: Additional keyword argueents returns: final_url: The URL f...
Below is the the instruction that describes the task: ### Input: Construct the URL for talking to an individual resource. http://myapi.com/api/resource/1 Args: url: The url for this resource uid: The unique identifier for an individual resource kwargs: Additiona...
async def sdiff(self, keys, *args): "Return the difference of sets specified by ``keys``" args = list_or_args(keys, args) return await self.execute_command('SDIFF', *args)
Return the difference of sets specified by ``keys``
Below is the the instruction that describes the task: ### Input: Return the difference of sets specified by ``keys`` ### Response: async def sdiff(self, keys, *args): "Return the difference of sets specified by ``keys``" args = list_or_args(keys, args) return await self.execute_command('SDI...
def indent(text, prefix): """ Adds `prefix` to the beginning of non-empty lines in `text`. """ # Based on Python 3's textwrap.indent def prefixed_lines(): for line in text.splitlines(True): yield (prefix + line if line.strip() else line) return u"".join(prefixed_lines())
Adds `prefix` to the beginning of non-empty lines in `text`.
Below is the the instruction that describes the task: ### Input: Adds `prefix` to the beginning of non-empty lines in `text`. ### Response: def indent(text, prefix): """ Adds `prefix` to the beginning of non-empty lines in `text`. """ # Based on Python 3's textwrap.indent def prefixed_lines(): ...
def markers_to_events(self, keep_name=False): """Copy all markers in dataset to event type. """ markers = self.parent.info.markers if markers is None: self.parent.statusBar.showMessage('No markers in dataset.') return if not keep_name: ...
Copy all markers in dataset to event type.
Below is the the instruction that describes the task: ### Input: Copy all markers in dataset to event type. ### Response: def markers_to_events(self, keep_name=False): """Copy all markers in dataset to event type. """ markers = self.parent.info.markers if markers is None: ...
def patch_namespaced_stateful_set_scale(self, name, namespace, body, **kwargs): # noqa: E501 """patch_namespaced_stateful_set_scale # noqa: E501 partially update scale of the specified StatefulSet # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynch...
patch_namespaced_stateful_set_scale # noqa: E501 partially update scale of the specified StatefulSet # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.patch_namespaced_stateful_set_sc...
Below is the the instruction that describes the task: ### Input: patch_namespaced_stateful_set_scale # noqa: E501 partially update scale of the specified StatefulSet # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass asy...
def switch(stage): """ Switch to given stage (dev/qa/production) + pull """ stage = stage.lower() local("git pull") if stage in ['dev', 'devel', 'develop']: branch_name = 'develop' elif stage in ['qa', 'release']: branches = local('git branch -r', capture=True) po...
Switch to given stage (dev/qa/production) + pull
Below is the the instruction that describes the task: ### Input: Switch to given stage (dev/qa/production) + pull ### Response: def switch(stage): """ Switch to given stage (dev/qa/production) + pull """ stage = stage.lower() local("git pull") if stage in ['dev', 'devel', 'develop']: ...
def list_scheduled_queries(self): """ List all scheduled_queries :return: A list of all scheduled query dicts :rtype: list of dict :raises: This will raise a :class:`ServerException<logentries_api.exceptions.ServerException>` if there is an error from Lo...
List all scheduled_queries :return: A list of all scheduled query dicts :rtype: list of dict :raises: This will raise a :class:`ServerException<logentries_api.exceptions.ServerException>` if there is an error from Logentries
Below is the the instruction that describes the task: ### Input: List all scheduled_queries :return: A list of all scheduled query dicts :rtype: list of dict :raises: This will raise a :class:`ServerException<logentries_api.exceptions.ServerException>` if there is a...
def task_postponed(self): """ Track (if required) postponing event and do the same job as :meth:`.WScheduleRecord.task_postponed` method do :return: None """ tracker = self.task().tracker_storage() if tracker is not None and self.track_wait() is True: details = self.task().event_details(WTrackerEvents.w...
Track (if required) postponing event and do the same job as :meth:`.WScheduleRecord.task_postponed` method do :return: None
Below is the the instruction that describes the task: ### Input: Track (if required) postponing event and do the same job as :meth:`.WScheduleRecord.task_postponed` method do :return: None ### Response: def task_postponed(self): """ Track (if required) postponing event and do the same job as :meth:`.WSchedu...
def insert(self, idx, value): """ Inserts a value in the ``ListVariable`` at an appropriate index. :param idx: The index before which to insert the new value. :param value: The value to insert. """ self._value.insert(idx, value) self._rebuild()
Inserts a value in the ``ListVariable`` at an appropriate index. :param idx: The index before which to insert the new value. :param value: The value to insert.
Below is the the instruction that describes the task: ### Input: Inserts a value in the ``ListVariable`` at an appropriate index. :param idx: The index before which to insert the new value. :param value: The value to insert. ### Response: def insert(self, idx, value): """ Inserts a...
def p_OperationRest(p): """OperationRest : ReturnType OptionalIdentifier "(" ArgumentList ")" ";" """ p[0] = model.Operation(return_type=p[1], name=p[2], arguments=p[4])
OperationRest : ReturnType OptionalIdentifier "(" ArgumentList ")" ";"
Below is the the instruction that describes the task: ### Input: OperationRest : ReturnType OptionalIdentifier "(" ArgumentList ")" ";" ### Response: def p_OperationRest(p): """OperationRest : ReturnType OptionalIdentifier "(" ArgumentList ")" ";" """ p[0] = model.Operation(return_type=p[1], name=p[2], argum...
def nslookup(cls): """ Implementation of UNIX nslookup. """ try: # We try to get the addresse information of the given domain or IP. if "current_test_data" in PyFunceble.INTERN: # pragma: no cover # The end-user want more information whith his t...
Implementation of UNIX nslookup.
Below is the the instruction that describes the task: ### Input: Implementation of UNIX nslookup. ### Response: def nslookup(cls): """ Implementation of UNIX nslookup. """ try: # We try to get the addresse information of the given domain or IP. if "current_...
def connect_async(self, connection_id, connection_string, callback): """Connect to a device by its connection_string This function asynchronously connects to a device by its BLE address passed in the connection_string parameter and calls callback when finished. Callback is called on ei...
Connect to a device by its connection_string This function asynchronously connects to a device by its BLE address passed in the connection_string parameter and calls callback when finished. Callback is called on either success or failure with the signature: callback(conection_...
Below is the the instruction that describes the task: ### Input: Connect to a device by its connection_string This function asynchronously connects to a device by its BLE address passed in the connection_string parameter and calls callback when finished. Callback is called on either succes...
def get_validated_object(self, field_type, value): """ Returns the value validated by the field_type """ if field_type.check_value(value) or field_type.can_use_value(value): data = field_type.use_value(value) self._prepare_child(data) return data ...
Returns the value validated by the field_type
Below is the the instruction that describes the task: ### Input: Returns the value validated by the field_type ### Response: def get_validated_object(self, field_type, value): """ Returns the value validated by the field_type """ if field_type.check_value(value) or field_type.can_us...
def get_data_times_for_job_legacy(self, num_job): """ Get the data that this job will need to read in. """ # Should all be integers, so no rounding needed shift_dur = self.curr_seg[0] + int(self.job_time_shift * num_job) job_data_seg = self.data_chunk.shift(shift_dur) # If this ...
Get the data that this job will need to read in.
Below is the the instruction that describes the task: ### Input: Get the data that this job will need to read in. ### Response: def get_data_times_for_job_legacy(self, num_job): """ Get the data that this job will need to read in. """ # Should all be integers, so no rounding needed shift_du...
def validate(self, graph): """ Validate the graph by checking whether it is a directed acyclic graph. Args: graph (DiGraph): Reference to a DiGraph object from NetworkX. Raises: DirectedAcyclicGraphInvalid: If the graph is not a valid dag. """ if not nx....
Validate the graph by checking whether it is a directed acyclic graph. Args: graph (DiGraph): Reference to a DiGraph object from NetworkX. Raises: DirectedAcyclicGraphInvalid: If the graph is not a valid dag.
Below is the the instruction that describes the task: ### Input: Validate the graph by checking whether it is a directed acyclic graph. Args: graph (DiGraph): Reference to a DiGraph object from NetworkX. Raises: DirectedAcyclicGraphInvalid: If the graph is not a valid dag. ...
def _get_kind_and_names(attributes): """Gets kind and possible names for :tl:`DocumentAttribute`.""" kind = 'document' possible_names = [] for attr in attributes: if isinstance(attr, types.DocumentAttributeFilename): possible_names.insert(0, attr.file_name) ...
Gets kind and possible names for :tl:`DocumentAttribute`.
Below is the the instruction that describes the task: ### Input: Gets kind and possible names for :tl:`DocumentAttribute`. ### Response: def _get_kind_and_names(attributes): """Gets kind and possible names for :tl:`DocumentAttribute`.""" kind = 'document' possible_names = [] for att...
def delete_events(self, event_collection, timeframe=None, timezone=None, filters=None): """ Deletes events. :param event_collection: string, the event collection from which event are being deleted :param timeframe: string or dict, the timeframe in which the events happened example: "pre...
Deletes events. :param event_collection: string, the event collection from which event are being deleted :param timeframe: string or dict, the timeframe in which the events happened example: "previous_7_days" :param timezone: int, the timezone you'd like to use for the timeframe ...
Below is the the instruction that describes the task: ### Input: Deletes events. :param event_collection: string, the event collection from which event are being deleted :param timeframe: string or dict, the timeframe in which the events happened example: "previous_7_days" :param ti...
def returns(self, val): """Set the last call to return a value. Set a static value to return when a method is called. I.E.:: >>> f = Fake().provides('get_number').returns(64) >>> f.get_number() 64 """ exp = self._get_current_call() exp.retu...
Set the last call to return a value. Set a static value to return when a method is called. I.E.:: >>> f = Fake().provides('get_number').returns(64) >>> f.get_number() 64
Below is the the instruction that describes the task: ### Input: Set the last call to return a value. Set a static value to return when a method is called. I.E.:: >>> f = Fake().provides('get_number').returns(64) >>> f.get_number() 64 ### Response: def returns(self, v...
def is_subscriber(self): """Returns whether the user is a subscriber or not. True or False.""" doc = self._request(self.ws_prefix + ".getInfo", True) return _extract(doc, "subscriber") == "1"
Returns whether the user is a subscriber or not. True or False.
Below is the the instruction that describes the task: ### Input: Returns whether the user is a subscriber or not. True or False. ### Response: def is_subscriber(self): """Returns whether the user is a subscriber or not. True or False.""" doc = self._request(self.ws_prefix + ".getInfo", True) ...
async def build(self, building: UnitTypeId, near: Union[Point2, Point3], max_distance: int=20, unit: Optional[Unit]=None, random_alternative: bool=True, placement_step: int=2): """Build a building.""" if isinstance(near, Unit): near = near.position.to2 elif near is not None: ...
Build a building.
Below is the the instruction that describes the task: ### Input: Build a building. ### Response: async def build(self, building: UnitTypeId, near: Union[Point2, Point3], max_distance: int=20, unit: Optional[Unit]=None, random_alternative: bool=True, placement_step: int=2): """Build a building.""" ...
def format_diff_xml(a_xml, b_xml): """Create a diff between two XML documents. Args: a_xml: str b_xml: str Returns: str : `Differ`-style delta """ return '\n'.join( difflib.ndiff( reformat_to_pretty_xml(a_xml).splitlines(), reformat_to_pretty_xml(...
Create a diff between two XML documents. Args: a_xml: str b_xml: str Returns: str : `Differ`-style delta
Below is the the instruction that describes the task: ### Input: Create a diff between two XML documents. Args: a_xml: str b_xml: str Returns: str : `Differ`-style delta ### Response: def format_diff_xml(a_xml, b_xml): """Create a diff between two XML documents. Args: a_x...
def calcTm(seq, mv_conc=50, dv_conc=0, dntp_conc=0.8, dna_conc=50, max_nn_length=60, tm_method='santalucia', salt_corrections_method='santalucia'): ''' Return the tm of `seq` as a float. ''' tm_meth = _tm_methods.get(tm_method) if tm_meth is None: raise ValueError('{} is no...
Return the tm of `seq` as a float.
Below is the the instruction that describes the task: ### Input: Return the tm of `seq` as a float. ### Response: def calcTm(seq, mv_conc=50, dv_conc=0, dntp_conc=0.8, dna_conc=50, max_nn_length=60, tm_method='santalucia', salt_corrections_method='santalucia'): ''' Return the tm of `seq` ...
def p_range(self, p): """range : value DOT_DOT value | value""" n = len(p) if n == 2: p[0] = (p[1],) elif n == 4: p[0] = (p[1], p[3])
range : value DOT_DOT value | value
Below is the the instruction that describes the task: ### Input: range : value DOT_DOT value | value ### Response: def p_range(self, p): """range : value DOT_DOT value | value""" n = len(p) if n == 2: p[0] = (p[1],) elif n == 4: ...
def channel_portion(image, channel): '''Estimates the amount of a color relative to other colors. :param image: numpy.ndarray :param channel: int :returns: portion of a channel in an image :rtype: float ''' # Separate color channels rgb = [] for i in range(3): rgb.append(im...
Estimates the amount of a color relative to other colors. :param image: numpy.ndarray :param channel: int :returns: portion of a channel in an image :rtype: float
Below is the the instruction that describes the task: ### Input: Estimates the amount of a color relative to other colors. :param image: numpy.ndarray :param channel: int :returns: portion of a channel in an image :rtype: float ### Response: def channel_portion(image, channel): '''Estimates th...
def transform(self, func): """ Apply a transformation to tokens in this :class:`.FeatureSet`\. Parameters ---------- func : callable Should take four parameters: token, value in document (e.g. count), value in :class:`.FeatureSet` (e.g. overall count), an...
Apply a transformation to tokens in this :class:`.FeatureSet`\. Parameters ---------- func : callable Should take four parameters: token, value in document (e.g. count), value in :class:`.FeatureSet` (e.g. overall count), and document count (i.e. number of do...
Below is the the instruction that describes the task: ### Input: Apply a transformation to tokens in this :class:`.FeatureSet`\. Parameters ---------- func : callable Should take four parameters: token, value in document (e.g. count), value in :class:`.FeatureSet` (e...
def _get_starting_population(initial_population, initial_position, population_size, population_stddev, seed): """Constructs the initial population. If an initial population is not already provided, t...
Constructs the initial population. If an initial population is not already provided, this function constructs a population by adding random normal noise to the initial position. Args: initial_population: None or a list of `Tensor`s. The initial population. initial_position: None or a list of `Tensor`s. ...
Below is the the instruction that describes the task: ### Input: Constructs the initial population. If an initial population is not already provided, this function constructs a population by adding random normal noise to the initial position. Args: initial_population: None or a list of `Tensor`s. The in...
def read_vcpu_struct_field(self, field_name, x, y, p): """Read a value out of the VCPU struct for a specific core. Similar to :py:meth:`.read_struct_field` except this method accesses the individual VCPU struct for to each core and contains application runtime status. Parameter...
Read a value out of the VCPU struct for a specific core. Similar to :py:meth:`.read_struct_field` except this method accesses the individual VCPU struct for to each core and contains application runtime status. Parameters ---------- field_name : string Name ...
Below is the the instruction that describes the task: ### Input: Read a value out of the VCPU struct for a specific core. Similar to :py:meth:`.read_struct_field` except this method accesses the individual VCPU struct for to each core and contains application runtime status. Parame...
def rename_model(self, old_model, new_model): """ Change the label of a model attached to the Bundle :parameter str old_model: the current name of the model (must exist) :parameter str new_model: the desired new name of the model (must not exist) :return:...
Change the label of a model attached to the Bundle :parameter str old_model: the current name of the model (must exist) :parameter str new_model: the desired new name of the model (must not exist) :return: None :raises ValueError: if the new_model is forbidden
Below is the the instruction that describes the task: ### Input: Change the label of a model attached to the Bundle :parameter str old_model: the current name of the model (must exist) :parameter str new_model: the desired new name of the model (must not exist) :retu...
def interfaces(device=None, interface=None, title=None, pattern=None, ipnet=None, best=True, display=_DEFAULT_DISPLAY): ''' Search for interfaces details in the following mine functions: - net.interfaces - net.ipa...
Search for interfaces details in the following mine functions: - net.interfaces - net.ipaddrs Optional arguments: device Return interface data from a certain device only. interface Return data selecting by interface name. pattern Return interfaces that contain a cert...
Below is the the instruction that describes the task: ### Input: Search for interfaces details in the following mine functions: - net.interfaces - net.ipaddrs Optional arguments: device Return interface data from a certain device only. interface Return data selecting by inter...
def shard_id(self): """Returns the shard ID for this guild if applicable.""" count = self._state.shard_count if count is None: return None return (self.id >> 22) % count
Returns the shard ID for this guild if applicable.
Below is the the instruction that describes the task: ### Input: Returns the shard ID for this guild if applicable. ### Response: def shard_id(self): """Returns the shard ID for this guild if applicable.""" count = self._state.shard_count if count is None: return None re...
def segment(f, output, target_duration, mpegts): """Segment command.""" try: target_duration = int(target_duration) except ValueError: exit('Error: Invalid target duration.') try: mpegts = int(mpegts) except ValueError: exit('Error: Invalid MPEGTS value.') WebVT...
Segment command.
Below is the the instruction that describes the task: ### Input: Segment command. ### Response: def segment(f, output, target_duration, mpegts): """Segment command.""" try: target_duration = int(target_duration) except ValueError: exit('Error: Invalid target duration.') try: ...
def get_info(self): ''' Get info regarding the current template state :return: info dictionary ''' self.render() info = super(Template, self).get_info() res = {} res['name'] = self.get_name() res['mutation'] = { 'current_index': self._...
Get info regarding the current template state :return: info dictionary
Below is the the instruction that describes the task: ### Input: Get info regarding the current template state :return: info dictionary ### Response: def get_info(self): ''' Get info regarding the current template state :return: info dictionary ''' self.render() ...
def cost_sampling(X, y, cost_mat, method='RejectionSampling', oversampling_norm=0.1, max_wc=97.5): """Cost-proportionate sampling. Parameters ---------- X : array-like of shape = [n_samples, n_features] The input samples. y : array-like of shape = [n_samples] Ground...
Cost-proportionate sampling. Parameters ---------- X : array-like of shape = [n_samples, n_features] The input samples. y : array-like of shape = [n_samples] Ground truth (correct) labels. cost_mat : array-like of shape = [n_samples, 4] Cost matrix ...
Below is the the instruction that describes the task: ### Input: Cost-proportionate sampling. Parameters ---------- X : array-like of shape = [n_samples, n_features] The input samples. y : array-like of shape = [n_samples] Ground truth (correct) labels. cos...
def set_hex_color(self, color, *, index=0, transition_time=None): """Set hex color of the light.""" values = { ATTR_LIGHT_COLOR_HEX: color, } if transition_time is not None: values[ATTR_TRANSITION_TIME] = transition_time return self.set_values(values, in...
Set hex color of the light.
Below is the the instruction that describes the task: ### Input: Set hex color of the light. ### Response: def set_hex_color(self, color, *, index=0, transition_time=None): """Set hex color of the light.""" values = { ATTR_LIGHT_COLOR_HEX: color, } if transition_time is...
def relation_set(relation_id=None, relation_settings=None, **kwargs): """Attempt to use leader-set if supported in the current version of Juju, otherwise falls back on relation-set. Note that we only attempt to use leader-set if the provided relation_id is a peer relation id or no relation id is provid...
Attempt to use leader-set if supported in the current version of Juju, otherwise falls back on relation-set. Note that we only attempt to use leader-set if the provided relation_id is a peer relation id or no relation id is provided (in which case we assume we are within the peer relation context).
Below is the the instruction that describes the task: ### Input: Attempt to use leader-set if supported in the current version of Juju, otherwise falls back on relation-set. Note that we only attempt to use leader-set if the provided relation_id is a peer relation id or no relation id is provided (in w...
def scale_and_center(mol): """Center and Scale molecule 2D coordinates. This method changes mol coordinates directly to center but not scale. This method returns width, height and MLB(median length of bond) and scaling will be done by drawer method with these values. Returns: width: float ...
Center and Scale molecule 2D coordinates. This method changes mol coordinates directly to center but not scale. This method returns width, height and MLB(median length of bond) and scaling will be done by drawer method with these values. Returns: width: float height: float mlb: ...
Below is the the instruction that describes the task: ### Input: Center and Scale molecule 2D coordinates. This method changes mol coordinates directly to center but not scale. This method returns width, height and MLB(median length of bond) and scaling will be done by drawer method with these values. ...
def get_res_stats(self,nonzero=True): """ get some common residual stats from the current obsvals, weights and grouping in self.observation_data and the modelled values in self.res. The key here is 'current' because if obsval, weights and/or groupings have changed in self.observation_da...
get some common residual stats from the current obsvals, weights and grouping in self.observation_data and the modelled values in self.res. The key here is 'current' because if obsval, weights and/or groupings have changed in self.observation_data since the res file was generated then t...
Below is the the instruction that describes the task: ### Input: get some common residual stats from the current obsvals, weights and grouping in self.observation_data and the modelled values in self.res. The key here is 'current' because if obsval, weights and/or groupings have changed in ...
def do_py(self, arg): """ :: Usage: py py COMMAND Arguments: COMMAND the command to be executed Description: The command without a parameter will be executed and the interactive pyth...
:: Usage: py py COMMAND Arguments: COMMAND the command to be executed Description: The command without a parameter will be executed and the interactive python mode is entered. The python mode can be...
Below is the the instruction that describes the task: ### Input: :: Usage: py py COMMAND Arguments: COMMAND the command to be executed Description: The command without a parameter will be executed and the ...
def upload_file(self, file): """The method is posting file to the remote server""" url = self._get_url('/api/1.0/upload/post') fcontent = FileContent(file) binary_data = fcontent.get_binary() headers = self._get_request_headers() req = urllib.request.Request(u...
The method is posting file to the remote server
Below is the the instruction that describes the task: ### Input: The method is posting file to the remote server ### Response: def upload_file(self, file): """The method is posting file to the remote server""" url = self._get_url('/api/1.0/upload/post') fcontent = FileContent(file) ...
def transpose(self, *axes): """Permute the dimensions of a Timeseries.""" if self.ndim <= 1: return self ar = np.asarray(self).transpose(*axes) if axes[0] != 0: # then axis 0 is unaffected by the transposition newlabels = [self.labels[ax] for ax in axe...
Permute the dimensions of a Timeseries.
Below is the the instruction that describes the task: ### Input: Permute the dimensions of a Timeseries. ### Response: def transpose(self, *axes): """Permute the dimensions of a Timeseries.""" if self.ndim <= 1: return self ar = np.asarray(self).transpose(*axes) if axes[...
async def export_tree(self, tree, dest, previous_tree=None, *, force=False, previous_index_file=None): '''This method is the core of `peru sync`. If the con...
This method is the core of `peru sync`. If the contents of "dest" match "previous_tree", then export_tree() updates them to match "tree". If not, it raises an error and doesn't touch any files. Because it's important for the no-op `peru sync` to be fast, we make an extra optimization fo...
Below is the the instruction that describes the task: ### Input: This method is the core of `peru sync`. If the contents of "dest" match "previous_tree", then export_tree() updates them to match "tree". If not, it raises an error and doesn't touch any files. Because it's important for the n...
def debug(self, topLeftIndex, bottomRightIndex): """ Temporary debug to test the dataChanged signal. TODO: remove. """ if topLeftIndex.isValid() and bottomRightIndex.isValid(): topRow = topLeftIndex.row() bottomRow = bottomRightIndex.row() for row in range(top...
Temporary debug to test the dataChanged signal. TODO: remove.
Below is the the instruction that describes the task: ### Input: Temporary debug to test the dataChanged signal. TODO: remove. ### Response: def debug(self, topLeftIndex, bottomRightIndex): """ Temporary debug to test the dataChanged signal. TODO: remove. """ if topLeftIndex.isValid() and b...
def delete(key, service=None, profile=None): # pylint: disable=W0613 ''' Get a value from the cache service ''' key, profile = _parse_key(key, profile) cache = salt.cache.Cache(__opts__) try: cache.flush(profile['bank'], key=key) return True except Exception: return ...
Get a value from the cache service
Below is the the instruction that describes the task: ### Input: Get a value from the cache service ### Response: def delete(key, service=None, profile=None): # pylint: disable=W0613 ''' Get a value from the cache service ''' key, profile = _parse_key(key, profile) cache = salt.cache.Cache(__o...
def get_version(version): """Dynamically calculate the version based on VERSION tuple.""" if len(version) > 2 and version[2] is not None: if isinstance(version[2], int): str_version = "%s.%s.%s" % version[:3] else: str_version = "%s.%s_%s" % version[:3] else: ...
Dynamically calculate the version based on VERSION tuple.
Below is the the instruction that describes the task: ### Input: Dynamically calculate the version based on VERSION tuple. ### Response: def get_version(version): """Dynamically calculate the version based on VERSION tuple.""" if len(version) > 2 and version[2] is not None: if isinstance(version[2]...
def mknod(self, req, parent, name, mode, rdev): """Create file node Valid replies: reply_entry reply_err """ self.reply_err(req, errno.EROFS)
Create file node Valid replies: reply_entry reply_err
Below is the the instruction that describes the task: ### Input: Create file node Valid replies: reply_entry reply_err ### Response: def mknod(self, req, parent, name, mode, rdev): """Create file node Valid replies: reply_entry reply_err ...
def _places(client, url_part, query=None, location=None, radius=None, keyword=None, language=None, min_price=0, max_price=4, name=None, open_now=False, rank_by=None, type=None, region=None, page_token=None): """ Internal handler for ``places``, ``places_nearby``, and ``places_radar``. ...
Internal handler for ``places``, ``places_nearby``, and ``places_radar``. See each method's docs for arg details.
Below is the the instruction that describes the task: ### Input: Internal handler for ``places``, ``places_nearby``, and ``places_radar``. See each method's docs for arg details. ### Response: def _places(client, url_part, query=None, location=None, radius=None, keyword=None, language=None, min_pri...
def route_handler(context, content, pargs, kwargs): """ Route shortcode works a lot like rendering a page based on the url or route. This allows inserting in rendered HTML within another page. Activate it with the 'shortcodes' template filter. Within the content use the chill route shortcode: "[ch...
Route shortcode works a lot like rendering a page based on the url or route. This allows inserting in rendered HTML within another page. Activate it with the 'shortcodes' template filter. Within the content use the chill route shortcode: "[chill route /path/to/something/]" where the '[chill' and ']' a...
Below is the the instruction that describes the task: ### Input: Route shortcode works a lot like rendering a page based on the url or route. This allows inserting in rendered HTML within another page. Activate it with the 'shortcodes' template filter. Within the content use the chill route shortcode:...
def p_sum_lvl_1(self, p): """ sum_lvl_1 : script_lvl_1 | script_lvl_1 PLUS sum_lvl_1""" if len(p) == 4: p[3].append(p[1]) p[0] = p[3] else: p[0] = [p[1]]
sum_lvl_1 : script_lvl_1 | script_lvl_1 PLUS sum_lvl_1
Below is the the instruction that describes the task: ### Input: sum_lvl_1 : script_lvl_1 | script_lvl_1 PLUS sum_lvl_1 ### Response: def p_sum_lvl_1(self, p): """ sum_lvl_1 : script_lvl_1 | script_lvl_1 PLUS sum_lvl_1""" if len(p) == 4: p[3].ap...