def get_counters(counter_list):

    if not isinstance(counter_list, list):
        raise CommandExecutionError('counter_list must be a list of tuples')

    try:

        query = win32pdh.OpenQuery()

        counters = build_counter_list(counter_list)

        for counter in counters:
            counter.add_to_query(query)

        win32pdh.CollectQueryData(query)

        time.sleep(1)
        win32pdh.CollectQueryData(query)
        ret = {}

        for counter in counters:
            try:
                ret.update({counter.path: counter.value()})
            except pywintypes.error as exc:
                if exc.strerror == 'No data to return.':

                    continue
                else:
                    raise

    finally:
        win32pdh.CloseQuery(query)

    return ret

Get the values for the passes list of counters

Args:
counter_list (list):
A list of counters to lookup

Returns:
dict: A dictionary of counters and their values


def add_defaults(self, ctype: ContentType=None) -> 'InstanceNode':
    val = self.value
    if (not (isinstance(val, StructuredValue) and self.is_internal())):
        return self
    res = self
    if isinstance(val, ObjectValue):
        if val:
            for mn in self._member_names():
                m = (res._member(mn) if (res is self) else res.sibling(mn))
                res = m.add_defaults(ctype)
            res = res.up()
        return self.schema_node._add_defaults(res, ctype)
    if (not val):
        return res
    en = res[0]
    while True:
        res = en.add_defaults(ctype)
        try:
            en = res.next()
        except NonexistentInstance:
            break
    return res.up()

Return the receiver with defaults added recursively to its value.

Args:
ctype: Content type of the defaults to be added. If it is
``None``, the content type will be the same as receiver's.


def get_imagery(cls, lat, lon, date=None, dim=None, cloud_score=False):
    instance = cls('planetary/earth/imagery')
    filters = {'lat': lat, 'lon': lon, 'date': date, 'dim': dim, 'cloud_score': cloud_score}
    return instance.get_resource(**filters)

Returns satellite image

Args:
lat: latitude float
lon: longitude float
date: date instance of available date from `get_assets`
dim: width and height of image in degrees as float
cloud_score: boolean to calculate the percentage of the image covered by clouds

Returns:
json


def iplot_state_qsphere(rho, figsize=None):

    html_template = Template()

    javascript_template = Template()
    rho = _validate_input_state(rho)
    if figsize is None:
        options = {}
    else:
        options = {'width': figsize[0], 'height': figsize[1]}

    qspheres_data = []

    num = int(np.log2(len(rho)))

    weig, stateall = linalg.eigh(rho)

    for _ in range(2**num):

        probmix = weig.max()
        prob_location = weig.argmax()
        if probmix > 0.001:

            state = stateall[:, prob_location]
            loc = np.absolute(state).argmax()

            for j in range(2**num):
                test = np.absolute(np.absolute(state[j]) -
                                   np.absolute(state[loc]))
                if test < 0.001:
                    loc = j
                    break

            angles = (np.angle(state[loc]) + 2 * np.pi) % (2 * np.pi)
            angleset = np.exp(-1j*angles)
            state = angleset*state
            state.flatten()

            spherepoints = []
            for i in range(2**num):

                element = bin(i)[2:].zfill(num)
                weight = element.count("1")

                number_of_divisions = n_choose_k(num, weight)
                weight_order = bit_string_index(element)

                angle = weight_order * 2 * np.pi / number_of_divisions

                zvalue = -2 * weight / num + 1
                xvalue = np.sqrt(1 - zvalue**2) * np.cos(angle)
                yvalue = np.sqrt(1 - zvalue**2) * np.sin(angle)

                prob = np.real(np.dot(state[i], state[i].conj()))
                angles = (np.angle(state[i]) + 2 * np.pi) % (2 * np.pi)
                qpoint = {
                    'x': xvalue,
                    'y': yvalue,
                    'z': zvalue,
                    'prob': prob,
                    'phase': angles
                }
                spherepoints.append(qpoint)

            sphere = {
                'points': spherepoints,
                'eigenvalue': probmix
            }

            qspheres_data.append(sphere)
            weig[prob_location] = 0

    div_number = str(time.time())
    div_number = re.sub('[.]', '', div_number)

    html = html_template.substitute({
        'divNumber': div_number
    })

    javascript = javascript_template.substitute({
        'data': qspheres_data,
        'divNumber': div_number,
        'options': options
    })

    display(HTML(html + javascript))

Create a Q sphere representation.

Graphical representation of the input array, using a Q sphere for each
eigenvalue.

Args:
rho (array): State vector or density matrix.
figsize (tuple): Figure size in pixels.


def _GetMessageFromFactory(factory, full_name):
    proto_descriptor = factory.pool.FindMessageTypeByName(full_name)
    proto_cls = factory.GetPrototype(proto_descriptor)
    return proto_cls

Get a proto class from the MessageFactory by name.

Args:
factory: a MessageFactory instance.
full_name: str, the fully qualified name of the proto type.
Returns:
A class, for the type identified by full_name.
Raises:
KeyError, if the proto is not found in the factory's descriptor pool.


def _kl_laplace_laplace(a, b, name=None):

  with tf.name_scope(name or "kl_laplace_laplace"):

    distance = tf.abs(a.loc - b.loc)
    ratio = a.scale / b.scale

    return (-tf.math.log(ratio) - 1 + distance / b.scale +
            ratio * tf.exp(-distance / a.scale))

Calculate the batched KL divergence KL(a || b) with a and b Laplace.

Args:
a: instance of a Laplace distribution object.
b: instance of a Laplace distribution object.
name: (optional) Name to use for created operations.
default is "kl_laplace_laplace".

Returns:
Batchwise KL(a || b)


def set_privilege(self, name, value=None):

        cmd = 'username %s' % name
        if value is not None:
            if not isprivilege(value):
                raise TypeError('priviledge value must be between 0 and 15')
            cmd += ' privilege %s' % value
        else:
            cmd += ' privilege 1'
        return self.configure(cmd)

Configures the user privilege value in EOS

Args:
name (str): The name of the user to craete

value (int): The privilege value to assign to the user.  Valid
values are in the range of 0 to 15

Returns:
True if the operation was successful otherwise False

Raises:
TypeError: if the value is not in the valid range


def _call_wrapped_cell(self, inputs, state, cell_call_fn, **kwargs):
    outputs, new_state = cell_call_fn(inputs, state, **kwargs)

    def assert_shape_match(inp, out):
        inp.get_shape().assert_is_compatible_with(out.get_shape())

    def default_residual_fn(inputs, outputs):
        nest.assert_same_structure(inputs, outputs)
        nest.map_structure(assert_shape_match, inputs, outputs)
        return nest.map_structure(lambda inp, out: inp + out, inputs, outputs)
    res_outputs = (self._residual_fn or default_residual_fn)(inputs, outputs)
    return (res_outputs, new_state)

Run the cell and then apply the residual_fn on its inputs to its outputs.

Args:
inputs: cell inputs.
state: cell state.
cell_call_fn: Wrapped cell's method to use for step computation (cell's
`__call__` or 'call' method).
**kwargs: Additional arguments passed to the wrapped cell's `call`.

Returns:
Tuple of cell outputs and new state.

Raises:
TypeError: If cell inputs and outputs have different structure (type).
ValueError: If cell inputs and outputs have different structure (value).


def bessel_i1(x, name=None):
    with ops.name_scope(name, 'bessel_i1', [x]):
        return gen_special_math_ops.bessel_i1(x)

Computes the Bessel i1 function of `x` element-wise.

Modified Bessel function of order 1.

It is preferable to use the numerically stabler function `i1e(x)` instead.

>>> tf.math.special.bessel_i1([-1., -0.5, 0.5, 1.]).numpy()
array([-0.5651591 , -0.25789431,  0.25789431,  0.5651591 ], dtype=float32)

Args:
x: A `Tensor` or `SparseTensor`. Must be one of the following types: `half`,
`float32`, `float64`.
name: A name for the operation (optional).

Returns:
A `Tensor` or `SparseTensor`, respectively. Has the same type as `x`.

@compatibility(scipy)
Equivalent to scipy.special.i1
@end_compatibility


def get_variation_for_experiment(self, experiment_id):
    return self.experiment_bucket_map.get(experiment_id, {self.VARIATION_ID_KEY: None}).get(self.VARIATION_ID_KEY)

Helper method to retrieve variation ID for given experiment.

Args:
experiment_id: ID for experiment for which variation needs to be looked up for.

Returns:
Variation ID corresponding to the experiment. None if no decision available.


def create_dir(self, directory_path, perm_bits=PERM_DEF):

        directory_path = self.make_string_path(directory_path)
        directory_path = self.absnormpath(directory_path)
        self._auto_mount_drive_if_needed(directory_path)
        if self.exists(directory_path, check_link=True):
            self.raise_os_error(errno.EEXIST, directory_path)
        path_components = self._path_components(directory_path)
        current_dir = self.root

        new_dirs = []
        for component in path_components:
            directory = self._directory_content(current_dir, component)[1]
            if not directory:
                new_dir = FakeDirectory(component, filesystem=self)
                new_dirs.append(new_dir)
                current_dir.add_entry(new_dir)
                current_dir = new_dir
            else:
                if S_ISLNK(directory.st_mode):
                    directory = self.resolve(directory.contents)
                current_dir = directory
                if directory.st_mode & S_IFDIR != S_IFDIR:
                    self.raise_os_error(errno.ENOTDIR, current_dir.path)

        for new_dir in new_dirs:
            new_dir.st_mode = S_IFDIR | perm_bits

        self._last_ino += 1
        current_dir.st_ino = self._last_ino
        return current_dir

Create `directory_path`, and all the parent directories.

Helper method to set up your test faster.

Args:
directory_path: The full directory path to create.
perm_bits: The permission bits as set by `chmod`.

Returns:
The newly created FakeDirectory object.

Raises:
OSError: if the directory already exists.


def get_momentum_variable(self):
    optimizer = self.get_optimizer()
    if hasattr(optimizer, 'rho'):
        return optimizer.rho
    elif hasattr(optimizer, 'beta_1'):
        return optimizer.beta_1
    return None

Extract values of momentum variables from optimizer

Returns:
optimizer's `rho` or `beta_1`


def __getitem__(self, key: Union[int, slice, str, utils.KeyPath, 'DecisionPoint']) -> Union[None, 'DNA', List[Optional['DNA']]]:
    if isinstance(key, (int, slice)):
        return self.children[key]
    if isinstance(key, DNASpec):
        key = key.id
        return self._decision_by_id[key]
    else:
        v = self.named_decisions.get(key, None)
        if v is None:
            v = self._decision_by_id[key]
        return v

Get an immediate child DNA or DNA in the sub-tree.

Args:
key: The key for retrieving the sub-DNA or sub-DNA list. The key should
be one of:
1) An integer as the index of an immediate child DNA.
2) A name (string) for named decisions whose DNASpec has a not-None
`name` argument.
3) An ID (string or KeyPath) for the decision point to retrieve.
See `DNASpec.id` for details.
4) A DecisionPoint object whose decision value will be retrived.

Returns:
The return value should be one of the following:
1) A DNA object if the key only maps to a single DNA object.
2) None if the decision point exists but it's inactive.
3) A list of DNA or None if there are multiple decision points associated
with the key.


def _ExtractOAuth2Client(product_yaml_key, product_data, proxy_config):
    oauth2_kwargs = {'proxy_config': proxy_config}
    if all(((config in product_data) for config in _OAUTH2_INSTALLED_APP_KEYS)):
        oauth2_args = [product_data['client_id'], product_data['client_secret'], product_data['refresh_token']]
        oauth2_client = googleads.oauth2.GoogleRefreshTokenClient
        for key in _OAUTH2_INSTALLED_APP_KEYS:
            del product_data[key]
    elif all(((config in product_data) for config in _OAUTH2_SERVICE_ACCT_KEYS)):
        oauth2_args = [product_data['path_to_private_key_file'], googleads.oauth2.GetAPIScope(product_yaml_key)]
        oauth2_kwargs.update({'sub': product_data.get('delegated_account')})
        oauth2_client = googleads.oauth2.GoogleServiceAccountClient
        for key in _OAUTH2_SERVICE_ACCT_KEYS:
            del product_data[key]
        for optional_key in _OAUTH2_SERVICE_ACCT_KEYS_OPTIONAL:
            if (optional_key in product_data):
                del product_data[optional_key]
    else:
        raise googleads.errors.GoogleAdsValueError(('Your yaml file is incorrectly configured for OAuth2. You need to specify credentials for either the installed application flow (%s) or service account flow (%s).' % (_OAUTH2_INSTALLED_APP_KEYS, _OAUTH2_SERVICE_ACCT_KEYS)))
    return oauth2_client(*oauth2_args, **oauth2_kwargs)

Generates an GoogleOAuth2Client subclass using the given product_data.

Args:
product_yaml_key: a string key identifying the product being configured.
product_data: a dict containing the configurations for a given product.
proxy_config: a ProxyConfig instance.

Returns:
An instantiated GoogleOAuth2Client subclass.

Raises:
A GoogleAdsValueError if the OAuth2 configuration for the given product is
misconfigured.


def mme_nodes(mme_base_url, token):
    nodes = []
    if ((not mme_base_url) or (not token)):
        return nodes
    url = ''.join([mme_base_url, '/nodes'])
    nodes = matchmaker_request(url=url, token=token, method='GET')
    LOG.info('Matchmaker has the following connected nodes:{}'.format(nodes))
    return nodes

Return the available MatchMaker nodes

Args:
mme_base_url(str): base URL of MME service
token(str): MME server authorization token

Returns:
nodes(list): a list of node disctionaries


def validate_allowed_values(allowed_values, value):

    if not allowed_values or isinstance(value, CFNParameter):
        return True

    return value in allowed_values

Support a variable defining which values it allows.

Args:
allowed_values (Optional[list]): A list of allowed values from the
variable definition
value (obj): The object representing the value provided for the
variable

Returns:
bool: Boolean for whether or not the value is valid.


async def on_message(message):

    server = message.server
    author = message.author
    channel = message.channel
    content = message.content

    data = datatools.get_data()

    if not data["discord"]["servers"][server.id][_data.modulename]["activated"]:
        return

    if server is not None and author != channel.server.me:

        prefix = data["discord"]["servers"][server.id]["prefix"]
        if content.startswith(prefix):

            package = content.split(" ")
            command = package[0][len(prefix):]
            args = package[1:]
            arg = ' '.join(args)

            if server.id not in _data.cache or _data.cache[server.id].state == 'destroyed':
                _data.cache[server.id] = _musicplayer.MusicPlayer(server.id)

            if command in ['play', 'playnext', 'playnow', 'playshuffle', 'insert',
                           'pause', 'resume', 'skip', 'remove',
                           'rewind', 'restart', 'shuffle', 'volume',
                           'stop', 'destroy', 'front', 'movehere',
                           'settopic', 'cleartopic', 'notopic', 'loop']:
                try:
                    await client.delete_message(message)
                except discord.errors.NotFound:
                    logger.warning("Could not delete music player command message - NotFound")
                except discord.errors.Forbidden:
                    logger.warning("Could not delete music player command message - Forbidden")

            if command == 'play':
                await _data.cache[server.id].play(author, channel, arg)

            if command == 'playnext':
                await _data.cache[server.id].play(author, channel, arg, index=1)

            if command == 'playnow':
                await _data.cache[server.id].play(author, channel, arg, index=1, stop_current=True)

            if command == 'playshuffle':
                await _data.cache[server.id].play(author, channel, arg, shuffle=True)

            if command == 'insert':
                if len(args) >= 2:
                    index = args[0]
                    query = ' '.join(args[1:])
                    await _data.cache[server.id].play(author, channel, query, index=index)
                else:
                    await _data.cache[server.id].play(author, channel, arg)

            elif command == 'pause':
                await _data.cache[server.id].pause()

            elif command == 'resume':
                await _data.cache[server.id].resume()

            elif command == 'skip':
                await _data.cache[server.id].skip(query=arg)

            elif command == 'remove':
                await _data.cache[server.id].remove(index=arg)

            elif command == 'rewind':
                await _data.cache[server.id].rewind(query=arg)

            elif command == 'restart':
                await _data.cache[server.id].rewind(query="0")

            elif command == 'shuffle':
                await _data.cache[server.id].shuffle()

            elif command == 'loop':
                await _data.cache[server.id].set_loop(arg)

            elif command == 'stop':
                await _data.cache[server.id].stop(log_stop=True)

            elif command == 'volume':
                await _data.cache[server.id].setvolume(arg)

            elif command == 'settopic':
                await _data.cache[server.id].set_topic_channel(channel)

            elif command == 'cleartopic' or command == 'notopic':
                await _data.cache[server.id].clear_topic_channel(channel)

            elif command == 'nowplaying':
                await _data.cache[server.id].nowplaying_info(channel)

            elif command == 'destroy':
                await _data.cache[server.id].destroy()

            elif command == 'front' or command == 'movehere':
                await _data.cache[server.id].movehere(channel)

The on_message event handler for this module

Args:
message (discord.Message): Input message


def jacobian(output, inputs, use_pfor=True, parallel_iterations=None):
    flat_inputs = nest.flatten(inputs)
    output_tensor_shape = output.shape
    output_shape = array_ops.shape(output)
    output = array_ops.reshape(output, [-1])

    def loop_fn(i):
        y = array_ops.gather(output, i)
        return gradient_ops.gradients(y, flat_inputs)
    try:
        output_size = int(output.shape[0])
    except TypeError:
        output_size = array_ops.shape(output)[0]
    if use_pfor:
        pfor_outputs = control_flow_ops.pfor(loop_fn, output_size, parallel_iterations=parallel_iterations)
    else:
        pfor_outputs = control_flow_ops.for_loop(loop_fn, [output.dtype] * len(flat_inputs), output_size, parallel_iterations=parallel_iterations)
    for i, out in enumerate(pfor_outputs):
        if isinstance(out, tensor.Tensor):
            new_shape = array_ops.concat([output_shape, array_ops.shape(out)[1:]], axis=0)
            out = array_ops.reshape(out, new_shape)
            out.set_shape(output_tensor_shape.concatenate(flat_inputs[i].shape))
            pfor_outputs[i] = out
    return nest.pack_sequence_as(inputs, pfor_outputs)

Computes jacobian of `output` w.r.t. `inputs`.

Args:
output: A tensor.
inputs: A tensor or a nested structure of tensor objects.
use_pfor: If true, uses pfor for computing the jacobian. Else uses
tf.while_loop.
parallel_iterations: A knob to control how many iterations and dispatched in
parallel. This knob can be used to control the total memory usage.

Returns:
A tensor or a nested structure of tensors with the same structure as
`inputs`. Each entry is the jacobian of `output` w.r.t. to the corresponding
value in `inputs`. If output has shape [y_1, ..., y_n] and inputs_i has
shape [x_1, ..., x_m], the corresponding jacobian has shape
[y_1, ..., y_n, x_1, ..., x_m]. Note that in cases where the gradient is
sparse (IndexedSlices), jacobian function currently makes it dense and
returns a Tensor instead. This may change in the future.


def set_dimension(tensor, axis, value):
    shape = tensor.shape.as_list()
    if (shape[axis] not in (value, None)):
        message = 'Cannot set dimension {} of tensor {} to {}; is already {}.'
        raise ValueError(message.format(axis, tensor.name, value, shape[axis]))
    shape[axis] = value
    tensor.set_shape(shape)

Set the length of a tensor along the specified dimension.

Args:
tensor: Tensor to define shape of.
axis: Dimension to set the static shape for.
value: Integer holding the length.

Raises:
ValueError: When the tensor already has a different length specified.


def money(s, thousand_sep=".", decimal_sep=","):

        s = s.replace(thousand_sep, "")
        s = s.replace(decimal_sep, ".")
        return Decimal(s)

Converts money amount in string to a Decimal object.

With the default arguments, the format is expected to be
``-38.500,00``, where dots separate thousands and comma the decimals.

Args:
thousand_sep: Separator for thousands.
decimal_sep: Separator for decimals.

Returns:
A ``Decimal`` object of the string encoded money amount.


def add_real_directory(self, source_path, read_only=True, lazy_read=True, target_path=None):
    source_path = self._path_without_trailing_separators(source_path)
    if (not os.path.exists(source_path)):
        self.raise_io_error(errno.ENOENT, source_path)
    target_path = (target_path or source_path)
    if lazy_read:
        parent_path = os.path.split(target_path)[0]
        if self.exists(parent_path):
            parent_dir = self.get_object(parent_path)
        else:
            parent_dir = self.create_dir(parent_path)
        new_dir = FakeDirectoryFromRealDirectory(source_path, self, read_only, target_path)
        parent_dir.add_entry(new_dir)
        self._last_ino += 1
        new_dir.st_ino = self._last_ino
    else:
        new_dir = self.create_dir(target_path)
        for (base, _, files) in os.walk(source_path):
            new_base = os.path.join(new_dir.path, os.path.relpath(base, source_path))
            for fileEntry in files:
                self.add_real_file(os.path.join(base, fileEntry), read_only, os.path.join(new_base, fileEntry))
    return new_dir

Create a fake directory corresponding to the real directory at the
specified path.  Add entries in the fake directory corresponding to
the entries in the real directory.

Args:
source_path: The path to the existing directory.
read_only: If set, all files under the directory are treated as
read-only, e.g. a write access raises an exception;
otherwise, writing to the files changes the fake files only
as usually.
lazy_read: If set (default), directory contents are only read when
accessed, and only until the needed subdirectory level.

.. note:: This means that the file system size is only updated
at the time the directory contents are read; set this to
`False` only if you are dependent on accurate file system
size in your test
target_path: If given, the target directory, otherwise,
the target directory is the same as `source_path`.

Returns:
the newly created FakeDirectory object.

Raises:
OSError: if the directory does not exist in the real file system.
IOError: if the directory already exists in the fake file system.


def is_diagonal_scale(scale):
    if (not isinstance(scale, tf.linalg.LinearOperator)):
        raise TypeError(("Expected argument 'scale' to be instance of LinearOperator. Found: %s" % scale))
    return (isinstance(scale, tf.linalg.LinearOperatorIdentity) or isinstance(scale, tf.linalg.LinearOperatorScaledIdentity) or isinstance(scale, tf.linalg.LinearOperatorDiag))

Returns `True` if `scale` is a `LinearOperator` that is known to be diag.

Args:
scale:  `LinearOperator` instance.

Returns:
Python `bool`.

Raises:
TypeError:  If `scale` is not a `LinearOperator`.


def _slot_dict(self, slot_name):
    named_slots = self._slots.get(slot_name, None)
    if named_slots is None:
        named_slots = {}
        self._slots[slot_name] = named_slots
    return named_slots

Returns a dict for caching slots created under the given name.

Args:
slot_name: Name for the slot.

Returns:
A dict that maps primary `Variable` objects to the slot created
for that variable, under the given slot name.


def get_cohp_by_label(self, label):

        if label.lower() == "average":
            return Cohp(efermi=self.efermi, energies=self.energies,
                        cohp=self.cohp, are_coops=self.are_coops, icohp=self.icohp)
        else:
            try:
                return Cohp(efermi=self.efermi, energies=self.energies,
                            cohp=self.all_cohps[label].get_cohp(spin=None, integrated=False),
                            are_coops=self.are_coops,
                            icohp=self.all_cohps[label].get_icohp(spin=None))

            except KeyError:
                print("The label does not exist")

Get specific COHP object.

Args:
label: string (for newer Lobster versions: a number)

Returns:
Returns the COHP object to simplify plotting


def getWhoisInfo(domain):

    new = []

    try:
        emails = {}
        emails["type"] = "i3visio.alias"
        emails["value"] = str(domain.split(".")[0])
        emails["attributes"] = []
        new.append(emails)
    except:
        pass

    info = whois.whois(domain)

    if info.status == None:
        raise Exception("UnknownDomainError: " + domain + " could not be resolved.")

    try:
        emails = {}
        emails["type"] = "i3visio.email"
        if type(info.emails) is not list:
            aux = [info.emails]
            emails["value"] = json.dumps(aux)
        else:
            emails["value"] = json.dumps(info.emails)
        emails["attributes"] = []
        new.append(emails)
    except:
        pass

    try:
        tmp = {}
        tmp["type"] = "i3visio.location.country"
        tmp["value"] = str(info.country)
        tmp["attributes"] = []
        new.append(tmp)
    except:
        pass

    try:
        tmp = {}
        tmp["type"] = "i3visio.registrar"
        tmp["value"] = str(info.registrar)
        tmp["attributes"] = []
        new.append(tmp)
    except:
        pass

    try:
        tmp = {}
        tmp["type"] = "i3visio.fullname"
        try:
            tmp["value"] = str(info.name)
        except:
            tmp["value"] = info.name
        tmp["attributes"] = []
        new.append(tmp)
    except:
        pass

    return new

Method that trie to recover the whois info from a domain.

Args:
-----
domain: The domain to verify.

Returns:
--------
dict: A dictionary containing the result as an i3visio entity with its
`value`, `type` and `attributes`.


def read(self, vals):

        i = 0
        count = int(vals[i])
        i += 1
        for _ in range(count):
            obj = GroundTemperature()
            obj.read(vals[i:i + obj.field_count])
            self.add_ground_temperature(obj)
            i += obj.field_count

Read values.

Args:
vals (list): list of strings representing values


def get_keyvault(access_token, subscription_id, rgname, vault_name):
    endpoint = ''.join([get_rm_endpoint(), '/subscriptions/', subscription_id, '/resourcegroups/', rgname, '/providers/Microsoft.KeyVault/vaults/', vault_name, '?api-version=', KEYVAULT_API])
    return do_get(endpoint, access_token)

Gets details about the named key vault.

Args:
access_token (str): A valid Azure authentication token.
subscription_id (str): Azure subscription id.
rgname (str): Azure resource group name.
vault_name (str): Name of the key vault.

Returns:
HTTP response. JSON body of key vault properties.


def find_in_coord_list(coord_list, coord, atol=1e-8):

    if len(coord_list) == 0:
        return []
    diff = np.array(coord_list) - np.array(coord)[None, :]
    return np.where(np.all(np.abs(diff) < atol, axis=1))[0]

Find the indices of matches of a particular coord in a coord_list.

Args:
coord_list: List of coords to test
coord: Specific coordinates
atol: Absolute tolerance. Defaults to 1e-8. Accepts both scalar and
array.

Returns:
Indices of matches, e.g., [0, 1, 2, 3]. Empty list if not found.


def _as_graph_element(obj):
    conv_fn = getattr(obj, '_as_graph_element', None)
    if conv_fn and callable(conv_fn):
        return conv_fn()
    return None

Convert `obj` to a graph element if possible, otherwise return `None`.

Args:
obj: Object to convert.

Returns:
The result of `obj._as_graph_element()` if that method is available;
otherwise `None`.


def _open_debug_interface(self, conn_id, callback, connection_string=None):
    self._try_connect(connection_string)
    callback(conn_id, self.id, True, None)

Enable debug interface for this IOTile device

Args:
conn_id (int): the unique identifier for the connection
callback (callback): Callback to be called when this command finishes
callback(conn_id, adapter_id, success, failure_reason)


def read_hdf(cls, path, key=None):
    df = pd.read_hdf(path, key)
    df['scored_calls'] = df['scored_calls'].apply((lambda x: json.loads(x)))
    df['channel_values'] = df['channel_values'].apply((lambda x: json.loads(x)))
    df['regions'] = df['regions'].apply((lambda x: json.loads(x)))
    df['phenotype_calls'] = df['phenotype_calls'].apply((lambda x: json.loads(x)))
    df['neighbors'] = df['neighbors'].apply((lambda x: json.loads(x)))
    df['neighbors'] = df['neighbors'].apply((lambda x: (np.nan if (not isinstance(x, dict)) else dict(zip([int(y) for y in x.keys()], x.values())))))
    df['frame_shape'] = df['frame_shape'].apply((lambda x: tuple(json.loads(x))))
    df = cls(df)
    f = h5py.File(path, 'r')
    mpp = f[key].attrs['microns_per_pixel']
    if (not np.isnan(mpp)):
        df.microns_per_pixel = mpp
    f.close()
    return df

Read a CellDataFrame from an hdf5 file.

Args:
path (str): the path to read from
key (str): the name of the location to read from

Returns:
CellDataFrame


def select_executor(elem, doc):

    executor = EXECUTORS['default']

    if 'cmd' in elem.attributes.keys():
        executor = elem.attributes['cmd']
    elif 'runas' in elem.attributes.keys():
        executor = EXECUTORS[elem.attributes['runas']]
    elif elem.classes[0] != 'exec':
        executor = EXECUTORS[elem.classes[0]]

    return executor

Determines the executor for the code in `elem.text`.

The elem attributes and classes select the executor in this order (highest
to lowest):
- custom commands (cmd=...)
- runas (runas=...) takes a key for the executors
- first element class (.class) determines language and thus executor

Args:
elem The AST element.
doc  The document.

Returns:
The command to execute code.


async def init(self, *, advertise_addr: str=None, listen_addr: str='0.0.0.0:2377', force_new_cluster: bool=False, swarm_spec: Mapping=None) -> str:
    data = {'AdvertiseAddr': advertise_addr, 'ListenAddr': listen_addr, 'ForceNewCluster': force_new_cluster, 'Spec': swarm_spec}
    response = (await self.docker._query_json('swarm/init', method='POST', data=data))
    return response

Initialize a new swarm.

Args:
ListenAddr: listen address used for inter-manager communication
AdvertiseAddr: address advertised to other nodes.
ForceNewCluster: Force creation of a new swarm.
SwarmSpec: User modifiable swarm configuration.

Returns:
id of the swarm node


def Remove(self, row):
    if ((row == 0) or (row > self.size)):
        raise TableError('Attempt to remove header row')
    new_table = []
    for t_row in self._table:
        if (t_row.row != row):
            new_table.append(t_row)
            if (t_row.row > row):
                t_row.row -= 1
    self._table = new_table

Removes a row from the table.

Args:
row: int, the row number to delete. Must be >= 1, as the header
cannot be removed.

Raises:
TableError: Attempt to remove nonexistent or header row.


def delete_url(self, url, token=''):

        if (token == ''):
            token = self._user_token

        return requests.delete(url,
                               headers={
                                   'Authorization': 'Token {}'.format(token)},
                               verify=False,)

Returns a delete resquest object taking in a url and user token.

Arguments:
url (str): The url to make post to
token (str): The authentication token

Returns:
obj: Delete request object


def plot_state_paulivec(rho, title='', figsize=None, color=None):
    if (not HAS_MATPLOTLIB):
        raise ImportError('Must have Matplotlib installed.')
    rho = _validate_input_state(rho)
    if (figsize is None):
        figsize = (7, 5)
    num = int(np.log2(len(rho)))
    labels = list(map((lambda x: x.to_label()), pauli_group(num)))
    values = list(map((lambda x: np.real(np.trace(np.dot(x.to_matrix(), rho)))), pauli_group(num)))
    numelem = len(values)
    if (color is None):
        color = '
    ind = np.arange(numelem)
    width = 0.5
    (fig, ax) = plt.subplots(figsize=figsize)
    ax.grid(zorder=0, linewidth=1, linestyle='--')
    ax.bar(ind, values, width, color=color, zorder=2)
    ax.axhline(linewidth=1, color='k')
    ax.set_ylabel('Expectation value', fontsize=14)
    ax.set_xticks(ind)
    ax.set_yticks([(- 1), (- 0.5), 0, 0.5, 1])
    ax.set_xticklabels(labels, fontsize=14, rotation=70)
    ax.set_xlabel('Pauli', fontsize=14)
    ax.set_ylim([(- 1), 1])
    ax.set_facecolor('
    for tick in (ax.xaxis.get_major_ticks() + ax.yaxis.get_major_ticks()):
        tick.label.set_fontsize(14)
    ax.set_title(title, fontsize=16)
    plt.close(fig)
    return fig

Plot the paulivec representation of a quantum state.

Plot a bargraph of the mixed state rho over the pauli matrices

Args:
rho (ndarray): Numpy array for state vector or density matrix
title (str): a string that represents the plot title
figsize (tuple): Figure size in inches.
color (list or str): Color of the expectation value bars.
Returns:
matplotlib.Figure: The matplotlib.Figure of the visualization
Raises:
ImportError: Requires matplotlib.


def _unique_parameters(self) -> 'list[cfg.Variable]':
    return []

Get unique parameter subtypes as variables.

This will retrieve 'children' of this value that contribute to the
type of it. So it will retrieve type parameters, but not attributes. To
keep the number of possible combinations reasonable, when we encounter
multiple instances of the same type, we include only one.

Returns:
A list of variables.


def metric(self, name, description, data_type, interval, keyed=False):
    from .tcex_metrics_v2 import TcExMetricsV2
    return TcExMetricsV2(self, name, description, data_type, interval, keyed)

Get instance of the Metrics module.

Args:
name (string): The name for the metric.
description (string): The description of the metric.
data_type (string): The type of metric: Sum, Count, Min, Max, First, Last, and Average.
interval (string): The metric interval: Hourly, Daily, Weekly, Monthly, and Yearly.
keyed (boolean): Indicates whether the data will have a keyed value.

Returns:
(object): An instance of the Metrics Class.


class FlaxBeamSearchOutput(ModelOutput):
    sequences: Optional[jnp.ndarray] = None
    scores: Optional[jnp.ndarray] = None

Flax Base class for outputs of decoder-only generation models using greedy search.

Args:
sequences (`jnp.ndarray` of shape `(batch_size, max_length)`):
The generated sequences.
scores (`jnp.ndarray` of shape `(batch_size,)`):
The scores (log probabilities) of the generated sequences.


def _dict_to_tensor(self, x, k1, k2):
    return array_ops_stack.stack([array_ops_stack.stack([x[i, j] for j in range(k2)]) for i in range(k1)])

Convert a dictionary to a tensor.

Args:
x: A k1 * k2 dictionary.
k1: First dimension of x.
k2: Second dimension of x.

Returns:
A k1 * k2 tensor.


def urlretrieve(url, filename, reporthook=None, data=None):

    def chunk_read(response, chunk_size=8192, reporthook=None):
        content_type = response.info().get('Content-Length')
        total_size = -1
        if content_type is not None:
            total_size = int(content_type.strip())
        count = 0
        while True:
            chunk = response.read(chunk_size)
            count += 1
            if reporthook is not None:
                reporthook(count, chunk_size, total_size)
            if chunk:
                yield chunk
            else:
                break
    response = urlopen(url, data)
    with open(filename, 'wb') as fd:
        for chunk in chunk_read(response, reporthook=reporthook):
            fd.write(chunk)

Replacement for `urlretrieve` for Python 2.

Under Python 2, `urlretrieve` relies on `FancyURLopener` from legacy
`urllib` module, known to have issues with proxy management.

Args:
url: url to retrieve.
filename: where to store the retrieved data locally.
reporthook: a hook function that will be called once on establishment of
the network connection and once after each block read thereafter. The
hook will be passed three arguments; a count of blocks transferred so
far, a block size in bytes, and the total size of the file.
data: `data` argument passed to `urlopen`.


def by_type(blocks, slist=None):
    layout = []
    data = []
    int_vol = []
    unknown = []
    for i in blocks:
        if (slist and (i not in slist)):
            continue
        if (blocks[i].is_vtbl and blocks[i].is_valid):
            layout.append(i)
        elif (blocks[i].is_internal_vol and blocks[i].is_valid):
            int_vol.append(i)
        elif blocks[i].is_valid:
            data.append(i)
        else:
            unknown.append(i)
    return (layout, data, int_vol, unknown)

Sort blocks into layout, internal volume, data or unknown

Arguments:
Obj:blocks   -- List of block objects.
List:slist   -- (optional) List of block indexes.

Returns:
List:layout  -- List of block indexes of blocks containing the
volume table records.
List:data    -- List of block indexes containing filesystem data.
List:int_vol -- List of block indexes  containing volume ids
greater than UBI_INTERNAL_VOL_START that are not
layout volumes.
List:unknown -- List of block indexes of blocks that failed validation
of crc in ed_hdr or vid_hdr.


def plot_seebeck_mu(self, temp=600, output='eig', xlim=None):

        import matplotlib.pyplot as plt
        plt.figure(figsize=(9, 7))
        seebeck = self._bz.get_seebeck(output=output, doping_levels=False)[
            temp]
        plt.plot(self._bz.mu_steps, seebeck,
                 linewidth=3.0)

        self._plot_bg_limits()
        self._plot_doping(temp)
        if output == 'eig':
            plt.legend(['S$_1$', 'S$_2$', 'S$_3$'])
        if xlim is None:
            plt.xlim(-0.5, self._bz.gap + 0.5)
        else:
            plt.xlim(xlim[0], xlim[1])
        plt.ylabel("Seebeck \n coefficient  ($\\mu$V/K)", fontsize=30.0)
        plt.xlabel("E-E$_f$ (eV)", fontsize=30)
        plt.xticks(fontsize=25)
        plt.yticks(fontsize=25)
        plt.tight_layout()
        return plt

Plot the seebeck coefficient in function of Fermi level

Args:
temp:
the temperature
xlim:
a list of min and max fermi energy by default (0, and band gap)
Returns:
a matplotlib object


def are_symmetrically_related(self, point_a, point_b, tol=0.001):
    if np.allclose(self.operate(point_a), point_b, atol=tol):
        return True
    if np.allclose(self.operate(point_b), point_a, atol=tol):
        return True
    return False

Checks if two points are symmetrically related.

Args:
point_a (3x1 array): First point.
point_b (3x1 array): Second point.
tol (float): Absolute tolerance for checking distance.

Returns:
True if self.operate(point_a) == point_b or vice versa.


def Write(self, string):

    if sys.version_info[0] < 3:
      super(StdoutOutputWriter, self).Write(string)
    else:

      sys.stdout.write(string)

Writes a string to the output.

Args:
string (str): output.


def unique(ar):
    r

    import dask.array as da

    if isinstance(ar, da.core.Array):
        return da.unique(ar)

    return _unique(ar)

r"""Find the unique elements of an array.

It uses ``dask.array.unique`` if necessary.

Args:
ar (array_like): Input array.

Returns:
array_like: the sorted unique elements.


def _RemoveDefaultAttrs(producer_op_list, graph_def):
    producer_op_dict = {op.name: op for op in producer_op_list.op}
    for node in graph_def.node:
        if node.op in producer_op_dict:
            op_def = op_def_registry.get(node.op)
            if op_def is None:
                continue
            producer_op_def = producer_op_dict[node.op]
            for key in list(node.attr):
                if _FindAttrInOpDef(key, op_def) is None:
                    attr_def = _FindAttrInOpDef(key, producer_op_def)
                    if attr_def and attr_def.HasField('default_value') and (node.attr[key] == attr_def.default_value):
                        del node.attr[key]

Removes unknown default attrs according to `producer_op_list`.

Removes any unknown attrs in `graph_def` (i.e. attrs that do not appear in
registered OpDefs) that have a default value in `producer_op_list`.

Args:
producer_op_list: OpList proto.
graph_def: GraphDef proto


def SetHasherNames(self, hasher_names_string):
    hasher_names = hashers_manager.HashersManager.GetHasherNamesFromString(hasher_names_string)
    debug_hasher_names = ', '.join(hasher_names)
    logger.debug('Got hasher names: {0:s}'.format(debug_hasher_names))
    self._hashers = hashers_manager.HashersManager.GetHashers(hasher_names)
    self._hasher_names_string = hasher_names_string

Sets the hashers that should be enabled.

Args:
hasher_names_string (str): comma separated names of hashers to enable.


def _set_auditpol_data(option, value):
    auditpol_values = {'None': 'No Auditing', '0': 'No Auditing', '1': 'Success', '2': 'Failure', '3': 'Success and Failure'}
    defaults = _get_audit_defaults(option)
    return __utils__['auditpol.set_setting'](name=defaults['Auditpol Name'], value=auditpol_values[value])

Helper function that updates the current applied settings to match what has
just been set in the audit.csv files. We're doing it this way instead of
running `gpupdate`

Args:
option (str): The name of the option to set
value (str): The value to set. ['None', '0', '1', '2', '3']

Returns:
bool: ``True`` if successful, otherwise ``False``


def prepare_xml_read(data, objectify=False):
    mod = (_objectify if objectify else etree)
    if hasattr(data, 'readlines'):
        data = mod.parse(data).getroot()
    elif isinstance(data, list):
        data = mod.fromstring(''.join(data))
    elif isinstance(data, basestring):
        data = mod.parse(open(data)).getroot()
    else:
        raise TypeError(('Unable to handle data of type %r' % type(data)))
    return data

Prepare various input types for XML parsing.

Args:
data (iter): Data to read
objectify (bool): Parse using lxml's objectify data binding

Returns:
etree.ElementTree: Tree suitable for parsing

Raises:
TypeError: Invalid value for data


def _parse_single_video(self, example_proto):
    context_features = {'game_duration_loops': tf.io.FixedLenFeature([1], tf.int64), 'game_duration_seconds': tf.io.FixedLenFeature([1], tf.float32), 'n_steps': tf.io.FixedLenFeature([1], tf.int64), 'screen_size': tf.io.FixedLenFeature([2], tf.int64)}
    sequence_features = {'rgb_screen': tf.io.FixedLenSequenceFeature([], tf.string)}
    (_, seq_feat) = tf.io.parse_single_sequence_example(example_proto, context_features=context_features, sequence_features=sequence_features)
    video_frames = tf.map_fn(tf.image.decode_png, seq_feat['rgb_screen'], dtype=tf.uint8)
    return video_frames

Parses single video from the input tfrecords.

Args:
example_proto: tfExample proto with a single video.

Returns:
dict with all frames, positions and actions.


def on_snapshot(self, proto):

        TargetChange = firestore_pb2.TargetChange

        target_changetype_dispatch = {
            TargetChange.NO_CHANGE: self._on_snapshot_target_change_no_change,
            TargetChange.ADD: self._on_snapshot_target_change_add,
            TargetChange.REMOVE: self._on_snapshot_target_change_remove,
            TargetChange.RESET: self._on_snapshot_target_change_reset,
            TargetChange.CURRENT: self._on_snapshot_target_change_current,
        }

        target_change = proto.target_change
        if str(target_change):
            target_change_type = target_change.target_change_type
            _LOGGER.debug("on_snapshot: target change: " + str(target_change_type))
            meth = target_changetype_dispatch.get(target_change_type)
            if meth is None:
                _LOGGER.info(
                    "on_snapshot: Unknown target change " + str(target_change_type)
                )
                self.close(
                    reason="Unknown target change type: %s " % str(target_change_type)
                )
            else:
                try:
                    meth(proto)
                except Exception as exc2:
                    _LOGGER.debug("meth(proto) exc: " + str(exc2))
                    raise

        elif str(proto.document_change):
            _LOGGER.debug("on_snapshot: document change")

            target_ids = proto.document_change.target_ids or []
            removed_target_ids = proto.document_change.removed_target_ids or []
            changed = False
            removed = False

            if WATCH_TARGET_ID in target_ids:
                changed = True

            if WATCH_TARGET_ID in removed_target_ids:
                removed = True

            if changed:
                _LOGGER.debug("on_snapshot: document change: CHANGED")

                document_change = proto.document_change

                document = document_change.document

                data = _helpers.decode_dict(document.fields, self._firestore)

                document_name = document.name
                db_str = self._firestore._database_string
                db_str_documents = db_str + "/documents/"
                if document_name.startswith(db_str_documents):
                    document_name = document_name[len(db_str_documents) :]

                document_ref = self._firestore.document(document_name)

                snapshot = self.DocumentSnapshot(
                    reference=document_ref,
                    data=data,
                    exists=True,
                    read_time=None,
                    create_time=document.create_time,
                    update_time=document.update_time,
                )
                self.change_map[document.name] = snapshot

            elif removed:
                _LOGGER.debug("on_snapshot: document change: REMOVED")
                document = proto.document_change.document
                self.change_map[document.name] = ChangeType.REMOVED

        elif str(proto.document_delete):
            _LOGGER.debug("on_snapshot: document change: DELETE")
            name = proto.document_delete.document
            self.change_map[name] = ChangeType.REMOVED

        elif str(proto.document_remove):
            _LOGGER.debug("on_snapshot: document change: REMOVE")
            name = proto.document_remove.document
            self.change_map[name] = ChangeType.REMOVED

        elif proto.filter:
            _LOGGER.debug("on_snapshot: filter update")
            if proto.filter.count != self._current_size():

                self._reset_docs()

        else:
            _LOGGER.debug("UNKNOWN TYPE. UHOH")
            self.close(reason=ValueError("Unknown listen response type: %s" % proto))

Called everytime there is a response from listen. Collect changes
and 'push' the changes in a batch to the customer when we receive
'current' from the listen response.

Args:
listen_response(`google.cloud.firestore_v1beta1.types.ListenResponse`):
Callback method that receives a object to


def get_tick(self, index):

        name = self.tick_name(index)
        if name is None:
            return [pack_error(ControllerSubsystem.SENSOR_GRAPH, Error.INVALID_ARRAY_KEY), 0]

        return [Error.NO_ERROR, self.ticks[name]]

Get a tick's interval.

Args:
index (int): The index of the tick that you want to fetch.

Returns:
int, int: Error code and The tick's interval in seconds.

A value of 0 means that the tick is disabled.


def data_in_db(db_data, user_data):
    if isinstance(user_data, list):
        if (db_data in user_data):
            return True
    return False

Validate db data in user data.

Args:
db_data (str): The data store in Redis.
user_data (list): The user provided data.

Returns:
bool: True if the data passed validation.


def add_timestamps(with_ms: bool=False, substream_name: str | None=None) -> processor.Processor:
    if substream_name is None:
        substream_name = ''
    return processor.processor_function(functools.partial(_add_timestamps, with_ms=with_ms, substream_name=substream_name))

Adds timestamps to image chunks.

By default the timestamps are added with the format `mm:ss` where
`mm` is the number of minutes, `ss` is the number of seconds.

Args:
with_ms: Whether to add milliseconds to the timestamp. When `True`, the
timestamp is added with the format `mm:ss.SSS` where `SSS` is the number
of milliseconds.
substream_name: The substream name to use for the timestamps.

Returns:
A processor that adds timestamps after each image chunk.


def set(config, section, opt, value):

        if section not in config.keys():
            config[section] = {}

        config[section][opt] = value

Sets specified option in the config.

Args:
config (configobj.ConfigObj): config to work on.
section (str): section name.
opt (str): option name.
value: value to set option to.


def override(state, solution):
    old_ast = state.solution_ast
    new_ast = ast.parse(solution)
    if ((not isinstance(old_ast, ast.Module)) and (len(new_ast.body) == 1)):
        expr = new_ast.body[0]
        candidates = ([expr, expr.value] if isinstance(expr, ast.Expr) else [expr])
        for node in candidates:
            if isinstance(node, old_ast.__class__):
                new_ast = node
                break
    kwargs = (state.messages[(- 1)] if state.messages else {})
    child = state.to_child(solution_ast=new_ast, student_ast=state.student_ast, highlight=state.highlight, append_message={'msg': '', 'kwargs': kwargs})
    return child

Override the solution code with something arbitrary.

There might be cases in which you want to temporarily override the solution code
so you can allow for alternative ways of solving an exercise.
When you use ``override()`` in an SCT chain, the remainder of that SCT chain will
run as if the solution code you specified is the only code that was in the solution.

Check the glossary for an example (pandas plotting)

Args:
solution: solution code as a string that overrides the original solution code.
state: State instance describing student and solution code. Can be omitted if used with Ex().


def get_pipeline_options(project: str, job_name: str, mode: str, num_workers: int=cfg.NUM_WORKERS, streaming: bool=True) -> PipelineOptions:
    job_name = f'{job_name}-{datetime.now().strftime('%Y%m%d%H%M%S')}'
    staging_bucket = f'gs:
    dataflow_options = {'runner': 'DirectRunner' if mode == 'local' else 'DataflowRunner', 'job_name': job_name, 'project': project, 'region': cfg.REGION, 'staging_location': f'{staging_bucket}/dflow-staging', 'temp_location': f'{staging_bucket}/dflow-temp', 'setup_file': './setup.py', 'streaming': streaming}
    if num_workers:
        dataflow_options.update({'num_workers': num_workers})
    return PipelineOptions(flags=[], **dataflow_options)

Function to retrieve the pipeline options.
Args:
project: GCP project to run on
mode: Indicator to run local, cloud or template
num_workers: Number of Workers for running the job parallely
max_num_workers: Maximum number of workers running the job parallely
Returns:
Dataflow pipeline options


def check_provider_healthcheck(settings, default_provider='Discovery'):
    ProviderHealthCheck = collections.namedtuple('ProviderHealthCheck', ['providers', 'has_healthcheck'])
    eureka_enabled = settings['app']['eureka_enabled']
    providers = settings['asg']['provider_healthcheck']
    LOG.debug('Template defined Health Check Providers: %s', providers)
    health_check_providers = []
    has_healthcheck = False
    normalized_default_provider = default_provider.capitalize()
    if eureka_enabled:
        LOG.info('Eureka enabled, enabling default Provider Health Check: %s', normalized_default_provider)
        for (provider, active) in providers.items():
            if (provider.lower() == normalized_default_provider.lower()):
                providers[provider] = True
                LOG.debug('Override defined Provider Health Check: %s -> %s', active, providers[provider])
                break
        else:
            LOG.debug('Adding default Provider Health Check: %s', normalized_default_provider)
            providers[normalized_default_provider] = True
    for (provider, active) in providers.items():
        if active:
            health_check_providers.append(provider.capitalize())
    LOG.info('Provider healthchecks: %s', health_check_providers)
    if health_check_providers:
        has_healthcheck = True
    return ProviderHealthCheck(providers=health_check_providers, has_healthcheck=has_healthcheck)

Set Provider Health Check when specified.

Returns:
collections.namedtuple: **ProviderHealthCheck** with attributes:

* providers (list): Providers set to use native Health Check.
* has_healthcheck (bool): If any native Health Checks requested.


def __init__(self, raise_warnings=False):

    self.raise_warnings = raise_warnings
    self.accumulator = SimpleProblemAccumulator()

Initialise.

Args:
raise_warnings: If this is True then warnings are also raised as
exceptions.
If it is false, warnings are printed to the console using
SimpleProblemAccumulator.


def get_group(self, group_id):

    group = self.group_id_map.get(group_id)

    if group:
      return group

    self.logger.error('Group ID "%s" is not in datafile.' % group_id)
    self.error_handler.handle_error(exceptions.InvalidGroupException(enums.Errors.INVALID_GROUP_ID_ERROR))
    return None

Get group for the provided group ID.

Args:
group_id: Group ID for which group is to be determined.

Returns:
Group corresponding to the provided group ID.


def ParseFileEntry(self, parser_mediator, file_entry):

    stat_object = file_entry.GetStat()
    if not stat_object:
      return

    file_system_type = self._GetFileSystemTypeFromFileEntry(file_entry)

    event_data = FileStatEventData()
    event_data.file_entry_type = stat_object.type
    event_data.file_size = getattr(stat_object, 'size', None)
    event_data.file_system_type = file_system_type
    event_data.is_allocated = file_entry.IsAllocated()

    if file_entry.access_time:
      event = time_events.DateTimeValuesEvent(
          file_entry.access_time, definitions.TIME_DESCRIPTION_LAST_ACCESS)
      parser_mediator.ProduceEventWithEventData(event, event_data)

    if file_entry.creation_time:
      event = time_events.DateTimeValuesEvent(
          file_entry.creation_time, definitions.TIME_DESCRIPTION_CREATION)
      parser_mediator.ProduceEventWithEventData(event, event_data)

    if file_entry.change_time:
      event = time_events.DateTimeValuesEvent(
          file_entry.change_time, definitions.TIME_DESCRIPTION_CHANGE)
      parser_mediator.ProduceEventWithEventData(event, event_data)

    if file_entry.modification_time:
      event = time_events.DateTimeValuesEvent(
          file_entry.modification_time,
          definitions.TIME_DESCRIPTION_MODIFICATION)
      parser_mediator.ProduceEventWithEventData(event, event_data)

    for time_attribute, usage in self._TIMESTAMP_DESCRIPTIONS.items():
      posix_time = getattr(stat_object, time_attribute, None)
      if posix_time is None:
        continue

      nano_time_attribute = '{0:s}_nano'.format(time_attribute)
      nano_time_attribute = getattr(stat_object, nano_time_attribute, None)

      timestamp = posix_time * 1000000
      if nano_time_attribute is not None:

        micro_time_attribute, _ = divmod(nano_time_attribute, 10)
        timestamp += micro_time_attribute

      if (file_entry.type_indicator == dfvfs_definitions.TYPE_INDICATOR_TSK and
          not timestamp):
        continue

      date_time = dfdatetime_posix_time.PosixTimeInMicroseconds(
          timestamp=timestamp)
      event = time_events.DateTimeValuesEvent(date_time, usage)
      parser_mediator.ProduceEventWithEventData(event, event_data)

Parses a file entry.

Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
file_entry (dfvfs.FileEntry): a file entry.


def __verify_server_version(self):
    if (compare_versions('.'.join([_lib_major_version, _lib_minor_version]), self.product_version) > 0):
        logger.warning('Client version {} connecting to server with newer minor release {}.'.format(_lib_full_version, self.product_version))
    if (compare_versions(_lib_major_version, self.product_version) != 0):
        raise InvalidSwimlaneProductVersion(self, '{}.0'.format(_lib_major_version), '{}.0'.format(str((int(_lib_major_version) + 1))))

Verify connected to supported server product version

Notes:
Logs warning if connecting to a newer minor server version

Raises:
swimlane.exceptions.InvalidServerVersion: If server major version is higher than package major version


def cosmic_link(variant_obj):
    cosmic_ids = variant_obj.get('cosmic_ids')
    if (not cosmic_ids):
        return None
    else:
        cosmic_id = cosmic_ids[0]
        url_template = 'https:
    return url_template.format(cosmic_id)

Compose link to COSMIC Database.

Args:
variant_obj(scout.models.Variant)

Returns:
url_template(str): Link to COSMIIC database if cosmic id is present


def call_fn(fn: TransitionOperator, args: Union[(Tuple[Any], Any)]) -> Any:
    if (isinstance(args, (list, tuple)) and (not mcmc_util.is_namedtuple_like(args))):
        args = args
        return fn(*args)
    else:
        return fn(args)

Calls a transition operator with args, unpacking args if its a sequence.

Args:
fn: A `TransitionOperator`.
args: Arguments to `fn`

Returns:
ret: Return value of `fn`.


def get_counter(self, name, combine_fn):
    with self._lock:
        counter = self.counters.get(name, None)
        if counter:
            assert counter.combine_fn == combine_fn
        else:
            if isinstance(combine_fn, cy_combiners.AccumulatorCombineFn):
                counter = AccumulatorCombineFnCounter(name, combine_fn)
            else:
                counter = Counter(name, combine_fn)
            self.counters[name] = counter
        return counter

Returns a counter with the requested name.

Passing in the same name will return the same counter; the
combine_fn must agree.

Args:
name: the name of this counter.  Typically has three parts:
"step-output-counter".
combine_fn: the CombineFn to use for aggregation
Returns:
A new or existing counter with the requested name.


def _CreateEventTag(self, event, comment, labels):

    event_identifier = event.GetIdentifier()

    event_tag = events.EventTag(comment=comment)
    event_tag.SetEventIdentifier(event_identifier)
    event_tag.AddLabels(labels)

    event_identifier_string = event_identifier.CopyToString()
    logger.debug('Created event tag: {0:s} for event: {1:s}'.format(
        comment, event_identifier_string))

    return event_tag

Creates an event tag.

Args:
event (EventObject): event to tag.
comment (str): event tag comment.
labels (list[str]): event tag labels.

Returns:
EventTag: the event tag.


def create_token_type_ids_from_sequences(self, token_ids_0: List[int], token_ids_1: Optional[List[int]]=None) -> List[int]:
    sep = [self.sep_token_id]
    cls = [self.cls_token_id]
    if token_ids_1 is None:
        return len(cls + token_ids_0 + sep) * [0]
    return len(cls + token_ids_0 + sep + sep + token_ids_1 + sep) * [0]

Create a mask from the two sequences passed to be used in a sequence-pair classification task. PhoBERT does not
make use of token type ids, therefore a list of zeros is returned.

Args:
token_ids_0 (`List[int]`):
List of IDs.
token_ids_1 (`List[int]`, *optional*):
Optional second list of IDs for sequence pairs.

Returns:
`List[int]`: List of zeros.


def nr_cases(self, snv_cases=None, sv_cases=None):

        query = {}

        if snv_cases:
            query = {'vcf_path': {'$exists':True}}
        if sv_cases:
            query = {'vcf_sv_path': {'$exists':True}}
        if snv_cases and sv_cases:
            query = None

        return self.db.case.count_documents(query)

Return the number of cases in the database

Args:
snv_cases(bool): If only snv cases should be searched
sv_cases(bool): If only snv cases should be searched

Returns:
cases (Iterable(Case)): A iterable with mongo cases


async def _open_connection_http(self, location):

        sock = await connect_tcp(location[0], location[1], bind_host=self.source_address)
        sock._active = True
        return sock

Creates a normal async socket, returns it.
Args:
location (tuple(str, int)): A tuple of net location (eg
'127.0.0.1' or 'example.org') and port (eg 80 or 25000).


def importGurobiSolution(self, grbmodel):
    self.eval(''.join(('let {} := {};'.format(var.VarName, var.X) for var in grbmodel.getVars() if ('$' not in var.VarName))))

Import the solution from a gurobipy.Model object.

Args:
grbmodel: A :class:`gurobipy.Model` object with the model solved.


def get_use_xla_spmd(device_type):
    return device_type == 'TPU' and '0' != os.environ.get('DTENSOR_TEST_USE_XLA_SPMD', '0')

Returns True when device_type is TPU and environment variable is set.

Args:
device_type: A str representing the type of device on the mesh.

Returns:
bool: True when device_type is TPU and environment variable is set.


def __add__(self, other):

        if isinstance(other, FieldPath):
            parts = self.parts + other.parts
            return FieldPath(*parts)
        elif isinstance(other, six.string_types):
            parts = self.parts + FieldPath.from_string(other).parts
            return FieldPath(*parts)
        else:
            return NotImplemented

Adds `other` field path to end of this field path.

Args:
other (~google.cloud.firestore_v1beta1._helpers.FieldPath, str):
The field path to add to the end of this `FieldPath`.


def create_token_type_ids_from_sequences(self, token_ids_0: List[int], token_ids_1: Optional[List[int]]=None) -> List[int]:
    sep = [self.sep_token_id]
    if token_ids_1 is None:
        return len(sep + token_ids_0) * [0]
    return len(sep + token_ids_0 + sep + sep + token_ids_1) * [0]

Create a mask from the two sequences passed to be used in a sequence-pair classification task. XLM-RoBERTa does
not make use of token type ids, therefore a list of zeros is returned.

Args:
token_ids_0 (`List[int]`):
List of IDs.
token_ids_1 (`List[int]`, *optional*):
Optional second list of IDs for sequence pairs.

Returns:
`List[int]`: List of zeros.


def CheckAddressState(self, script_hash):
    for (key, contract) in self._contracts.items():
        if (contract.ScriptHash.ToBytes() == script_hash.ToBytes()):
            return AddressState.InWallet
    for watch in self._watch_only:
        if (watch == script_hash):
            return (AddressState.InWallet | AddressState.WatchOnly)
    return AddressState.NoState

Determine the address state of the provided script hash.

Args:
script_hash (UInt160): a script hash to determine the address state of.

Returns:
AddressState: the address state.


def mds(means, weights, d):
    X = dim_reduce(means, weights, d)
    if (X.shape[0] == 2):
        return X.dot(weights)
    else:
        return X.T.dot(weights)

Dimensionality reduction using MDS.

Args:
means (array): genes x clusters
weights (array): clusters x cells
d (int): desired dimensionality

Returns:
W_reduced (array): array of shape (d, cells)


def memory_write32(self, addr, data, zone=None):
    return self.memory_write(addr, data, zone, 32)

Writes words to memory of a target system.

Args:
self (JLink): the ``JLink`` instance
addr (int): start address to write to
data (list): list of words to write
zone (str): optional memory zone to access

Returns:
Number of words written to target.

Raises:
JLinkException: on memory access error.


def set_status(self, status, msg):
    if (len(msg) > 2000):
        msg = msg[:2000]
        msg += '\n... snip ...\n'
    if ((self.status == self.S_LOCKED) or (status == self.S_LOCKED)):
        err_msg = ('Locked files must be explicitly unlocked before calling set_status but\ntask.status = %s, input status = %s' % (self.status, status))
        raise RuntimeError(err_msg)
    status = Status.as_status(status)
    changed = True
    if hasattr(self, '_status'):
        changed = (status != self._status)
    self._status = status
    if (status == self.S_RUN):
        if (self.datetimes.start is None):
            self.datetimes.start = datetime.datetime.now()
    if changed:
        if (status == self.S_SUB):
            self.datetimes.submission = datetime.datetime.now()
            self.history.info(('Submitted with MPI=%s, Omp=%s, Memproc=%.1f [Gb] %s ' % (self.mpi_procs, self.omp_threads, self.mem_per_proc.to('Gb'), msg)))
        elif (status == self.S_OK):
            self.history.info('Task completed %s', msg)
        elif (status == self.S_ABICRITICAL):
            self.history.info('Status set to S_ABI_CRITICAL due to: %s', msg)
        else:
            self.history.info('Status changed to %s. msg: %s', status, msg)
    if (status == self.S_DONE):
        self._on_done()
    if (status == self.S_OK):
        if (not self.finalized):
            self._on_ok()
            if ((self.gc is not None) and (self.gc.policy == 'task')):
                self.clean_output_files()
        if (self.status == self.S_OK):
            self.send_signal(self.S_OK)
    return status

Set and return the status of the task.

Args:
status: Status object or string representation of the status
msg: string with human-readable message used in the case of errors.


def deploy_ray_func(func, partition, kwargs):

    try:
        return func(partition, **kwargs)

    except ValueError:
        return func(partition.copy(), **kwargs)

Deploy a function to a partition in Ray.

Note: Ray functions are not detected by codecov (thus pragma: no cover)

Args:
func: The function to apply.
partition: The partition to apply the function to.
kwargs: A dictionary of keyword arguments for the function.

Returns:
The result of the function.


def __send_ses_email(self, recipients, subject, body_html, body_text):
    source_arn = dbconfig.get('source_arn', NS_EMAIL)
    return_arn = dbconfig.get('return_path_arn', NS_EMAIL)
    session = get_local_aws_session()
    ses = session.client('ses', region_name=dbconfig.get('ses_region', NS_EMAIL, 'us-west-2'))
    body = {}
    if body_html:
        body['Html'] = {'Data': body_html}
    if body_text:
        body['Text'] = {'Data': body_text}
    ses_options = {'Source': self.sender, 'Destination': {'ToAddresses': recipients}, 'Message': {'Subject': {'Data': subject}, 'Body': body}}
    if (source_arn and return_arn):
        ses_options.update({'SourceArn': source_arn, 'ReturnPathArn': return_arn})
    ses.send_email(**ses_options)

Send an email using SES

Args:
recipients (`1ist` of `str`): List of recipient email addresses
subject (str): Subject of the email
body_html (str): HTML body of the email
body_text (str): Text body of the email

Returns:
`None`


def _create_events_writer(self, directory):
    total_size = 0
    events_files = self._fetch_events_files_on_disk()
    for file_name in events_files:
        file_path = os.path.join(self._events_directory, file_name)
        total_size += tf.io.gfile.stat(file_path).length
    if (total_size >= self.total_file_size_cap_bytes):
        for file_name in events_files:
            if (total_size < self.total_file_size_cap_bytes):
                break
            file_path = os.path.join(self._events_directory, file_name)
            file_size = tf.io.gfile.stat(file_path).length
            try:
                tf.io.gfile.remove(file_path)
                total_size -= file_size
                logger.info('Deleted %s because events files take up over %d bytes', file_path, self.total_file_size_cap_bytes)
            except IOError as err:
                logger.error('Deleting %s failed: %s', file_path, err)
    self._events_file_count += 1
    file_path = ('%s.%d.%d' % (os.path.join(directory, DEBUGGER_EVENTS_FILE_STARTING_TEXT), time.time(), self._events_file_count))
    logger.info('Creating events file %s', file_path)
    return pywrap_tensorflow.EventsWriter(tf.compat.as_bytes(file_path))

Creates a new events writer.

Args:
directory: The directory in which to write files containing events.

Returns:
A new events writer, which corresponds to a new events file.


def register_list(self):
    num_items = self.MAX_NUM_CPU_REGISTERS
    buf = (ctypes.c_uint32 * num_items)()
    num_regs = self._dll.JLINKARM_GetRegisterList(buf, num_items)
    return buf[:num_regs]

Returns a list of the indices for the CPU registers.

The returned indices can be used to read the register content or grab
the register name.

Args:
self (JLink): the ``JLink`` instance

Returns:
List of registers.


def GetUpdates(self, s3_client, bucket, obj, since):
    try:
        if since is not None:
            response = s3_client.get_object(Bucket=bucket, IfModifiedSince=timestamps.FromTimestampToDateTime(since), Key=obj)
        else:
            response = s3_client.get_object(Bucket=bucket, Key=obj)
        body = response['Body']
        last_modified_ts = timestamps.FromDateTimeToTimestamp(response['LastModified'])
    except ClientError as e:
        error_code = int(e.response['Error']['Code'])
        if error_code == 304:
            return []
        self.log.error('error getting S3 object ({}): {}'.format(obj, e))
        raise error.SourceUnavailable('unable to download object from S3')
    data_map = self.GetMap(cache_info=body)
    data_map.SetModifyTimestamp(last_modified_ts)
    return data_map

Get updates from a source.

Args:
s3_client: initialized s3 client
bucket: s3 bucket
obj: object with the data
since: a timestamp representing the last change (None to force-get)

Returns:
A tuple containing the map of updates and a maximum timestamp

Raises:
ValueError: an object in the source map is malformed
ConfigurationError:


def to_hour(num) -> str:

    to_str = str(int(num))
    return pd.Timestamp(f'{to_str[:-2]}:{to_str[-2:]}').strftime('%H:%M')

Convert YAML input to hours

Args:
num: number in YMAL file, e.g., 900, 1700, etc.

Returns:
str

Examples:
>>> to_hour(900)
'09:00'
>>> to_hour(1700)
'17:00'


def make_initializable_iterator(self):
    return self._make_initializable_iterator()

Get an initializable iterator for DistributedDatasetV1.

Note: This API is deprecated. Please use
`tf.compat.v1.data.make_initializable_iterator(dataset)` to create an
initializable iterator.

Returns:
A DistributedIteratorV1 instance.


def _fluent_range_type(cls, fluents, ordering) -> Sequence[str]:
    range_types = []
    for name in ordering:
        fluent = fluents[name]
        range_type = fluent.range
        range_types.append(range_type)
    return tuple(range_types)

Returns the range types of `fluents` following the given `ordering`.

Returns:
Sequence[str]: A tuple of range types representing
the range of each fluent.


def _scalar_to_vector(self, m):

        if not isinstance(m.y0, numbers.Number):
            return m
        else:
            m = copy.deepcopy(m)
            t0 = 0.0
            if isinstance(m.y0, numbers.Integral):
                numtype = np.float64
            else:
                numtype = type(m.y0)
            y0_orig = m.y0
            m.y0 = np.array([m.y0], dtype=numtype)
            def make_vector_fn(fn):
                def newfn(y, t):
                    return np.array([fn(y[0], t)], dtype=numtype)
                newfn.__name__ = fn.__name__
                return newfn
            def make_matrix_fn(fn):
                def newfn(y, t):
                    return np.array([[fn(y[0], t)]], dtype=numtype)
                newfn.__name__ = fn.__name__
                return newfn
            def make_coupling_fn(fn):
                def newfn(source_y, target_y, weight):
                    return np.array([fn(source_y[0], target_y[0], weight)])
                newfn.__name__ = fn.__name__
                return newfn
            if isinstance(m.f(y0_orig, t0), numbers.Number):
                m.f = make_vector_fn(m.f)
            if hasattr(m, 'G') and isinstance(m.G(y0_orig,t0), numbers.Number):
                m.G = make_matrix_fn(m.G)
            if (hasattr(m, 'coupling') and
                    isinstance(m.coupling(y0_orig, y0_orig, 0.5),
                               numbers.Number)):
                m.coupling = make_coupling_fn(m.coupling)
            return m

Allow submodels with scalar equations. Convert to 1D vector systems.
Args:
m (Model)


def main():
    parser = argparse.ArgumentParser(description='Cherry picking automation.')
    parser.add_argument('--filename', help='path to whl file we are copying', required=True)
    parser.add_argument('--new_py_ver', help='two digit py version eg. 27 or 33', required=True)
    args = parser.parse_args()
    args.filename = os.path.abspath(args.filename)
    check_existence(args.filename)
    regex_groups = re.search(TF_NIGHTLY_REGEX, args.filename)
    directory = regex_groups.group(1)
    package = regex_groups.group(2)
    version = regex_groups.group(3)
    origin_tag = regex_groups.group(4)
    old_py_ver = re.search('(cp\\d\\d)', origin_tag).group(1)
    new_tag = origin_tag.replace(old_py_ver, 'cp' + args.new_py_ver)
    copy_binary(directory, origin_tag, new_tag, version, package)

This script copies binaries.

Requirements:
filename: The path to the whl file
AND
new_py_ver: Create a nightly tag with current date

Raises:
RuntimeError: If the whl file was not found


def delete(self, option=None):
    write_pb = _helpers.pb_for_delete(self._document_path, option)
    commit_response = self._client._firestore_api.commit(self._client._database_string, [write_pb], transaction=None, metadata=self._client._rpc_metadata)
    return commit_response.commit_time

Delete the current document in the Firestore database.

Args:
option (Optional[~.firestore_v1beta1.client.WriteOption]): A
write option to make assertions / preconditions on the server
state of the document before applying changes.

Returns:
google.protobuf.timestamp_pb2.Timestamp: The time that the delete
request was received by the server. If the document did not exist
when the delete was sent (i.e. nothing was deleted), this method
will still succeed and will still return the time that the
request was received by the server.


def make_message(self, text, channel):
    try:
        channel_id = self.slack.channel_from_name(channel)['id']
    except ValueError:
        channel_id = channel
    return pack({'text': text, 'type': 'message', 'channel': channel_id, 'id': self.message_id})

High-level function for creating messages. Return packed bytes.

Args:
text: {str}
channel: {str} Either name or ID


def extract(self, destdir, decompress='auto'):
    for e in self.mardata.index.entries:
        name = e.name
        entry_path = safejoin(destdir, name)
        entry_dir = os.path.dirname(entry_path)
        mkdir(entry_dir)
        with open(entry_path, 'wb') as f:
            write_to_file(self.extract_entry(e, decompress), f)
            os.chmod(entry_path, e.flags)

Extract the entire MAR file into a directory.

Args:
destdir (str): A local directory on disk into which the contents of
this MAR file will be extracted. Required parent directories
will be created as necessary.
decompress (obj, optional): Controls whether files are decompressed
when extracted. Must be one of 'auto' or None. Defaults to
'auto'.


def linear_extrapolation_plot(log_prob_adv_array, y, file_name, min_epsilon=(- 10), max_epsilon=10, num_points=21):
    import matplotlib
    matplotlib.use('Agg')
    import matplotlib.pyplot as plt
    figure = plt.figure()
    figure.canvas.set_window_title('Cleverhans: Linear Extrapolation Plot')
    correct_idx = np.argmax(y, axis=0)
    fig = plt.figure()
    plt.xlabel('Epsilon')
    plt.ylabel('Logits')
    x_axis = np.linspace(min_epsilon, max_epsilon, num_points)
    plt.xlim((min_epsilon - 1), (max_epsilon + 1))
    for i in range(y.shape[0]):
        if (i == correct_idx):
            ls = '-'
            linewidth = 5
        else:
            ls = '--'
            linewidth = 2
        plt.plot(x_axis, log_prob_adv_array[(:, i)], ls=ls, linewidth=linewidth, label='{}'.format(i))
    plt.legend(loc='best', fontsize=14)
    plt.show()
    fig.savefig(file_name)
    plt.clf()
    return figure

Generate linear extrapolation plot.

Args:
log_prob_adv_array: Numpy array containing log probabilities
y: Tf placeholder for the labels
file_name: Plot filename
min_epsilon: Minimum value of epsilon over the interval
max_epsilon: Maximum value of epsilon over the interval
num_points: Number of points used to interpolate


def build_bird_configuration(config):
    bird_configuration = {}
    if config.getboolean('daemon', 'ipv4'):
        if os.path.islink(config.get('daemon', 'bird_conf')):
            config_file = os.path.realpath(config.get('daemon', 'bird_conf'))
            print("'bird_conf' is set to a symbolic link ({s} -> {d}, but we will use the canonical path of that link".format(s=config.get('daemon', 'bird_conf'), d=config_file))
        else:
            config_file = config.get('daemon', 'bird_conf')
        dummy_ip_prefix = config.get('daemon', 'dummy_ip_prefix')
        if (not valid_ip_prefix(dummy_ip_prefix)):
            raise ValueError('invalid dummy IPv4 prefix: {i}'.format(i=dummy_ip_prefix))
        bird_configuration[4] = {'config_file': config_file, 'variable_name': config.get('daemon', 'bird_variable'), 'dummy_ip_prefix': dummy_ip_prefix, 'reconfigure_cmd': config.get('daemon', 'bird_reconfigure_cmd'), 'keep_changes': config.getboolean('daemon', 'bird_keep_changes'), 'changes_counter': config.getint('daemon', 'bird_changes_counter')}
    if config.getboolean('daemon', 'ipv6'):
        if os.path.islink(config.get('daemon', 'bird6_conf')):
            config_file = os.path.realpath(config.get('daemon', 'bird6_conf'))
            print("'bird6_conf' is set to a symbolic link ({s} -> {d}, but we will use the canonical path of that link".format(s=config.get('daemon', 'bird6_conf'), d=config_file))
        else:
            config_file = config.get('daemon', 'bird6_conf')
        dummy_ip_prefix = config.get('daemon', 'dummy_ip6_prefix')
        if (not valid_ip_prefix(dummy_ip_prefix)):
            raise ValueError('invalid dummy IPv6 prefix: {i}'.format(i=dummy_ip_prefix))
        bird_configuration[6] = {'config_file': config_file, 'variable_name': config.get('daemon', 'bird6_variable'), 'dummy_ip_prefix': dummy_ip_prefix, 'reconfigure_cmd': config.get('daemon', 'bird6_reconfigure_cmd'), 'keep_changes': config.getboolean('daemon', 'bird6_keep_changes'), 'changes_counter': config.getint('daemon', 'bird6_changes_counter')}
    return bird_configuration

Build bird configuration structure.

First it performs a sanity check against bird settings and then builds a
dictionary structure with bird configuration per IP version.

Arguments:
config (obj): A configparser object which holds our configuration.

Returns:
A dictionary

Raises:
ValueError if sanity check fails.


def add_object(self, file_path, file_object, error_fct=None):
    error_fct = (error_fct or self.raise_os_error)
    if (not file_path):
        target_directory = self.root
    else:
        target_directory = self.resolve(file_path)
        if (not S_ISDIR(target_directory.st_mode)):
            error = (errno.ENOENT if self.is_windows_fs else errno.ENOTDIR)
            error_fct(error, file_path)
    target_directory.add_entry(file_object)

Add a fake file or directory into the filesystem at file_path.

Args:
file_path: The path to the file to be added relative to self.
file_object: File or directory to add.
error_class: The error class to be thrown if file_path does
not correspond to a directory (used internally(

Raises:
IOError or OSError: if file_path does not correspond to a
directory.


def inverse_guass(self, mu: float, sigma: float) -> float:

        return float(
            lib.TCOD_random_get_gaussian_double_inv(self.random_c, mu, sigma)
        )

Return a random Gaussian number using the Box-Muller transform.

Args:
mu (float): The median returned value.
sigma (float): The standard deviation.

Returns:
float: A random float.


def get_max_instability(self, min_voltage=None, max_voltage=None):
    data = []
    for pair in self._select_in_voltage_range(min_voltage, max_voltage):
        if (pair.decomp_e_charge is not None):
            data.append(pair.decomp_e_charge)
        if (pair.decomp_e_discharge is not None):
            data.append(pair.decomp_e_discharge)
    return (max(data) if (len(data) > 0) else None)

The maximum instability along a path for a specific voltage range.

Args:
min_voltage: The minimum allowable voltage.
max_voltage: The maximum allowable voltage.

Returns:
Maximum decomposition energy of all compounds along the insertion
path (a subset of the path can be chosen by the optional arguments)


def add_adsorbate_atom(self, indices, specie, distance):

        center = np.sum([self[i].coords for i in indices], axis=0) / len(
            indices)

        coords = center + self.normal * distance / np.linalg.norm(self.normal)

        self.append(specie, coords, coords_are_cartesian=True)

Gets the structure of single atom adsorption.
slab structure from the Slab class(in [0, 0, 1])

Args:
indices ([int]): Indices of sites on which to put the absorbate.
Absorbed atom will be displaced relative to the center of
these sites.
specie (Specie/Element/str): adsorbed atom species
distance (float): between centers of the adsorbed atom and the
given site in Angstroms.


def set_property_filter(filter_proto, name, op, value):

  filter_proto.Clear()
  pf = filter_proto.property_filter
  pf.property.name = name
  pf.op = op
  set_value(pf.value, value)
  return filter_proto

Set property filter contraint in the given datastore.Filter proto message.

Args:
filter_proto: datastore.Filter proto message
name: property name
op: datastore.PropertyFilter.Operation
value: property value

Returns:
the same datastore.Filter.

Usage:
>>> set_property_filter(filter_proto, 'foo',
...   datastore.PropertyFilter.EQUAL, 'a')  # WHERE 'foo' = 'a'


def from_hyperplane(basis, origin, point, internal = True):

        basis = np.array(basis)
        assert basis.shape[0] + 1 == basis.shape[1]

        big_basis = np.zeros((basis.shape[1], basis.shape[1]))
        big_basis[:basis.shape[0],:basis.shape[1]] = basis

        u, s, vh = np.linalg.svd(big_basis)
        null_mask = (s <= 1e-8)
        normal = np.compress(null_mask, vh, axis=0)[0]

        if np.inner(np.array(point)-np.array(origin), normal) > 0:
            if internal:
                normal *= -1
        else:
            if not internal:
                normal *= -1
        offset = -np.dot(origin, normal)
        return Halfspace(normal, offset)

Returns a Halfspace defined by a list of vectors parallel to the
bounding hyperplane.

Args:
basis: basis for the hyperplane (array with vector rows)
origin: point on the hyperplane
point: point not on the hyperplane
internal: whether point is inside the halfspace


def get_decor(self, c, match_only=None):

        if isinstance(c, Component):
            if c:
                if match_only:

                    c = Component({k: getattr(c, k, None) for k in match_only})
                for decor in self.__list:
                    try:
                        if c == decor.component:
                            return decor
                    except AttributeError:
                        continue
        else:
            for decor in self.__list:
                try:
                    if getattr(c, 'mnemonic').lower() == decor.curve.mnemonic:
                        return decor
                except AttributeError:
                    continue
        return Decor({'colour': '

Get the decor for a component.

Args:
c (component): The component to look up.
match_only (list of str): The component attributes to include in the
comparison. Default: All of them.

Returns:
Decor. The matching Decor from the Legend, or None if not found.


def __init__(self, system_time_tuple=None):

    super(Systemtime, self).__init__()
    self._number_of_seconds = None
    self._precision = definitions.PRECISION_1_MILLISECOND
    self.day_of_month = None
    self.day_of_week = None
    self.hours = None
    self.milliseconds = None
    self.minutes = None
    self.month = None
    self.seconds = None
    self.year = None

    if system_time_tuple:
      if len(system_time_tuple) < 8:
        raise ValueError('Invalid system time tuple 8 elements required.')

      if system_time_tuple[0] < 1601 or system_time_tuple[0] > 30827:
        raise ValueError('Year value out of bounds.')

      if system_time_tuple[1] not in range(1, 13):
        raise ValueError('Month value out of bounds.')

      if system_time_tuple[2] not in range(0, 7):
        raise ValueError('Day of week value out of bounds.')

      days_per_month = self._GetDaysPerMonth(
          system_time_tuple[0], system_time_tuple[1])
      if system_time_tuple[3] < 1 or system_time_tuple[3] > days_per_month:
        raise ValueError('Day of month value out of bounds.')

      if system_time_tuple[4] not in range(0, 24):
        raise ValueError('Hours value out of bounds.')

      if system_time_tuple[5] not in range(0, 60):
        raise ValueError('Minutes value out of bounds.')

      if system_time_tuple[6] not in range(0, 60):
        raise ValueError('Seconds value out of bounds.')

      if system_time_tuple[7] < 0 or system_time_tuple[7] > 999:
        raise ValueError('Milliseconds value out of bounds.')

      self.day_of_month = system_time_tuple[3]
      self.day_of_week = system_time_tuple[2]
      self.hours = system_time_tuple[4]
      self.milliseconds = system_time_tuple[7]
      self.minutes = system_time_tuple[5]
      self.month = system_time_tuple[1]
      self.seconds = system_time_tuple[6]
      self.year = system_time_tuple[0]

      self._number_of_seconds = self._GetNumberOfSecondsFromElements(
          self.year, self.month, self.day_of_month, self.hours, self.minutes,
          self.seconds)

Initializes a SYSTEMTIME structure.

Args:
system_time_tuple
(Optional[tuple[int, int, int, int, int, int, int, int]]):
system time, contains year, month, day of week, day of month,
hours, minutes, seconds and milliseconds.

Raises:
ValueError: if the system time is invalid.


def get_product_value(self, value_name, wanted_type=None):
    if (not self.__reg_products_handle):
        return None
    (subkey, search_value_name) = os.path.split(value_name)
    try:
        if subkey:
            handle = win32api.RegOpenKeyEx(self.__reg_products_handle, subkey, 0, (win32con.KEY_READ | self.__reg_32bit_access))
            (item_value, item_type) = self.__reg_query_value(handle, search_value_name)
            win32api.RegCloseKey(handle)
        else:
            (item_value, item_type) = win32api.RegQueryValueEx(self.__reg_products_handle, value_name)
    except pywintypes.error as exc:
        if (exc.winerror == winerror.ERROR_FILE_NOT_FOUND):
            return None
        raise
    if (wanted_type and (item_type not in self.__reg_types[wanted_type])):
        item_value = None
    return item_value

For the product section of the registry return the name value.

Args:
value_name (str): Registry value name.
wanted_type (str):
The type of value wanted if the type does not match
None is return. wanted_type support values are
``str`` ``int`` ``list`` ``bytes``.

Returns:
value: Value requested or ``None`` if not found.


def union(self, other, recursive=True, overwrite=False):
    if (not isinstance(other, composite)):
        raise AssertionError('Cannot union composite and {} types'.format(type(other)))
    if (self.meta_type != other.meta_type):
        return composite([self, other])
    if (self.meta_type == 'list'):
        keep = []
        for item in self._list:
            keep.append(item)
        for item in other._list:
            if (item not in self._list):
                keep.append(item)
        return composite(keep)
    elif (self.meta_type == 'dict'):
        keep = {}
        for key in list(set((list(self._dict.keys()) + list(other._dict.keys())))):
            left = self._dict.get(key)
            right = other._dict.get(key)
            if (recursive and isinstance(left, composite) and isinstance(right, composite)):
                keep[key] = left.union(right, recursive=recursive, overwrite=overwrite)
            elif (left == right):
                keep[key] = left
            elif (left is None):
                keep[key] = right
            elif (right is None):
                keep[key] = left
            elif overwrite:
                keep[key] = right
            else:
                keep[key] = composite([left, right])
        return composite(keep)
    return

Recursively compute union of data. For dictionaries, items
for specific keys will be combined into a list, depending on the
status of the overwrite= parameter. For lists, items will be appended
and reduced to unique items. This method is meant to be analogous
to set.union for composite objects.

Args:
other (composite): Other composite object to union with.
recursive (bool): Whether or not to perform the operation recursively,
for all nested composite objects.
overwrite (bool): Whether or not to overwrite entries with the same
key in a nested dictionary.


def ParseFileObject(self, parser_mediator, file_object):

    fixed_section_data_map = self._GetDataTypeMap(
        'job_fixed_length_data_section')

    try:
      fixed_length_section, file_offset = self._ReadStructureFromFileObject(
          file_object, 0, fixed_section_data_map)
    except (ValueError, errors.ParseError) as exception:
      raise errors.UnableToParseFile(
          'Unable to parse fixed-length data section with error: {0!s}'.format(
              exception))

    if not fixed_length_section.product_version in self._PRODUCT_VERSIONS:
      raise errors.UnableToParseFile(
          'Unsupported product version in: 0x{0:04x}'.format(
              fixed_length_section.product_version))

    if not fixed_length_section.format_version == 1:
      raise errors.UnableToParseFile(
          'Unsupported format version in: {0:d}'.format(
              fixed_length_section.format_version))

    variable_section_data_map = self._GetDataTypeMap(
        'job_variable_length_data_section')

    try:
      variable_length_section, data_size = self._ReadStructureFromFileObject(
          file_object, file_offset, variable_section_data_map)
    except (ValueError, errors.ParseError) as exception:
      raise errors.UnableToParseFile((
          'Unable to parse variable-length data section with error: '
          '{0!s}').format(exception))

    file_offset += data_size

    event_data = self._ParseEventData(variable_length_section)

    date_time = self._ParseLastRunTime(parser_mediator, fixed_length_section)
    if date_time:
      event = time_events.DateTimeValuesEvent(
          date_time, definitions.TIME_DESCRIPTION_LAST_RUN)
      parser_mediator.ProduceEventWithEventData(event, event_data)

    trigger_data_map = self._GetDataTypeMap('job_trigger')

    for trigger_index in range(0, variable_length_section.number_of_triggers):
      try:
        trigger, data_size = self._ReadStructureFromFileObject(
            file_object, file_offset, trigger_data_map)
      except (ValueError, errors.ParseError) as exception:
        raise errors.UnableToParseFile((
            'Unable to parse trigger: {0:d} with error: {2!s}').format(
                trigger_index, exception))

      file_offset += data_size

      event_data.trigger_type = trigger.trigger_type

      date_time = self._ParseTriggerStartTime(parser_mediator, trigger)
      if date_time:
        event = time_events.DateTimeValuesEvent(
            date_time, definitions.TIME_DESCRIPTION_SCHEDULED_TO_START,
            time_zone=parser_mediator.timezone)
        parser_mediator.ProduceEventWithEventData(event, event_data)

      date_time = self._ParseTriggerEndTime(parser_mediator, trigger)
      if date_time:
        event = time_events.DateTimeValuesEvent(
            date_time, definitions.TIME_DESCRIPTION_SCHEDULED_TO_START,
            time_zone=parser_mediator.timezone)
        parser_mediator.ProduceEventWithEventData(event, event_data)

Parses a Windows job file-like object.

Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
file_object (dfvfs.FileIO): a file-like object.

Raises:
UnableToParseFile: when the file cannot be parsed.


def load(self, read_tuple_name):
    self.prefix_width = 0
    self.read_tuple_id_width = 0
    self.genome_id_width = 0
    self.chr_id_width = 0
    self.coor_width = 0
    parts = read_tuple_name.split('__')
    self.prefix_width = len(parts[0])
    self.read_tuple_id_width = len(parts[1])
    segments = parts[2][1:(- 1)].split('),(')
    for segment in segments:
        int_widths = list(map(len, segment.split(',')))
        self.genome_id_width = max(self.genome_id_width, int_widths[0])
        self.chr_id_width = max(self.chr_id_width, int_widths[1])
        self.coor_width = max(self.coor_width, int_widths[2], int_widths[3])

Load RNF values from a read tuple name.

Args:
read_tuple_name (str): Read tuple name which the values are taken from.


def struct_member_error(err, sid, name, offset, size):

    exception, msg = STRUCT_ERROR_MAP[err]
    struct_name = idc.GetStrucName(sid)
    return exception(('AddStructMember(struct="{}", member="{}", offset={}, size={}) '
                      'failed: {}').format(
        struct_name,
        name,
        offset,
        size,
        msg
    ))

Create and format a struct member exception.

Args:
err: The error value returned from struct member creation
sid: The struct id
name: The member name
offset: Memeber offset
size: Member size

Returns:
A ``SarkErrorAddStructMemeberFailed`` derivative exception, with an
informative message.


def _get_message(self, target_message, indices, pending, timeout, condition):
    start_time = time.time()
    target_id = self._get_message_id(target_message)
    if (target_id not in indices):
        for (i, incoming) in enumerate(self._incoming):
            if (incoming.id > target_id):
                indices[target_id] = i
                break
        else:
            indices[target_id] = len(self._incoming)
    future = self._client.loop.create_future()
    last_idx = indices[target_id]
    if (last_idx < len(self._incoming)):
        incoming = self._incoming[last_idx]
        if condition(incoming, target_id):
            indices[target_id] += 1
            future.set_result(incoming)
            return future
    pending[target_id] = future
    return self._get_result(future, start_time, timeout)

Gets the next desired message under the desired condition.

Args:
target_message (`object`):
The target message for which we want to find another
response that applies based on `condition`.

indices (`dict`):
This dictionary remembers the last ID chosen for the
input `target_message`.

pending (`dict`):
This dictionary remembers {msg_id: Future} to be set
once `condition` is met.

timeout (`int`):
The timeout (in seconds) override to use for this operation.

condition (`callable`):
The condition callable that checks if an incoming
message is a valid response.


def whois_domains_history(self, domains):
    api_name = 'opendns-whois-domain-history'
    fmt_url_path = u'whois/{0}/history'
    return self._multi_get(api_name, fmt_url_path, domains)

Calls WHOIS domain history end point

Args:
domains: An enumerable of domains
Returns:
A dict of {domain: domain_history_result}


def copy(source_file_names, destination_file_names):
    if len(source_file_names) == 0:
        return
    filesystem = FileSystems.get_filesystem(source_file_names[0])
    return filesystem.copy(source_file_names, destination_file_names)

Recursively copy the file list from the source to the destination

Args:
source_file_names: list of source file objects that needs to be copied
destination_file_names: list of destination of the new object

Raises:
``BeamIOError``: if any of the copy operations fail


def _is_in_targets(self, site, targets):

        elems = self._get_elements(site)
        for elem in elems:
            if elem not in targets:
                return False
        return True

Test whether a site contains elements in the target list

Args:
site (Site): Site to assess
targets ([Element]) List of elements
Returns:
(boolean) Whether this site contains a certain list of elements


def __init__(self, max_attempts, *args, **kwargs):

        Exception.__init__(self, *args, **kwargs)
        self.max_attempts = max_attempts

Initializer.

Args:
max_attempts: Maximum number of attempts to make for this task,
inclusive. So 2 means try two times and then retire the task.
*args, **kwargs: Optional Exception arguments.


def simple_layer_stack(include_encdec_attention, num_layers=6, d_ff=2048, num_heads=8, d_kv=128, dropout_rate=0.1):
    ret = []
    for _ in xrange(num_layers):
        ret.append(transformer_layers.SelfAttention(num_heads=num_heads, key_value_size=d_kv, attention_kwargs={'dropout_rate': dropout_rate}))
        if include_encdec_attention:
            ret.append(transformer_layers.EncDecAttention(num_heads=num_heads, key_value_size=d_kv, attention_kwargs={'dropout_rate': dropout_rate}))
        ret.append(transformer_layers.DenseReluDense(hidden_size=d_ff, dropout_rate=dropout_rate))
    return transformer.LayerStack(ret)

Create a layer stack.

Args:
include_encdec_attention: a boolean
num_layers: an integer
d_ff: an integer
num_heads: an integer
d_kv: an integer
dropout_rate: a float

Returns:
a LayerStack