def AsDict(self, dt=True):

        data = {}

        if self.sharekey:
            data['sharekey'] = self.sharekey
        if self.name:
            data['name'] = self.name
        if self.user:
            data['user'] = self.user.AsDict()
        if self.title:
            data['title'] = self.title
        if self.description:
            data['description'] = self.description
        if self.posted_at:
            if dt:
                data['posted_at'] = self.posted_at
            else:
                data['posted_at'] = self.posted_at_iso
        if self.permalink:
            data['permalink'] = self.permalink
        if self.width:
            data['width'] = self.width
        if self.height:
            data['height'] = self.height
        if self.image_url:
            data['image_url'] = self.image_url
        if self.source_url:
            data['source_url'] = self.source_url
        data['views'] = self.views
        data['likes'] = self.likes
        data['saves'] = self.saves
        data['comments'] = self.comments
        data['nsfw'] = self.nsfw
        data['saved'] = self.saved
        data['liked'] = self.liked

        return data

A dict representation of this Shake instance.

The return value uses the same key names as the JSON representation.

Args:
dt (bool): If True, return dates as python datetime objects. If
False, return dates as ISO strings.

Return:
A dict representing this Shake instance


def from_json_str(cls, json_str: str, primitive_cls: Type[message.Message], context: Context) -> 'PrimitiveWrapper':

Serializes json_str into an instance of primitive_cls and wraps.

Args:
json_str: The string-representation of the raw json_value to serialize
into primitive_cls and wrap.
primitive_cls: The FHIR primitive class to serialize into and wrap.
context: Related primitive information to use for printing/parsing a
wrapped primitive.

Returns:
An instance of PrimitiveWrapper.


def does_attribute_meet_condition(self, attribute, conditions):

        if conditions is None or len(conditions) == 0:
            return True

        for attribute_name, attribute_value in conditions.items():
            value = getattr(attribute, attribute_name, False)
            if value != attribute_value and bool(value) != attribute_value:
                return False

        return True

Check if the attribute meet all the given conditions

Args:
attribute: the attribute information
conditions: a dictionary of condition to match

Returns:
True if the attribute match all conditions. False otherwise


def _repr_to_list(value: torch.Tensor):
    torch.set_printoptions(sci_mode=True, linewidth=120)
    with StringIO() as buf, redirect_stdout(buf):
        print(value)
        raw = buf.getvalue()
    return _sanitize_repr_for_diff(raw).splitlines()

Converts a tensor into a sanitized multi-line string representation.

Args:
value (`torch.Tensor`): The tensor to represent.

Returns:
`List[str]`: List of string lines representing the tensor.


def open_if_needed(self, mode=None):

        was_open = self.is_open()

        if not was_open:
            self.open(mode=mode)

        try:
            yield self
        finally:
            if not was_open:
                self.close()

Convenience context-manager for the use with ``with``.
Opens the container if not already done.
Only closes the container if it was opened within this context.

Args:
mode (str): Either 'r' for read-only, 'w' for truncate and write or
'a' for append. (default: 'a').
If ``None``, uses ``self.mode``.


def get_field(proto: message.Message, fields: FieldTypes) -> tuple[Any, Optional[descriptor.FieldDescriptor]]:
    field_proto = proto
    field_desc = None
    for field_proto, field_desc, _, _ in _walk_fields(proto, fields):
        pass
    return (field_proto, field_desc)

Returns the field and field descriptor from the proto.

Args:
proto: Parent proto of any message type.
fields: List of string/int/map key fields, e.g. ["nodes", "attr", "value"]
can represent `proto.nodes.attr["value"]`.

Returns:
Tuple of (
Field in the proto or `None` if none are found,
Field descriptor
)


def get(cls, blob_key, **ctx_options):

    fut = cls.get_async(blob_key, **ctx_options)
    return fut.get_result()

Retrieve a BlobInfo by key.

Args:
blob_key: A blob key.  This may be a str, unicode or BlobKey instance.
**ctx_options: Context options for Model().get_by_id().

Returns:
A BlobInfo entity associated with the provided key,  If there was
no such entity, returns None.


def mark_experimental(fn):

    @wraps(fn)
    def wrapper(*args, **kw):
        from peltak.core import shell
        if shell.is_tty:
            warnings.warn('This command is has experimental status. The interface is not yet stable and might change without notice within with a patch version update. Use at your own risk')
        return fn(*args, **kw)
    return wrapper

Mark function as experimental.

Args:
fn (FunctionType):
The command function to decorate.


def _create_record_internal(self, rtype, name, content, identifier=None):
    name = (self._relative_name(name) if (name is not None) else name)
    LOGGER.debug('Creating record with name %s', name)
    if self._is_duplicate_record(rtype, name, content):
        return True
    data = self._get_post_data_to_create_dns_entry(rtype, name, content, identifier)
    LOGGER.debug('Create DNS data: %s', data)
    create_response = self.session.post(self.URLS['dns_create_entry'].format(self.domain_id), data=data)
    self._invalidate_records_cache()
    self._log('Create DNS entry', create_response)
    was_success = (len(self._list_records(rtype, name, content)) > 0)
    if was_success:
        msg = 'Successfully added record %s'
    else:
        msg = 'Failed to add record %s'
    LOGGER.info(msg, name)
    return was_success

Create a new DNS entry in the domain zone if it does not already exist.

Args:
rtype (str): The DNS type (e.g. A, TXT, MX, etc) of the new entry.
name (str): The name of the new DNS entry, e.g the domain for which a
MX entry shall be valid.
content (str): The content of the new DNS entry, e.g. the mail server
hostname for a MX entry.
[identifier] (str): The easyname id of a DNS entry. Use to overwrite an
existing entry.

Returns:
bool: True if the record was created successfully, False otherwise.


def create_output(self, key, value, variable_type=None):

        results = None
        if key is not None:
            key = key.strip()
            key_type = '{}-{}'.format(key, variable_type)
            if self.out_variables_type.get(key_type) is not None:

                v = self.out_variables_type.get(key_type)
                self.tcex.log.info(
                    u'Variable {} was requested by downstream app.'.format(v.get('variable'))
                )
                if value is not None:
                    results = self.create(v.get('variable'), value)
                else:
                    self.tcex.log.info(
                        u'Variable {} has a none value and will not be written.'.format(key)
                    )
            elif self.out_variables.get(key) is not None and variable_type is None:

                v = self.out_variables.get(key)
                self.tcex.log.info(
                    u'Variable {} was requested by downstream app.'.format(v.get('variable'))
                )
                if value is not None:
                    results = self.create(v.get('variable'), value)
                else:
                    self.tcex.log.info(
                        u'Variable {} has a none value and will not be written.'.format(
                            v.get('variable')
                        )
                    )
            else:
                var_value = key
                if variable_type is not None:
                    var_value = key_type
                self.tcex.log.info(
                    u'Variable {} was NOT requested by downstream app.'.format(var_value)
                )
        return results

Wrapper for Create method of CRUD operation for working with KeyValue DB.

This method will automatically check to see if provided variable was requested by
a downstream app and if so create the data in the KeyValue DB.

Args:
key (string): The variable to write to the DB.
value (any): The data to write to the DB.
variable_type (string): The variable type being written.

Returns:
(string): Result string of DB write.


def port_tag_details(cls, tags):

        for tag in tags:
            match = port_tag_re.match(tag)
            if match:
                source_sink, port, extra = match.groups()
                return source_sink == "source", cls(port), extra

Search tags for port info, returning it

Args:
tags: A list of tags to check

Returns:
None or (is_source, port, connected_value|disconnected_value)
where port is one of the Enum entries of Port


def topological_sort(data):

    def check_self_dependencies(input_data):

        for k, v in input_data.items():
            if k in v:
                raise ValueError('Self-dependency, {} depends on itself.'.format(k))

    def prepare_input_data(input_data):

        return {k: set(v) for k, v in input_data.items()}

    def find_items_without_dependencies(input_data):

        return list(reduce(set.union, input_data.values()) - set(input_data.keys()))

    def add_empty_dependencies(data):
        items_without_dependencies = find_items_without_dependencies(data)
        data.update({item: set() for item in items_without_dependencies})

    def get_sorted(input_data):
        data = input_data
        while True:
            ordered = set(item for item, dep in data.items() if len(dep) == 0)
            if not ordered:
                break
            yield ordered
            data = {item: (dep - ordered) for item, dep in data.items() if item not in ordered}

        if len(data) != 0:
            raise ValueError('Cyclic dependencies exist '
                             'among these items: {}'.format(', '.join(repr(x) for x in data.items())))

    check_self_dependencies(data)

    if not len(data):
        return []

    data_copy = prepare_input_data(data)
    add_empty_dependencies(data_copy)

    result = []
    for d in get_sorted(data_copy):
        try:
            d = sorted(d)
        except TypeError:
            d = list(d)

        result.extend(d)
    return result

Topological sort the given dictionary structure.

Args:
data (dict); dictionary structure where the value is a list of dependencies for that given key.
For example: ``{'a': (), 'b': ('a',)}``, where ``a`` depends on nothing and ``b`` depends on ``a``.

Returns:
tuple: the dependencies in constructor order


async def get_tournaments(self, subdomain: str = None, force_update: bool = False) -> list:

        if self.tournaments is None:
            force_update = True
            self._subdomains_searched.append('' if subdomain is None else subdomain)
        elif subdomain is None and '' not in self._subdomains_searched:
            force_update = True
            self._subdomains_searched.append('')
        elif subdomain is not None and subdomain not in self._subdomains_searched:
            force_update = True
            self._subdomains_searched.append(subdomain)

        if force_update:
            params = {
                'include_participants': 1 if AUTO_GET_PARTICIPANTS else 0,
                'include_matches': 1 if AUTO_GET_MATCHES else 0
            }
            if subdomain is not None:
                params['subdomain'] = subdomain

            res = await self.connection('GET', 'tournaments', **params)
            if len(res) == 0:
                self.tournaments = []
            else:
                for t_data in res:
                    self._refresh_tournament_from_json(t_data)

        return self.tournaments

gets all user's tournaments

|methcoro|

Args:
subdomain: *optional* subdomain needs to be given explicitely to get tournaments in a subdomain
force_update: *optional* set to True to force the data update from Challonge

Returns:
list[Tournament]: list of all the user tournaments

Raises:
APIException


def set_hostname(self, value=None, default=False, disable=False):

        cmd = self.command_builder('hostname', value=value, default=default,
                                   disable=disable)
        return self.configure(cmd)

Configures the global system hostname setting

EosVersion:
4.13.7M

Args:
value (str): The hostname value
default (bool): Controls use of the default keyword
disable (bool): Controls the use of the no keyword

Returns:
bool: True if the commands are completed successfully


def _insert(self, item, feed_item):
    return self._api().insert(profileId=self.profile_id, body=item).execute()

Inserts a new item into CM.

Args:
item: The CM object to insert.
feed_item: The feed item from the Bulkdozer feed representing the item to
insert.

Returns:
The CM object representing the item inserted.


def pull(self, project, run=None, entity=None):
    (project, run) = self.parse_slug(project, run=run)
    urls = self.download_urls(project, run, entity)
    responses = []
    for fileName in urls:
        (_, response) = self.download_write_file(urls[fileName])
        if response:
            responses.append(response)
    return responses

Download files from W&B

Args:
project (str): The project to download
run (str, optional): The run to upload to
entity (str, optional): The entity to scope this project to.  Defaults to wandb models

Returns:
The requests library response object


def _GetPathSegmentSeparator(self, path):

    if path.startswith('\\') or path[1:].startswith(':\\'):
      return '\\'

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

    if '/' and '\\' in path:

      forward_count = len(path.split('/'))
      backward_count = len(path.split('\\'))

      if forward_count > backward_count:
        return '/'

      return '\\'

    if '/' in path:
      return '/'

    return '\\'

Given a path give back the path separator as a best guess.

Args:
path (str): path.

Returns:
str: path segment separator.


def forward(self, hidden_states: List[torch.Tensor], patch_height, patch_width) -> List[torch.Tensor]:
    if not isinstance(hidden_states, (tuple, list)):
        raise TypeError('hidden_states should be a tuple or list of tensors')
    if len(hidden_states) != len(self.config.neck_hidden_sizes):
        raise ValueError('The number of hidden states should be equal to the number of neck hidden sizes.')
    if self.reassemble_stage is not None:
        hidden_states = self.reassemble_stage(hidden_states, patch_height, patch_width)
    features = [self.convs[i](feature) for i, feature in enumerate(hidden_states)]
    output = self.fusion_stage(features)
    return (output, features[-1])

Args:
hidden_states (`List[torch.FloatTensor]`, each of shape `(batch_size, sequence_length, hidden_size)` or `(batch_size, hidden_size, height, width)`):
List of hidden states from the backbone.


def __init__(self, profile_id: str, profile_location: Optional[str]=None, log_results: bool=False, file_copy_fn: Optional[Callable[[str, str], None]]=None, time_prefix: str='%Y-%m-%d_%H_%M_%S-', enable_cpu_profiling: bool=False, enable_memory_profiling: bool=False):
    self.profile_id = str(profile_id)
    self.profile_location = profile_location
    self.log_results = log_results
    self.file_copy_fn = file_copy_fn or self.default_file_copy_fn
    self.time_prefix = time_prefix
    self.enable_cpu_profiling = enable_cpu_profiling
    self.enable_memory_profiling = enable_memory_profiling

Creates a Profile object.

Args:
profile_id: Unique id of the profiling session.
profile_location: The file location where the profiling results will be
stored.
log_results: Log the result to console if true.
file_copy_fn: Lambda function for copying files.
time_prefix: Format of the timestamp prefix in profiling result files.
enable_cpu_profiling: CPU profiler will be enabled during the profiling
session.
enable_memory_profiling: Memory profiler will be enabled during the
profiling session, the profiler only records the newly allocated objects
in this session.


def materialize(self, ref, table_name=None, index_columns=None, logger=None):
    from ambry.library import Library
    assert isinstance(self._library, Library)
    logger.debug('Materializing warehouse partition.\n    partition: {}'.format(ref))
    partition = self._library.partition(ref)
    connection = self._backend._get_connection()
    return self._backend.install(connection, partition, table_name=table_name, index_columns=index_columns, materialize=True, logger=logger)

Creates materialized table for given partition reference.

Args:
ref (str): id, vid, name or vname of the partition.

Returns:
str: name of the partition table in the database.


def thermal_conductivity(self, temperature, volume):

        gamma = self.gruneisen_parameter(temperature, volume)
        theta_d = self.debye_temperature(volume)
        theta_a = theta_d * self.natoms**(-1./3.)
        prefactor = (0.849 * 3 * 4**(1./3.)) / (20. * np.pi**3)

        prefactor = prefactor * (self.kb/self.hbar)**3 * self.avg_mass
        kappa = prefactor / (gamma**2 - 0.514 * gamma + 0.228)

        kappa = kappa * theta_a**2 * volume**(1./3.) * 1e-10
        return kappa

Eq(17) in 10.1103/PhysRevB.90.174107

Args:
temperature (float): temperature in K
volume (float): in Ang^3

Returns:
float: thermal conductivity in W/K/m


def visit_invoke_reference(self, identifier: InvokeReferenceNode) -> Any:
    return self.visit_invoke_expression(identifier)

Allows visitors to implement custom Reference logic.

By default, calls `visit_invoke_expression`. Subclasses may override this
method to introduce custom logic for handling references.

This function is called when the 'reference' identifier is invoked against a
FHIR Reference resource. The visit_invoke_expression function is called for
all other invocations.

Args:
identifier: The identifier on the right hand side of an invocation.

Returns:
The result of the reference invocation.


def verify_id_token(id_token, audience, http=None, cert_uri=ID_TOKEN_VERIFICATION_CERTS):
    _require_crypto_or_die()
    if (http is None):
        http = transport.get_cached_http()
    (resp, content) = transport.request(http, cert_uri)
    if (resp.status == http_client.OK):
        certs = json.loads(_helpers._from_bytes(content))
        return crypt.verify_signed_jwt_with_certs(id_token, certs, audience)
    else:
        raise VerifyJwtTokenError('Status code: {0}'.format(resp.status))

Verifies a signed JWT id_token.

This function requires PyOpenSSL and because of that it does not work on
App Engine.

Args:
id_token: string, A Signed JWT.
audience: string, The audience 'aud' that the token should be for.
http: httplib2.Http, instance to use to make the HTTP request. Callers
should supply an instance that has caching enabled.
cert_uri: string, URI of the certificates in JSON format to
verify the JWT against.

Returns:
The deserialized JSON in the JWT.

Raises:
oauth2client.crypt.AppIdentityError: if the JWT fails to verify.
CryptoUnavailableError: if no crypto library is available.


def _get_single_variable(self, name, shape=None, dtype=dtypes.float32, initializer=None, regularizer=None, partition_info=None, reuse=None, trainable=None, collections=None, caching_device=None, validate_shape=True, use_resource=None, constraint=None, synchronization=VariableSynchronization.AUTO, aggregation=VariableAggregation.NONE):
    initializing_from_value = False
    if initializer is not None and (not callable(initializer)):
        initializing_from_value = True
    if shape is not None and initializing_from_value:
        raise ValueError('If initializer is a constant, do not specify shape.')
    dtype = dtypes.as_dtype(dtype)
    if shape is not None:
        shape = tensor_shape.as_shape(shape)
    if name in self._vars:
        if reuse is False:
            var = self._vars[name]
            err_msg = 'Variable %s already exists, disallowed. Did you mean to set reuse=True or reuse=tf.AUTO_REUSE in VarScope?' % name
            if isinstance(var, resource_variable_ops.ResourceVariable):
                raise ValueError(err_msg)
            tb = var.op.traceback[::-1]
            tb = [x for x in tb if 'tensorflow/python' not in x[0]][:5]
            raise ValueError('%s Originally defined at:\n\n%s' % (err_msg, ''.join(traceback.format_list(tb))))
        found_var = self._vars[name]
        if shape is not None and (not shape.is_compatible_with(found_var.get_shape())):
            raise ValueError('Trying to share variable %s, but specified shape %s and found shape %s.' % (name, shape, found_var.get_shape()))
        if not dtype.is_compatible_with(found_var.dtype):
            dtype_str = dtype.name
            found_type_str = found_var.dtype.name
            raise ValueError('Trying to share variable %s, but specified dtype %s and found dtype %s.' % (name, dtype_str, found_type_str))
        return found_var
    if reuse is True:
        raise ValueError('Variable %s does not exist, or was not created with tf.get_variable(). Did you mean to set reuse=tf.AUTO_REUSE in VarScope?' % name)
    if initializer is None:
        if shape is None:
            raise ValueError(f'Variable {name} did not get an initializer, so its `shape` argument must be specified.')
        initializer, initializing_from_value = self._get_default_initializer(name=name, shape=shape, dtype=dtype)
    with ops.init_scope():
        if initializing_from_value:
            init_val = initializer
            variable_dtype = None
        else:
            if tf_inspect.isclass(initializer):
                initializer = initializer()
            if shape is not None and shape.is_fully_defined():
                if 'partition_info' in tf_inspect.getargspec(initializer).args:
                    init_val = functools.partial(initializer, shape.as_list(), dtype=dtype, partition_info=partition_info)
                else:
                    init_val = functools.partial(initializer, shape.as_list(), dtype=dtype)
                variable_dtype = dtype.base_dtype
            elif _needs_no_arguments(initializer):
                init_val = initializer
                variable_dtype = None
            else:
                raise ValueError("The initializer passed is not valid. It should be a callable with no arguments and the shape should not be provided or an instance of `tf.keras.initializers.*' and `shape` should be fully defined.")
    if use_resource is None:
        use_resource = resource_variables_toggle.resource_variables_enabled()
    v = _variable_v1(initial_value=init_val, name=name, trainable=trainable, collections=collections, caching_device=caching_device, dtype=variable_dtype, validate_shape=validate_shape, constraint=constraint, use_resource=use_resource, synchronization=synchronization, aggregation=aggregation, shape=shape)
    if context.executing_eagerly() and self._store_eager_variables:
        if collections:
            ops.add_to_collections(collections, v)
        else:
            ops.add_to_collection(ops.GraphKeys.GLOBAL_VARIABLES, v)
        if trainable:
            ops.add_to_collection(ops.GraphKeys.TRAINABLE_VARIABLES, v)
    if not context.executing_eagerly() or self._store_eager_variables:
        self._vars[name] = v
    logging.vlog(1, 'Created variable %s with shape %s and init %s', v.name, format(shape), initializer)
    if regularizer:

        def make_regularizer_op():
            with ops.colocate_with(v):
                with ops.name_scope(name + '/Regularizer/'):
                    return regularizer(v)
        if regularizer(v) is not None:
            lazy_eval_tensor = _LazyEvalTensor(make_regularizer_op)
            ops.add_to_collection(ops.GraphKeys.REGULARIZATION_LOSSES, lazy_eval_tensor)
    return v

Get or create a single Variable (e.g.

a shard or entire variable).

See the documentation of get_variable above (ignore partitioning components)
for details.

Args:
name: see get_variable.
shape: see get_variable.
dtype: see get_variable.
initializer: see get_variable.
regularizer: see get_variable.
partition_info: _PartitionInfo object.
reuse: see get_variable.
trainable: see get_variable.
collections: see get_variable.
caching_device: see get_variable.
validate_shape: see get_variable.
use_resource: see get_variable.
constraint: see get_variable.
synchronization: see get_variable.
aggregation: see get_variable.

Returns:
A Variable.  See documentation of get_variable above.

Raises:
ValueError: See documentation of get_variable above.


def generate_lars_path(weighted_data, weighted_labels):
    x_vector = weighted_data
    (alphas, _, coefs) = lars_path(x_vector, weighted_labels, method='lasso', verbose=False)
    return (alphas, coefs)

Generates the lars path for weighted data.

Args:
weighted_data: data that has been weighted by kernel
weighted_label: labels, weighted by kernel

Returns:
(alphas, coefs), both are arrays corresponding to the
regularization parameter and coefficients, respectively


def snr(*args, **kwargs):
    squeeze = False
    max_length = 0
    for arg in args:
        try:
            length = len(arg)
            if (length > max_length):
                max_length = length
        except TypeError:
            pass
    if (max_length == 0):
        squeeze = True
    kwargs['length'] = max_length
    snr_main = SNR(**kwargs)
    if squeeze:
        snr_out = snr_main(*args)
        return {key: np.squeeze(snr_out[key]) for key in snr_out}
    return snr_main(*args)

Compute the SNR of binaries.

snr is a function that takes binary parameters and sensitivity curves as inputs,
and returns snr for chosen phases.

Warning: All binary parameters must be either scalar, len-1 arrays,
or arrays of the same length. All of these can be used at once. However,
you cannot input multiple arrays of different lengths.

Arguments:
*args: Arguments for :meth:`gwsnrcalc.utils.pyphenomd.PhenomDWaveforms.__call__`
**kwargs: Keyword arguments related to
parallel generation (see :class:`gwsnrcalc.utils.parallel`),
waveforms (see :class:`gwsnrcalc.utils.pyphenomd`),
or sensitivity information (see :class:`gwsnrcalc.utils.sensitivity`).

Returns:
(dict or list of dict): Signal-to-Noise Ratio dictionary for requested phases.


def _get_showcase_dataset_dict(self, dataset):

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

Get showcase dataset dict

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

Returns:
Dict: showcase dataset dict


def _CheckIsDevice(self, file_entry):

    if definitions.FILE_ENTRY_TYPE_DEVICE not in self._file_entry_types:
      return False
    return file_entry.IsDevice()

Checks the is_device find specification.

Args:
file_entry (FileEntry): file entry.

Returns:
bool: True if the file entry matches the find specification, False if not.


def clean_args(self, args, keys):
    for k in keys:
        if getattr(args, k) is None:
            delattr(args, k)

Clean None values out of the arg namespace.

This lets us check for a config file arg based on whether the None default
was overwritten.

Args:
args: an argparse.Namespace.
keys: Keys to clean if None


def transform(self, col):

        out = pd.DataFrame(index=col.index)
        out[self.col_name] = col.fillna(self.default_value)
        out[self.new_name] = (pd.notnull(col) * 1).astype(int)
        return out

Prepare the transformer to convert data and return the processed table.

Args:
col(pandas.DataFrame): Data to transform.

Returns:
pandas.DataFrame


def bdp(tickers, flds, **kwargs):

    logger = logs.get_logger(bdp, level=kwargs.pop('log', logs.LOG_LEVEL))
    con, _ = create_connection()
    ovrds = assist.proc_ovrds(**kwargs)

    logger.info(
        f'loading reference data from Bloomberg:\n'
        f'{assist.info_qry(tickers=tickers, flds=flds)}'
    )
    data = con.ref(tickers=tickers, flds=flds, ovrds=ovrds)
    if not kwargs.get('cache', False): return [data]

    qry_data = []
    for r, snap in data.iterrows():
        subset = [r]
        data_file = storage.ref_file(
            ticker=snap.ticker, fld=snap.field, ext='pkl', **kwargs
        )
        if data_file:
            if not files.exists(data_file): qry_data.append(data.iloc[subset])
            files.create_folder(data_file, is_file=True)
            data.iloc[subset].to_pickle(data_file)

    return qry_data

Bloomberg reference data

Args:
tickers: tickers
flds: fields to query
**kwargs: bbg overrides

Returns:
pd.DataFrame

Examples:
>>> bdp('IQ US Equity', 'Crncy', raw=True)
ticker  field value
0  IQ US Equity  Crncy   USD
>>> bdp('IQ US Equity', 'Crncy').reset_index()
ticker crncy
0  IQ US Equity   USD


def load_subclasses(klass, modules=None):
    if modules:
        if isinstance(modules, six.string_types):
            modules = [modules]
        loader = Loader()
        loader.load(*modules)
    return klass.__subclasses__()

Load recursively all all subclasses from a module.

Args:
klass (str or list of str): Class whose subclasses we want to load.
modules: List of additional modules or module names that should be
recursively imported in order to find all the subclasses of the
desired class. Default: None

FIXME: This function is kept only for backward compatibility reasons, it
should not be used. Deprecation warning should be raised and it should
be replaces by the ``Loader`` class.


def relative_humidity(self, value=999):

        if value is not None:
            try:
                value = int(value)
            except ValueError:
                raise ValueError('value {} need to be of type int '
                                 'for field `relative_humidity`'.format(value))
            if value < 0:
                raise ValueError('value need to be greater or equal 0 '
                                 'for field `relative_humidity`')
            if value > 110:
                raise ValueError('value need to be smaller 110 '
                                 'for field `relative_humidity`')

        self._relative_humidity = value

Corresponds to IDD Field `relative_humidity`

Args:
value (int): value for IDD Field `relative_humidity`
value >= 0
value <= 110
Missing value: 999
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 to_tensor_list(element_spec, element):
    return _to_tensor_list_helper(lambda state, spec, component: state + spec._to_tensor_list(component), element_spec, element)

Returns a tensor list representation of the element.

Args:
element_spec: A nested structure of `tf.TypeSpec` objects representing to
element type specification.
element: The element to convert to tensor list representation.

Returns:
A tensor list representation of `element`.

Raises:
ValueError: If `element_spec` and `element` do not have the same number of
elements or if the two structures are not nested in the same way.
TypeError: If `element_spec` and `element` differ in the type of sequence
in any of their substructures.


def write_tarball(voevents, filepath):

    tuple_gen = ( (v.ivorn, v.xml) for v in voevents)
    return write_tarball_from_ivorn_xml_tuples(tuple_gen,
                                               filepath)

Iterate over voevent models / dbrows and write to bz'd tarball.

Args:
voevents (iterable): An iterable (e.g. list) of e.g. Voevent db-rows,
with access to the 'ivorn' and 'xml' attributes.
filepath (string): Path to the new tarball to create. Typically of form
'/path/to/foo.tar.bz2'
Returns
packet_count (int): Number of packets written to tarball


def AcceptableMimeType(accept_patterns, mime_type):
    if ('/' not in mime_type):
        raise exceptions.InvalidUserInputError(('Invalid MIME type: "%s"' % mime_type))
    unsupported_patterns = [p for p in accept_patterns if (';' in p)]
    if unsupported_patterns:
        raise exceptions.GeneratedClientError(('MIME patterns with parameter unsupported: "%s"' % ', '.join(unsupported_patterns)))

    def MimeTypeMatches(pattern, mime_type):
        'Return True iff mime_type is acceptable for pattern.'
        if (pattern == '*'):
            pattern = '*/*'
        return all(((accept in ('*', provided)) for (accept, provided) in zip(pattern.split('/'), mime_type.split('/'))))
    return any((MimeTypeMatches(pattern, mime_type) for pattern in accept_patterns))

Return True iff mime_type is acceptable for one of accept_patterns.

Note that this function assumes that all patterns in accept_patterns
will be simple types of the form "type/subtype", where one or both
of these can be "*". We do not support parameters (i.e. "; q=") in
patterns.

Args:
accept_patterns: list of acceptable MIME types.
mime_type: the mime type we would like to match.

Returns:
Whether or not mime_type matches (at least) one of these patterns.


def get_item_concept_mapping(self, lang):

        concepts = self.filter(active=True, lang=lang)
        return group_keys_by_value_lists(Concept.objects.get_concept_item_mapping(concepts, lang))

Get mapping of items_ids to concepts containing these items

Args:
lang (str): language of concepts

Returns:
dict: item (int) -> set of concepts (int)


def get_lonlatalts(self):
    band = self.filehandle
    ((xpoints, ypoints), (gcp_lons, gcp_lats, gcp_alts), (gcps, crs)) = self.get_gcps()
    longitudes = interpolate_xarray(xpoints, ypoints, gcp_lons, band.shape)
    latitudes = interpolate_xarray(xpoints, ypoints, gcp_lats, band.shape)
    altitudes = interpolate_xarray(xpoints, ypoints, gcp_alts, band.shape)
    longitudes.attrs['gcps'] = gcps
    longitudes.attrs['crs'] = crs
    latitudes.attrs['gcps'] = gcps
    latitudes.attrs['crs'] = crs
    altitudes.attrs['gcps'] = gcps
    altitudes.attrs['crs'] = crs
    return (longitudes, latitudes, altitudes)

Obtain GCPs and construct latitude and longitude arrays.

Args:
band (gdal band): Measurement band which comes with GCP's
array_shape (tuple) : The size of the data array
Returns:
coordinates (tuple): A tuple with longitude and latitude arrays


def get(self):
    chunk_size = self._smallest_buffer()
    all_full = self._all_full()
    if all_full:
        right_context = 0
        num_frames = (chunk_size - self.current_left_context)
    else:
        right_context = self.right_context
        num_frames = self.min_frames
    chunk_size_needed = ((num_frames + self.current_left_context) + right_context)
    if (chunk_size >= chunk_size_needed):
        data = []
        keep_frames = (self.left_context + self.right_context)
        keep_from = max(0, (chunk_size - keep_frames))
        for index in range(self.num_buffers):
            data.append(self.buffers[index][:chunk_size])
            self.buffers[index] = self.buffers[index][keep_from:]
        if (self.num_buffers == 1):
            data = data[0]
        chunk = Chunk(data, self.current_frame, all_full, self.current_left_context, right_context)
        self.current_left_context = min(self.left_context, chunk_size)
        self.current_frame = max(((self.current_frame + chunk_size) - keep_frames), 0)
        return chunk

Get a new chunk if available.

Returns:
Chunk or list: If enough frames are available a chunk is returned. Otherwise None.
If ``self.num_buffer >= 1`` a list instead of single chunk is returned.


def MapFile(self, key_path_prefix, registry_file):

    self._registry_files[key_path_prefix.upper()] = registry_file
    registry_file.SetKeyPathPrefix(key_path_prefix)

Maps the Windows Registry file to a specific key path prefix.

Args:
key_path_prefix (str): key path prefix.
registry_file (WinRegistryFile): Windows Registry file.


def milliseconds(value: Union[int, float]) -> Duration:
    return float(value / 1000)

Converts input value from milliseconds to a `Duration` in seconds.

Example:
```python
>>> duration = tp.duration.milliseconds(250)
>>> duration
0.25

>>> # Usage in a window operation
>>> a = tp.event_set(
...     timestamps=[0.5, 1.0, 1.2],
...     features={"f1": [1, 5, -5]}
... )
>>> a.moving_sum(window_length=duration)
indexes: ...
timestamps: [0.5 1.  1.2]
'f1': [1 5 0]
...

```

Args:
value: Number of milliseconds.

Returns:
Equivalent number of seconds.


def assert_visible(self, selector, testid=None, **kwargs):
    self.info_log(('Assert visible selector(%s) testid(%s)' % (selector, testid)))
    highlight = kwargs.get('highlight', BROME_CONFIG['highlight']['highlight_on_assertion_success'])
    self.debug_log(('effective highlight: %s' % highlight))
    wait_until_visible = kwargs.get('wait_until_visible', BROME_CONFIG['proxy_driver']['wait_until_visible_before_assert_visible'])
    self.debug_log(('effective wait_until_visible: %s' % wait_until_visible))
    if wait_until_visible:
        self.wait_until_visible(selector, raise_exception=False)
    element = self.find(selector, raise_exception=False, wait_until_visible=False, wait_until_present=False)
    if (element and element.is_displayed(raise_exception=False)):
        if highlight:
            element.highlight(style=BROME_CONFIG['highlight']['style_on_assertion_success'])
        if (testid is not None):
            self.create_test_result(testid, True)
        return True
    else:
        if (testid is not None):
            self.create_test_result(testid, False)
        return False

Assert that the element is visible in the dom

Args:
selector (str): the selector used to find the element
testid (str): the test_id or a str

Kwargs:
wait_until_visible (bool)
highlight (bool)

Returns:
bool: True is the assertion succeed; False otherwise.


def price(self, valuation_date, market, model=None, pricing_context=None, name=None):
    del model, pricing_context
    name = name or self._name + '_price'
    with tf.name_scope(name):
        discount_curve = market.discount_curve
        discount_factors = discount_curve.get_discount_factor(self._payment_dates)
        future_cashflows = tf.cast(self._payment_dates >= valuation_date, dtype=self._dtype)
        cashflow_pvs = self._notional * (future_cashflows * self._daycount_fractions * self._coupon_rate * discount_factors)
        return tf.math.reduce_sum(tf.reshape(cashflow_pvs, (self._batch_size, self._num_cashflows)), axis=1)

Returns the present value of the stream on the valuation date.

Args:
valuation_date: A scalar `DateTensor` specifying the date on which
valuation is being desired.
market: A namedtuple of type `InterestRateMarket` which contains the
necessary information for pricing the cashflow stream.
model: Reserved for future use.
pricing_context: Additional context relevant for pricing.
name: Python str. The name to give to the ops created by this function.
Default value: `None` which maps to 'price'.

Returns:
A Rank 1 `Tensor` of real type containing the modeled price of each stream
based on the input market data.


def find_equivalent_sites(self, site):

        for sites in self.equivalent_sites:
            if site in sites:
                return sites

        raise ValueError("Site not in structure")

Finds all symmetrically equivalent sites for a particular site

Args:
site (PeriodicSite): A site in the structure

Returns:
([PeriodicSite]): List of all symmetrically equivalent sites.


def watch(self, enable=True, gpsd_protocol=PROTOCOL, devicepath=None):

        command = '?WATCH={{"enable":true,"{0}":true}}'.format(gpsd_protocol)

        if gpsd_protocol == 'rare':
            command = command.replace('"rare":true', '"raw":1')
        if gpsd_protocol == 'raw':
            command = command.replace('"raw":true', '"raw",2')
        if not enable:
            command = command.replace('true', 'false')
        if devicepath:
            command = command.replace('}', ',"device":"') + devicepath + '"}'

        return self.send(command)

watch gpsd in various gpsd_protocols or devices.
Arguments:
enable: (bool) stream data to socket
gpsd_protocol: (str) 'json' | 'nmea' | 'rare' | 'raw' | 'scaled' | 'split24' | 'pps'
devicepath: (str) device path - '/dev/ttyUSBn' for some number n or '/dev/whatever_works'
Returns:
command: (str) e.g., '?WATCH={"enable":true,"json":true};'


def _start_profiler(self, logdir):
    if self._profiler_started:
        return
    try:
        profiler.start(logdir=logdir)
        self._profiler_started = True
    except errors.AlreadyExistsError as e:
        logging.error('Failed to start profiler: %s', e.message)

Starts the profiler if currently inactive.

Args:
logdir: Directory where profiler results will be saved.


def get_internal_urls(self):
    internal_urls = self.get_subfields('856', 'u', i1='4', i2='0')
    internal_urls.extend(self.get_subfields('998', 'a'))
    internal_urls.extend(self.get_subfields('URL', 'u'))
    return map((lambda x: x.replace('&', '&')), internal_urls)

URL's, which may point to edeposit, aleph, kramerius and so on.

Fields ``856u40``, ``998a`` and ``URLu``.

Returns:
list: List of internal URLs.


def kill_raylet(self, check_alive=True):
    self._kill_process_type(ray_constants.PROCESS_TYPE_RAYLET, check_alive=check_alive)

Kill the raylet.

Args:
check_alive (bool): Raise an exception if the process was already
dead.


def _extract_inner_match(self, candidate, offset):

        for possible_inner_match in _INNER_MATCHES:
            group_match = possible_inner_match.search(candidate)
            is_first_match = True
            while group_match and self._max_tries > 0:
                if is_first_match:

                    group = self._trim_after_first_match(_UNWANTED_END_CHAR_PATTERN,
                                                         candidate[:group_match.start()])
                    match = self._parse_and_verify(group, offset)
                    if match is not None:
                        return match
                    self._max_tries -= 1
                    is_first_match = False
                group = self._trim_after_first_match(_UNWANTED_END_CHAR_PATTERN,
                                                     group_match.group(1))
                match = self._parse_and_verify(group, offset + group_match.start(1))
                if match is not None:
                    return match
                self._max_tries -= 1
                group_match = possible_inner_match.search(candidate, group_match.start() + 1)
        return None

Attempts to extract a match from candidate if the whole candidate
does not qualify as a match.

Arguments:
candidate -- The candidate text that might contain a phone number
offset -- The current offset of candidate within text
Returns the match found, None if none can be found


def _ImportAll(self, module):
    aliases = []
    getattrs = set()
    ast = self._module_map[module]
    type_param_names = set()
    if module == 'http.client':
        exports = None
    else:
        exports = [x for x in ast.constants if x.name.endswith('.__all__')]
        if exports:
            exports = exports[0].value
    for member in sum((ast.constants, ast.type_params, ast.classes, ast.functions, ast.aliases), ()):
        _, _, member_name = member.name.rpartition('.')
        if exports and member_name not in exports:
            continue
        new_name = self._ModulePrefix() + member_name
        if isinstance(member, pytd.Function) and member_name == '__getattr__':
            getattrs.add(member.Replace(name=new_name))
        else:
            if isinstance(member, pytd.TypeParameter):
                type_param_names.add(new_name)
            elif new_name in type_param_names:
                continue
            if member_name.startswith('_'):
                continue
            t = pytd.ToType(member, allow_constants=True, allow_functions=True)
            aliases.append(pytd.Alias(new_name, t))
    return (aliases, getattrs)

Get the new members that would result from a star import of the module.

Args:
module: The module name.

Returns:
A tuple of:
- a list of new aliases,
- a set of new __getattr__ functions.


def visit_and_get_function_nodes(self, definition, first_node):
    len_before_visiting_func = len(self.nodes)
    previous_node = self.nodes[(- 1)]
    entry_node = self.append_node(EntryOrExitNode(('Function Entry ' + definition.name)))
    if (not first_node):
        first_node = entry_node
    self.connect_if_allowed(previous_node, entry_node)
    function_body_connect_statements = self.stmt_star_handler(definition.node.body)
    entry_node.connect(function_body_connect_statements.first_statement)
    exit_node = self.append_node(EntryOrExitNode(('Exit ' + definition.name)))
    exit_node.connect_predecessors(function_body_connect_statements.last_statements)
    the_new_nodes = self.nodes[len_before_visiting_func:]
    return_connection_handler(the_new_nodes, exit_node)
    return (the_new_nodes, first_node)

Visits the nodes of a user defined function.

Args:
definition(LocalModuleDefinition): Definition of the function being added.
first_node(EntryOrExitNode or None or RestoreNode): Used to connect previous statements to this function.

Returns:
the_new_nodes(list[Node]): The nodes added while visiting the function.
first_node(EntryOrExitNode or None or RestoreNode): Used to connect previous statements to this function.


def save_driver_logs(driver, prefix):

    browser_name = os.environ.get('SELENIUM_BROWSER', 'firefox')
    log_dir = os.environ.get('SELENIUM_DRIVER_LOG_DIR')
    if not log_dir:
        LOGGER.warning('The SELENIUM_DRIVER_LOG_DIR environment variable was not set; not saving logs')
        return
    elif not os.path.exists(log_dir):
        os.makedirs(log_dir)
    if browser_name == 'firefox':

        log_path = os.path.join(os.getcwd(), 'geckodriver.log')
        if os.path.exists(log_path):
            dest_path = os.path.join(log_dir, '{}_geckodriver.log'.format(prefix))
            copyfile(log_path, dest_path)
        return

    log_types = driver.log_types
    for log_type in log_types:
        try:
            log = driver.get_log(log_type)
            file_name = os.path.join(
                log_dir, '{}_{}.log'.format(prefix, log_type)
            )
            with open(file_name, 'w') as output_file:
                for line in log:
                    output_file.write("{}{}".format(dumps(line), '\n'))
        except:
            msg = (
                u"Could not save browser log of type '{log_type}'. "
                u"It may be that the browser does not support it."
            ).format(log_type=log_type)

            LOGGER.warning(msg, exc_info=True)

Save the selenium driver logs.

The location of the driver log files can be configured
by the environment variable `SELENIUM_DRIVER_LOG_DIR`.  If not set,
this defaults to the current working directory.

Args:
driver (selenium.webdriver): The Selenium-controlled browser.
prefix (str): A prefix which will be used in the output file names for the logs.

Returns:
None


def _scalar(tf_fn, x, promote_to_float=False):
    x = np_array_ops.asarray(x)
    if promote_to_float and (not np.issubdtype(x.dtype.as_numpy_dtype, np.inexact)):
        x = x.astype(np_utils.result_type(float))
    return tf_fn(x)

Computes the tf_fn(x) for each element in `x`.

Args:
tf_fn: function that takes a single Tensor argument.
x: array_like. Could be an ndarray, a Tensor or any object that can be
converted to a Tensor using `ops.convert_to_tensor`.
promote_to_float: whether to cast the argument to a float dtype if it is not
already.

Returns:
An ndarray with the same shape as `x`. The default output dtype is
determined by `np_utils.result_type(float)`, unless x is an ndarray with a
floating point type, in which case the output type is same as x.dtype.


def gates_to_idx(gates, qregs):
    sizes = [qr.size for qr in qregs.values()]
    reg_idx = np.cumsum(([0] + sizes))
    regint = {}
    for (ind, qreg) in enumerate(qregs.values()):
        regint[qreg] = ind
    out = np.zeros((2 * len(gates)), dtype=np.int32)
    for (idx, gate) in enumerate(gates):
        out[(2 * idx)] = (reg_idx[regint[gate[0][0]]] + gate[0][1])
        out[((2 * idx) + 1)] = (reg_idx[regint[gate[1][0]]] + gate[1][1])
    return out

Converts gate tuples into a nested list of integers.

Args:
gates (list): List of (QuantumRegister, int) pairs
representing gates.
qregs (dict): List of )QuantumRegister, int) tuples.

Returns:
list: Nested list of integers for gates.


def to_sql(cls, qc, **kwargs):

        empty_df = qc.head(1).to_pandas().head(0)
        empty_df.to_sql(**kwargs)

        kwargs["if_exists"] = "append"
        columns = qc.columns

        def func(df, **kwargs):
            df.columns = columns
            df.to_sql(**kwargs)
            return pandas.DataFrame()

        map_func = qc._prepare_method(func, **kwargs)
        result = qc._map_across_full_axis(1, map_func)

        result.to_pandas()

Write records stored in a DataFrame to a SQL database.
Args:
qc: the query compiler of the DF that we want to run to_sql on
kwargs: parameters for pandas.to_sql(**kwargs)


def from_keras_log(csv_path, output_dir_path, **kwargs):

    data = pd.read_csv(csv_path, sep=None, engine='python')
    _from_keras_log_format(data, output_dir_path=output_dir_path, **kwargs)

Plot accuracy and loss from a Keras CSV log.

Args:
csv_path: The path to the CSV log with the actual data.
output_dir_path: The path to the directory where the resultings plots
should end up.


def series_with_slh(self, other):

        new_S = self.S * other.S
        new_L = self.S * other.L + self.L

        def ImAdjoint(m):
            return (m.H - m) * (I / 2)

        delta = ImAdjoint(self.L.adjoint() * self.S * other.L)

        if isinstance(delta, Matrix):
            new_H = self.H + other.H + delta[0, 0]
        else:
            assert delta == 0
            new_H = self.H + other.H

        return SLH(new_S, new_L, new_H)

Series product with another :class:`SLH` object

Args:
other (SLH): An upstream SLH circuit.

Returns:
SLH: The combined system.


def _sequence_search(self, start: GridQubit, current: List[GridQubit]) -> List[GridQubit]:
    used = set(current)
    seq = []
    n = start
    while (n is not None):
        seq.append(n)
        used.add(n)
        n = self._choose_next_qubit(n, used)
    return seq

Search for the continuous linear sequence from the given qubit.

This method is called twice for the same starting qubit, so that
sequences that begin and end on this qubit are searched for.

Args:
start: The first qubit, where search should be trigerred from.
current: Previously found linear sequence, which qubits are
forbidden to use during the search.

Returns:
Continuous linear sequence that begins with the starting qubit and
does not contain any qubits from the current list.


def set_heat_pump_mode(self, device_label, mode):

        response = None
        try:
            response = requests.put(
                urls.set_heatpump_state(self._giid, device_label),
                headers={
                    'Accept': 'application/json',
                    'Content-Type': 'application/json',
                    'Cookie': 'vid={}'.format(self._vid)},
                data=json.dumps({'mode': mode}))
        except requests.exceptions.RequestException as ex:
            raise RequestError(ex)
        _validate_response(response)
        return json.loads(response.text)

Set heatpump mode
Args:
mode (str): 'HEAT', 'COOL', 'FAN' or 'AUTO'


def __call__(self, fn):

        def completion(app, *args, **kwargs):

            app.exit_message = self.msg
            return fn(app, *args, **kwargs)

        return completion

Implement __call__ function for decorator.

Args:
fn (function): The decorated function.

Returns:
function: The custom decorator function.


def _check_arg_equality(node_a, node_b, attr_name):

    return getattr(node_a, attr_name) == getattr(node_b, attr_name)

Check equality of nodes based on the comparison of their attributes named attr_name.

Args:
node_a (astroid.node): first node to compare.
node_b (astroid.node): second node to compare.
attr_name (str): name of the nodes attribute to use for comparison.

Returns:
bool: True if node_a.attr_name == node_b.attr_name, False otherwise.


def start_publishing(mysql_settings, **kwargs):

    _logger.info('Start publishing from %s with:\n%s'
                 % (mysql_settings, kwargs))

    kwargs.setdefault('server_id', random.randint(1000000000, 4294967295))
    kwargs.setdefault('freeze_schema', True)

    stream = pymysqlreplication.BinLogStreamReader(
        mysql_settings,
        only_events=[row_event.DeleteRowsEvent,
                     row_event.UpdateRowsEvent,
                     row_event.WriteRowsEvent],
        **kwargs
    )

    for event in stream:

        if not isinstance(event, row_event.RowsEvent):
            continue

        _logger.debug('Send binlog signal "%s@%s.%s"' % (
            event.__class__.__name__,
            event.schema,
            event.table
        ))
        signals.binlog_signal.send(event, stream=stream)
        signals.binlog_position_signal.send((stream.log_file, stream.log_pos))

Start publishing MySQL row-based binlog events to blinker signals

Args:
mysql_settings (dict): information to connect to mysql via pymysql
**kwargs: The additional kwargs will be passed to
:py:class:`pymysqlreplication.BinLogStreamReader`.


def __call__(self, dumper: 'Dumper', data: Any) -> yaml.MappingNode:

        logger.info('Representing {} of class {}'.format(
            data, self.class_.__name__))

        represented = dumper.represent_str(data.name)

        snode = Node(represented)
        if hasattr(self.class_, 'yatiml_sweeten'):
            self.class_.yatiml_sweeten(snode)
            represented = snode.yaml_node

        logger.debug('End representing {}'.format(data))
        return represented

Represents the class as a ScalarNode.

Args:
dumper: The dumper to use.
data: The user-defined object to dump.

Returns:
A yaml.Node representing the object.


def fit2d(samples, e_x, e_y, remove_zeros=False, p_est=None, **kw):
    if (p_est is None):
        height = (len(e_y) - 1)
        width = (len(e_x) - 1)
        (p_est, _) = np.histogramdd(samples, (e_x, e_y))
    else:
        p_est = p_est.T
        (width, height) = p_est.shape
    shape = p_est.shape
    p_est = (p_est / sum(p_est.flat)).reshape(shape)
    mx = p_est.sum(1)
    my = p_est.sum(0)
    p_est = p_est.T.flatten()
    (basis, knots) = spline_base2d(width, height, marginal_x=mx, marginal_y=my, **kw)
    model = linear_model.BayesianRidge()
    if remove_zeros:
        non_zero = (~ (p_est == 0))
        model.fit(basis[(:, non_zero)].T, p_est[non_zero])
    else:
        non_zero = (p_est >= 0)
        p_est[((~ non_zero), :)] = np.finfo(float).eps
        model.fit(basis.T, p_est)
    return (model.predict(basis.T).reshape((height, width)), p_est.reshape((height, width)), knots)

Fits a 2D distribution with splines.

Input:
samples: Matrix or list of arrays
If matrix, it must be of size Nx2, where N is the number of
observations. If list, it must contain two arrays of length
N.
e_x: Array
Edges that define the events in the probability
distribution along the x direction. For example,
e_x[0] < samples[0] <= e_x[1] picks out all
samples that are associated with the first event.
e_y: Array
See e_x, but for the y direction.
remove_zeros: Bool
If True, events that are not observed will not
be part of the fitting process. If False, those
events will be modelled as finfo('float').eps
**kw: Arguments that are passed on to spline_bse1d.

Returns:
distribution: Array
An array that gives an estimate of probability for
events defined by e.
knots: Tuple of arrays
Sequence of knots that were used for the spline basis (x,y)


def pad_to_best_fit(images: 'torch.Tensor', target_size: Tuple[int, int], background_color: Union[int, Tuple[int, int, int]]=0) -> 'torch.Tensor':
    num_channels = images.shape[1] if len(images.shape) == 4 else images.shape[0]
    if isinstance(background_color, int):
        background_color = [background_color] + [0] * (num_channels - 1)
    elif len(background_color) != num_channels:
        raise ValueError(f'background_color must have no more than {num_channels} elements to match the number of channels')
    height, width = images.shape[-2:]
    target_height, target_width = target_size
    paste_x_right = target_width - width
    paste_y_right = target_height - height
    padded_images = F.pad(images, padding=[0, 0, paste_x_right, paste_y_right], fill=background_color)
    return padded_images

Pads an image to fit the target size.

Args:
images (`np.ndarray`):
The images to pad.
background_color (`int` or `Tuple[int, int, int]`, *optional*, defaults to 0):
The color to use for the padding. Can be an integer for single channel or a
tuple of integers representing for multi-channel images. If passed as integer
in mutli-channel mode, it will default to `0` in subsequent channels.
Returns:
`torch.Tensor`: The padded images.


def ismount(self, path):

        path = make_string_path(path)
        if not path:
            return False
        normed_path = self.filesystem.absnormpath(path)
        sep = self.filesystem._path_separator(path)
        if self.filesystem.is_windows_fs:
            if self.filesystem.alternative_path_separator is not None:
                path_seps = (
                    sep, self.filesystem._alternative_path_separator(path)
                )
            else:
                path_seps = (sep, )
            drive, rest = self.filesystem.splitdrive(normed_path)
            if drive and drive[:1] in path_seps:
                return (not rest) or (rest in path_seps)
            if rest in path_seps:
                return True
        for mount_point in self.filesystem.mount_points:
            if normed_path.rstrip(sep) == mount_point.rstrip(sep):
                return True
        return False

Return true if the given path is a mount point.

Args:
path: Path to filesystem object to be checked

Returns:
`True` if path is a mount point added to the fake file system.
Under Windows also returns True for drive and UNC roots
(independent of their existence).


def Open(self, file_object, ascii_codepage='cp1252'):

    registry_file = dfwinreg_regf.REGFWinRegistryFile(
        ascii_codepage=ascii_codepage)

    registry_file.Open(file_object)

    return registry_file

Opens a Windows Registry file-like object.

Args:
file_object (dfvfs.FileIO): Windows Registry file-like object.
ascii_codepage (Optional[str]): ASCII string codepage.

Returns:
WinRegistryFile: Windows Registry file or None.


def test_encode_with_backbone_element_constraint_succeeds(self, fhir_path_expression: str, expected_sql_expression: str, expected_fhir_path_sql_expression: str, expected_fields_referenced: List[str]):
    constraint = self.build_constraint(fhir_path_expression=fhir_path_expression)
    self.assert_constraint_is_equal_to_expression(base_id='Patient', element_definition_id='Patient.contact.name', constraint=constraint, expected_sql_expression=expected_sql_expression, expected_fhir_path_sql_expression=expected_fhir_path_sql_expression, expected_fields_referenced=expected_fields_referenced)

Tests encoding of a "transitive constraint" defined on a BackboneElement.

A "transitive constraint" is a constraint defined relative to a resource
elsewhere in the FHIR resource graph than what we're querying against.

Args:
fhir_path_expression: The FHIRPath expression to encode.
expected_sql_expression: The expected generated Standard SQL from v1.
expected_fhir_path_sql_expression: The expected generated Standard SQL
without any contextual subqueries.
expected_fields_referenced: The expected fields_referenced_by_expression
attribute on the resulting constraint.


def flownet2_fusion(self, x):
    with argscope([tf.layers.conv2d], activation=(lambda x: tf.nn.leaky_relu(x, 0.1)), padding='valid', strides=2, kernel_size=3, data_format='channels_first'), argscope([tf.layers.conv2d_transpose], padding='same', activation=tf.identity, data_format='channels_first', strides=2, kernel_size=4):
        conv0 = tf.layers.conv2d(pad(x, 1), 64, name='conv0', strides=1)
        x = tf.layers.conv2d(pad(conv0, 1), 64, name='conv1')
        conv1 = tf.layers.conv2d(pad(x, 1), 128, name='conv1_1', strides=1)
        x = tf.layers.conv2d(pad(conv1, 1), 128, name='conv2')
        conv2 = tf.layers.conv2d(pad(x, 1), 128, name='conv2_1', strides=1)
        flow2 = tf.layers.conv2d(pad(conv2, 1), 2, name='predict_flow2', strides=1, activation=tf.identity)
        flow2_up = tf.layers.conv2d_transpose(flow2, 2, name='upsampled_flow2_to_1')
        x = tf.layers.conv2d_transpose(conv2, 32, name='deconv1', activation=(lambda x: tf.nn.leaky_relu(x, 0.1)))
        concat1 = tf.concat([conv1, x, flow2_up], axis=1, name='concat1')
        interconv1 = tf.layers.conv2d(pad(concat1, 1), 32, strides=1, name='inter_conv1', activation=tf.identity)
        flow1 = tf.layers.conv2d(pad(interconv1, 1), 2, name='predict_flow1', strides=1, activation=tf.identity)
        flow1_up = tf.layers.conv2d_transpose(flow1, 2, name='upsampled_flow1_to_0')
        x = tf.layers.conv2d_transpose(concat1, 16, name='deconv0', activation=(lambda x: tf.nn.leaky_relu(x, 0.1)))
        concat0 = tf.concat([conv0, x, flow1_up], axis=1, name='concat0')
        interconv0 = tf.layers.conv2d(pad(concat0, 1), 16, strides=1, name='inter_conv0', activation=tf.identity)
        flow0 = tf.layers.conv2d(pad(interconv0, 1), 2, name='predict_flow0', strides=1, activation=tf.identity)
        return tf.identity(flow0, name='flow2')

Architecture in Table 4 of FlowNet 2.0.

Args:
x: NCHW tensor, where C=11 is the concatenation of 7 items of [3, 2, 2, 1, 1, 1, 1] channels.


def str_of_constant(self, printer: 'Callable[[_base.BaseValue], str]') -> str:
    del printer
    return repr(self.pyval)

Get a string representation of this constant.

Args:
printer: A BaseValue -> str function that will be used to print abstract
values.

Returns:
A string of self.pyval.


def _get_num_multimodal_tokens(self, image_sizes=None, **kwargs):
    vision_data = {}
    if image_sizes is not None:
        num_image_tokens = [self.image_seq_length] * len(image_sizes)
        num_image_patches = [1] * len(image_sizes)
        vision_data.update({'num_image_tokens': num_image_tokens, 'num_image_patches': num_image_patches})
    return MultiModalData(**vision_data)

Computes the number of placeholder tokens needed for multimodal inputs with the given sizes.

Args:
image_sizes (List[List[str]], *optional*):
The input sizes formatted as (height, width) per each image.
Returns:
Dict[str, List[int]]: A dictionary mapping each modality ("image", "video", "audio")
to a list containing the number of placeholder tokens required. If the model doesn't accept
a certain modality or no input sizes are provided, the dict value is set to an empty list.


def CompleteBreakpoint(self, breakpoint_id):

    with self._lock:
      self._completed.add(breakpoint_id)
      if breakpoint_id in self._active:
        self._active.pop(breakpoint_id).Clear()

Marks the specified breaking as completed.

Appends the ID to set of completed breakpoints and clears it.

Args:
breakpoint_id: breakpoint ID to complete.


def as_dict(self, voigt=False):

        input_array = self.voigt if voigt else self
        d = {"@module": self.__class__.__module__,
             "@class": self.__class__.__name__,
             "input_array": input_array.tolist()}
        if voigt:
            d.update({"voigt": voigt})
        return d

Serializes the tensor object

Args:
voigt (bool): flag for whether to store entries in
voigt-notation.  Defaults to false, as information
may be lost in conversion.

Returns (Dict):
serialized format tensor object


def map_feeds(self, ad_feed, ad_creative_assignment, ad_placement_assignment, ad_event_tag_assignment, placement_feed, event_tag_profile_feed):
    for ad in ad_feed:
        ad['creative_assignment'] = [association for association in ad_creative_assignment if self._assignment_matches(ad, association)]
        ad['placement_assignment'] = [association for association in ad_placement_assignment if self._assignment_matches(ad, association)]
        if ad.get(FieldMap.PLACEMENT_ID, None) or ad.get(FieldMap.PLACEMENT_NAME, None):
            ad['placement_assignment'].append(ad)
        ad['event_tag_assignment'] = [association for association in ad_event_tag_assignment if self._assignment_matches(ad, association)]
        if ad.get(FieldMap.EVENT_TAG_ID, None) or ad.get(FieldMap.EVENT_TAG_NAME, None):
            ad['event_tag_assignment'].append(ad)
        ad['placement_event_tag_profile'] = []
        for placement_assignment in ad['placement_assignment']:
            placement = self._placement_dao.get(placement_assignment, required=True)
            if placement:
                ad_placement = None
                for item in placement_feed:
                    if int(placement['id']) == item.get(FieldMap.PLACEMENT_ID, None):
                        ad_placement = item
                if ad_placement:
                    event_tag_profile_name = ad_placement.get(FieldMap.EVENT_TAG_PROFILE_NAME, '')
                    if event_tag_profile_name:
                        ad['placement_event_tag_profile'] += [event_tag_profile for event_tag_profile in event_tag_profile_feed if event_tag_profile.get(FieldMap.EVENT_TAG_PROFILE_NAME, None) == event_tag_profile_name]

Maps subfeeds to the corresponding ad.

The Ad is an object that has several other dependent entities, they could be
other entities like creative assignment, or complex sub objects in the ad
entity like the placement assignment. This function maps those feeds by ID
and injects the child feeds into the feed item representing the ad.

Also, the ad level is where placement event tag profiles are assigned, and
therefore this function is also responsible to determining if the placement
event tag profile should be used, or if the direct event tag assignment in
the ad should be used.

Args:
ad_feed: Ad feed.
ad_creative_assignment: Ad creative assignment feed.
ad_placement_assignment: Ad placement assignment feed.
placement_feed: Placement feed.
event_tag_profile_feed: Event tag profile feed.


def __init__(self, urns, service, managed_replacement=None):
    self._urns = urns
    self._service = service
    self._schema_transforms = None
    self._managed_replacement = managed_replacement

Initializes the ExternalProvider.

Args:
urns: a set of URNs that uniquely identify the transforms supported.
service: the gradle target that identified the expansion service jar.
managed_replacement (Optional): a map that defines the transform for
which the SDK may replace the transform with an available managed
transform.


def _infer_all_output_dims(self, inputs):

    batch_size = tf.expand_dims(tf.shape(inputs)[0], 0)
    out_channels = (self.output_channels,)

    if self._n == 1:
      out_shape = (1,) + self.output_shape
    else:
      out_shape = self.output_shape

    if self._data_format.startswith("NC"):
      out_shape_tuple = out_channels + out_shape
    elif self._data_format.startswith("N") and self._data_format.endswith("C"):
      out_shape_tuple = out_shape + out_channels

    output_shape = tf.concat([batch_size, out_shape_tuple], 0)
    return output_shape

Calculate the output shape for `inputs` after a deconvolution.

Args:
inputs: A Tensor of shape `data_format` and of type `tf.float16`,
`tf.bfloat16` or `tf.float32`.

Returns:
output_shape: A tensor of shape (`batch_size`, `conv_output_shape`).


def _mel_to_hertz(mel_values, name=None):
    with ops.name_scope(name, 'mel_to_hertz', [mel_values]):
        mel_values = ops.convert_to_tensor(mel_values)
        return _MEL_BREAK_FREQUENCY_HERTZ * (math_ops.exp(mel_values / _MEL_HIGH_FREQUENCY_Q) - 1.0)

Converts frequencies in `mel_values` from the mel scale to linear scale.

Args:
mel_values: A `Tensor` of frequencies in the mel scale.
name: An optional name for the operation.

Returns:
A `Tensor` of the same shape and type as `mel_values` containing linear
scale frequencies in Hertz.


def bridge_delete(br, if_exists=True):

    param_if_exists = _param_if_exists(if_exists)
    cmd = 'ovs-vsctl {1}del-br {0}'.format(br, param_if_exists)
    result = __salt__['cmd.run_all'](cmd)
    retcode = result['retcode']
    return _retcode_to_bool(retcode)

Deletes bridge and all of  its  ports.

Args:
br: A string - bridge name
if_exists: Bool, if False - attempting to delete a bridge that does not exist returns False.

Returns:
True on success, else False.

.. versionadded:: 2016.3.0

CLI Example:
.. code-block:: bash

salt '*' openvswitch.bridge_delete br0


def calculate_energy(self, energies):

        return sum([amt * energies[c] for amt, c in zip(self._coeffs,
                                                        self._all_comp)])

Calculates the energy of the reaction.

Args:
energies ({Composition: float}): Energy for each composition.
E.g ., {comp1: energy1, comp2: energy2}.

Returns:
reaction energy as a float.


def import_tsv(self, tsv_file):

        r = fapi.upload_entities_tsv(self.namespace, self.name,
                                     self.tsv_file, self.api_url)
        fapi._check_response_code(r, 201)

Upload entity data to workspace from tsv loadfile.

Args:
tsv_file (file): Tab-delimited file of entity data


def save_tiles(tiles, prefix='', directory=os.getcwd(), format='png'):

    for tile in tiles:
        tile.save(filename=tile.generate_filename(prefix=prefix,
                                                  directory=directory,
                                                  format=format),
                                                  format=format)
    return tuple(tiles)

Write image files to disk. Create specified folder(s) if they
don't exist. Return list of :class:`Tile` instance.

Args:
tiles (list):  List, tuple or set of :class:`Tile` objects to save.
prefix (str):  Filename prefix of saved tiles.

Kwargs:
directory (str):  Directory to save tiles. Created if non-existant.

Returns:
Tuple of :class:`Tile` instances.


def pad(self, image: np.ndarray, size: Dict[str, int], aspect_ratio: Tuple[int, int], data_format: Optional[Union[str, ChannelDimension]]=None, input_data_format: Optional[Union[str, ChannelDimension]]=None) -> np.ndarray:
    _validate_size(size)
    image_height, image_width = get_image_size(image, channel_dim=input_data_format)
    num_tiles_height, num_tiles_width = aspect_ratio
    padded_height = num_tiles_height * size['height']
    padded_width = num_tiles_width * size['width']
    pad_size = ((0, padded_height - image_height), (0, padded_width - image_width))
    image = pad(image, pad_size, mode=PaddingMode.CONSTANT, constant_values=0, data_format=data_format, input_data_format=input_data_format)
    return image

Pad an image to the `size` x `aspect_ratio`. For example, if size is {height: 224, width: 224} and aspect ratio is
(1, 2), the image will be padded to 224x448.

Args:
image (`np.ndarray`):
Image to resize.
size (`Dict[str, int]`):
Size of the output image.
aspect_ratio (`Tuple[int, int]`):
The aspect ratio of the image.
data_format (`str` or `ChannelDimension`, *optional*):
The channel dimension format of the image. If not provided, it will be the same as the input image.
input_data_format (`ChannelDimension` or `str`, *optional*):
The channel dimension format of the input image. If not provided, it will be inferred.

Returns:
`np.ndarray`: The padded image.


def send_message(host, data, timeout=None, properties=None):

    channel = _get_channel(host, timeout)

    if not properties:
        properties = pika.BasicProperties(
            content_type="application/json",
            delivery_mode=2,
            headers={"UUID": str(uuid.uuid4())}
        )

    parameters = settings.get_amqp_settings()[host]

    channel.basic_publish(
        exchange=parameters["exchange"],
        routing_key=parameters["in_key"],
        properties=properties,
        body=data
    )

Send message to given `host`.

Args:
host (str): Specified host: aleph/ftp/whatever available host.
data (str): JSON data.
timeout (int, default None): How much time wait for connection.


def VisitUnionType(self, union):
    if not any((isinstance(t, pytd.GenericType) for t in union.type_list)):
        return union
    union = pytd_utils.JoinTypes(union.type_list)
    if not isinstance(union, pytd.UnionType):
        union = pytd.UnionType((union,))
    merge_tuples = self._should_merge(pytd.TupleType, union)
    merge_callables = self._should_merge(pytd.CallableType, union)
    if merge_tuples or merge_callables:
        type_list = []
        for t in union.type_list:
            if merge_tuples and isinstance(t, pytd.TupleType):
                t = pytd.GenericType(base_type=t.base_type, parameters=(pytd_utils.JoinTypes(t.parameters),))
            elif merge_callables and isinstance(t, pytd.CallableType):
                t = pytd.GenericType(base_type=t.base_type, parameters=(pytd.AnythingType(), t.ret))
            type_list.append(t)
        union = union.Replace(type_list=tuple(type_list))
    collect = {}
    has_redundant_base_types = False
    for t in union.type_list:
        if isinstance(t, pytd.GenericType):
            key = self._key(t)
            if key in collect:
                has_redundant_base_types = True
                collect[key] = tuple((pytd_utils.JoinTypes([p1, p2]) for p1, p2 in zip(collect[key], t.parameters)))
            else:
                collect[key] = t.parameters
    if not has_redundant_base_types:
        return union
    result = pytd.NothingType()
    done = set()
    for t in union.type_list:
        if isinstance(t, pytd.GenericType):
            key = self._key(t)
            if key in done:
                continue
            parameters = collect[key]
            add = t.Replace(parameters=tuple((p.Visit(CombineContainers()) for p in parameters)))
            done.add(key)
        else:
            add = t
        result = pytd_utils.JoinTypes([result, add])
    return result

Push unions down into containers.

This collects similar container types in unions and merges them into
single instances with the union type pushed down to the element_type level.

Arguments:
union: A pytd.Union instance. Might appear in a parameter, a return type,
a constant type, etc.

Returns:
A simplified pytd.Union.


def country_code_for_valid_region(region_code):

    metadata = PhoneMetadata.metadata_for_region(region_code.upper(), None)
    if metadata is None:
        raise Exception("Invalid region code %s" % region_code)
    return metadata.country_code

Returns the country calling code for a specific region.

For example, this would be 1 for the United States, and 64 for New
Zealand.  Assumes the region is already valid.

Arguments:
region_code -- The region that we want to get the country calling code for.

Returns the country calling code for the region denoted by region_code.


def unpack(self, buff, offset=0):

        super().unpack(buff, offset)
        if self.tpid.value:
            self._validate()
            self.tpid = self.tpid.value
            self.pcp = self._tci.value >> 13
            self.cfi = (self._tci.value >> 12) & 1
            self.vid = self._tci.value & 4095
        else:
            self.tpid = EtherType.VLAN
            self.pcp = None
            self.cfi = None
            self.vid = None

Unpack a binary struct into this object's attributes.

Return the values instead of the lib's basic types.

After unpacking, the abscence of a `tpid` value causes the assignment
of None to the field values to indicate that there is no VLAN
information.

Args:
buff (bytes): Binary buffer.
offset (int): Where to begin unpacking.

Raises:
:exc:`~.exceptions.UnpackException`: If unpack fails.


def timeRange(start: datetime.time, end: datetime.time, step: float) -> Iterator[datetime.datetime]:
    assert (step > 0)
    start = _fillDate(start)
    end = _fillDate(end)
    delta = datetime.timedelta(seconds=step)
    t = start
    while (t < datetime.datetime.now()):
        t += delta
    while (t <= end):
        waitUntil(t)
        (yield t)
        t += delta

Iterator that waits periodically until certain time points are
reached while yielding those time points.

Args:
start: Start time, can be specified as datetime.datetime,
or as datetime.time in which case today is used as the date
end: End time, can be specified as datetime.datetime,
or as datetime.time in which case today is used as the date
step (float): The number of seconds of each period


def _dominant_task_for_jobs(tasks):
    per_job = _group_tasks_by_jobid(tasks)
    ret = []
    for job_id in per_job.keys():
        tasks_in_salience_order = sorted(per_job[job_id], key=_importance_of_task)
        ret.append(tasks_in_salience_order[0])
    return ret

A list with, for each job, its dominant task.

The dominant task is the one that exemplifies its job's
status. It is either:
- the first (FAILURE or CANCELED) task, or if none
- the first RUNNING task, or if none
- the first SUCCESS task.

Args:
tasks: a list of tasks to consider

Returns:
A list with, for each job, its dominant task.


def sys_check_for_event(
    mask: int, k: Optional[Key], m: Optional[Mouse]
) -> int:

    return int(
        lib.TCOD_sys_check_for_event(
            mask, k.key_p if k else ffi.NULL, m.mouse_p if m else ffi.NULL
        )
    )

Check for and return an event.

Args:
mask (int): :any:`Event types` to wait for.
k (Optional[Key]): A tcod.Key instance which might be updated with
an event.  Can be None.
m (Optional[Mouse]): A tcod.Mouse instance which might be updated
with an event.  Can be None.

.. deprecated:: 9.3
Use the :any:`tcod.event.get` function to check for events.


def GetFormatterObject(cls, data_type):

    data_type = data_type.lower()
    if data_type not in cls._formatter_objects:
      formatter_object = None

      if data_type in cls._formatter_classes:
        formatter_class = cls._formatter_classes[data_type]

        formatter_object = formatter_class()

      if not formatter_object:
        logger.warning(
            'Using default formatter for data type: {0:s}'.format(data_type))
        formatter_object = default.DefaultFormatter()

      cls._formatter_objects[data_type] = formatter_object

    return cls._formatter_objects[data_type]

Retrieves the formatter object for a specific data type.

Args:
data_type (str): data type.

Returns:
EventFormatter: corresponding formatter or the default formatter if
not available.


def _load_saved_model(self, saved_model_dir, saved_model_tags):
    graph = _ops.Graph()
    saved_model = _loader_impl.SavedModelLoader(saved_model_dir)
    saved_model.load_graph(graph, tags=saved_model_tags)
    meta_graph = saved_model.get_meta_graph_def_from_tags(saved_model_tags)
    graph_def = meta_graph.graph_def
    signature_def = meta_graph.signature_def[_signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY]
    input_tensors = [graph.get_tensor_by_name(signature_def.inputs[key].name) for key in signature_def.inputs]
    output_tensors = [graph.get_tensor_by_name(signature_def.outputs[key].name) for key in signature_def.outputs]
    return (graph_def, input_tensors, output_tensors)

Load graph_def from saved model with the default serving signature key.

Args:
saved_model_dir: Directory of the SavedModel.
saved_model_tags: Set of tags identifying the MetaGraphDef within the
SavedModel to analyze.

Returns:
graph_def: The loaded GraphDef.
input_tensors: List of input tensors.
output_tensors: List of output tensors.


def equal(x, y):
    return math_ops.equal(x, y)

Element-wise equality between two tensors.

Args:
x: Tensor or variable.
y: Tensor or variable.

Returns:
A bool tensor.


def alloc(self):
    if (not self._free):
        self._expand()
    id = self._free.pop()
    self._used.add(id)
    return id

Allocate an ID value and return it.

Raises:
ValueError: Out of capacity in ID pool.


def to_csv(self, filename: str, latexify_names: bool = False):

        elements = set()
        for entry in self.entries:
            elements.update(entry.composition.elements)
        elements = sorted(list(elements), key=lambda a: a.X)
        writer = csv.writer(open(filename, "w"), delimiter=unicode2str(","),
                            quotechar=unicode2str("\""),
                            quoting=csv.QUOTE_MINIMAL)
        writer.writerow(["Name"] + elements + ["Energy"])
        for entry in self.entries:
            row = [entry.name if not latexify_names
                   else re.sub(r"([0-9]+)", r"_{\1}", entry.name)]
            row.extend([entry.composition[el] for el in elements])
            row.append(entry.energy)
            writer.writerow(row)

Exports PDEntries to a csv

Args:
filename: Filename to write to.
entries: PDEntries to export.
latexify_names: Format entry names to be LaTex compatible,
e.g., Li_{2}O


def get_path(self, temp_ver):
    if (temp_ver not in self):
        raise RuntimeError('Template: {} not present'.format(temp_ver.name))
    return self._prefixed(temp_ver.name)

Get the path of the given version in this store

Args:
temp_ver TemplateVersion: version to look for

Returns:
str: The path to the template version inside the store

Raises:
RuntimeError: if the template is not in the store


def convertDateStrToDateTimeStr(date, time='00:00:00'):
    if not date == None:
        date = '%sT%sZ' % (date, time)
    return date

Convert Date string (YYYY-MM-DD) to a datetime string by adding the desired time (YYYY-MM-DDTHH:mm:SSZ)

Args:
date: the date as a string to be converted
time: the time as a string to be added to the date

Returns:
A string representation of a datetime in the following
format YYYY-MM-DDTHH:mm:SSZ


def GetValidHostsForCert(cert):
    if ('subjectAltName' in cert):
        return [x[1] for x in cert['subjectAltName'] if (x[0].lower() == 'dns')]
    else:
        return [x[0][1] for x in cert['subject'] if (x[0][0].lower() == 'commonname')]

Returns a list of valid host globs for an SSL certificate.

Args:
cert: A dictionary representing an SSL certificate.
Returns:
list: A list of valid host globs.


def open_streaming_interface(self):
    super(ReferenceDevice, self).open_streaming_interface()
    self.rpc(8, rpcs.SG_GRAPH_INPUT, 8, streams.COMM_TILE_OPEN)
    return []

Called when someone opens a streaming interface to the device.

This method will automatically notify sensor_graph that there is a
streaming interface opened.

Returns:
list: A list of IOTileReport objects that should be sent out
the streaming interface.


def ParseLocalEntryRow(self, parser_mediator, query, row, cache=None, database=None, **unused_kwargs):
    query_hash = hash(query)
    inode_number = self._GetRowValue(query_hash, row, 'inode_number')
    local_path = self.GetLocalPath(inode_number, cache, database)
    event_data = GoogleDriveSnapshotLocalEntryEventData()
    event_data.path = local_path
    event_data.query = query
    event_data.size = self._GetRowValue(query_hash, row, 'size')
    timestamp = self._GetRowValue(query_hash, row, 'modified')
    date_time = dfdatetime_posix_time.PosixTime(timestamp=timestamp)
    event = time_events.DateTimeValuesEvent(date_time, definitions.TIME_DESCRIPTION_MODIFICATION)
    parser_mediator.ProduceEventWithEventData(event, event_data)

Parses a local entry row.

Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
query (str): query that created the row.
row (sqlite3.Row): row.
cache (Optional[SQLiteCache]): cache.
database (Optional[SQLiteDatabase]): database.


def optionally_with_args(phase, **kwargs):
    if isinstance(phase, PhaseGroup):
        return phase.with_args(**kwargs)
    if isinstance(phase, collections.Iterable):
        return [optionally_with_args(p, **kwargs) for p in phase]
    if (not isinstance(phase, phase_descriptor.PhaseDescriptor)):
        phase = phase_descriptor.PhaseDescriptor.wrap_or_copy(phase)
    return phase.with_known_args(**kwargs)

Apply only the args that the phase knows.

If the phase has a **kwargs-style argument, it counts as knowing all args.

Args:
phase: phase_descriptor.PhaseDescriptor or PhaseGroup or callable, or
iterable of those, the phase or phase group (or iterable) to apply
with_args to.
**kwargs: arguments to apply to the phase.

Returns:
phase_descriptor.PhaseDescriptor or PhaseGroup or iterable with the updated
args.


def diff_configurations(model_config, bench_config, model_bundle, bench_bundle):

    diff_dict = LIVVDict()
    model_data = model_bundle.parse_config(model_config)
    bench_data = bench_bundle.parse_config(bench_config)
    if model_data == {} and bench_data == {}:
        return elements.error("Configuration Comparison",
                              "Could not open file: " + model_config.split(os.path.sep)[-1])

    model_sections = set(six.iterkeys(model_data))
    bench_sections = set(six.iterkeys(bench_data))
    all_sections = set(model_sections.union(bench_sections))

    for s in all_sections:
        model_vars = set(six.iterkeys(model_data[s])) if s in model_sections else set()
        bench_vars = set(six.iterkeys(bench_data[s])) if s in bench_sections else set()
        all_vars = set(model_vars.union(bench_vars))
        for v in all_vars:
            model_val = model_data[s][v] if s in model_sections and v in model_vars else 'NA'
            bench_val = bench_data[s][v] if s in bench_sections and v in bench_vars else 'NA'
            same = True if model_val == bench_val and model_val != 'NA' else False
            diff_dict[s][v] = (same, model_val, bench_val)
    return elements.file_diff("Configuration Comparison", diff_dict)

Description

Args:
model_config: a dictionary with the model configuration data
bench_config: a dictionary with the benchmark configuration data
model_bundle: a LIVVkit model bundle object
bench_bundle: a LIVVkit model bundle object

Returns:
A dictionary created by the elements object corresponding to
the results of the bit for bit testing


def prettify(unicode_text):

    import xml.dom.minidom
    reparsed = xml.dom.minidom.parseString(unicode_text.encode('utf-8'))
    return reparsed.toprettyxml(indent="  ", newl="\n")

Return a pretty-printed version of a unicode XML string.

Useful for debugging.

Args:
unicode_text (str): A text representation of XML (unicode,
*not* utf-8).

Returns:
str: A pretty-printed version of the input.


def json_to_url(json, symbol):

    start = json[0]['date']
    end = json[-1]['date']
    diff = end - start

    periods = [300, 900, 1800, 7200, 14400, 86400]

    diffs = {}
    for p in periods:
        diffs[p] = abs(1 - (p / (diff / len(json))))

    period = min(diffs, key=diffs.get)

    url = ('https:
           '=returnChartData&currencyPair={0}&start={1}'
           '&end={2}&period={3}').format(symbol, start, end, period)
    return url

Converts a JSON to a URL by the Poloniex API

Args:
json: JSON data as a list of dict dates, where the keys are
the raw market statistics.
symbol: String of currency pair, like a ticker symbol.

Returns:
String URL to Poloniex API representing the given JSON.


def concat(cartesians, ignore_index=False, keys=None):
    frames = [molecule._frame for molecule in cartesians]
    new = pd.concat(frames, ignore_index=ignore_index, keys=keys, verify_integrity=True)
    if (type(ignore_index) is bool):
        new = pd.concat(frames, ignore_index=ignore_index, keys=keys, verify_integrity=True)
    else:
        new = pd.concat(frames, ignore_index=True, keys=keys, verify_integrity=True)
        if (type(ignore_index) is int):
            new.index = range(ignore_index, (ignore_index + len(new)))
        else:
            new.index = ignore_index
    return cartesians[0].__class__(new)

Join list of cartesians into one molecule.

Wrapper around the :func:`pandas.concat` function.
Default values are the same as in the pandas function except for
``verify_integrity`` which is set to true in case of this library.

Args:
ignore_index (sequence, bool, int): If it is a boolean, it
behaves like in the description of
:meth:`pandas.DataFrame.append`.
If it is a sequence, it becomes the new index.
If it is an integer,
``range(ignore_index, ignore_index + len(new))``
becomes the new index.
keys (sequence): If multiple levels passed, should contain tuples.
Construct hierarchical index using the passed keys as
the outermost level

Returns:
Cartesian:


def get_class_in_module(class_name: str, module_path: Union[str, os.PathLike], *, force_reload: bool=False) -> type:
    name = os.path.normpath(module_path)
    if name.endswith('.py'):
        name = name[:-3]
    name = name.replace(os.path.sep, '.')
    module_file: Path = Path(HF_MODULES_CACHE) / module_path
    with _HF_REMOTE_CODE_LOCK:
        if force_reload:
            sys.modules.pop(name, None)
            importlib.invalidate_caches()
        cached_module: Optional[ModuleType] = sys.modules.get(name)
        module_spec = importlib.util.spec_from_file_location(name, location=module_file)
        module_files: list[Path] = [module_file] + sorted(map(Path, get_relative_import_files(module_file)))
        module_hash: str = hashlib.sha256(b''.join((bytes(f) + f.read_bytes() for f in module_files))).hexdigest()
        module: ModuleType
        if cached_module is None:
            module = importlib.util.module_from_spec(module_spec)
            sys.modules[name] = module
        else:
            module = cached_module
        if getattr(module, '__transformers_module_hash__', '') != module_hash:
            module_spec.loader.exec_module(module)
            module.__transformers_module_hash__ = module_hash
        return getattr(module, class_name)

Import a module on the cache directory for modules and extract a class from it.

Args:
class_name (`str`): The name of the class to import.
module_path (`str` or `os.PathLike`): The path to the module to import.
force_reload (`bool`, *optional*, defaults to `False`):
Whether to reload the dynamic module from file if it already exists in `sys.modules`.
Otherwise, the module is only reloaded if the file has changed.

Returns:
`typing.Type`: The class looked for.


def CopyFromDateTimeString(self, time_string):
    super(APFSTime, self)._CopyFromDateTimeString(time_string)
    if ((self._timestamp is None) or (self._timestamp < self._INT64_MIN) or (self._timestamp > self._INT64_MAX)):
        raise ValueError('Date time value not supported.')

Copies a APFS timestamp from a date and time string.

Args:
time_string (str): date and time value formatted as:
YYYY-MM-DD hh:mm:ss.######[+-]##:##

Where # are numeric digits ranging from 0 to 9 and the seconds
fraction can be either 3 or 6 digits. The time of day, seconds
fraction and time zone offset are optional. The default time zone
is UTC.

Raises:
ValueError: if the date and time value is not supported.


def _ReadLine(self, file_object):
    if (len(self._buffer) < self._buffer_size):
        content = file_object.read(self._buffer_size)
        content = content.decode(self._encoding)
        self._buffer = ''.join([self._buffer, content])
    (line, new_line, self._buffer) = self._buffer.partition('\n')
    if ((not line) and (not new_line)):
        line = self._buffer
        self._buffer = ''
    self._current_offset += len(line)
    if line.endswith('\r'):
        line = line[:(- len('\r'))]
    if new_line:
        line = ''.join([line, '\n'])
        self._current_offset += len('\n')
    return line

Reads a line from the file object.

Args:
file_object (dfvfs.FileIO): file-like object.

Returns:
str: line read from the file-like object.


def astype(array, y):
    if isinstance(y, autograd.core.Node):
        return array.astype(numpy.array(y.value).dtype)
    return array.astype(numpy.array(y).dtype)

A functional form of the `astype` method.

Args:
array: The array or number to cast.
y: An array or number, as the input, whose type should be that of array.

Returns:
An array or number with the same dtype as `y`.


def _convert_path(path, name):

    table = os.path.splitext(path)[0]
    table = table.replace(os.path.sep, '__')
    if name is not None:
        table = '___'.join([table, name])
    table = re.sub('[^0-9a-zA-Z_]+', '_', table)
    table = table.lower()
    return table

Convert resource's path and name to storage's table name.

Args:
path (str): resource path
name (str): resource name

Returns:
str: table name


def add_lambda_permissions(function='',
                           statement_id='',
                           action='lambda:InvokeFunction',
                           principal='',
                           source_arn='',
                           env='',
                           region='us-east-1'):

    session = boto3.Session(profile_name=env, region_name=region)
    lambda_client = session.client('lambda')
    response_action = None
    prefixed_sid = FOREMAST_PREFIX + statement_id

    add_permissions_kwargs = {
        'FunctionName': function,
        'StatementId': prefixed_sid,
        'Action': action,
        'Principal': principal,
    }

    if source_arn:
        add_permissions_kwargs['SourceArn'] = source_arn

    try:
        lambda_client.add_permission(**add_permissions_kwargs)
        response_action = 'Add permission with Sid: {}'.format(prefixed_sid)
    except boto3.exceptions.botocore.exceptions.ClientError as error:
        LOG.debug('Add permission error: %s', error)
        response_action = "Did not add permissions"

    LOG.debug('Related StatementId (SID): %s', prefixed_sid)
    LOG.info(response_action)

Add permission to Lambda for the event trigger.

Args:
function (str): Lambda function name
statement_id (str): IAM policy statement (principal) id
action (str): Lambda action to allow
principal (str): AWS principal to add permissions
source_arn (str): ARN of the source of the event. Only needed for S3
env (str): Environment/account of function
region (str): AWS region of function


def _static_cache_update(k_cache: torch.Tensor, v_cache: torch.Tensor, key_states: torch.Tensor, value_states: torch.Tensor, cache_position: Optional[torch.LongTensor]) -> Tuple[torch.Tensor, torch.Tensor]:
    if cache_position is None:
        k_cache.copy_(key_states)
        v_cache.copy_(value_states)
    else:
        try:
            k_cache.index_copy_(2, cache_position, key_states)
            v_cache.index_copy_(2, cache_position, value_states)
        except NotImplementedError:
            k_cache[:, :, cache_position] = key_states
            v_cache[:, :, cache_position] = value_states
    return (k_cache, v_cache)

Updates the static cache tensors in place.

Args:
k_cache (`torch.Tensor`): The key cache tensor to update.
v_cache (`torch.Tensor`): The value cache tensor to update.
key_states (`torch.Tensor`): The new key states to add.
value_states (`torch.Tensor`): The new value states to add.
cache_position (`Optional[torch.LongTensor]`): The position indices where the new states should be inserted.
If None, the entire cache is overwritten (prefill).

Returns:
Tuple[`torch.Tensor`, `torch.Tensor`]: The updated key and value cache tensors (modified in-place).


def join(input_files, output_file):
    final_features = []
    for file in input_files:
        with open(file) as f:
            feat_collection = geojson.load(f)
            final_features += feat_collection['features']
    feat_collection['features'] = final_features
    with open(output_file, 'w') as f:
        geojson.dump(feat_collection, f)

Join geojsons into one. The spatial reference system of the output file is the same
as the one of the last file in the list.

Args:
input_files (list): List of file name strings.
output_file (str): Output file name.


def findLocalOptima(self,fast=False,verbose=True,n_times=10,lambd=None):

        if not self.init:       self.initGP(fast)

        opt_list = []

        fixed0 = SP.zeros_like(self.gp.getParams()['dataTerm'])

        for i in range(n_times):

            scales1 = self._getScalesRand()
            fixed1  = 1e-1*SP.randn(fixed0.shape[0],fixed0.shape[1])
            conv = self.trainGP(fast=fast,scales0=scales1,fixed0=fixed1,lambd=lambd)

            if conv:

                temp=1
                for j in range(len(opt_list)):
                    if SP.allclose(abs(self.getScales()),abs(opt_list[j]['scales'])):
                        temp=0
                        opt_list[j]['counter']+=1
                        break
                if temp==1:
                    opt = {}
                    opt['counter'] = 1
                    opt['LML'] = self.getLML()
                    opt['scales'] = self.getScales()
                    opt_list.append(opt)

        LML = SP.array([opt_list[i]['LML'] for i in range(len(opt_list))])
        index   = LML.argsort()[::-1]
        out = []
        if verbose:
            print("\nLocal mimima\n")
            print("n_times\t\tLML")
            print("------------------------------------")
            for i in range(len(opt_list)):
                out.append(opt_list[index[i]])
                if verbose:
                    print(("%d\t\t%f" % (opt_list[index[i]]['counter'], opt_list[index[i]]['LML'])))
                print("")

        return out

Train the model repeadly up to a number specified by the users with random restarts and
return a list of all relative minima that have been found

Args:
fast:       Boolean. if set to True initalize kronSumGP
verbose:    Boolean. If set to True, verbose output is produced. (default True)
n_times:    number of re-starts of the optimization. (default 10)


def get_extension_by_name(cert_obj, extension_name):

    try:
        return cert_obj.extensions.get_extension_for_oid(
            getattr(cryptography.x509.oid.ExtensionOID, extension_name)
        )
    except cryptography.x509.ExtensionNotFound:
        pass

Get a standard certificate extension by attribute name.

Args:
cert_obj: cryptography.Certificate
Certificate containing a standard extension.

extension_name : str
Extension name. E.g., 'SUBJECT_DIRECTORY_ATTRIBUTES'.

Returns:
Cryptography.Extension


async def _async_supervisor(func, animation_, step, *args, **kwargs):

    with ThreadPoolExecutor(max_workers=2) as pool:
        with _terminating_event() as event:
            pool.submit(animate_cli, animation_, step, event)
            result = await func(*args, **kwargs)
    return result

Supervisor for running an animation with an asynchronous function.

Args:
func: A function to be run alongside an animation.
animation_: An infinite generator that produces
strings for the animation.
step: Seconds between each animation frame.
*args: Arguments for func.
**kwargs: Keyword arguments for func.
Returns:
The result of func(*args, **kwargs)
Raises:
Any exception that is thrown when executing func.