def contains(array, ty, string):
    weld_obj = WeldObject(encoder_, decoder_)
    string_obj = weld_obj.update(string)
    if isinstance(string, WeldObject):
        string_obj = string.obj_id
        weld_obj.dependencies[string_obj] = string
    array_var = weld_obj.update(array)
    if isinstance(array, WeldObject):
        array_var = array.obj_id
        weld_obj.dependencies[array_var] = array
    (start, end) = (0, len(string))
    weld_template = '\n       map(\n         %(array)s,\n         |str: vec[%(ty)s]|\n           let tstr = str;\n           result(\n             for(\n               str,\n               merger[i8,+](i8(0)),\n               |b,i,e|\n                 if(slice(tstr, i, i64(%(end)s)) == %(cmpstr)s,\n                    merge(b, i8(1)),\n                    b\n                 )\n              )\n            ) > i8(0)\n       )\n    '
    weld_obj.weld_code = (weld_template % {'array': array_var, 'ty': ty, 'start': start, 'end': end, 'cmpstr': string_obj})
    return weld_obj

Checks if given string is contained in each string in the array.
Output is a vec of booleans.

Args:
array (WeldObject / Numpy.ndarray): Input array
start (int): starting index
size (int): length to truncate at
ty (WeldType): Type of each element in the input array

Returns:
A WeldObject representing this computation


def to_representation(self, instance):

        updated_course_run = copy.deepcopy(instance)
        enterprise_customer_catalog = self.context['enterprise_customer_catalog']
        updated_course_run['enrollment_url'] = enterprise_customer_catalog.get_course_run_enrollment_url(
            updated_course_run['key']
        )
        return updated_course_run

Return the updated course run data dictionary.

Arguments:
instance (dict): The course run data.

Returns:
dict: The updated course run data.


def dict_setdiff(dict_, negative_keys):
    r
    keys = [key for key in six.iterkeys(dict_)
            if key not in set(negative_keys)]
    subdict_ = dict_subset(dict_, keys)
    return subdict_

r"""
returns a copy of dict_ without keys in the negative_keys list

Args:
dict_ (dict):
negative_keys (list):


def compute_area_features(features, max_area_width, max_area_height=1, height=1, epsilon=1e-06):
    with tf.name_scope('compute_area_features'):
        tf.logging.info('area_attention compute_area_features: %d x %d', max_area_height, max_area_width)
        (area_sum, area_heights, area_widths) = _compute_sum_image(features, max_area_width=max_area_width, max_area_height=max_area_height, height=height)
        (area_squared_sum, _, _) = _compute_sum_image(tf.pow(features, 2), max_area_width=max_area_width, max_area_height=max_area_height, height=height)
        sizes = tf.multiply(area_heights, area_widths)
        float_area_sizes = tf.to_float(sizes)
        area_mean = tf.div(area_sum, float_area_sizes)
        s2_n = tf.div(area_squared_sum, float_area_sizes)
        area_variance = tf.subtract(s2_n, tf.pow(area_mean, 2))
        area_std = tf.sqrt((tf.abs(area_variance) + epsilon))
        return (area_mean, area_std, area_sum, area_heights, area_widths)

Computes features for each area.

Args:
features: a Tensor in a shape of [batch_size, height * width, depth].
max_area_width: the max width allowed for an area.
max_area_height: the max height allowed for an area.
height: the height of the image.
epsilon: the epsilon added to the variance for computing standard deviation.
Returns:
area_mean: A Tensor of shape [batch_size, num_areas, depth]
area_std: A Tensor of shape [batch_size, num_areas, depth]
area_sum: A Tensor of shape [batch_size, num_areas, depth]
area_heights: A Tensor of shape [batch_size, num_areas, 1]
area_widths: A Tensor of shape [batch_size, num_areas, 1]


def path_to_bytes(path):
    if hasattr(path, '__fspath__'):
        path = path.__fspath__()
    return as_bytes(path)

Converts input which is a `PathLike` object to `bytes`.

Converts from any python constant representation of a `PathLike` object
or `str` to bytes.

Args:
path: An object that can be converted to path representation.

Returns:
A `bytes` object.

Usage:
In case a simplified `bytes` version of the path is needed from an
`os.PathLike` object.


def from_file(filename="feff.inp"):

        with zopen(filename, "rt") as f:
            lines = list(clean_lines(f.readlines()))
        params = {}
        eels_params = []
        ieels = -1
        ieels_max = -1
        for i, line in enumerate(lines):
            m = re.match(r"([A-Z]+\d*\d*)\s*(.*)", line)
            if m:
                key = m.group(1).strip()
                val = m.group(2).strip()
                val = Tags.proc_val(key, val)
                if key not in ("ATOMS", "POTENTIALS", "END", "TITLE"):
                    if key in ["ELNES", "EXELFS"]:
                        ieels = i
                        ieels_max = ieels + 5
                    else:
                        params[key] = val
            if ieels >= 0:
                if i >= ieels and i <= ieels_max:
                    if i == ieels + 1:
                        if int(line.split()[1]) == 1:
                            ieels_max -= 1
                    eels_params.append(line)

        if eels_params:
            if len(eels_params) == 6:
                eels_keys = ['BEAM_ENERGY', 'BEAM_DIRECTION', 'ANGLES', 'MESH', 'POSITION']
            else:
                eels_keys = ['BEAM_ENERGY', 'ANGLES', 'MESH', 'POSITION']
            eels_dict = {"ENERGY": Tags._stringify_val(eels_params[0].split()[1:])}
            for k, v in zip(eels_keys, eels_params[1:]):
                eels_dict[k] = str(v)
            params[str(eels_params[0].split()[0])] = eels_dict

        return Tags(params)

Creates a Feff_tag dictionary from a PARAMETER or feff.inp file.

Args:
filename: Filename for either PARAMETER or feff.inp file

Returns:
Feff_tag object


def charspan(cls, start, end):

        return cls(Lnk.CHARSPAN, (int(start), int(end)))

Create a Lnk object for a character span.

Args:
start: the initial character position (cfrom)
end: the final character position (cto)


def reset( self ):

        self.number_of_hops = 0
        self.dr = np.array( [ 0.0, 0.0, 0.0 ] )
        self.summed_dr2 = 0.0
        self.sites_visited = [ self._site.number ]

Reinitialise the stored displacements, number of hops, and list of sites visited for this `Atom`.

Args:
None

Returns:
None


def _parse_options(self, options):

        for key in ('username', 'client_name', 'client_id', 'client_secret', 'trusted', 'logout_uri'):
            value = options.get(key)
            if value is not None:
                self.fields[key] = value

        username = self.fields.pop('username', None)
        if username is not None:
            try:
                user_model = get_user_model()
                self.fields['user'] = user_model.objects.get(username=username)
            except user_model.DoesNotExist:
                raise CommandError("User matching the provided username does not exist.")

        client_name = self.fields.pop('client_name', None)
        if client_name is not None:
            self.fields['name'] = client_name

        logout_uri = self.fields.get('logout_uri')

        if logout_uri:
            try:
                URLValidator()(logout_uri)
            except ValidationError:
                raise CommandError("The logout_uri is invalid.")

Parse the command's options.

Arguments:
options (dict): Options with which the command was called.

Raises:
CommandError, if a user matching the provided username does not exist.


def get_transaction(self, tx_hash, id=None, endpoint=None):

        return self._call_endpoint(GET_RAW_TRANSACTION, params=[tx_hash, 1], id=id, endpoint=endpoint)

Look up a transaction by hash.
Args:
tx_hash: (str) hash in the form '58c634f81fbd4ae2733d7e3930a9849021840fc19dc6af064d6f2812a333f91d'
id: (int, optional) id to use for response tracking
endpoint: (RPCEndpoint, optional) endpoint to specify to use

Returns:
json: the transaction as a json object


def legal_check(self, message):

        if message["method"] == "LEGAL":
            logger.debug("<%s> <euuid:%s> Event LEGAL" % (str(self.cuuid),
                                                           message["euuid"]))
            logger.debug("<%s> <euuid:%s> Removing event from event "
                   "buffer." % (str(self.cuuid), message["euuid"]))

            if message["priority"] == "high":
                self.event_confirmations[
                    message["euuid"]] = self.event_uuids[message["euuid"]]
                logger.debug("<%s> <euuid:%s> Event was high priority. Adding "
                              "to confirmations buffer." % (str(self.cuuid),
                                                            message["euuid"]))
                logger.debug("<%s> <euuid:%s> Current event confirmation "
                              "buffer: %s" % (str(self.cuuid),
                                              message["euuid"],
                                              pformat(self.event_confirmations)))

            try:
                del self.event_uuids[message["euuid"]]
            except KeyError:
                logger.warning("<%s> <euuid:%s> Euuid does not exist in event "
                               "buffer. Key was removed before we could process "
                               "it." % (str(self.cuuid), message["euuid"]))

        elif message["method"] == "ILLEGAL":
            logger.debug("<%s> <euuid:%s> Event ILLEGAL" % (str(self.cuuid),
                                                            message["euuid"]))
            logger.debug("<%s> <euuid:%s> Removing event from event buffer and "
                         "adding to rollback buffer." % (str(self.cuuid),
                                                         message["euuid"]))
            self.event_rollbacks[
                message["euuid"]] = self.event_uuids[message["euuid"]]
            del self.event_uuids[message["euuid"]]

This method handles event legality check messages from the server.

Args:
message (dict): The unserialized legality dictionary received from
the server.

Returns:
None

Examples:
>>> message


def _read_arg(arg):

    if arg is None:
        arg_out = arg

    else:

        if len(arg) == 1 and os.path.exists(arg[0]):
            arg_out = grp.read(arg[0])
        else:
            arg_out = arg

        assert isinstance(arg_out, list), "arg_out must be a list."
        assert type(arg_out[0]) == str, "arg_out must be a list of strings."

    return arg_out

If arg is a list with 1 element that corresponds to a valid file path, use
set_io.grp to read the grp file. Otherwise, check that arg is a list of strings.

Args:
arg (list or None)

Returns:
arg_out (list or None)


def realpath(path):

    if path == '~':
        return userdir

    if path == '/':
        return sysroot

    if path.startswith('/'):
        return os.path.abspath(path)

    if path.startswith('~/'):
        return os.path.expanduser(path)

    if path.startswith('./'):
        return os.path.abspath(os.path.join(os.path.curdir, path[2:]))

    return os.path.abspath(path)

Create the real absolute path for the given path.

Add supports for userdir & / supports.

Args:
* path: pathname to use for realpath.

Returns:
Platform independent real absolute path.


def mount(dmg):

    temp_dir = __salt__['temp.dir'](prefix='dmg-')

    cmd = 'hdiutil attach -readonly -nobrowse -mountpoint {0} "{1}"'.format(temp_dir, dmg)

    return __salt__['cmd.run'](cmd), temp_dir

Attempt to mount a dmg file to a temporary location and return the
location of the pkg file inside

Args:
dmg (str): The location of the dmg file to mount

Returns:
tuple: Tuple containing the results of the command along with the mount
point

CLI Example:

.. code-block:: bash

salt '*' macpackage.mount /tmp/software.dmg


def notify_batch_pending(self, batch):
    txn_ids = {t.header_signature for t in batch.transactions}
    with self._lock:
        self._pending.add(batch.header_signature)
        self._batch_info[batch.header_signature] = txn_ids
        self._update_observers(batch.header_signature, ClientBatchStatus.PENDING)

Adds a Batch id to the pending cache, with its transaction ids.

Args:
batch (str): The id of the pending batch


def _split(self, rect):

        max_rects = collections.deque()

        for r in self._max_rects:
            if r.intersects(rect):
                max_rects.extend(self._generate_splits(r, rect))
            else:
                max_rects.append(r)

        self._max_rects = list(max_rects)

Split all max_rects intersecting the rectangle rect into up to
4 new max_rects.

Arguments:
rect (Rectangle): Rectangle

Returns:
split (Rectangle list): List of rectangles resulting from the split


def _get_task_target():
    import pipeline
    if pipeline._TEST_MODE:
        return None
    if (('CURRENT_VERSION_ID' not in os.environ) or ('CURRENT_MODULE_ID' not in os.environ)):
        logging.warning('Running Pipeline in non TEST_MODE but important env vars are not set.')
        return None
    version = os.environ['CURRENT_VERSION_ID'].split('.')[0]
    module = os.environ['CURRENT_MODULE_ID']
    return ('%s.%s' % (version, module))

Get the default target for a pipeline task.

Current version id format is: user_defined_version.minor_version_number
Current module id is just the module's name. It could be "default"

Returns:
A complete target name is of format version.module. If module is the
default module, just version. None if target can not be determined.


def accept(self, context):

        _next = 0
        for _s in context:
            _data = [self.data[j] for j in self.trn[_next]]
            if _s in _data:
                _next = self.trn[_next][_data.index(_s)]
            else:
                return 0, _next
        return 1, _next

Check if the context could be accepted by the oracle

Args:
context: s sequence same type as the oracle data

Returns:
bAccepted: whether the sequence is accepted or not
_next: the state where the sequence is accepted


def _get_elements(self, site):
    try:
        if isinstance(site.specie, Element):
            return [site.specie]
        return [Element(site.specie)]
    except:
        return site.species.elements

Get the list of elements for a Site

Args:
site (Site): Site to assess
Returns:
[Element]: List of elements


def _isinstance(self, model, raise_error=True):

        rv = isinstance(model, self.__model__)
        if not rv and raise_error:
            raise ValueError('%s is not of type %s' % (model, self.__model__))
        return rv

Checks if the specified model instance matches the class model.
By default this method will raise a `ValueError` if the model is not of
expected type.

Args:

model (Model) : The instance to be type checked

raise_error (bool) : Flag to specify whether to raise error on
type check failure

Raises:

ValueError: If `model` is not an instance of the respective Model
class


def generate(exported_program: torch.export.ExportedProgram, tokenizer, prompt: str, max_new_tokens: int=20, do_sample: bool=False, temperature: float=1.0, top_k: int=50, top_p: float=1.0, device: str='cpu') -> str:
    exported_module = exported_program.module()
    input_ids = tokenizer(prompt, return_tensors='pt').input_ids.to(device)
    generated_ids = input_ids.clone()
    curr_position = 0
    for i in range(input_ids.shape[1]):
        curr_input_ids = input_ids[:, i:i + 1]
        curr_cache_position = torch.tensor([curr_position], dtype=torch.long, device=device)
        _ = exported_module(curr_input_ids, curr_cache_position)
        curr_position += 1
    for _ in range(max_new_tokens):
        curr_input_ids = generated_ids[:, -1:]
        curr_cache_position = torch.tensor([curr_position], dtype=torch.long, device=device)
        outputs = exported_module(curr_input_ids, curr_cache_position)
        if do_sample:
            if temperature > 0:
                logits = outputs / temperature
            else:
                logits = outputs
            if top_k > 0:
                indices_to_remove = logits < torch.topk(logits, top_k)[0][..., -1, None]
                logits[indices_to_remove] = float('-inf')
            if top_p < 1.0:
                sorted_logits, sorted_indices = torch.sort(logits, descending=True)
                cumulative_probs = torch.cumsum(torch.softmax(sorted_logits, dim=-1), dim=-1)
                sorted_indices_to_remove = cumulative_probs > top_p
                sorted_indices_to_remove[..., 1:] = sorted_indices_to_remove[..., :-1].clone()
                sorted_indices_to_remove[..., 0] = 0
                indices_to_remove = sorted_indices_to_remove.scatter(-1, sorted_indices, sorted_indices_to_remove)
                logits[indices_to_remove] = float('-inf')
            probs = torch.softmax(logits, dim=-1)
            next_token_id = torch.multinomial(probs, num_samples=1)
        else:
            next_token_id = outputs.argmax(dim=-1, keepdim=True)
        if next_token_id.dim() > 2:
            next_token_id = next_token_id.squeeze(-1)
        generated_ids = torch.cat([generated_ids, next_token_id], dim=-1)
        curr_position += 1
        if next_token_id.item() == tokenizer.eos_token_id:
            break
    return tokenizer.decode(generated_ids[0], skip_special_tokens=True)

Generate a sequence of tokens using an exported program.

Args:
exported_program (`torch.export.ExportedProgram`): The exported model being used for generate.
tokenizer: The tokenizer to use.
prompt (str): The input prompt.
max_new_tokens (int): Maximum number of new tokens to generate.
do_sample (bool): Whether to use sampling or greedy decoding.
temperature (float): The temperature for sampling.
top_k (int): The number of highest probability tokens to keep for top-k sampling.
top_p (float): The cumulative probability for nucleus sampling.
device (str): The device to use.

Returns:
str: The generated text.


def attach(self, observer):
    if (not (observer in self._observers)):
        self._observers.append(observer)
    return self

Attach an observer.

Args:
observer (func): A function to be called when new messages arrive

Returns:
:class:`Stream`. Current instance to allow chaining


def __strip_tags(self, node: yaml.Node) -> None:

        if isinstance(node, yaml.SequenceNode):
            for subnode in node.value:
                self.__strip_tags(subnode)
        elif isinstance(node, yaml.MappingNode):
            node.tag = 'tag:yaml.org,2002:map'
            for key_node, value_node in node.value:
                self.__strip_tags(key_node)
                self.__strip_tags(value_node)

Strips tags from mappings in the tree headed by node.

This keeps yaml from constructing any objects in this tree.

Args:
node: Head of the tree to strip


def _ParseLogFileOptions(self, options):

    self._log_file = self.ParseStringOption(options, 'log_file')
    if not self._log_file:
      local_date_time = datetime.datetime.now()
      self._log_file = (
          '{0:s}-{1:04d}{2:02d}{3:02d}T{4:02d}{5:02d}{6:02d}.log.gz').format(
              self.NAME, local_date_time.year, local_date_time.month,
              local_date_time.day, local_date_time.hour, local_date_time.minute,
              local_date_time.second)

Parses the log file options.

Args:
options (argparse.Namespace): command line arguments.


def ed25519_public_key_from_string(string):

    try:
        return Ed25519PublicKey.from_public_bytes(
            base64.b64decode(string)
        )
    except (UnsupportedAlgorithm, Base64Error) as exc:
        raise ScriptWorkerEd25519Error("Can't create Ed25519PublicKey: {}!".format(str(exc)))

Create an ed25519 public key from ``string``, which is a seed.

Args:
string (str): the string to use as a seed.

Returns:
Ed25519PublicKey: the public key


def upload_backup_bundle_from_file(self, file_path, deployment_groups_id_or_uri):
    deployment_groups_uri = deployment_groups_id_or_uri
    if (self.DEPLOYMENT_GROUPS_URI not in deployment_groups_id_or_uri):
        deployment_groups_uri = (self.DEPLOYMENT_GROUPS_URI + deployment_groups_id_or_uri)
    uri = ((self.BACKUP_ARCHIVE_PATH + '?deploymentGrpUri=') + deployment_groups_uri)
    return self._client.upload(file_path, uri)

Restore an Artifact Bundle from a backup file.

Args:
file_path (str): The File Path to restore the Artifact Bundle.
deployment_groups_id_or_uri: ID or URI of the Deployment Groups.

Returns:
dict: Deployment group.


def visit_Import(self, node):
    for import_alias in node.names:
        if import_alias.name == 'tensorflow.compat.v1' and import_alias.asname == 'tf':
            import_alias.name = 'tensorflow'
    self.generic_visit(node)

Handle visiting an import node in the AST.

Args:
node: Current Node


def number_type(numobj):

    region_code = region_code_for_number(numobj)
    metadata = PhoneMetadata.metadata_for_region_or_calling_code(numobj.country_code, region_code)
    if metadata is None:
        return PhoneNumberType.UNKNOWN
    national_number = national_significant_number(numobj)
    return _number_type_helper(national_number, metadata)

Gets the type of a valid phone number.

Arguments:
numobj -- The PhoneNumber object that we want to know the type of.

Returns the type of the phone number, as a PhoneNumberType value;
returns PhoneNumberType.UNKNOWN if it is invalid.


def convert_n_to_tensor(values, dtype=None, name=None, preferred_dtype=None) -> list[Union[EagerTensor, SymbolicTensor]]:
    return internal_convert_n_to_tensor(values=values, dtype=dtype, name=name, preferred_dtype=preferred_dtype, as_ref=False)

Converts `values` to a list of `Tensor` objects.

Args:
values: A list of objects that can be consumed by `tf.convert_to_tensor()`.
dtype: (Optional.) The required `DType` of the returned `Tensor` objects.
name: (Optional.) A name prefix to used when a new `Tensor` is created, in
which case element `i` will be given the name `name + '_' + i`.
preferred_dtype: Optional element type for the returned tensors, used when
dtype is None. In some cases, a caller may not have a dtype in mind when
converting to a tensor, so preferred_dtype can be used as a soft
preference.  If the conversion to `preferred_dtype` is not possible, this
argument has no effect.

Returns:
A list of `Tensor` and/or `IndexedSlices` objects.

Raises:
TypeError: If no conversion function is registered for an element in
`values`.
RuntimeError: If a registered conversion function returns an invalid
value.


def _get_task_host():
    version = os.environ['CURRENT_VERSION_ID'].split('.')[0]
    default_host = os.environ['DEFAULT_VERSION_HOSTNAME']
    module = os.environ['CURRENT_MODULE_ID']
    if (os.environ['CURRENT_MODULE_ID'] == 'default'):
        return ('%s.%s' % (version, default_host))
    return ('%s.%s.%s' % (version, module, default_host))

Get the Host header value for all mr tasks.

Task Host header determines which instance this task would be routed to.

Current version id format is: v7.368834058928280579
Current module id is just the module's name. It could be "default"
Default version hostname is app_id.appspot.com

Returns:
A complete host name is of format version.module.app_id.appspot.com
If module is the default module, just version.app_id.appspot.com. The reason
is if an app doesn't have modules enabled and the url is
"version.default.app_id", "version" is ignored and "default" is used as
version. If "default" version doesn't exist, the url is routed to the
default version.


def _placement_points_generator(self, skyline, width):
    skyline_r = skyline[(- 1)].right
    skyline_l = skyline[0].left
    ppointsl = (s.left for s in skyline if ((s.left + width) <= skyline_r))
    ppointsr = ((s.right - width) for s in skyline if ((s.right - width) >= skyline_l))
    return heapq.merge(ppointsl, ppointsr)

Returns a generator for the x coordinates of all the placement
points on the skyline for a given rectangle.

WARNING: In some cases could be duplicated points, but it is faster
to compute them twice than to remove them.

Arguments:
skyline (list): Skyline HSegment list
width (int, float): Rectangle width

Returns:
generator


def dump_connection_info(engine: Engine, fileobj: TextIO = sys.stdout) -> None:

    meta = MetaData(bind=engine)
    writeline_nl(fileobj, sql_comment('Database info: {}'.format(meta)))

Dumps some connection info, as an SQL comment. Obscures passwords.

Args:
engine: the SQLAlchemy :class:`Engine` to dump metadata information
from
fileobj: the file-like object (default ``sys.stdout``) to write
information to


def _concatenate_inner(self, direction):

    tmp_bucket = []
    source_chunks = self if direction else self[::-1]
    target_chunks = ChunkList()
    for chunk in source_chunks:
      if (

          chunk.dependency == direction or

          (direction is False and chunk.is_space())
          ):
        tmp_bucket.append(chunk)
        continue
      tmp_bucket.append(chunk)
      if not direction:
        tmp_bucket = tmp_bucket[::-1]
      new_word = ''.join([tmp_chunk.word for tmp_chunk in tmp_bucket])
      new_chunk = Chunk(new_word, pos=chunk.pos, label=chunk.label,
                        dependency=chunk.dependency)
      target_chunks.append(new_chunk)
      tmp_bucket = ChunkList()
    if tmp_bucket:
      target_chunks += tmp_bucket
    if not direction:
      target_chunks = target_chunks[::-1]
    self.list = target_chunks

Concatenates chunks based on each chunk's dependency.

Args:
direction (bool): Direction of concatenation process. True for forward.


def check_table_dtypes(table, key_dtype, value_dtype):
    if key_dtype.base_dtype != table.key_dtype:
        raise TypeError(f'Invalid key dtype for table, expected {table.key_dtype} but got {key_dtype}.')
    if value_dtype.base_dtype != table.value_dtype:
        raise TypeError(f'Invalid value dtype for table, expected {table.value_dtype} but got {value_dtype}.')

Check that the given key_dtype and value_dtype matches the table dtypes.

Args:
table: The table to check types against to.
key_dtype: The key data type to check.
value_dtype: The value data type to check.

Raises:
TypeError: when 'key_dtype' or 'value_dtype' doesn't match the table data
types.


def __call__(self, fn, *args, **kwargs):

    if args:
      my_args = transpose_list_of_lists(
          [self._maybe_repeat(arg) for arg in args])
    else:
      my_args = [[] for _ in range(self.n)]
    my_kwargs = [{} for _ in range(self.n)]
    for k, v in six.iteritems(kwargs):
      vals = self._maybe_repeat(v)
      for i in range(self.n):
        my_kwargs[i][k] = vals[i]

    fns = self._maybe_repeat(fn)

    outputs = []
    cache = {}
    tensor_to_var = {}
    for i in range(self.n):

      def daisy_chain_getter(getter, name, *args, **kwargs):

        device_var_key = (self._devices[i], name)
        if device_var_key in cache:

          return cache[device_var_key]
        if name in cache:

          last_device_v = cache[name]
          var = tensor_to_var[last_device_v]
          v = tf.identity(last_device_v)
        else:
          var = getter(name, *args, **kwargs)
          v = var.read_value()

        tensor_to_var[v] = var
        _add_variable_proxy_methods(tensor_to_var[v], v)

        cache[name] = v
        cache[device_var_key] = v
        return v

      def caching_getter(getter, name, *args, **kwargs):

        key = (self._caching_devices[i], name)
        if key in cache:
          return cache[key]

        v = getter(name, *args, **kwargs)
        with tf.device(self._caching_devices[i]):
          ret = v.read_value()
        _add_variable_proxy_methods(v, ret)
        cache[key] = ret
        return ret

      if self._daisy_chain_variables:
        custom_getter = daisy_chain_getter
      elif self._caching_devices[i]:
        custom_getter = caching_getter
      else:
        custom_getter = None

      with tf.name_scope("parallel_%d" % i):
        with tf.variable_scope(
            tf.get_variable_scope() if self._reuse else "parallel_%d" % i,
            reuse=True if i > 0 and self._reuse else None,
            caching_device=self._caching_devices[i],
            custom_getter=custom_getter):

          if self._devices[i] != DEFAULT_DEV_STRING:
            with tf.device(self._devices[i]):
              outputs.append(fns[i](*my_args[i], **my_kwargs[i]))
          else:
            outputs.append(fns[i](*my_args[i], **my_kwargs[i]))
    if isinstance(outputs[0], tuple):
      outputs = list(zip(*outputs))
      outputs = tuple([list(o) for o in outputs])
    return outputs

A parallel set of function calls (using the specified devices).

Args:
fn: a function or a list of n functions.
*args: additional args.  Each arg should either be not a list, or a list
of length n.
**kwargs: additional keyword args.  Each arg should either be not a
list, or a list of length n.

Returns:
either a single list of length n (if fn does not return a tuple), or a
tuple of lists of length n (if fn returns a tuple).


def encode_fast(self, text: Union[str, List[str]], return_tensors: Union[str, bool]=False) -> Union[List[int], List[List[int]], 'torch.Tensor']:
    if isinstance(text, str):
        text = self.preprocess_text(text)
        token_ids = self.sp_model.encode(text)
    else:
        text = [self.preprocess_text(t) for t in text]
        token_ids = self.sp_model.encode(text)
    if return_tensors is True or return_tensors == 'pt':
        token_ids = torch.tensor(token_ids)
    return token_ids

Encodes a text or batch of texts to token ids using preprocessing and the raw SP tokenizer. This has reduced
functionality but is often much faster.

Does NOT handle special tokens correctly, these can manually be added as ids afterwards.

Does NOT support padding, these can manually be added as ids afterwards.

Use default HuggingFace tokenization methods for full functionality.

Args:
text (`str` or `List[str]`): One or several text(s) to convert to token ids.
return_tensors (`str` or `bool`): Returns PyTorch tensors if set to True or "pt"

Returns:
`List[int]`, `List[List[int]]`, or `torch.Tensor`: The encoded text(s) as token ids.


def write_file(self, name, fp_src, blocksize=DEFAULT_BLOCKSIZE, callback=None):

        assert compat.is_native(name)
        self.check_write(name)
        self.ftp.storbinary("STOR {}".format(name), fp_src, blocksize, callback)

Write file-like `fp_src` to cur_dir/name.

Args:
name (str): file name, located in self.curdir
fp_src (file-like): must support read() method
blocksize (int, optional):
callback (function, optional):
Called like `func(buf)` for every written chunk


def generate_jwt_token(user, authsys, **kwargs):

    from cloud_inquisitor.config import dbconfig

    token = {
        'auth_system': authsys,
        'exp': time.time() + dbconfig.get('session_expire_time'),
        'roles': [role.name for role in user.roles]
    }

    if kwargs:
        token.update(**kwargs)

    enc = jwt.encode(token, get_jwt_key_data(), algorithm='HS512')
    return enc.decode()

Generate a new JWT token, with optional extra information. Any data provided in `**kwargs`
will be added into the token object for auth specific usage

Args:
user (:obj:`User`): User object to generate token for
authsys (str): The auth system for which the token was generated
**kwargs (dict): Any optional items to add to the token

Returns:
Encoded JWT token


def erase(self, **kwargs):

        path = '%s/%s/erase' % (self.manager.path, self.get_id())
        self.manager.gitlab.http_post(path)

Erase the job (remove job artifacts and trace).

Args:
**kwargs: Extra options to send to the server (e.g. sudo)

Raises:
GitlabAuthenticationError: If authentication is not correct
GitlabJobEraseError: If the job could not be erased


def chosen_angle_to_canonical_half_turns(half_turns: Optional[Union[(sympy.Basic, float)]]=None, rads: Optional[float]=None, degs: Optional[float]=None, default: float=1.0) -> Union[(sympy.Basic, float)]:
    return canonicalize_half_turns(chosen_angle_to_half_turns(half_turns=half_turns, rads=rads, degs=degs, default=default))

Returns a canonicalized half_turns based on the given arguments.

At most one of half_turns, rads, degs must be specified. If none are
specified, the output defaults to half_turns=1.

Args:
half_turns: The number of half turns to rotate by.
rads: The number of radians to rotate by.
degs: The number of degrees to rotate by
default: The half turns angle to use if nothing else is specified.

Returns:
A number of half turns.


def Histograms(self, run, tag):

    accumulator = self.GetAccumulator(run)
    return accumulator.Histograms(tag)

Retrieve the histogram events associated with a run and tag.

Args:
run: A string name of the run for which values are retrieved.
tag: A string name of the tag for which values are retrieved.

Raises:
KeyError: If the run is not found, or the tag is not available for
the given run.

Returns:
An array of `event_accumulator.HistogramEvents`.


def __init__(self, arguments=None, value_expander=None):

    self.value_expander = None
    self.value_expander_cls = value_expander
    if self.value_expander_cls:
      if not issubclass(self.value_expander_cls, ValueExpander):
        raise ValueError('{0:s} is not a valid value expander'.format(
            self.value_expander_cls))
      self.value_expander = self.value_expander_cls()
    self.args = arguments or []
    logging.debug('Adding {0!s}'.format(arguments))

Constructor.

Args:
arguments: Arguments to the filter.
value_expander: A callable that will be used to expand values for the
objects passed to this filter. Implementations expanders are provided by
subclassing ValueExpander.

Raises:
ValueError: If the given value_expander is not a subclass of ValueExpander


def of_cte(cls, header: Optional[ContentTransferEncodingHeader]) -> 'MessageDecoder':
    if (header is None):
        return _NoopDecoder()
    hdr_str = str(header).lower()
    custom = cls.registry.get(hdr_str)
    if (custom is not None):
        return custom
    elif (hdr_str in ('7bit', '8bit')):
        return _NoopDecoder()
    elif (hdr_str == 'quoted-printable'):
        return _QuotedPrintableDecoder()
    elif (hdr_str == 'base64'):
        return _Base64Decoder()
    else:
        raise NotImplementedError(hdr_str)

Return a decoder from the CTE header value.

There is built-in support for ``7bit``, ``8bit``, ``quoted-printable``,
and ``base64`` CTE header values. Decoders can be added or overridden
with the :attr:`.registry` dictionary.

Args:
header: The CTE header value.


def experimental_feature_scope(feature_name):
    env_varname = 'TF_TRT_EXPERIMENTAL_FEATURES'
    env_value_bckp = os.environ.get(env_varname, default='')
    exp_features = env_value_bckp.split(',')
    os.environ[env_varname] = ','.join(list(set(exp_features + [feature_name])))
    try:
        yield
    finally:
        os.environ[env_varname] = env_value_bckp

Creates a context manager to enable the given experimental feature.

This helper function creates a context manager setting up an experimental
feature temporarily.

Example:

```python
with self._experimental_feature_scope("feature_1"):
do_smthg()
```

Args:
feature_name: Name of the feature being tested for activation.


def _make_auth(self, method, date, nonce, path, query={}, ctype='application/json'):
    query = urlencode(query)
    hmac_str = (((((((((((method + '\n') + nonce) + '\n') + date) + '\n') + ctype) + '\n') + path) + '\n') + query) + '\n').lower().encode('utf-8')
    signature = base64.b64encode(hmac.new(self._secret_key, hmac_str, digestmod=hashlib.sha256).digest())
    auth = ((('On ' + self._access_key.decode('utf-8')) + ':HmacSHA256:') + signature.decode('utf-8'))
    if self._logging:
        utils.log({'query': query, 'hmac_str': hmac_str, 'signature': signature, 'auth': auth})
    return auth

Create the request signature to authenticate

Args:
- method (str): HTTP method
- date (str): HTTP date header string
- nonce (str): Cryptographic nonce
- path (str): URL pathname
- query (dict, default={}): URL query string in key-value pairs
- ctype (str, default='application/json'): HTTP Content-Type


def write(name, value):
    if (value is not None):
        environ[name] = builtins.str(value)
    elif environ.get(name):
        del environ[name]

Write a raw env value.

A ``None`` value clears the environment variable.

Args:
name: The environment variable name
value: The value to write


def __extract_directory(self, path, files, destination):
    destination_path = os.path.join(destination, path)
    if (not os.path.exists(destination_path)):
        os.makedirs(destination_path)
    for (name, contents) in files.items():
        item_path = os.path.join(path, name)
        if ('files' in contents):
            self.__extract_directory(item_path, contents['files'], destination)
            continue
        self.__extract_file(item_path, contents, destination)

Extracts a single directory to the specified directory on disk.

Args:
path (str):
Relative (to the root of the archive) path of the directory
to extract.

files (dict):
A dictionary of files from a *.asar file header.

destination (str):
The path to extract the files to.


def install_app(app, target='/Applications/'):

    if target[-4:] != '.app':
        if app[-1:] == '/':
            base_app = os.path.basename(app[:-1])
        else:
            base_app = os.path.basename(app)

        target = os.path.join(target, base_app)

    if not app[-1] == '/':
        app += '/'

    cmd = 'rsync -a --delete "{0}" "{1}"'.format(app, target)
    return __salt__['cmd.run'](cmd)

Install an app file by moving it into the specified Applications directory

Args:
app (str): The location of the .app file
target (str): The target in which to install the package to
Default is ''/Applications/''

Returns:
str: The results of the rsync command

CLI Example:

.. code-block:: bash

salt '*' macpackage.install_app /tmp/tmp.app /Applications/


def MakeClass(descriptor):
    if (descriptor in MESSAGE_CLASS_CACHE):
        return MESSAGE_CLASS_CACHE[descriptor]
    attributes = {}
    for (name, nested_type) in descriptor.nested_types_by_name.items():
        attributes[name] = MakeClass(nested_type)
    attributes[GeneratedProtocolMessageType._DESCRIPTOR_KEY] = descriptor
    result = GeneratedProtocolMessageType(str(descriptor.name), (message.Message,), attributes)
    MESSAGE_CLASS_CACHE[descriptor] = result
    return result

Construct a class object for a protobuf described by descriptor.

Composite descriptors are handled by defining the new class as a member of the
parent class, recursing as deep as necessary.
This is the dynamic equivalent to:

class Parent(message.Message):
__metaclass__ = GeneratedProtocolMessageType
DESCRIPTOR = descriptor
class Child(message.Message):
__metaclass__ = GeneratedProtocolMessageType
DESCRIPTOR = descriptor.nested_types[0]

Sample usage:
file_descriptor = descriptor_pb2.FileDescriptorProto()
file_descriptor.ParseFromString(proto2_string)
msg_descriptor = descriptor.MakeDescriptor(file_descriptor.message_type[0])
msg_class = reflection.MakeClass(msg_descriptor)
msg = msg_class()

Args:
descriptor: A descriptor.Descriptor object describing the protobuf.
Returns:
The Message class object described by the descriptor.


def build_debug_info_func(original_graph):

    def f(original_nodes):

        if not original_graph:
            return None
        useful_ops = []
        for func, name in original_nodes:
            try:
                if not func:
                    useful_ops.append((func, original_graph.get_operation_by_name(name)))
                else:
                    sub_func = original_graph._get_function(func)
                    if isinstance(sub_func, function.AtomicFunction):
                        useful_ops.append((func, sub_func.graph.get_operation_by_name(name)))
                    else:
                        sys.stderr.write("Use '@tf.function' or '@defun' to decorate the function.\n")
                        continue
            except KeyError:
                continue
        return _error_interpolation.create_graph_debug_info_def(useful_ops)
    return f

Returns a method to retrieve the `GraphDebugInfo` from the original graph.

Args:
original_graph: The original `Graph` containing all the op stack traces.

Returns:
A function which retrieves the stack traces from the original graph and
converts them to a `GraphDebugInfo` for a given set of nodes.


def Match(self, registry_key):

    key_path_upper = registry_key.path.upper()

    for ignore_key_path_suffix in self._IGNORE_KEY_PATH_SUFFIXES:
      if key_path_upper.endswith(ignore_key_path_suffix):
        return False

    for ignore_key_path_segment in self._IGNORE_KEY_PATH_SEGMENTS:
      if ignore_key_path_segment in key_path_upper:
        return False

    return super(MRUListExStringRegistryKeyFilter, self).Match(registry_key)

Determines if a Windows Registry key matches the filter.

Args:
registry_key (dfwinreg.WinRegistryKey): Windows Registry key.

Returns:
bool: True if the Windows Registry key matches the filter.


def add_period_and_roll(self, date_tensor, period_tensor, roll_convention=constants.BusinessDayConvention.NONE):
    return self.roll_to_business_day(date_tensor + period_tensor, roll_convention)

Adds given periods to given dates and rolls to business days.

The original dates are not rolled prior to addition.

Args:
date_tensor: `DateTensor` of dates to add to.
period_tensor: PeriodTensor broadcastable to `date_tensor`.
roll_convention: BusinessDayConvention. Determines how to roll a date that
falls on a holiday.

Returns:
The resulting `DateTensor`.


def _FindExecutableOnPath(executable, path, pathext):
    if isinstance(pathext, str):
        raise ValueError("_FindExecutableOnPath(..., pathext='{0}') failed because pathext must be an iterable of strings, but got a string.".format(pathext))
    for ext in pathext:
        for directory in path.split(os.pathsep):
            directory = directory.strip('"')
            full = os.path.normpath(os.path.join(directory, executable) + ext)
            if os.path.isfile(full) and os.access(full, os.X_OK):
                return full
    return None

Internal function to a find an executable.

Args:
executable: The name of the executable to find.
path: A list of directories to search separated by 'os.pathsep'.
pathext: An iterable of file name extensions to use.

Returns:
str, the path to a file on `path` with name `executable` + `p` for
`p` in `pathext`.

Raises:
ValueError: invalid input.


def read_var(self, v):
    raise NotImplementedError('must be implemented in descendants')

Reads the value of a variable.

Returns the aggregate value of a replica-local variable, or the
(read-only) value of any other variable.

Args:
v: A variable allocated within the scope of this `tf.distribute.Strategy`.

Returns:
A tensor representing the value of `v`, aggregated across replicas if
necessary.


def add_package(self, pkg, action_type='Install'):
    if isinstance(pkg, Package):
        if (action_type not in ('Install', 'Cache', 'Install Cached')):
            raise ValueError
        package = self.add_object_to_path(pkg, 'package_configuration/packages')
        action = package.find('action')
        if (not action):
            action = ElementTree.SubElement(package, 'action')
        action.text = action_type
    else:
        raise ValueError('Please pass a Package object to parameter: pkg.')

Add a Package object to the policy with action=install.

Args:
pkg: A Package object to add.
action_type (str, optional): One of "Install", "Cache", or
"Install Cached".  Defaults to "Install".


def check_full_copies(overwrite: bool=False):
    diffs = []
    for target, source in FULL_COPIES.items():
        with open(source, 'r', encoding='utf-8') as f:
            source_code = f.read()
        with open(target, 'r', encoding='utf-8') as f:
            target_code = f.read()
        if source_code != target_code:
            if overwrite:
                with open(target, 'w', encoding='utf-8') as f:
                    print(f'Replacing the content of {target} by the one of {source}.')
                    f.write(source_code)
            else:
                diffs.append(f'- {target}: copy does not match {source}.')
    if not overwrite and len(diffs) > 0:
        diff = '\n'.join(diffs)
        raise Exception('Found the following copy inconsistencies:\n' + diff + '\nRun `make fix-copies` or `python utils/check_copies.py --fix_and_overwrite` to fix them.')

Check the files that are full copies of others (as indicated in `FULL_COPIES`) are copy-consistent.

Args:
overwrite (`bool`, *optional*, defaults to `False`):
Whether or not to overwrite the copies when they don't match.


def register_drops(self, dropin):
    drops = self.app.extensions['dropin'].setdefault(self.drops_type, [])
    drops.extend(self.load_drops(dropin))

Register the `drops` in given `dropin` to a flask app.

Args:
app (Flask): the flask app to be initialized
dropin (string): path of a python module or object, e.g. dropin.auth

This is the only method that a drops loader **must** implment. The default
behavior in the base loader is to store all the drops object in the app's
extentions dict.

For example, the drops with type `models` will be stored in a list which
is accessible through::

app.extensions['dropin']['models']

or through DropInManager instance which provide a simple proxy to the dropin
extension of `current_app`::

dropin = DropInManager()
dropin.models

Whereas the BlueprintsLoader overrided this method to actually register
the blueprints to the app.


def Write(self, grr_message):

    grr_message = grr_message.SerializeToString()
    try:
      winreg.SetValueEx(_GetServiceKey(), "Transaction", 0, winreg.REG_BINARY,
                        grr_message)
      self._synced = False
    except OSError:
      pass

Write the message into the transaction log.

Args:
grr_message: A GrrMessage instance.


def get(self, path):
    if self.mode != 'r':
        raise ValueError('`get` is only allowed in read mode.')
    self._h5_entry_path = path
    self._h5_entry_group = {}
    if not path:
        if 'vars' in self.h5_file:
            self._h5_entry_group = self.h5_file['vars']
    elif path in self.h5_file and 'vars' in self.h5_file[path]:
        self._h5_entry_group = self.h5_file[path]['vars']
    elif '_layer_checkpoint_dependencies' in self.h5_file:
        path = path.replace('layers', '_layer_checkpoint_dependencies')
        if path in self.h5_file and 'vars' in self.h5_file[path]:
            self._h5_entry_group = self.h5_file[path]['vars']
    self._h5_entry_initialized = True
    return self

Get the H5 entry group.

This method is only available in read mode.

Args:
path: `str`. The variable path.


def search(self, kw):

		if not kw:
			return requests.codes.bad_request, None

		code, data = self._req('get', self.search_uri + kw)

		return code, data

Takes a keyword and returns the search results.
Works for boxes only?
Args:
kw		keyword (str) to search for.
return	(code, list(dicts))


def createEmails(nicks=None, nicksFile=None):
    candidate_emails = set()
    if (nicks != None):
        for n in nicks:
            for e in email_providers.domains:
                candidate_emails.add('{}@{}'.format(n, e))
    elif (nicksFile != None):
        with open(nicksFile, 'r') as iF:
            nicks = iF.read().splitlines()
            for n in nicks:
                for e in email_providers.domains:
                    candidate_emails.add('{}@{}'.format(n, e))
    return candidate_emails

Method that globally permits to generate the emails to be checked.

Args:
-----
nicks: List of aliases.
nicksFile: The filepath to the aliases file.

Returns:
--------
list: list of emails to be checked.


def create_executable_script(filepath, body, program=None):
    program = (program or 'python')
    if callable(body):
        from rez.utils.sourcecode import SourceCode
        code = SourceCode(func=body)
        body = code.source
    if (not body.endswith('\n')):
        body += '\n'
    with open(filepath, 'w') as f:
        f.write(('
        f.write(body)
    if (os.name == 'posix'):
        os.chmod(filepath, (((((stat.S_IRUSR | stat.S_IRGRP) | stat.S_IROTH) | stat.S_IXUSR) | stat.S_IXGRP) | stat.S_IXOTH))

Create an executable script.

Args:
filepath (str): File to create.
body (str or callable): Contents of the script. If a callable, its code
is used as the script body.
program (str): Name of program to launch the script, 'python' if None


def scale_losses_by_sample_weight(losses, sample_weight):
    losses = math_ops.cast(losses, dtypes.float32)
    sample_weight = math_ops.cast(sample_weight, dtypes.float32)
    losses, _, sample_weight = squeeze_or_expand_dimensions(losses, None, sample_weight)
    return math_ops.multiply(losses, sample_weight)

Scales loss values by the given sample weights.

`sample_weight` dimensions are updated to match with the dimension of `losses`
if possible by using squeeze/expand/broadcast.

Args:
losses: Loss tensor.
sample_weight: Sample weights tensor.

Returns:
`losses` scaled by `sample_weight` with dtype float32.


def urlToIds(url):

        urlId = url.split("/")[-1]
        convUrl = "https:
        json = SkypeConnection.externalCall("POST", convUrl, json={"shortId": urlId, "type": "wl"}).json()
        return {"id": json.get("Resource"),
                "long": json.get("Id"),
                "blob": json.get("ChatBlob")}

Resolve a ``join.skype.com`` URL and returns various identifiers for the group conversation.

Args:
url (str): public join URL, or identifier from it

Returns:
dict: related conversation's identifiers -- keys: ``id``, ``long``, ``blob``


def is_unit_acceptable(self, unit, raise_exception=True):

        _is_acceptable = unit in self.units

        if _is_acceptable or raise_exception is False:
            return _is_acceptable
        else:
            raise ValueError(
                '{0} is not an acceptable unit type for {1}. '
                'Choose from the following: {2}'.format(
                    unit, self.__class__.__name__, self.units
                )
            )

Check if a certain unit is acceptable for the data type.

Args:
unit: A text string representing the abbreviated unit.
raise_exception: Set to True to raise an exception if not acceptable.


def ordered_dump(data, Dumper=yaml.Dumper, **kws):

    class OrderedDumper(Dumper):
        pass

    def _dict_representer(dumper, data):
        return dumper.represent_mapping(
            yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG,
            data.items())
    OrderedDumper.add_representer(OrderedDict,
                                  _dict_representer)
    return yaml.dump(data, None, OrderedDumper, **kws)

Expand PyYAML's built-in dumper to support parsing OrderedDict. Return
a string as parse result of the original data structure, which includes
OrderedDict.

Args:
data: the data structure to be dumped(parsed) which is supposed to
contain OrderedDict.
Dumper: the yaml serializer to be expanded and used.
kws: extra key-value arguments to be passed to yaml.dump.


def validate_id_pool(self, id_or_uri, ids_pools):

        uri = self._client.build_uri(id_or_uri) + "/validate?idList=" + "&idList=".join(ids_pools)
        return self._client.get(uri)

Validates an ID pool.

Args:
id_or_uri:
ID or URI of range.
ids_pools (list):
List of Id Pools.

Returns:
dict: A dict containing a list with IDs.


def time_pad(x, filter_size, dilations):
    x_shape = common_layers.shape_list(x)
    if (filter_size == [1, 1, 1]):
        return x
    (_, h, w) = filter_size
    eff_h = (h + ((h - 1) * (dilations[2] - 1)))
    eff_w = (w + ((w - 1) * (dilations[3] - 1)))
    a = ((eff_h - 1)
    b = ((eff_w - 1)
    c = (filter_size[0] - 1)
    padding = [[0, 0], [c, 0], [a, a], [b, b], [0, 0]]
    x_bias = tf.zeros((x_shape[:(- 1)] + [1]))
    x_bias = tf.pad(x_bias, padding, constant_values=1)
    x_pad = tf.pad(x, padding)
    x_pad = tf.concat((x_bias, x_pad), axis=(- 1))
    return x_pad

Pad left across time and pad valid across the spatial components.

Also concats a binary feature that indicates if a feature is padded or not.

Args:
x: 5-D Tensor, (NTHWC)
filter_size: list of ints
dilations: list of ints, dilations - 1 specifies the number of holes
between two filter elements.
Returns:
x_pad: 5-D Tensor.


def command(task: Task, command: str) -> Result:

    cmd = subprocess.Popen(
        shlex.split(command),
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE,
        shell=False,
    )

    stdout, stderr = cmd.communicate()
    stdout = stdout.decode()
    stderr = stderr.decode()

    if cmd.poll():
        raise CommandError(command, cmd.returncode, stdout, stderr)

    result = stderr if stderr else stdout
    return Result(result=result, host=task.host, stderr=stderr, stdout=stdout)

Executes a command locally

Arguments:
command: command to execute

Returns:
Result object with the following attributes set:
* result (``str``): stderr or stdout
* stdout (``str``): stdout
* stderr (``str``): stderr

Raises:
:obj:`nornir.core.exceptions.CommandError`: when there is a command error


def _safe_initial_value_from_op(name, op, op_cache):
    op_type = op.node_def.op
    if op_type in ('IsVariableInitialized', 'VarIsInitializedOp', 'ReadVariableOp', 'If'):
        return op
    if op_type in ('Variable', 'VariableV2', 'VarHandleOp'):
        initialized_value = _find_initialized_value_for_variable(op)
        return op if initialized_value is None else initialized_value.op
    modified = False
    new_op_inputs = []
    for op_input in op.inputs:
        new_op_input = _safe_initial_value_from_tensor(name, op_input, op_cache)
        new_op_inputs.append(new_op_input)
        modified = modified or new_op_input != op_input
    if modified:
        new_op_type = op_type
        if new_op_type == 'RefSwitch':
            new_op_type = 'Switch'
        new_op_name = op.node_def.name + '_' + name
        new_op_name = new_op_name.replace(':', '_')
        return op.graph.create_op(new_op_type, new_op_inputs, op._output_types, name=new_op_name, attrs=op.node_def.attr)
    return op

Replace dependencies on variables with their initialized values.

Args:
name: Variable name.
op: An `Operation`. The operation to replace.
op_cache: A dict mapping operation names to `Operation`s. Used to memoize
the results so as to avoid creating redundant operations.

Returns:
An `Operation` compatible with `op`. Any inputs that lead to variable
values will be replaced with a corresponding graph that uses the
variable's initialized values. This is done on a best-effort basis. If no
modifications need to be made then `op` will be returned unchanged.


def SmartUnicode(string):
    if isinstance(string, Text):
        return string
    if isinstance(string, bytes):
        return string.decode('utf-8', 'ignore')
    if compatibility.PY2:
        return str(string).__native__()
    else:
        return str(string)

Returns a unicode object.

This function will always return a unicode object. It should be used to
guarantee that something is always a unicode object.

Args:
string: The string to convert.

Returns:
a unicode object.


def get_inst_info(qry_string):
    qry_prefix = 'EC2C.describe_instances('
    qry_real = ((qry_prefix + qry_string) + ')')
    qry_results = eval(qry_real)
    return qry_results

Get details for instances that match the qry_string.

Execute a query against the AWS EC2 client object, that is
based on the contents of qry_string.

Args:
qry_string (str): the query to be used against the aws ec2 client.
Returns:
qry_results (dict): raw information returned from AWS.


def trajectory(self, horizon: int, initial_state: Optional[StateTensor]=None) -> TrajectoryOutput:
    if (initial_state is None):
        initial_state = self._cell.initial_state()
    with self.graph.as_default():
        self.inputs = self.timesteps(horizon)
        (outputs, _) = tf.nn.dynamic_rnn(self._cell, self.inputs, initial_state=initial_state, dtype=tf.float32, scope='trajectory')
        (states, actions, interms, rewards) = outputs
        state_dtype = map(rddl2tf.utils.range_type_to_dtype, self._cell._compiler.rddl.state_range_type)
        states = self._output(states, state_dtype)
        interm_dtype = map(rddl2tf.utils.range_type_to_dtype, self._cell._compiler.rddl.interm_range_type)
        interms = self._output(interms, interm_dtype)
        action_dtype = map(rddl2tf.utils.range_type_to_dtype, self._cell._compiler.rddl.action_range_type)
        actions = self._output(actions, action_dtype)
        outputs = (initial_state, states, actions, interms, rewards)
    return outputs

Returns the ops for the trajectory generation with given `horizon`
and `initial_state`.

The simulation returns states, actions and interms as a
sequence of tensors (i.e., all representations are factored).
The reward is a batch sized tensor.
The trajectoty output is a tuple: (initial_state, states, actions, interms, rewards).
If initial state is None, use default compiler's initial state.

Note:
All tensors have shape: (batch_size, horizon, fluent_shape).
Except initial state that has shape: (batch_size, fluent_shape).

Args:
horizon (int): The number of simulation timesteps.
initial_state (Optional[Sequence[tf.Tensor]]): The initial state tensors.

Returns:
Tuple[StateTensor, StatesTensor, ActionsTensor, IntermsTensor, tf.Tensor]: Trajectory output tuple.


def compose(*funcs):
    if (not funcs):
        return (lambda *args: (args[0] if args else None))
    if (len(funcs) == 1):
        return funcs[0]
    last = funcs[(- 1)]
    rest = funcs[0:(- 1)]
    return (lambda *args: reduce((lambda ax, func: func(ax)), reversed(rest), last(*args)))

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


def normalize_to_element(self, element, factor=1):

        all_comp = self._all_comp
        coeffs = self._coeffs
        current_el_amount = sum([all_comp[i][element] * abs(coeffs[i])
                                 for i in range(len(all_comp))]) / 2
        scale_factor = factor / current_el_amount
        self._coeffs = [c * scale_factor for c in coeffs]

Normalizes the reaction to one of the elements.
By default, normalizes such that the amount of the element is 1.
Another factor can be specified.

Args:
element (Element/Specie): Element to normalize to.
factor (float): Factor to normalize to. Defaults to 1.


def _prepare_dict_inputs(inputs, tensor_info_map):

  if inputs is None:
    dict_inputs = {}
  elif isinstance(inputs, dict):
    dict_inputs = inputs
  elif len(tensor_info_map) == 1:
    dict_inputs = {list(tensor_info_map.keys())[0]: inputs}
  elif not tensor_info_map:
    raise TypeError("Signature expects no inputs.")
  else:
    raise TypeError("Signature expects multiple inputs. Use a dict.")

  dict_inputs_keys = set(dict_inputs.keys())
  tensor_info_map_keys = set(tensor_info_map.keys())
  if dict_inputs_keys != tensor_info_map_keys:
    raise TypeError("Cannot convert dict_inputs: missing %r, extra given %r" %
                    (sorted(list(tensor_info_map_keys - dict_inputs_keys)),
                     sorted(list(dict_inputs_keys - tensor_info_map_keys))))

  return dict_inputs

Converts inputs to a dict of inputs and checks extra/missing args.

Args:
inputs: inputs fed to Module.__call__().
tensor_info_map: A map from string to `tensor_info.ParsedTensorInfo`
describing the signature inputs.

Returns:
A dict of values with the same keys as tensor_info_map.

Raises:
TypeError: If it fails to convert the input values into a dict of tensors
to feed to the signature instantiation.


def __init__(self, text=None, delay=None):

    self._text = text or ''
    self._delay = delay
    try:
      self._tty = open('/dev/tty')
    except IOError:

      self._tty = sys.stdin
    self.SetLines(None)
    self.Reset()

Constructor.

Args:
text: A string, the text that will be paged through.
delay: A boolean, if True will cause a slight delay
between line printing for more obvious scrolling.


class PatchTSMixerLayer(nn.Module):

    def __init__(self, config: PatchTSMixerConfig):
        super().__init__()
        self.patch_mixer = PatchMixerBlock(config=config)
        self.feature_mixer = FeatureMixerBlock(config=config)
        self.mode = config.mode
        if config.mode == 'mix_channel':
            self.channel_feature_mixer = PatchTSMixerChannelFeatureMixerBlock(config=config)

    def forward(self, hidden: torch.Tensor):

        if self.mode == 'mix_channel':
            hidden = self.channel_feature_mixer(hidden)
        hidden = self.patch_mixer(hidden)
        hidden = self.feature_mixer(hidden)
        return hidden

The `PatchTSMixer` layer that does all three kinds of mixing.

Args:
config (`PatchTSMixerConfig`):
Configuration.


def from_file(cls, name: str, mod_path: Tuple[str] = (".",),
                  description: str = None) -> "DataModel":

        with open(name, encoding="utf-8") as infile:
            yltxt = infile.read()
        return cls(yltxt, mod_path, description)

Initialize the data model from a file with YANG library data.

Args:
name: Name of a file with YANG library data.
mod_path: Tuple of directories where to look for YANG modules.
description:  Optional description of the data model.

Returns:
The data model instance.

Raises:
The same exceptions as the class constructor above.


def parse_hpo_genes(hpo_lines):

    LOG.info("Parsing HPO genes ...")
    genes = {}
    for index, line in enumerate(hpo_lines):

        if index == 0:
            continue
        if len(line) < 5:
            continue
        gene_info = parse_hpo_gene(line)
        hgnc_symbol = gene_info['hgnc_symbol']
        description = gene_info['description']

        if hgnc_symbol not in genes:
            genes[hgnc_symbol] = {
                'hgnc_symbol': hgnc_symbol
            }

        gene = genes[hgnc_symbol]
        if description == 'Incomplete penetrance':
            gene['incomplete_penetrance'] = True
        if description == 'Autosomal dominant inheritance':
            gene['ad'] = True
        if description == 'Autosomal recessive inheritance':
            gene['ar'] = True
        if description == 'Mithochondrial inheritance':
            gene['mt'] = True
        if description == 'X-linked dominant inheritance':
            gene['xd'] = True
        if description == 'X-linked recessive inheritance':
            gene['xr'] = True
        if description == 'Y-linked inheritance':
            gene['x'] = True
        if description == 'X-linked inheritance':
            gene['y'] = True
    LOG.info("Parsing done.")
    return genes

Parse HPO gene information

Args:
hpo_lines(iterable(str))

Returns:
diseases(dict): A dictionary with hgnc symbols as keys


def parse_peddy_sex_check(lines):

    sex_check = []
    header = []
    for i,line in enumerate(lines):
        line = line.rstrip()
        if i == 0:

            header = line.lstrip('
        else:
            ind_info = dict(zip(header, line.split(',')))

            ind_info['error'] = make_bool(ind_info.get('error'))

            ind_info['hom_alt_count'] = convert_number(ind_info['hom_alt_count'])

            ind_info['hom_ref_count'] = convert_number(ind_info['hom_ref_count'])

            ind_info['het_count'] = convert_number(ind_info['het_count'])

            ind_info['het_ratio'] = convert_number(ind_info['het_ratio'])

            sex_check.append(ind_info)

    return sex_check

Parse a .ped_check.csv file

Args:
lines(iterable(str))

Returns:
sex_check(list(dict))


def init_subclass(self, node: 'cfg.CFGNode', cls: '_classes.InterpreterClass') -> 'cfg.CFGNode':
    del cls
    return node

Allow metaprogramming via __init_subclass__.

We do not analyse __init_subclass__ methods in the code, but overlays that
wish to replicate metaprogramming constructs using __init_subclass__ can
define a class overriding this method, and ctx.make_class will call
Class.call_init_subclass(), which will invoke the init_subclass() method for
all classes in the list of base classes.

This is here rather than in class_mixin.Class because a class's list of
bases can include abstract objects that do not derive from Class (e.g.
Unknown and Unsolvable).

Args:
node: cfg node
cls: the abstract.InterpreterClass that is being constructed with subclass
as a base

Returns:
A possibly new cfg node


def run_feed_keys_info(self):
    output = self._run_feed_keys_info
    return output[0] if len(output) == 1 else output

Get a str representation of the feed_dict used in the Session.run() call.

Returns:
If the information is available from one `Session.run` call, a `str`
obtained from `repr(feed_dict)`.
If the information is available from multiple `Session.run` calls, a
`list` of `str` obtained from `repr(feed_dict)`.
If the information is not available, `None`.


def contains(self, rect):
    return ((rect.y >= self.y) and (rect.x >= self.x) and ((rect.y + rect.height) <= (self.y + self.height)) and ((rect.x + rect.width) <= (self.x + self.width)))

Tests if another rectangle is contained by this one

Arguments:
rect (Rectangle): The other rectangle

Returns:
bool: True if it is container, False otherwise


def _binary_op(cls, x: 'TensorFluent', y: 'TensorFluent', op: Callable[([tf.Tensor, tf.Tensor], tf.Tensor)], dtype: tf.DType) -> 'TensorFluent':
    s1 = x.scope.as_list()
    s2 = y.scope.as_list()
    (scope, perm1, perm2) = TensorFluentScope.broadcast(s1, s2)
    if (x.batch and (perm1 != [])):
        perm1 = ([0] + [(p + 1) for p in perm1])
    if (y.batch and (perm2 != [])):
        perm2 = ([0] + [(p + 1) for p in perm2])
    x = x.transpose(perm1)
    y = y.transpose(perm2)
    (reshape1, reshape2) = TensorFluentShape.broadcast(x.shape, y.shape)
    if (reshape1 is not None):
        x = x.reshape(reshape1)
    if (reshape2 is not None):
        y = y.reshape(reshape2)
    x = x.cast(dtype)
    y = y.cast(dtype)
    t = op(x.tensor, y.tensor)
    batch = (x.batch or y.batch)
    return TensorFluent(t, scope, batch=batch)

Returns a TensorFluent for the binary `op` applied to fluents `x` and `y`.

Args:
x: The first operand.
y: The second operand.
op: The binary operator.
dtype: The output's data type.

Returns:
A TensorFluent wrapping the binary operator's output.


def testRaggedConst(self, pylist, dtype=None, ragged_rank=None, inner_shape=None, expected_shape=None, expected_dtype=None):
    rt = ragged_factory_ops.constant(pylist, dtype=dtype, ragged_rank=ragged_rank, inner_shape=inner_shape)
    pylist = _normalize_pylist(pylist)
    if dtype is not None:
        self.assertEqual(rt.dtype, dtype)
    if expected_dtype is not None:
        self.assertEqual(rt.dtype, expected_dtype)
    if ragged_rank is not None:
        if isinstance(rt, ragged_tensor.RaggedTensor):
            self.assertEqual(rt.ragged_rank, ragged_rank)
        else:
            self.assertEqual(0, ragged_rank)
    if inner_shape is not None:
        if isinstance(rt, ragged_tensor.RaggedTensor):
            self.assertEqual(rt.flat_values.shape.as_list()[1:], list(inner_shape))
        else:
            self.assertEqual(rt.shape.as_list(), list(inner_shape))
    if expected_shape is not None:
        self.assertEqual(tuple(rt.shape.as_list()), expected_shape)
        if expected_shape and expected_shape[0] == 0 and (None not in expected_shape):
            pylist = np.zeros(expected_shape, rt.dtype.as_numpy_dtype)
    self.assertAllEqual(rt, pylist)

Tests that `ragged_const(pylist).eval().tolist() == pylist`.

Args:
pylist: The `pylist` argument for `ragged_const()`.
dtype: The `dtype` argument for `ragged_const()`.  If not None, then also
test that the resulting ragged tensor has this `dtype`.
ragged_rank: The `ragged_rank` argument for `ragged_const()`.  If not
None, then also test that the resulting ragged tensor has this
`ragged_rank`.
inner_shape: The `inner_shape` argument for `ragged_const()`.  If not
None, then also test that the resulting ragged tensor has this
`inner_shape`.
expected_shape: The expected shape for the resulting ragged tensor.
expected_dtype: The expected dtype for the resulting ragged tensor (used
to test default/inferred types when dtype=None).


def add_metric(self, labels, value, created=None, timestamp=None):

        self.samples.append(Sample(self.name + '_total', dict(zip(self._labelnames, labels)), value, timestamp))
        if created is not None:
            self.samples.append(Sample(self.name + '_created', dict(zip(self._labelnames, labels)), created, timestamp))

Add a metric to the metric family.

Args:
labels: A list of label values
value: The value of the metric
created: Optional unix timestamp the child was created at.


def JobDueToRun(self, job):
    if (not job.enabled):
        return False
    if job.forced_run_requested:
        return True
    now = rdfvalue.RDFDatetime.Now()
    if ((job.last_run_time is not None) and ((job.last_run_time + job.frequency) > now)):
        return False
    if (not job.current_run_id):
        return True
    if job.allow_overruns:
        return True
    return False

Determines if the given job is due for another run.

Args:
job: The cron job rdfvalue object.

Returns:
True if it is time to run based on the specified frequency.


def open(self, filename):

        if filename:
            self.binary = BinaryFile(filename)
            self.text_section = self.binary.text_section

            self._load(arch_mode=self.binary.architecture_mode)

Open a file for analysis.

Args:
filename (str): Name of an executable file.


def diffuse_horizontal_radiation(self, value=9999.0):

        if value is not None:
            try:
                value = float(value)
            except ValueError:
                raise ValueError(
                    'value {} need to be of type float '
                    'for field `diffuse_horizontal_radiation`'.format(value))
            if value < 0.0:
                raise ValueError('value need to be greater or equal 0.0 '
                                 'for field `diffuse_horizontal_radiation`')

        self._diffuse_horizontal_radiation = value

Corresponds to IDD Field `diffuse_horizontal_radiation`

Args:
value (float): value for IDD Field `diffuse_horizontal_radiation`
Unit: Wh/m2
value >= 0.0
Missing value: 9999.0
if `value` is None it will not be checked against the
specification and is assumed to be a missing value

Raises:
ValueError: if `value` is not a valid value


def _check_stop_conditions(self, sensor_graph):

        for stop in self.stop_conditions:
            if stop.should_stop(self.tick_count, self.tick_count - self._start_tick, sensor_graph):
                return True

        return False

Check if any of our stop conditions are met.

Args:
sensor_graph (SensorGraph): The sensor graph we are currently simulating

Returns:
bool: True if we should stop the simulation


def arccosh(x):
    if any_symbolic_tensors((x,)):
        return Arccosh().symbolic_call(x)
    return backend.numpy.arccosh(x)

Inverse hyperbolic cosine, element-wise.

Arguments:
x: Input tensor.

Returns:
Output tensor of same shape as x.

Example:
>>> x = keras.ops.convert_to_tensor([10, 100])
>>> keras.ops.arccosh(x)
array([2.993223, 5.298292], dtype=float32)


def hours(start, end=None):
    return iterate.between(start, datetime.timedelta(hours=1), end)

Iterate over the hours between the given datetime_tzs.

Args:
start: datetime_tz to start from.
end: (Optional) Date to end at, if not given the iterator will never
terminate.

Returns:
An iterator which generates datetime_tz objects a hour apart.


def show_available_noise_curves(return_curves=True, print_curves=False):

    if return_curves is False and print_curves is False:
        raise ValueError("Both return curves and print_curves are False."
                         + " You will not see the options")
    cfd = os.path.dirname(os.path.abspath(__file__))
    curves = [curve.split('.')[0] for curve in os.listdir(cfd + '/noise_curves/')]
    if print_curves:
        for f in curves:
            print(f)
    if return_curves:
        return curves
    return

List available sensitivity curves

This function lists the available sensitivity curve strings in noise_curves folder.

Args:
return_curves (bool, optional): If True, return a list of curve options.
print_curves (bool, optional): If True, print each curve option.

Returns:
(optional list of str): List of curve options.

Raises:
ValueError: Both args are False.


def format(self, *args, **kwargs):
    inplace = kwargs.pop('inplace', False)
    if (not inplace):
        return str(self).format(*args, **kwargs)
    self._lines = str(self).format(*args, **kwargs).splitlines()

Format the string representation of the editor.

Args:
inplace (bool): If True, overwrite editor's contents with formatted contents


def commit_history(filename):
    result = []
    repo = Repo()
    for commit in repo.head.commit.iter_parents(paths=(_delta_dir() + filename)):
        result.append({'date': datetime.fromtimestamp((commit.committed_date + commit.committer_tz_offset)), 'hexsha': commit.hexsha})
    return result

Retrieve the commit history for a given filename.

Keyword Arguments:
:filename: (str) -- full name of the file

Returns:
list of dicts -- list of commit
if the file is not found, returns an empty list


def set_exception(self, exc_class, exc_info, exc_stack):

        if self.is_finished():
            raise InternalError("set_exception called on finished AsynchronousResponse",
                                result=self._result, exception=self._exception)

        self._exception = (exc_class, exc_info, exc_stack)
        self.finish()

Set an exception as the result of this operation.

Args:
exc_class (object): The exception type


def time_series_h5(timefile, colnames):
    if (not timefile.is_file()):
        return None
    with h5py.File(timefile, 'r') as h5f:
        dset = h5f['tseries']
        (_, ncols) = dset.shape
        ncols -= 1
        h5names = map(bytes.decode, h5f['names'][(len(colnames) + 1):])
        _tidy_names(colnames, ncols, h5names)
        data = dset[()]
    return pd.DataFrame(data[(:, 1:)], index=np.int_(data[(:, 0)]), columns=colnames)

Read temporal series HDF5 file.

If :data:`colnames` is too long, it will be truncated. If it is too short,
additional column names will be deduced from the content of the file.

Args:
timefile (:class:`pathlib.Path`): path of the TimeSeries.h5 file.
colnames (list of names): names of the variables expected in
:data:`timefile` (may be modified).

Returns:
:class:`pandas.DataFrame`:
Time series, with the variables in columns and the time steps in
rows.


def remove_extra_presentations(self, resource, timeout=(- 1)):
    uri = (self.URI + '/repair')
    custom_headers = {'Accept-Language': 'en_US'}
    return self._client.create(resource, uri=uri, timeout=timeout, custom_headers=custom_headers)

Removes extra presentations from a specified server profile.

Args:
resource (dict):
Object to create
timeout:
Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation
in OneView; it just stops waiting for its completion.
Returns:
dict: Associated storage attachment resource.


def __call__(self, observed_obj, *arg, **kw):

        bound_method = getattr(self.inst(), self.method_name)
        if self.identify_observed:
            return bound_method(observed_obj, *arg, **kw)
        else:
            return bound_method(*arg, **kw)

Call the function I wrap.

Args:
*arg: The arguments passed to me by the observed object.
**kw: The keyword args passed to me by the observed object.
observed_obj: The observed object which called me.

Returns:
Whatever the function I wrap returns.


def to_inputs(self, indices=None):
    indices = (indices or range(len(self.outputs)))
    return [Input(self.outputs[idx].fulfillment, self.outputs[idx].public_keys, TransactionLink(self.id, idx)) for idx in indices]

Converts a Transaction's outputs to spendable inputs.

Note:
Takes the Transaction's outputs and derives inputs
from that can then be passed into `Transaction.transfer` as
`inputs`.
A list of integers can be passed to `indices` that
defines which outputs should be returned as inputs.
If no `indices` are passed (empty list or None) all
outputs of the Transaction are returned.

Args:
indices (:obj:`list` of int): Defines which
outputs should be returned as inputs.

Returns:
:obj:`list` of :class:`~bigchaindb.common.transaction.
Input`


def _validate_observation_data(
    kernel, observation_index_points, observations):

  ndims = kernel.feature_ndims
  if (tensorshape_util.is_fully_defined(
      observation_index_points.shape[:-ndims]) and
      tensorshape_util.is_fully_defined(observations.shape)):
    index_point_count = observation_index_points.shape[:-ndims]
    observation_count = observations.shape
    try:
      tf.broadcast_static_shape(index_point_count, observation_count)
    except ValueError:

      raise ValueError(
          'Observation index point and observation counts are not '
          'broadcastable: {} and {}, respectively.'.format(
              index_point_count, observation_count))

Ensure that observation data and locations have consistent shapes.

This basically means that the batch shapes are broadcastable. We can only
ensure this when those shapes are fully statically defined.

Args:
kernel: The GP kernel.
observation_index_points: the observation data locations in the index set.
observations: the observation data.

Raises:
ValueError: if the observations' batch shapes are not broadcastable.


async def get_log(self, pipeline_uuid: str, example_filepath: str) -> str:
    self._verify_pipeline_uuid(pipeline_uuid)
    request = api_pb2.GetLogsRequest(pipeline_uuid=pipeline_uuid)
    response = await self._stub.GetLogs(request, **self._kwargs)
    if response.output == '':
        logging.info('Log for %s is empty', example_filepath)
    return response.output

Get the result of pipeline execution.

Args:
pipeline_uuid: uuid of the pipeline
example_filepath: path to the file of the example

Returns:
output: contain the result of pipeline execution


def _FormatTag(self, event):
    tag = getattr(event, 'tag', None)
    if (not tag):
        return '-'
    return ' '.join(tag.labels)

Formats the event tag.

Args:
event (EventObject): event.

Returns:
str: event tag field.


def reload_napps(self, napps=None):

        if napps is None:
            napps = []
            api = self._config.get('kytos', 'api')
            endpoint = os.path.join(api, 'api', 'kytos', 'core', 'reload',
                                    'all')
            response = self.make_request(endpoint)

        for napp in napps:
            api = self._config.get('kytos', 'api')
            endpoint = os.path.join(api, 'api', 'kytos', 'core', 'reload',
                                    napp[0], napp[1])
            response = self.make_request(endpoint)

        if response.status_code != 200:
            raise KytosException('Error reloading the napp: Module not founded'
                                 ' or could not be imported')

        return response.content

Reload a specific NApp or all Napps.

Args:
napp (list): NApp list to be reload.
Raises:
requests.HTTPError: When there's a server error.


def get_credit_card(self, credit_card_id):

        return self.client._get(self.url + 'creditCards/{}'.format(credit_card_id), headers=self.get_headers())

Check the information of a credit card (Token) data identifier.

Args:
credit_card_id: Credit Card Token you want to consult.

Returns:


def _SparseTensorDenseMatMulGrad(op: ops.Operation, grad):
    a_indices, a_values, a_shape = op.inputs[:3]
    b = op.inputs[3]
    adj_a = op.get_attr('adjoint_a')
    adj_b = op.get_attr('adjoint_b')
    a_type = a_values.dtype.base_dtype
    b_type = b.dtype.base_dtype
    if a_type != b_type:
        raise TypeError(f'SparseTensorDenseMatMul op received operands with different types: `{a_type}` and `{b_type}`.')
    b_grad = gen_sparse_ops.sparse_tensor_dense_mat_mul(a_indices, a_values, a_shape, grad, adjoint_a=not adj_a)
    if adj_b:
        b_grad = array_ops.matrix_transpose(b_grad, conjugate=True)
    rows = a_indices[:, 0]
    cols = a_indices[:, 1]
    parts_a = array_ops.gather(grad, rows if not adj_a else cols)
    parts_b = array_ops.gather(b if not adj_b else array_ops.transpose(b), cols if not adj_a else rows)
    if not adj_a and (not adj_b):
        a_values_grad = math_ops.matmul(array_ops.expand_dims(parts_a, -2), array_ops.expand_dims(parts_b, -2), adjoint_b=True)
    elif adj_a and (not adj_b):
        a_values_grad = math_ops.matmul(array_ops.expand_dims(parts_a, -1), array_ops.expand_dims(parts_b, -1), adjoint_a=True)
    elif not adj_a and adj_b:
        a_values_grad = math_ops.matmul(array_ops.expand_dims(parts_a, -2), array_ops.expand_dims(parts_b, -1))
    elif adj_a and adj_b:
        a_values_grad = math_ops.matmul(array_ops.expand_dims(parts_a, -1), array_ops.expand_dims(parts_b, -2), adjoint_a=True, adjoint_b=True)
    return (None, array_ops.squeeze(a_values_grad, axis=[-2, -1]), None, b_grad)

Gradients for the dense tensor in the SparseTensorDenseMatMul op.

Args:
op: the SparseTensorDenseMatMul op
grad: the incoming gradient

Returns:
Gradient for each of the 4 input tensors:
(sparse_indices, sparse_values, sparse_shape, dense_tensor)
The gradients for indices and shape are None.

Raises:
TypeError: When the two operands don't have the same type.


def process(self, element):
    (text, uid), prediction = element
    cluster = prediction.inference.item()
    bq_dict = {'text': text, 'id': uid, 'cluster': cluster}
    yield bq_dict

The `process` function takes the output of RunInference and returns a dictionary
with the text, uid, and cluster.**

Args:
element: The input element to be processed.


def get_dialect(mixed: Union[SQLCompiler, Engine, Dialect]) -> Dialect:

    if isinstance(mixed, Dialect):
        return mixed
    elif isinstance(mixed, Engine):
        return mixed.dialect
    elif isinstance(mixed, SQLCompiler):
        return mixed.dialect
    else:
        raise ValueError("get_dialect: 'mixed' parameter of wrong type")

Finds the SQLAlchemy dialect in use.

Args:
mixed: an SQLAlchemy :class:`SQLCompiler`, :class:`Engine`, or
:class:`Dialect` object

Returns: the SQLAlchemy :class:`Dialect` being used


def walk(self, address):

        for step in self._walk_to_address(address):
            node = step
            yield node.address, node.data

        to_process = deque()

        to_process.extendleft(
            node.children)

        while to_process:
            node = to_process.pop()

            yield node.address, node.data

            if node.children:
                to_process.extendleft(
                    node.children)

Returns a stream of pairs of node addresses and data, raising
AddressNotInTree if ADDRESS is not in the tree.

First the ancestors of ADDRESS (including itself) are yielded,
earliest to latest, and then the descendants of ADDRESS are
yielded in an unspecified order.

Arguments:
address (str): the address to be walked


def oauth_required(self, method):

        def check_oauth(request_handler, *args, **kwargs):
            if self._in_error:
                self._display_error_message(request_handler)
                return

            user = users.get_current_user()

            if not user:
                request_handler.redirect(users.create_login_url(
                    request_handler.request.uri))
                return

            self._create_flow(request_handler)

            self.flow.params['state'] = _build_state_value(
                request_handler, user)
            self.credentials = self._storage_class(
                self._credentials_class, None,
                self._credentials_property_name, user=user).get()

            if not self.has_credentials():
                return request_handler.redirect(self.authorize_url())
            try:
                resp = method(request_handler, *args, **kwargs)
            except client.AccessTokenRefreshError:
                return request_handler.redirect(self.authorize_url())
            finally:
                self.credentials = None
            return resp

        return check_oauth

Decorator that starts the OAuth 2.0 dance.

Starts the OAuth dance for the logged in user if they haven't already
granted access for this application.

Args:
method: callable, to be decorated method of a webapp.RequestHandler
instance.


def profile_setting_default_args(ij):

        profile_default_args = OrderedDict()
        profile_default_args['api_default_org'] = '$env.API_DEFAULT_ORG'
        profile_default_args['api_access_id'] = '$env.API_ACCESS_ID'
        profile_default_args['api_secret_key'] = '$envs.API_SECRET_KEY'
        profile_default_args['tc_api_path'] = '$env.TC_API_PATH'
        profile_default_args['tc_docker'] = False
        profile_default_args['tc_in_path'] = 'log'
        profile_default_args['tc_log_level'] = 'debug'
        profile_default_args['tc_log_path'] = 'log'
        profile_default_args['tc_log_to_api'] = False
        profile_default_args['tc_out_path'] = 'log'
        profile_default_args['tc_proxy_external'] = False
        profile_default_args['tc_proxy_host'] = '$env.TC_PROXY_HOST'
        profile_default_args['tc_proxy_port'] = '$env.TC_PROXY_PORT'
        profile_default_args['tc_proxy_password'] = '$envs.TC_PROXY_PASSWORD'
        profile_default_args['tc_proxy_tc'] = False
        profile_default_args['tc_proxy_username'] = '$env.TC_PROXY_USERNAME'
        profile_default_args['tc_temp_path'] = 'log'
        if ij.get('runtimeLevel') == 'Playbook':
            profile_default_args['tc_playbook_db_type'] = 'Redis'
            profile_default_args['tc_playbook_db_context'] = str(uuid4())
            profile_default_args['tc_playbook_db_path'] = '$env.DB_PATH'
            profile_default_args['tc_playbook_db_port'] = '$env.DB_PORT'
            profile_default_args['tc_playbook_out_variables'] = ''
        return profile_default_args

Build the default args for this profile.

Args:
ij (dict): The install.json contents.

Returns:
dict: The default args for a Job or Playbook App.


def gcd(*numbers):
    n = numbers[0]
    for i in numbers:
        n = pygcd(n, i)
    return n

Returns the greatest common divisor for a sequence of numbers.

Args:
\*numbers: Sequence of numbers.

Returns:
(int) Greatest common divisor of numbers.


def set(self, **kwargs):

        for port_name, port_value in kwargs.items():

            if hasattr(port_value, 'value'):
                port_value = port_value.value

            self.inputs.__setattr__(port_name, port_value)

Set input values on task

Args:
arbitrary_keys: values for the keys

Returns:
None


async def change_file(self, file_path: str, description: str=None):
    with open(file_path, 'rb') as f:
        (await self._change(asset=f.read()))

change the file of that attachment

|methcoro|

Warning:
|unstable|

Args:
file_path: path to the file you want to add / modify
description: *optional* description for your attachment

Raises:
ValueError: file_path must not be None
APIException


def _bump_version(version, component='patch'):

    if component not in ('major', 'minor', 'patch'):
        raise ValueError("Invalid version component: {}".format(component))

    m = RE_VERSION.match(version)
    if m is None:
        raise ValueError("Version must be in MAJOR.MINOR[.PATCH] format")

    major = m.group('major')
    minor = m.group('minor') or '0'
    patch = m.group('patch') or None

    if patch == '0':
        patch = None

    if component == 'major':
        major = str(int(major) + 1)
        minor = '0'
        patch = None

    elif component == 'minor':
        minor = str(int(minor) + 1)
        patch = None

    else:
        patch = patch or 0
        patch = str(int(patch) + 1)

    new_ver = '{}.{}'.format(major, minor)
    if patch is not None:
        new_ver += '.' + patch

    return new_ver

Bump the given version component.

Args:
version (str):
The current version. The format is: MAJOR.MINOR[.PATCH].
component (str):
What part of the version should be bumped. Can be one of:

- major
- minor
- patch

Returns:
str: Bumped version as a string.


def measure_states(states, measurement_matrix, measurement_covariance):

    measurement_matrix = np.atleast_2d(measurement_matrix)
    measurement_covariance = np.atleast_2d(measurement_covariance)
    measurement_dim = measurement_matrix.shape[0]
    if measurement_covariance.shape != (measurement_dim, measurement_dim):
        raise ValueError(("Measurement matrix and covariance have inconsistent "
                          "shapes {} and {}").format(measurement_matrix.shape,
                                                     measurement_covariance.shape))
    states = np.atleast_2d(states)

    if states.shape[0] == 0:
        return np.zeros((0, measurement_dim))

    measurement_means = measurement_matrix.dot(states.T).T
    measurement_noises = np.random.multivariate_normal(
        mean=np.zeros(measurement_dim), cov=measurement_covariance,
        size=states.shape[0]
    )

    return measurement_means + measurement_noises

Measure a list of states with a measurement matrix in the presence of
measurement noise.

Args:
states (array): states to measure. Shape is NxSTATE_DIM.
measurement_matrix (array): Each state in *states* is measured with this
matrix. Should be MEAS_DIMxSTATE_DIM in shape.
measurement_covariance (array): Measurement noise covariance. Should be
MEAS_DIMxMEAS_DIM.

Returns:
(array): NxMEAS_DIM array of measurements.


def _parse_authors(html_chunk):

    authors_tags = html_chunk.match(
        ["div", {"class": "polozka_autor"}],
        "a"
    )

    authors = []
    for author_tag in authors_tags:

        name = author_tag.getContent().strip()

        if not name:
            continue

        url = author_tag.params.get("href", None)
        if url:
            url = normalize_url(BASE_URL, url)

        authors.append(
            Author(name, url)
        )

    return authors

Parse authors of the book.

Args:
html_chunk (obj): HTMLElement containing slice of the page with details.

Returns:
list: List of :class:`structures.Author` objects. Blank if no author \
found.


def peak_signal_to_noise_ratio(true, pred):

  return 10.0 * tf.log(1.0 / mean_squared_error(true, pred)) / tf.log(10.0)

Image quality metric based on maximal signal power vs. power of the noise.

Args:
true: the ground truth image.
pred: the predicted image.
Returns:
peak signal to noise ratio (PSNR)


def dict_values(src):

    for v in src.values():
        if isinstance(v, dict):
            for v in dict_values(v):
                yield v
        else:
            yield v

Recursively get values in dict.

Unlike the builtin dict.values() function, this method will descend into
nested dicts, returning all nested values.

Arguments:
src (dict): Source dict.

Returns:
list: List of values.


def wait(self):
    if (self._status is not TaskStatus.STARTED):
        raise RuntimeError(('Cannot wait on %s in state %s' % (self, self._status)))
    self._wait()
    self.stop()
    return self.return_values

Wait on a task to finish and stop it when it has finished.

Raises:
RuntimeError: If the task hasn't been started or has already been
stopped.

Returns:
The ``return_values`` of the task.


def apply(coro, *args, **kw):
    assert_corofunction(coro=coro)

    @asyncio.coroutine
    def wrapper(*_args, **_kw):
        return (yield from coro(*args, **kw))
    return wrapper

Creates a continuation coroutine function with some arguments
already applied.

Useful as a shorthand when combined with other control flow functions.
Any arguments passed to the returned function are added to the arguments
originally passed to apply.

This is similar to `paco.partial()`.

This function can be used as decorator.

arguments:
coro (coroutinefunction): coroutine function to wrap.
*args (mixed): mixed variadic arguments for partial application.
*kwargs (mixed): mixed variadic keyword arguments for partial
application.

Raises:
TypeError: if coro argument is not a coroutine function.

Returns:
coroutinefunction: wrapped coroutine function.

Usage::

async def hello(name, mark='!'):
print('Hello, {name}{mark}'.format(name=name, mark=mark))

hello_mike = paco.apply(hello, 'Mike')
await hello_mike()
# => Hello, Mike!

hello_mike = paco.apply(hello, 'Mike', mark='?')
await hello_mike()
# => Hello, Mike?


def _get_dataset_showcase_dict(self, showcase):
    if (isinstance(showcase, hdx.data.showcase.Showcase) or isinstance(showcase, dict)):
        if ('id' not in showcase):
            showcase = hdx.data.showcase.Showcase.read_from_hdx(showcase['name'])
        showcase = showcase['id']
    elif (not isinstance(showcase, str)):
        raise HDXError(('Type %s cannot be added as a showcase!' % type(showcase).__name__))
    if (is_valid_uuid(showcase) is False):
        raise HDXError(('%s is not a valid showcase id!' % showcase))
    return {'package_id': self.data['id'], 'showcase_id': showcase}

Get dataset showcase dict

Args:
showcase (Union[Showcase,Dict,str]): Either a showcase id or Showcase metadata from a Showcase object or dictionary

Returns:
dict: dataset showcase dict


def validator(flag_name, message='Flag validation failed', flag_values=_flagvalues.FLAGS):

    def decorate(function):
        register_validator(flag_name, function, message=message, flag_values=flag_values)
        return function
    return decorate

A function decorator for defining a flag validator.

Registers the decorated function as a validator for flag_name, e.g.

@flags.validator('foo')
def _CheckFoo(foo):
...

See register_validator() for the specification of checker function.

Args:
flag_name: str, name of the flag to be checked.
message: str, error text to be shown to the user if checker returns False.
If checker raises flags.ValidationError, message from the raised
error will be shown.
flag_values: flags.FlagValues, optional FlagValues instance to validate
against.
Returns:
A function decorator that registers its function argument as a validator.
Raises:
AttributeError: Raised when flag_name is not registered as a valid flag
name.


def min_validator(min_value):

    def validator(value):
        if value < min_value:
            raise ValidationError("{} is not >= {}".format(value, min_value))

    return validator

Return validator function that ensures lower bound of a number.

Result validation function will validate the internal value of resource
instance field with the ``value >= min_value`` check

Args:
min_value: minimal value for new validator


def fmttime(tin):

    aaa, bbb = '{:.2e}'.format(tin).split('e')
    bbb = int(bbb)
    return r'$t={} \times 10^{{{}}}$'.format(aaa, bbb)

Return LaTeX expression with time in scientific notation.

Args:
tin (float): the time.
Returns:
str: the LaTeX expression.


def _extract_mnist_images(filename, num_images):
    with gzip.open(filename) as bytestream:
        bytestream.read(16)
        buf = bytestream.read(((_MNIST_IMAGE_SIZE * _MNIST_IMAGE_SIZE) * num_images))
        data = np.frombuffer(buf, dtype=np.uint8)
        data = data.reshape(num_images, _MNIST_IMAGE_SIZE, _MNIST_IMAGE_SIZE, 1)
    return data

Extract images from an MNIST file into a numpy array.

Args:
filename: The path to an MNIST images file.
num_images: The number of images in the file.

Returns:
A numpy array of shape [number_of_images, height, width, channels].


def refresh_tree(self, tree, items):

        if tree == self.tree_scripts or tree == self.tree_settings:
            tree.itemChanged.disconnect()
            self.fill_treewidget(tree, items)
            tree.itemChanged.connect(lambda: self.update_parameters(tree))
        elif tree == self.tree_gui_settings:
            self.fill_treeview(tree, items)

refresh trees with current settings
Args:
tree: a QtWidgets.QTreeWidget object or a QtWidgets.QTreeView object
items: dictionary or Parameter items with which to populate the tree
show_all: boolean if true show all parameters, if false only selected ones


def build(self, var_list):
    if self.built:
        return
    super().build(var_list)
    accumulator_initializer = initializers.Constant(self.initial_accumulator_value)
    self._accumulators, self._linears = self.add_optimizer_variables(var_list, ['accumulator', 'linear'], initializer=[accumulator_initializer, 'zeros'])

Initialize optimizer variables.

Args:
var_list: list of model variables to build Ftrl variables on.


def produce_csv_output(filehandle: TextIO, fields: Sequence[str], values: Iterable[str]) -> None:
    output_csv(filehandle, fields)
    for row in values:
        output_csv(filehandle, row)

Produce CSV output, without using ``csv.writer``, so the log can be used
for lots of things.

- ... eh? What was I talking about?
- POOR; DEPRECATED.

Args:
filehandle: file to write to
fields: field names
values: values


def get_lagged_subsequences(self, sequence: torch.Tensor, subsequences_length: int, shift: int=0) -> torch.Tensor:
    sequence_length = sequence.shape[1]
    indices = [lag - shift for lag in self.config.lags_sequence]
    if max(indices) + subsequences_length > sequence_length:
        raise ValueError(f'lags cannot go further than history length, found lag {max(indices)} while history length is only {sequence_length}')
    lagged_values = []
    for lag_index in indices:
        begin_index = -lag_index - subsequences_length
        end_index = -lag_index if lag_index > 0 else None
        lagged_values.append(sequence[:, begin_index:end_index, ...])
    return torch.stack(lagged_values, dim=-1)

Returns lagged subsequences of a given sequence. Returns a tensor of shape (N, S, C, I),
where S = subsequences_length and I = len(indices), containing lagged subsequences. Specifically, lagged[i,
j, :, k] = sequence[i, -indices[k]-S+j, :].

Args:
sequence: Tensor
The sequence from which lagged subsequences should be extracted. Shape: (N, T, C).
subsequences_length : int
Length of the subsequences to be extracted.
shift: int
Shift the lags by this amount back.


def add_event(self, event):
    if (not isinstance(event, event_pb2.Event)):
        raise TypeError(('Expected an event_pb2.Event proto,  but got %s' % type(event)))
    self._async_writer.write(event.SerializeToString())

Adds an event to the event file.

Args:
event: An `Event` protocol buffer.


def restart_apppool(name):
    ps_cmd = ['Restart-WebAppPool', "'{0}'".format(name)]
    cmd_ret = _srvmgr(ps_cmd)
    return (cmd_ret['retcode'] == 0)

Restart an IIS application pool.

.. versionadded:: 2016.11.0

Args:
name (str): The name of the IIS application pool.

Returns:
bool: True if successful, otherwise False

CLI Example:

.. code-block:: bash

salt '*' win_iis.restart_apppool name='MyTestPool'