def uid(uid):
    if uid is None:
        raise ValueError('UID cannot be None.')

    def decorate(test_func):

        @functools.wraps(test_func)
        def wrapper(*args, **kwargs):
            return test_func(*args, **kwargs)
        setattr(wrapper, 'uid', uid)
        return wrapper
    return decorate

Decorator specifying the unique identifier (UID) of a test case.

The UID will be recorded in the test's record when executed by Mobly.

If you use any other decorator for the test method, you may want to use
this as the outer-most one.

Note a common UID system is the Universal Unitque Identifier (UUID), but
we are not limiting people to use UUID, hence the more generic name `UID`.

Args:
uid: string, the uid for the decorated test function.


def create_scheduler(self, num_training_steps: int, optimizer: torch.optim.Optimizer=None):
    if self.lr_scheduler is None:
        self.lr_scheduler = get_scheduler(self.args.lr_scheduler_type, optimizer=self.optimizer if optimizer is None else optimizer, num_warmup_steps=self.args.get_warmup_steps(num_training_steps), num_training_steps=num_training_steps, scheduler_specific_kwargs=self.args.lr_scheduler_kwargs)
        self._created_lr_scheduler = True
    return self.lr_scheduler

Setup the scheduler. The optimizer of the trainer must have been set up either before this method is called or
passed as an argument.

Args:
num_training_steps (int): The number of training steps to do.


def get(self, name):

        name = str(name)
        if name not in self._properties:
            raise ArgumentError("Unknown property in DeviceModel", name=name)

        return self._properties[name]

Get a device model property.

Args:
name (str): The name of the property to get


def log_cdf(self, value, name='log_cdf'):
    return self._call_log_cdf(value, name)

Log cumulative distribution function.

Given random variable `X`, the cumulative distribution function `cdf` is:

```none
log_cdf(x) := Log[ P[X <= x] ]
```

Often, a numerical approximation can be used for `log_cdf(x)` that yields
a more accurate answer than simply taking the logarithm of the `cdf` when
`x << -1`.

Args:
value: `float` or `double` `Tensor`.
name: Python `str` prepended to names of ops created by this function.

Returns:
logcdf: a `Tensor` of shape `sample_shape(x) + self.batch_shape` with
values of type `self.dtype`.


def to_json_file(self, json_file_path: Union[str, os.PathLike]):
    with open(json_file_path, 'w', encoding='utf-8') as writer:
        writer.write(self.to_json_string())

Save this instance to a JSON file.

Args:
json_file_path (`str` or `os.PathLike`):
Path to the JSON file in which this feature_extractor instance's parameters will be saved.


def onTagAdd(self, name, func):

        if '*' in name:
            self.ontagaddglobs.add(name, func)
        else:
            self.ontagadds[name].append(func)

Register a callback for tag addition.

Args:
name (str): The name of the tag or tag glob.
func (function): The callback func(node, tagname, tagval).


def get_clinvar_submission(store, institute_id, case_name, variant_id, submission_id):

    institute_obj, case_obj = institute_and_case(store, institute_id, case_name)
    pinned = [store.variant(variant_id) or variant_id for variant_id in
                  case_obj.get('suspects', [])]
    variant_obj = store.variant(variant_id)
    clinvar_submission_objs = store.clinvars(submission_id=submission_id)
    return dict(
        today = str(date.today()),
        institute=institute_obj,
        case=case_obj,
        variant=variant_obj,
        pinned_vars=pinned,
        clinvars = clinvar_submission_objs
    )

Collects all variants from the clinvar submission collection with a specific submission_id

Args:
store(scout.adapter.MongoAdapter)
institute_id(str): Institute ID
case_name(str): case ID
variant_id(str): variant._id
submission_id(str): clinvar submission id, i.e. SUB76578

Returns:
A dictionary with all the data to display the clinvar_update.html template page


def _get_name_and_module(full_name):
    name_segments = full_name.split('.')
    return ('.'.join(name_segments[:-1]), name_segments[-1])

Split full_name into module and short name.

Args:
full_name: Full name of symbol that includes module.

Returns:
Full module name and short symbol name.


def list(cls, session, mailbox):

        endpoint = '/mailboxes/%d/conversations.json' % mailbox.id
        return super(Conversations, cls).list(session, endpoint)

Return conversations in a mailbox.

Args:
session (requests.sessions.Session): Authenticated session.
mailbox (helpscout.models.Mailbox): Mailbox to list.

Returns:
RequestPaginator(output_type=helpscout.models.Conversation):
Conversations iterator.


def put(self, filename, encoding=None):

        from . import LocalFile

        if os.path.isdir(filename) and self.source is None:
            raise ValueError("Cannot write this object to "
                             "directory %s without an explicit filename." % filename)

        target = get_target_path(filename, self.source)

        if encoding is None:
            encoding = self.encoding

        if self._isbytes:
            kwargs = {'mode': 'wb'}
        else:
            kwargs = {'mode': 'w', 'encoding': encoding}

        with open(target, **kwargs) as outfile:
            outfile.write(self._contents)

        return LocalFile(target, encoded_with=encoding)

Write the file to the given path

Args:
filename (str): path to write this file to
encoding (str): file encoding (default: system default)

Returns:
LocalFile: reference to the copy of the file stored at ``filename``


def print_colored_columns(printer, rows, padding=2):

    rows_ = [x[:-1] for x in rows]
    colors = [x[-1] for x in rows]
    for col, line in zip(colors, columnise(rows_, padding=padding)):
        printer(line, col)

Like `columnise`, but with colored rows.

Args:
printer (`colorize.Printer`): Printer object.

Note:
The last entry in each row is the row color, or None for no coloring.


def bit_to_int(x_bit, num_bits, base=2):

  x_l = tf.stop_gradient(tf.to_int32(tf.reshape(x_bit, [-1, num_bits])))
  x_labels = [
      x_l[:, i] * tf.to_int32(base)**tf.to_int32(i) for i in range(num_bits)]
  res = sum(x_labels)
  return tf.to_int32(tf.reshape(res, common_layers.shape_list(x_bit)[:-1]))

Turn x_bit representing numbers bitwise (lower-endian) to int tensor.

Args:
x_bit: Tensor containing numbers in a particular base to be converted to
int.
num_bits: Number of bits in the representation.
base: Base of the representation.

Returns:
Integer representation of this number.


def merge(self, obj):

        if obj.id in self.cache:
            self.cache[obj.id].merge(obj)
        else:
            self.cache[obj.id] = obj
        return self.cache[obj.id]

Add a given object to the cache, or update an existing entry to include more fields.

Args:
obj (SkypeObj): object to add to the cache


def GetFileEntryByPathSpec(self, path_spec):

    tsk_file = None
    inode = getattr(path_spec, 'inode', None)
    location = getattr(path_spec, 'location', None)

    root_inode = self.GetRootInode()
    if (location == self.LOCATION_ROOT or
        (inode is not None and root_inode is not None and inode == root_inode)):
      tsk_file = self._tsk_file_system.open(self.LOCATION_ROOT)
      return tsk_file_entry.TSKFileEntry(
          self._resolver_context, self, path_spec, tsk_file=tsk_file,
          is_root=True)

    try:
      if inode is not None:
        tsk_file = self._tsk_file_system.open_meta(inode=inode)
      elif location is not None:
        tsk_file = self._tsk_file_system.open(location)

    except IOError:
      pass

    if tsk_file is None:
      return None

    return tsk_file_entry.TSKFileEntry(
        self._resolver_context, self, path_spec, tsk_file=tsk_file)

Retrieves a file entry for a path specification.

Args:
path_spec (PathSpec): path specification.

Returns:
TSKFileEntry: a file entry or None if not available.


def supply(self, issuer):

        issuer_uri_config = self._issuer_uri_configs.get(issuer)

        if not issuer_uri_config:

            return

        jwks_uri = issuer_uri_config.jwks_uri
        if jwks_uri:

            return jwks_uri

        open_id_valid = issuer_uri_config.open_id_valid
        if open_id_valid:
            discovered_jwks_uri = _discover_jwks_uri(issuer)
            self._issuer_uri_configs[issuer] = IssuerUriConfig(False,
                                                               discovered_jwks_uri)
            return discovered_jwks_uri

Supplies the `jwks_uri` for the given issuer.

Args:
issuer: the issuer.

Returns:
The `jwks_uri` that is either statically configured or retrieved via
OpenId discovery. None is returned when the issuer is unknown or the
OpenId discovery fails.


def cancelTickByTickData(self, contract: Contract, tickType: str):

        ticker = self.ticker(contract)
        reqId = self.wrapper.endTicker(ticker, tickType)
        if reqId:
            self.client.cancelTickByTickData(reqId)
        else:
            self._logger.error(
                f'cancelMktData: No reqId found for contract {contract}')

Unsubscribe from tick-by-tick data

Args:
contract: The exact contract object that was used to
subscribe with.


def convertData(self, contents, def_buf, kwh_scale=ScaleKWH.EmptyScale):

        log_str = ""
        count = 0

        if kwh_scale == ScaleKWH.EmptyScale:
            scale_offset = int(def_buf.keys().index(Field.kWh_Scale))
            self.m_kwh_precision = kwh_scale = int(contents[scale_offset])

        for fld in def_buf:

            if def_buf[fld][MeterData.CalculatedFlag]:
                count += 1
                continue

            if len(contents) == 0:
                count += 1
                continue

            try:
                raw_data = contents[count]
                fld_type = def_buf[fld][MeterData.TypeValue]
                fld_scale = def_buf[fld][MeterData.ScaleValue]

                if fld_type == FieldType.Float:
                    float_data = float(str(raw_data))
                    divisor = 1
                    if fld_scale == ScaleType.KWH:
                        divisor = 1
                        if kwh_scale == ScaleKWH.Scale10:
                            divisor = 10
                        elif kwh_scale == ScaleKWH.Scale100:
                            divisor = 100
                        elif (kwh_scale != ScaleKWH.NoScale) and (kwh_scale != ScaleKWH.EmptyScale):
                            ekm_log("Unrecognized kwh scale.")
                    elif fld_scale == ScaleType.Div10:
                        divisor = 10
                    elif fld_scale == ScaleType.Div100:
                        divisor = 100
                    elif fld_scale != ScaleType.No:
                        ekm_log("Unrecognized float scale.")
                    float_data /= divisor
                    float_data_str = str(float_data)
                    def_buf[fld][MeterData.StringValue] = float_data_str
                    def_buf[fld][MeterData.NativeValue] = float_data

                elif fld_type == FieldType.Hex:
                    hex_data = raw_data.encode('hex')
                    def_buf[fld][MeterData.StringValue] = hex_data
                    def_buf[fld][MeterData.NativeValue] = hex_data

                elif fld_type == FieldType.Int:
                    integer_data = int(raw_data)
                    integer_data_str = str(integer_data)
                    if len(integer_data_str) == 0:
                        integer_data_str = str(0)
                    def_buf[fld][MeterData.StringValue] = integer_data_str
                    def_buf[fld][MeterData.NativeValue] = integer_data

                elif fld_type == FieldType.String:
                    string_data = str(raw_data)
                    def_buf[fld][MeterData.StringValue] = string_data
                    def_buf[fld][MeterData.NativeValue] = string_data

                elif fld_type == FieldType.PowerFactor:
                    def_buf[fld][MeterData.StringValue] = str(raw_data)
                    def_buf[fld][MeterData.NativeValue] = str(raw_data)

                else:
                    ekm_log("Unrecognized field type")

                log_str = log_str + '"' + fld + '":  "' + def_buf[fld][MeterData.StringValue] + '"\n'

            except:
                ekm_log("Exception on Field:" + str(fld))
                ekm_log(traceback.format_exc(sys.exc_info()))
                self.writeCmdMsg("Exception on Field:" + str(fld))

            count += 1

        return True

Move data from raw tuple into scaled and conveted values.

Args:
contents (tuple): Breakout of passed block from unpackStruct().
def_buf (): Read buffer destination.
kwh_scale (int):  :class:`~ekmmeters.ScaleKWH` as int, from Field.kWhScale`

Returns:
bool: True on completion.


def _setup_mock_socket_file(mock_socket_create_conn, resp):
    fake_file = mock.Mock()
    fake_file.readline.side_effect = resp
    fake_conn = mock.Mock()
    fake_conn.makefile.return_value = fake_file
    mock_socket_create_conn.return_value = fake_conn
    return fake_file

Sets up a mock socket file from the mock connection.

Args:
mock_socket_create_conn: The mock method for creating a socket connection.
resp: iterable, the side effect of the `readline` function of the mock
socket file.

Returns:
The mock socket file that will be injected into the code.


def get_paginated_catalog_courses(self, catalog_id, querystring=None):
    return self._load_data(self.CATALOGS_COURSES_ENDPOINT.format(catalog_id), default=[], querystring=querystring, traverse_pagination=False, many=False)

Return paginated response for all catalog courses.

Returns:
dict: API response with links to next and previous pages.


def price(
        self,
        instrument,
        **kwargs
    ):

        request = Request(
            'GET',
            '/v3/instruments/{instrument}/price'
        )

        request.set_path_param(
            'instrument',
            instrument
        )

        request.set_param(
            'time',
            kwargs.get('time')
        )

        response = self.ctx.request(request)

        if response.content_type is None:
            return response

        if not response.content_type.startswith("application/json"):
            return response

        jbody = json.loads(response.raw_body)

        parsed_body = {}

        if str(response.status) == "200":
            if jbody.get('price') is not None:
                parsed_body['price'] = \
                    self.ctx.pricing_common.Price.from_dict(
                        jbody['price'],
                        self.ctx
                    )

        elif str(response.status) == "400":
            if jbody.get('errorCode') is not None:
                parsed_body['errorCode'] = \
                    jbody.get('errorCode')

            if jbody.get('errorMessage') is not None:
                parsed_body['errorMessage'] = \
                    jbody.get('errorMessage')

        elif str(response.status) == "401":
            if jbody.get('errorCode') is not None:
                parsed_body['errorCode'] = \
                    jbody.get('errorCode')

            if jbody.get('errorMessage') is not None:
                parsed_body['errorMessage'] = \
                    jbody.get('errorMessage')

        elif str(response.status) == "404":
            if jbody.get('errorCode') is not None:
                parsed_body['errorCode'] = \
                    jbody.get('errorCode')

            if jbody.get('errorMessage') is not None:
                parsed_body['errorMessage'] = \
                    jbody.get('errorMessage')

        elif str(response.status) == "405":
            if jbody.get('errorCode') is not None:
                parsed_body['errorCode'] = \
                    jbody.get('errorCode')

            if jbody.get('errorMessage') is not None:
                parsed_body['errorMessage'] = \
                    jbody.get('errorMessage')

        else:
            parsed_body = jbody

        response.body = parsed_body

        return response

Fetch a price for an instrument. Accounts are not associated in any way
with this endpoint.

Args:
instrument:
Name of the Instrument
time:
The time at which the desired price is in effect. The current
price is returned if no time is provided.

Returns:
v20.response.Response containing the results from submitting the
request


def peek(self, iroute: 'InstanceRoute') -> Optional[Value]:
    val = self.value
    sn = self.schema_node
    for sel in iroute:
        (val, sn) = sel.peek_step(val, sn)
        if (val is None):
            return None
    return val

Return a value within the receiver's subtree.

Args:
iroute: Instance route (relative to the receiver).


def add_payload(self, key, val, append=True):

        if append:
            self._params.setdefault(key, []).append(val)
        else:
            self._params[key] = val

Add a key value pair to payload for this request.

.. Note:: For ``_search`` you can pass a search argument. (e.g. _search?summary=1.1.1.1).

Args:
key (string): The payload key
val (string): The payload value
append (bool): Indicates whether the value should be appended or overwritten.


def segments(seg_type=None):

    for index in xrange(idaapi.get_segm_qty()):
        seg = Segment(index=index)
        if (seg_type is None) or (seg.type == seg_type):
            yield Segment(index=index)

Iterate segments based on type

Args:
seg_type: type of segment e.g. SEG_CODE

Returns:
iterator of `Segment` objects. if seg_type is None , returns all segments
otherwise returns only the relevant ones


def _placement_points_generator(self, skyline, width):

        skyline_r = skyline[-1].right
        skyline_l = skyline[0].left

        ppointsl = (s.left for s in skyline if s.left+width <= skyline_r)

        ppointsr = (s.right-width for s in skyline if s.right-width >= skyline_l)

        return heapq.merge(ppointsl, ppointsr)

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

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

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

Returns:
generator


def getTraitCovar(self, term_i=None):

        assert term_i < self.n_randEffs, 'VarianceDecomposition:: specied term out of range'

        if term_i is None:
            RV = sp.zeros((self.P,self.P))
            for term_i in range(self.n_randEffs):
                RV += self.getTraitCovarFun().K()
        else:
            assert term_i<self.n_randEffs, 'Term index non valid'
            RV = self.getTraitCovarFun(term_i).K()
        return RV

Return the estimated trait covariance matrix for term_i (or the total if term_i is None)
To retrieve the matrix of correlation coefficient use \see getTraitCorrCoef

Args:
term_i:     index of the random effect term we want to retrieve the covariance matrix
Returns:
estimated trait covariance


def get_repo_config(self, repo='default'):

        for repo_config in self.repositories:
            if repo_config.name == repo or repo_config.url in RepositoryURL(repo):
                return repo_config

        return None

Retrieve configuration for a given repository.

Args:
repo (str): a repository "realm" (alias) or its URL

Returns:
RepositoryConfig: if there is configuration for that repository
None: otherwise


def to_dict(ramons, flatten=False):

    if type(ramons) is not list:
        ramons = [ramons]

    out_ramons = {}
    for r in ramons:
        out_ramons[r.id] = {
            "id": r.id,
            "type": _reverse_ramon_types[type(r)],
            "metadata": vars(r)
        }
    return out_ramons

Converts a RAMON object list to a JSON-style dictionary. Useful for going
from an array of RAMONs to a dictionary, indexed by ID.

Arguments:
ramons (RAMON[]): A list of RAMON objects
flatten (boolean: False): Not implemented

Returns:
dict: A python dictionary of RAMON objects.


def add(self, predicted, target):
    predicted = predicted.cpu().numpy()
    target = target.cpu().numpy()
    assert (predicted.shape[0] == target.shape[0]), 'number of targets and predicted outputs do not match'
    if (np.ndim(predicted) != 1):
        assert (predicted.shape[1] == self.k), 'number of predictions does not match size of confusion matrix'
        predicted = np.argmax(predicted, 1)
    else:
        assert ((predicted.max() < self.k) and (predicted.min() >= 0)), 'predicted values are not between 1 and k'
    onehot_target = (np.ndim(target) != 1)
    if onehot_target:
        assert (target.shape[1] == self.k), 'Onehot target does not match size of confusion matrix'
        assert ((target >= 0).all() and (target <= 1).all()), 'in one-hot encoding, target values should be 0 or 1'
        assert (target.sum(1) == 1).all(), 'multi-label setting is not supported'
        target = np.argmax(target, 1)
    else:
        assert ((predicted.max() < self.k) and (predicted.min() >= 0)), 'predicted values are not between 0 and k-1'
    x = (predicted + (self.k * target))
    bincount_2d = np.bincount(x.astype(np.int32), minlength=(self.k ** 2))
    assert (bincount_2d.size == (self.k ** 2))
    conf = bincount_2d.reshape((self.k, self.k))
    self.conf += conf

Computes the confusion matrix of K x K size where K is no of classes

Args:
predicted (tensor): Can be an N x K tensor of predicted scores obtained from
the model for N examples and K classes or an N-tensor of
integer values between 0 and K-1.
target (tensor): Can be a N-tensor of integer values assumed to be integer
values between 0 and K-1 or N x K tensor, where targets are
assumed to be provided as one-hot vectors


def get_attribute(self, main_type, sub_type, unique_id, attribute_id, owner=None, params=None):

        return self.attribute(
            main_type, sub_type, unique_id, attribute_id, action='GET', owner=owner, params=params
        )

Args:
owner:
main_type:
sub_type:
unique_id:
attribute_id:
params:

Return:


def update_panel(store, panel_name, csv_lines, option):
    new_genes = []
    panel_obj = store.gene_panel(panel_name)
    if (panel_obj is None):
        return None
    try:
        new_genes = parse_genes(csv_lines)
    except SyntaxError as error:
        flash(error.args[0], 'danger')
        return None
    if (option == 'replace'):
        for gene in panel_obj['genes']:
            gene['hgnc_symbol'] = gene['symbol']
            store.add_pending(panel_obj, gene, action='delete', info=None)
    for new_gene in new_genes:
        if (not new_gene['hgnc_id']):
            flash('gene missing hgnc id: {}'.format(new_gene['hgnc_symbol']), 'danger')
            continue
        gene_obj = store.hgnc_gene(new_gene['hgnc_id'])
        if (gene_obj is None):
            flash('gene not found: {} - {}'.format(new_gene['hgnc_id'], new_gene['hgnc_symbol']), 'danger')
            continue
        if (new_gene['hgnc_symbol'] and (gene_obj['hgnc_symbol'] != new_gene['hgnc_symbol'])):
            flash('symbol mis-match: {0} | {1}'.format(gene_obj['hgnc_symbol'], new_gene['hgnc_symbol']), 'warning')
        info_data = {'disease_associated_transcripts': new_gene['transcripts'], 'reduced_penetrance': new_gene['reduced_penetrance'], 'mosaicism': new_gene['mosaicism'], 'inheritance_models': new_gene['inheritance_models'], 'database_entry_version': new_gene['database_entry_version']}
        if (option == 'replace'):
            action = 'add'
        else:
            existing_genes = {gene['hgnc_id'] for gene in panel_obj['genes']}
            action = ('edit' if (gene_obj['hgnc_id'] in existing_genes) else 'add')
        store.add_pending(panel_obj, gene_obj, action=action, info=info_data)
    return panel_obj

Update an existing gene panel with genes.

Args:
store(scout.adapter.MongoAdapter)
panel_name(str)
csv_lines(iterable(str)): Stream with genes
option(str): 'add' or 'replace'

Returns:
panel_obj(dict)


def add_group_member(self, grp_name, user):

        self.project_service.set_auth(self._token_project)
        self.project_service.add_group_member(grp_name, user)

Add the given user to the named group.

Both group and user must already exist for this to succeed.

Args:
name (string): Name of group.
user_name (string): User to add to group.

Raises:
requests.HTTPError on failure.


def execute(self, command, data={}):
    (method, uri) = command
    try:
        path = self._formatter.format_map(uri, data)
        body = self._formatter.get_unused_kwargs()
        url = '{0}{1}'.format(self._url, path)
        return self._request(method, url, body)
    except KeyError as err:
        LOGGER.debug('Endpoint {0} is missing argument {1}'.format(uri, err))
        raise

Format the endpoint url by data and then request the remote server.

Args:
command(Command): WebDriver command to be executed.
data(dict): Data fulfill the uri template and json body.

Returns:
A dict represent the json body from server response.

Raises:
KeyError: Data cannot fulfill the variable which command needed.
ConnectionError: Meet network problem (e.g. DNS failure,
refused connection, etc).
Timeout: A request times out.
HTTPError: HTTP request returned an unsuccessful status code.


def __contains__(self, item):

        if self is item:
            return True
        elif self.package is item and self.name == '__init__':
            return True
        return False

Whether given item is contained inside this module.

Args:
item (Package/Module): a package or module.

Returns:
bool:
True if self is item or item is self's package and
self if an ``__init__`` module.


def reduce_and_verify(self, inputs, expect, options):

    def replica_fn():
        CollectiveReplicaLauncher._prefer_unique_instance_key = options.prefer_unique_instance_key
        collective, devices, pid = self.make_collective(options.num_processes, options.gpus_per_process)

        def reduce_fn():
            value_fn = lambda device_idx: inputs[pid * len(devices) + device_idx]
            per_replica_value = make_per_replica_value(value_fn, devices)
            reduced_values = collective.reduce(options.reduce_op, per_replica_value, per_replica_value, options.communication_options)
            if options.gpus_per_process > 1:
                self.assertIsInstance(reduced_values, value_lib.Mirrored)
            reduced_values = self.as_list(reduced_values)
            self.assertAllEqual(devices, [v.device for v in reduced_values])
            return [ops.convert_to_tensor(v) for v in reduced_values]
        per_replica_expect = [ops.convert_to_tensor(expect)] * len(devices)
        if 'eager' in options.mode:
            got = reduce_fn()
            self.assertAllClose(got, per_replica_expect)
        if 'func_graph' in options.mode:
            got = def_function.function(reduce_fn)()
            self.assertAllClose(got, per_replica_expect)
    get_global_mpr(options.num_processes).run(replica_fn)

Reduce the given `inputs` and verify the output matches `expect`.

Args:
inputs: a list of `Tensor` or `IndexedSlices`, where i-th value will be
fed to i-th replica.
expect: a `Tensor` or `IndexedSlices`. This should be the expected value
for one replica.
options: a `RunOpotions` instance.


def shift(self, time: int) -> 'Interval':
    return Interval((self._begin + time), (self._end + time))

Return a new interval shifted by `time` from self

Args:
time: time to be shifted

Returns:
Interval: interval shifted by `time`


def _create_grad_func(ys, xs, grads, cond_graph, body_graph, name, while_op, maximum_iterations):
    assert len(ys) == len(grads)
    total_iters = while_op.outputs[0]
    counter = constant_op.constant(0, dtype=total_iters.dtype, name='grad_counter')
    body_graph_inputs = object_identity.ObjectIdentitySet(body_graph.inputs)
    body_graph_outputs = object_identity.ObjectIdentitySet(body_graph.outputs)
    args = [counter, maximum_iterations, total_iters] + list(grads)
    grad_func_graph = func_graph_module.func_graph_from_py_func(name, lambda *args: _grad_fn(ys, xs, args, body_graph), args, {}, func_graph=_WhileBodyGradFuncGraph(name, cond_graph, body_graph, maximum_iterations, while_op, body_graph_inputs, body_graph_outputs))
    for external_capture, internal_capture in grad_func_graph.captures:
        if ops.tensor_id(internal_capture) in grad_func_graph.internal_capture_to_output:
            new_output = grad_func_graph.internal_capture_to_output[ops.tensor_id(internal_capture)]
        else:
            raise ValueError(f'Tensor {str(internal_capture)} which captures {str(external_capture)} is in list of internal_captures but not in internal_capture_to_output.')
        grad_func_graph.outputs.append(new_output)
        grad_func_graph.structured_outputs.append(new_output)
    return (grad_func_graph, args)

Builds and returns the gradient FuncGraph of `func_graph` and its args.

The returned grad_func_graph must be called with the returned
args + grad_func_graph.captures.

Args:
ys: A `Tensor` or list of tensors to be differentiated.
xs: A `Tensor` or list of tensors to be used for differentiation.
grads: The incoming grads for `ys`.
cond_graph: FuncGraph for the forward cond function.
body_graph: FuncGraph for the forward body function.
name: Name of the returned gradient function.
while_op: The forward While op.
maximum_iterations: Tensor. The maximum number of iterations.

Returns:
2-tuple of (grad_func_graph, args).


def update(self, data):

        if data.state['Name'] == 'terminated':
            self.delete(auto_commit=False)
            return True

        updated = self.set_property('launch_date', to_utc_date(data.launch_time).isoformat())
        updated |= self.set_property('state', data.state['Name'])
        updated |= self.set_property('instance_type', data.instance_type)
        updated |= self.set_property('public_ip', data.public_ip_address or None)
        updated |= self.set_property('public_dns', data.public_dns_name or None)

        tags = {x['Key']: x['Value'] for x in data.tags or {}}
        existing_tags = {x.key: x for x in self.tags}

        for key, value in list(tags.items()):
            updated |= self.set_tag(key, value)

        for key in list(existing_tags.keys()):
            if key not in tags:
                updated |= self.delete_tag(key)

        return updated

Updates the object information based on live data, if there were any changes made. Any changes will be
automatically applied to the object, but will not be automatically persisted. You must manually call
`db.session.add(instance)` on the object.

Args:
data (:obj:): AWS API Resource object fetched from AWS API

Returns:
True if there were any changes to the object, else false


def create_seq(character, action_metadata, direction, length=8, start=0):
    sprite_start = ((action_metadata[0] + direction) * FRAME_SIZE)
    sprite_end = (((action_metadata[0] + direction) + 1) * FRAME_SIZE)
    sprite_line = character[(sprite_start:sprite_end, ...)]
    frames = tf.stack(tf.split(sprite_line, 13, axis=1))
    frames = frames[0:action_metadata[1]]
    frames = tf.roll(frames, shift=(- start), axis=0)
    frames = tf.tile(frames, [2, 1, 1, 1])
    frames = frames[:length]
    frames = tf.cast(frames, dtype=tf.float32)
    frames.set_shape([length, FRAME_SIZE, FRAME_SIZE, CHANNELS])
    return frames

Creates a sequence.

Args:
character: A character sprite tensor.
action_metadata: An action metadata tuple.
direction: An integer representing the direction, i.e., the row
offset within each action group corresponding to a particular
direction.
length: Desired length of the sequence. If this is longer than
the number of available frames, it will roll over to the
beginning.
start: Index of possible frames at which to start the sequence.

Returns:
A sequence tensor.


def from_filename(filename, require=None):
    with io.open(filename, 'r', encoding='utf-8') as json_file:
        data = json.load(json_file)
        return (data, from_dict(data, require=require))

Reads a Google service account JSON file and returns its parsed info.

Args:
filename (str): The path to the service account .json file.
require (Sequence[str]): List of keys required to be present in the
info.

Returns:
Tuple[ Mapping[str, str], google.auth.crypt.Signer ]: The verified
info and a signer instance.


def get_nowait(self, name, default=_MISSING, autoremove=False):
    self._ensure_declared(name)
    try:
        future = self._data[name]
        if future.done():
            return future.result()
        if (default is _MISSING):
            raise KeyError('Key {} has not been assigned a value and no default given'.format(name))
        return default
    finally:
        if autoremove:
            self._data[name].cancel()
            del self._data[name]

Get the value of a key if it is already set.

This method allows you to check if a key has already been set
without blocking.  If the key has not been set you will get the
default value you pass in or KeyError() if no default is passed.

When this method returns the key is automatically removed unless
you pass ``autoremove=False``.

This method is not a coroutine and does not block.

Args:
name (str): The name of the key to wait on.
default (object): The default value to return if the key
has not yet been set.  Defaults to raising KeyError().
autoremove (bool): Whether to automatically remove the
key when get() returns.

Returns:
object: Whatever was set in the key by :meth:`set`.


def __init__(self, env):

    self._env = env
    self._observation_space = self._env.observation_space
    self._action_space = self._env.action_space

Cache observation and action space to not recompute them repeatedly.

Args:
env: OpenAI Gym environment.


def __init__(self, prefs, g, divPressureValues, kappa=2.0, omega=0.5,
            beta=1.0, mu=1.0,omega2=0.0,
            freeparams=['kappa', 'omega', 'beta', 'mu', 'omega2']):

        _checkParam('omega2',omega2, self.PARAMLIMITS, self.PARAMTYPES)
        self.omega2 = omega2
        self.deltar = scipy.array(divPressureValues.copy())
        assert (max(scipy.absolute(self.deltar))) <= 1, (
                "A scaled deltar value is > 1 or < -1.")
        super(ExpCM_empirical_phi_divpressure, self).__init__(prefs, g,
                kappa=kappa, omega=omega, beta=beta, mu=mu,
                freeparams=freeparams)

Initialize an `ExpCM_empirical_phi_divpressure` object.

Args:
`prefs`, `kappa`, `omega`, `beta`, `mu`, `g`, `freeparams`
Same meaning as for an `ExpCM_empirical_phi`
`divPressureValues`, `omega2`
Meaning described in the main class doc string.


def unwrap(data_type):

    unwrapped_nullable = False
    unwrapped_alias = False
    while is_alias(data_type) or is_nullable_type(data_type):
        if is_nullable_type(data_type):
            unwrapped_nullable = True
        if is_alias(data_type):
            unwrapped_alias = True
        data_type = data_type.data_type
    return data_type, unwrapped_nullable, unwrapped_alias

Convenience method to unwrap all Aliases and Nullables from around a
DataType. This checks for nullable wrapping aliases, as well as aliases
wrapping nullables.

Args:
data_type (DataType): The target to unwrap.

Return:
Tuple[DataType, bool, bool]: The underlying data type; a bool that is
set if a nullable was present; a bool that is set if an alias was
present.


def add(self, command, *args):
    cmd = Command(command, args)
    self.commands.append(cmd)

Add a command to this command file.

Args:
command (str): The command to add
*args (str): The parameters to call the command with


def create(self, ip_dest, next_hop, **kwargs):
    return self._set_route(ip_dest, next_hop, **kwargs)

Create a static route

Args:
ip_dest (string): The ip address of the destination in the
form of A.B.C.D/E
next_hop (string): The next hop interface or ip address
**kwargs['next_hop_ip'] (string): The next hop address on
destination interface
**kwargs['distance'] (string): Administrative distance for this
route
**kwargs['tag'] (string): Route tag
**kwargs['route_name'] (string): Route name

Returns:
True if the operation succeeds, otherwise False.


def spawn(self, function, *args, **kwargs):

        assert self.state != STOPPED, "Can't spawn when process stopped"
        spawned = Spawned(function, args, kwargs)
        self._spawned.append(spawned)
        self._spawn_count += 1

        if self._spawn_count > SPAWN_CLEAR_COUNT:
            self._clear_spawn_list()
        return spawned

Runs the function in a worker thread, returning a Result object

Args:
function: Function to run
args: Positional arguments to run the function with
kwargs: Keyword arguments to run the function with

Returns:
Spawned: Something you can call wait(timeout) on to see when it's
finished executing


def GetSizeHint(self, context=None, **unused_kwargs):

    context_state = getattr(context, 'state', {})

    elements_data_size = self.GetByteSize()
    if elements_data_size:
      return elements_data_size

    try:
      elements_data_size = self._CalculateElementsDataSize(context)
    except errors.MappingError:
      pass

    if elements_data_size is None and self._HasElementsTerminator():
      size_hints = context_state.get('size_hints', {})
      size_hint = size_hints.get(self._data_type_definition.name, None)

      elements_data_size = 0

      if size_hint:
        elements_data_size = size_hint.byte_size

      if not size_hint or not size_hint.is_complete:
        elements_data_size += self._element_data_type_definition.GetByteSize()

    return elements_data_size

Retrieves a hint about the size.

Args:
context (Optional[DataTypeMapContext]): data type map context, used to
determine the size hint.

Returns:
int: hint of the number of bytes needed from the byte stream or None.


def course_blocks(self, course_id, username):
    resp = self.requester.get(urljoin(self.base_url, '/api/courses/v1/blocks/'), params={'depth': 'all', 'username': username, 'course_id': course_id, 'requested_fields': 'children,display_name,id,type,visible_to_staff_only'})
    resp.raise_for_status()
    return Structure(resp.json())

Fetches course blocks.

Args:
course_id (str): An edx course id.
username (str): username of the user to query for (can reveal hidden
modules)

Returns:
Structure


def tuplesorted(items, *keys):
    tuple_keys = [Key(func=(lambda t, i=index, k=key: k.func(t[i])), reverse=key.reverse) for (index, key) in enumerate(keys)]
    return multisorted(items, *tuple_keys)

Sort by tuples with a different key for each item.

Args:
items: An iterable series of sequences (typically tuples)

*keys: Key objects which transform individual elements of
each tuple into sort keys. The zeroth object
transforms the zeroth element of each tuple, the first
key object transforms the first element of each tuple,
and so on.
Returns:
A list of items sorted according to keys.


def GetKeyByPath(self, key_path):

    key_path_upper = key_path.upper()
    if key_path_upper.startswith(self._key_path_prefix_upper):
      relative_key_path = key_path[self._key_path_prefix_length:]
    elif key_path.startswith(definitions.KEY_PATH_SEPARATOR):
      relative_key_path = key_path
      key_path = ''.join([self._key_path_prefix, key_path])
    else:
      return None

    path_segments = key_paths.SplitKeyPath(relative_key_path)
    registry_key = self._root_key
    if not registry_key:
      return None

    for path_segment in path_segments:
      registry_key = registry_key.GetSubkeyByName(path_segment)
      if not registry_key:
        return None

    return registry_key

Retrieves the key for a specific path.

Args:
key_path (str): Windows Registry key path.

Returns:
WinRegistryKey: Windows Registry key or None if not available.


def message_factory(msg_type, msg_types=MESSAGE_TYPES, *args, **kwargs):

    try:
        return msg_types[msg_type.lower()](*args, **kwargs)
    except (UnknownProfileError, InvalidMessageInputError) as e:
        err_exit("Unable to send message: ", e)
    except KeyError:
        raise UnsupportedMessageTypeError(msg_type, msg_types)

Factory function to return the specified message instance.

Args:
:msg_type: (str) the type of message to send, i.e. 'Email'
:msg_types: (str, list, or set) the supported message types
:kwargs: (dict) keywords arguments that are required for the
various message types.  See docstrings for each type.
i.e. help(messages.Email), help(messages.Twilio), etc.


def getPixmap(page, matrix = None, colorspace = csRGB, clip = None,
              alpha = True):

    CheckParent(page)

    cs = colorspace
    if type(colorspace) is str:
        if colorspace.upper() == "GRAY":
            cs = csGRAY
        elif colorspace.upper() == "CMYK":
            cs = csCMYK
        else:
            cs = csRGB
    if cs.n not in (1,3,4):
        raise ValueError("unsupported colorspace")

    dl = page.getDisplayList()
    if clip:
        scissor = Rect(clip)
    else:
        scissor = None
    pix = dl.getPixmap(matrix = matrix,
                       colorspace = cs,
                       alpha = alpha,
                       clip = scissor)
    del dl
    return pix

Create pixmap of page.

Args:
matrix: Matrix for transformation (default: Identity).
colorspace: (str/Colorspace) rgb, rgb, gray - case ignored, default csRGB.
clip: (irect-like) restrict rendering to this area.
alpha: (bool) include alpha channel


def _log_effective_mass_data(data, is_spin_polarized, mass_type='m_e'):
    s = (' ({})'.format(data['spin'].name) if is_spin_polarized else '')
    band_str = 'band {}{}'.format((data['band_id'] + 1), s)
    start_kpoint = data['start_kpoint']
    end_kpoint = data['end_kpoint']
    eff_mass = data['effective_mass']
    kpoint_str = kpt_str.format(k=start_kpoint.frac_coords)
    if start_kpoint.label:
        kpoint_str += ' ({})'.format(start_kpoint.label)
    kpoint_str += ' -> '
    kpoint_str += kpt_str.format(k=end_kpoint.frac_coords)
    if end_kpoint.label:
        kpoint_str += ' ({})'.format(end_kpoint.label)
    logging.info('  {}: {:.3f} | {} | {}'.format(mass_type, eff_mass, band_str, kpoint_str))

Log data about the effective masses and their directions.

Args:
data (dict): The effective mass data. Formatted as a :obj:`dict` with
the keys:

'effective_mass' (:obj:`float`)
The effective mass in units of electron rest mass, :math:`m_0`.

'energies' (:obj:`numpy.ndarray`)
Band eigenvalues in eV.

'band_id' (:obj:`int`)
The index of the band,

'spin' (:obj:`~pymatgen.electronic_structure.core.Spin`)
The spin channel

'start_kpoint' (:obj:`int`)
The index of the k-point at which the band extrema occurs

'end_kpoint' (:obj:`int`)
The k-point towards which the data has been sampled.

is_spin_polarized (bool): Whether the system is spin polarized.


def stations(self, station, limit=10):

        query = {
            'start': 1,
            'S': station + '?',
            'REQ0JourneyStopsB': limit
        }
        rsp = requests.get('http:
        return parse_stations(rsp.text)

Find stations for given queries

Args:
station (str): search query
limit (int): limit number of results


def generate_srt_from_sjson(sjson_subs):

        output = ''

        equal_len = len(sjson_subs['start']) == len(sjson_subs['end']) == len(sjson_subs['text'])
        if not equal_len:
            return output

        for i in range(len(sjson_subs['start'])):
            item = SubRipItem(
                index=i,
                start=SubRipTime(milliseconds=sjson_subs['start'][i]),
                end=SubRipTime(milliseconds=sjson_subs['end'][i]),
                text=sjson_subs['text'][i]
            )
            output += (six.text_type(item))
            output += '\n'
        return output

Generate transcripts from sjson to SubRip (*.srt).

Arguments:
sjson_subs (dict): `sjson` subs.

Returns:
Subtitles in SRT format.


def _process_celeba_config_file(self, file_path):
    with tf.io.gfile.GFile(file_path) as f:
        data_raw = f.read()
    lines = data_raw.split('\n')
    keys = lines[1].strip().split()
    values = {}
    for line in lines[2:(- 1)]:
        row_values = line.strip().split()
        values[row_values[0]] = [int(v) for v in row_values[1:]]
    return (keys, values)

Unpack the celeba config file.

The file starts with the number of lines, and a header.
Afterwards, there is a configuration for each file: one per line.

Args:
file_path: Path to the file with the configuration.

Returns:
keys: names of the attributes
values: map from the file name to the list of attribute values for
this file.


def validate_level_indexes(num_levels, v_level_indexes, h_level_indexes):
    if (num_levels < 1):
        raise ValueError('num_levels {} is less than one'.format(num_levels))
    all_levels = SortedFrozenSet(range(num_levels))
    if ((h_level_indexes is None) and (v_level_indexes is None)):
        v_level_indexes = range(0, num_levels, 2)
        h_level_indexes = range(1, num_levels, 2)
    h_level_set = SortedFrozenSet(h_level_indexes)
    v_level_set = SortedFrozenSet(v_level_indexes)
    if (h_level_indexes is None):
        h_level_indexes = (all_levels - v_level_set)
    if (v_level_indexes is None):
        v_level_indexes = (all_levels - h_level_set)
    if (len(h_level_indexes) != len(h_level_set)):
        raise ValueError('h_level_indexes contains duplicate values')
    if (h_level_set and ((h_level_set[0] < 0) or (h_level_set[(- 1)] >= num_levels))):
        raise ValueError('h_level_indexes contains out of range values')
    if (len(v_level_indexes) != len(v_level_set)):
        raise ValueError('v_level_indexes contains duplicate values')
    if (v_level_set and ((v_level_set[0] < 0) or (v_level_set[(- 1)] >= num_levels))):
        raise ValueError('v_level_indexes contains out of range values')
    unmentioned_levels = ((all_levels - v_level_set) - h_level_set)
    if (len(unmentioned_levels) > 0):
        raise ValueError('v_level_indexes and h_level_indexes do not together include levels {}'.format(', '.join(map(str, unmentioned_levels))))
    if (not h_level_set.isdisjoint(v_level_set)):
        raise ValueError('h_level_indexes and v_level_indexes are not disjoint')
    v_level_indexes = list(v_level_indexes)
    h_level_indexes = list(h_level_indexes)
    return (v_level_indexes, h_level_indexes)

Ensure that v_level_indexes and h_level_indexes are consistent.

Args:
num_levels: The number of levels of keys in the data structure being tabulated.
v_level_indexes: A sequence of level indexes between zero and num_levels for
the vertical axis, or None.
h_level_indexes: A sequence of level indexes between zero and num_levels for for
the horizontal axis, or None.

Returns:
A 2-tuple containing v_level_indexes and h_level_indexes sequences.

Raises:
ValueError: If v_level_indexes contains duplicate values.
ValueError: If h_level_indexes contains duplicate values.
ValueError: If v_level_indexes contains out of range values.
ValueError: If h_level_indexes contains out of range values.
ValueError: If taken together v_level_indexes and h_level_indexes
do not include all levels from zero to up to, but not including
num_levels.
ValueError: If v_level_indexes and h_level_indexes have items in
common.


def gradient_summaries(grad_vars, groups=None, scope='gradients'):

  groups = groups or {r'all': r'.*'}
  grouped = collections.defaultdict(list)
  for grad, var in grad_vars:
    if grad is None:
      continue
    for name, pattern in groups.items():
      if re.match(pattern, var.name):
        name = re.sub(pattern, name, var.name)
        grouped[name].append(grad)
  for name in groups:
    if name not in grouped:
      tf.logging.warn("No variables matching '{}' group.".format(name))
  summaries = []
  for name, grads in grouped.items():
    grads = [tf.reshape(grad, [-1]) for grad in grads]
    grads = tf.concat(grads, 0)
    summaries.append(tf.summary.histogram(scope + '/' + name, grads))
  return tf.summary.merge(summaries)

Create histogram summaries of the gradient.

Summaries can be grouped via regexes matching variables names.

Args:
grad_vars: List of (gradient, variable) tuples as returned by optimizers.
groups: Mapping of name to regex for grouping summaries.
scope: Name scope for this operation.

Returns:
Summary tensor.


def parse_hgnc_line(line, header):

    hgnc_gene = {}
    line = line.rstrip().split('\t')
    raw_info = dict(zip(header, line))

    if 'Withdrawn' in raw_info['status']:
        return hgnc_gene

    hgnc_symbol = raw_info['symbol']
    hgnc_gene['hgnc_symbol'] = hgnc_symbol
    hgnc_gene['hgnc_id'] = int(raw_info['hgnc_id'].split(':')[-1])
    hgnc_gene['description'] = raw_info['name']

    aliases = set([hgnc_symbol, hgnc_symbol.upper()])

    previous_names = raw_info['prev_symbol']
    if previous_names:
        for alias in previous_names.strip('"').split('|'):
            aliases.add(alias)

    alias_symbols = raw_info['alias_symbol']
    if alias_symbols:
        for alias in alias_symbols.strip('"').split('|'):
            aliases.add(alias)

    hgnc_gene['previous_symbols'] = list(aliases)

    hgnc_gene['ensembl_gene_id'] = raw_info.get('ensembl_gene_id')

    omim_id = raw_info.get('omim_id')
    if omim_id:
        hgnc_gene['omim_id'] = int(omim_id.strip('"').split('|')[0])
    else:
        hgnc_gene['omim_id'] = None

    entrez_id = hgnc_gene['entrez_id'] = raw_info.get('entrez_id')
    if entrez_id:
        hgnc_gene['entrez_id'] = int(entrez_id)
    else:
        hgnc_gene['entrez_id'] = None

    ref_seq = raw_info.get('refseq_accession')
    if ref_seq:
        hgnc_gene['ref_seq'] = ref_seq.strip('"').split('|')
    else:
        hgnc_gene['ref_seq'] = []

    uniprot_ids = raw_info.get('uniprot_ids')
    if uniprot_ids:
        hgnc_gene['uniprot_ids'] = uniprot_ids.strip('""').split('|')
    else:
        hgnc_gene['uniprot_ids'] = []

    ucsc_id = raw_info.get('ucsc_id')
    if ucsc_id:
        hgnc_gene['ucsc_id'] = ucsc_id
    else:
        hgnc_gene['ucsc_id'] = None

    vega_id = raw_info.get('vega_id')
    if vega_id:
        hgnc_gene['vega_id'] = vega_id
    else:
        hgnc_gene['vega_id'] = None

    return hgnc_gene

Parse an hgnc formated line

Args:
line(list): A list with hgnc gene info
header(list): A list with the header info

Returns:
hgnc_info(dict): A dictionary with the relevant info


def recompute_grad(fn):

    @functools.wraps(fn)
    def wrapped(*args):
        return _recompute_grad(fn, args)
    return wrapped

Decorator that recomputes the function on the backwards pass.

Args:
fn: a function that takes Tensors (all as positional arguments) and returns
a tuple of Tensors.

Returns:
A wrapped fn that is identical to fn when called, but its activations will
be discarded and recomputed on the backwards pass (i.e. on a call to
tf.gradients).


def make_qs(n, m=None):

    try:
        import sympy
    except ImportError:
        raise ImportError("This function requires sympy. Please install it.")
    if m is None:
        syms = sympy.symbols(" ".join(f"q{i}" for i in range(n)))
        if isinstance(syms, tuple):
            return syms
        else:
            return (syms,)
    syms = sympy.symbols(" ".join(f"q{i}" for i in range(n, m)))
    if isinstance(syms, tuple):
        return syms
    else:
        return (syms,)

Make sympy symbols q0, q1, ...

Args:
n(int), m(int, optional):
If specified both n and m, returns [qn, q(n+1), ..., qm],
Only n is specified, returns[q0, q1, ..., qn].

Return:
tuple(Symbol): Tuple of sympy symbols.


def CheckFile(self, filename):

    result = True
    artifact_reader = reader.YamlArtifactsReader()

    try:
      for artifact_definition in artifact_reader.ReadFile(filename):
        try:
          self._artifact_registry.RegisterDefinition(artifact_definition)
        except KeyError:
          logging.warning(
              'Duplicate artifact definition: {0:s} in file: {1:s}'.format(
                  artifact_definition.name, filename))
          result = False

        artifact_definition_supports_macos = (
            definitions.SUPPORTED_OS_DARWIN in (
                artifact_definition.supported_os))
        artifact_definition_supports_windows = (
            definitions.SUPPORTED_OS_WINDOWS in (
                artifact_definition.supported_os))

        for source in artifact_definition.sources:
          if source.type_indicator in (
              definitions.TYPE_INDICATOR_FILE, definitions.TYPE_INDICATOR_PATH):

            if (definitions.SUPPORTED_OS_DARWIN in source.supported_os or (
                artifact_definition_supports_macos and
                not source.supported_os)):
              if not self._CheckMacOSPaths(
                  filename, artifact_definition, source, source.paths):
                result = False

            elif (artifact_definition_supports_windows or
                  definitions.SUPPORTED_OS_WINDOWS in source.supported_os):
              for path in source.paths:
                if not self._CheckWindowsPath(
                    filename, artifact_definition, source, path):
                  result = False

          elif source.type_indicator == (
              definitions.TYPE_INDICATOR_WINDOWS_REGISTRY_KEY):

            if (filename != self.LEGACY_PATH and
                self._HasDuplicateRegistryKeyPaths(
                    filename, artifact_definition, source)):
              result = False

            for key_path in source.keys:
              if not self._CheckWindowsRegistryKeyPath(
                  filename, artifact_definition, key_path):
                result = False

          elif source.type_indicator == (
              definitions.TYPE_INDICATOR_WINDOWS_REGISTRY_VALUE):

            for key_value_pair in source.key_value_pairs:
              if not self._CheckWindowsRegistryKeyPath(
                  filename, artifact_definition, key_value_pair['key']):
                result = False

    except errors.FormatError as exception:
      logging.warning(
          'Unable to validate file: {0:s} with error: {1!s}'.format(
              filename, exception))
      result = False

    return result

Validates the artifacts definition in a specific file.

Args:
filename (str): name of the artifacts definition file.

Returns:
bool: True if the file contains valid artifacts definitions.


def _AddAttribute(self, attribute):
    if (attribute.identifier in self._attributes):
        raise KeyError('Volume attribute object already set for volume attribute identifier: {0:s}.'.format(attribute.identifier))
    self._attributes[attribute.identifier] = attribute

Adds an attribute.

Args:
attribute (VolumeAttribute): a volume attribute.

Raises:
KeyError: if volume attribute is already set for the corresponding volume
attribute identifier.


def set_colourtemp(self, colourtemp):
    if (not (0 <= colourtemp <= 255)):
        raise ValueError('The colour temperature needs to be between 0 and 255.')
    payload = self.generate_payload(SET, {self.DPS_INDEX_COLOURTEMP: colourtemp})
    data = self._send_receive(payload)
    return data

Set the colour temperature of an rgb bulb.

Args:
colourtemp(int): Value for the colour temperature (0-255).


def _remove_one_redundant_stack_unstack(in_graph_def):
    name_to_input_name, name_to_node, name_to_seq_num = _extract_graph_summary(in_graph_def)
    del name_to_seq_num
    do_generic_pack_unpack = True
    out = _graph_pb2.GraphDef()
    out.library.CopyFrom(in_graph_def.library)
    out.versions.CopyFrom(in_graph_def.versions)
    for n in in_graph_def.node:
        node_name = _tensor_name_base(n.name)
        if not node_name.startswith('OpHintStack') and (not n.op.startswith('Pack')):
            continue
        next_to_visit = [node_name]
        visited = set()
        unpack_nodes = set()
        pack_node = node_name
        matches_pattern = True
        is_hint_created_stack = False
        while next_to_visit:
            current_node_name = next_to_visit[0]
            visited.add(current_node_name)
            del next_to_visit[0]
            node = name_to_node[current_node_name]
            is_op_hint_stack = node.name.startswith('OpHintStack')
            is_op_hint_unstack = node.name.startswith('OpHintUnstack')
            if node.op == 'Identity' or is_op_hint_stack or (do_generic_pack_unpack and node.op == 'Pack'):
                is_hint_created_stack |= is_op_hint_stack
                next_to_visit += [input_node for input_node in name_to_input_name[current_node_name] if input_node not in visited]
            elif is_op_hint_unstack or (do_generic_pack_unpack and node.op == 'Unpack'):
                unpack_nodes.add(node.name)
                is_hint_created_stack &= is_op_hint_unstack
            else:
                matches_pattern = False
                break
            visited.add(node.name)
        if matches_pattern and len(unpack_nodes) == 1:
            pack_node = node_name
            no_external_dependency = True
            for other_n in in_graph_def.node:
                if other_n.name in visited:
                    continue
                for input_tensor in name_to_input_name[other_n.name]:
                    input_op = _tensor_name_base(input_tensor)
                    if input_op in visited and input_op != pack_node:
                        no_external_dependency = False
            if is_hint_created_stack or no_external_dependency:
                end = unpack_nodes.pop()
                end_input = name_to_node[end].input[0]
                for other_n in in_graph_def.node:
                    node_name = _tensor_name_base(other_n.name)
                    if node_name not in visited:
                        new_node = _copy.deepcopy(other_n)
                        new_node.input[:] = [end_input if stripped == pack_node else non_stripped for stripped, non_stripped in zip(name_to_input_name[node_name], new_node.input[:])]
                        out.node.extend([new_node])
                return (out, True)
    return (in_graph_def, False)

Removes a stack->unstack pattern from in_graph_def in a returned graph.

Args:
in_graph_def: Graph def to use as input.

Returns:
Simplified tuple (graph_def, changed_something) where changed_something
is true if anything was done.


def __init__(self, value_type, value):
    self.value_type = value_type
    self.value = value_type(value)

Args:
value_type: Type of the static value
value: Static value


def scatter(indices, values, shape):
    if any_symbolic_tensors((indices, values)):
        return Scatter(shape=shape).symbolic_call(indices, values)
    return backend.core.scatter(indices, values, shape)

Returns a tensor of shape `shape` where `indices` are set to `values`.

At a high level, this operation does `zeros[indices] = updates` and
returns the output. It is equivalent to:

```python
zeros = keras.ops.zeros(shape)
output = keras.ops.scatter_update(zeros, indices, values)
```

Args:
indices: A tensor or list/tuple specifying
indices for the values in `values`.
values: A tensor, the values to be set at `indices`.
shape: Shape of the output tensor.

Example:

>>> indices = [[0, 1], [1, 1]]
>>> values = np.array([1., 1.])
>>> keras.ops.scatter(indices, values, shape=(2, 2))
array([[0., 1.],
[0., 1.]])


def __init__(
      self, processing_configuration, enable_sigsegv_handler=False, **kwargs):

    super(MultiProcessBaseProcess, self).__init__(**kwargs)
    self._debug_output = False
    self._enable_sigsegv_handler = enable_sigsegv_handler
    self._guppy_memory_profiler = None
    self._log_filename = None
    self._memory_profiler = None
    self._original_sigsegv_handler = None

    self._pid = None
    self._processing_configuration = processing_configuration
    self._process_information = None
    self._processing_profiler = None
    self._quiet_mode = False
    self._rpc_server = None
    self._serializers_profiler = None
    self._status_is_running = False
    self._storage_profiler = None
    self._tasks_profiler = None

    if self._processing_configuration:
      self._debug_output = self._processing_configuration.debug_output

      if processing_configuration.log_filename:
        log_path = os.path.dirname(self._processing_configuration.log_filename)
        log_filename = os.path.basename(
            self._processing_configuration.log_filename)
        log_filename = '{0:s}_{1:s}'.format(self._name, log_filename)
        self._log_filename = os.path.join(log_path, log_filename)

    self.rpc_port = multiprocessing.Value('I', 0)

Initializes a process.

Args:
processing_configuration (ProcessingConfiguration): processing
configuration.
enable_sigsegv_handler (Optional[bool]): True if the SIGSEGV handler
should be enabled.
kwargs (dict[str,object]): keyword arguments to pass to
multiprocessing.Process.


def learn(self, state_arr, limit=1000):

        while self.t <= limit:

            next_action_arr = self.extract_possible_actions(state_arr)

            predicted_q_arr = self.__function_approximator.inference_q(next_action_arr)

            reward_value_arr = np.empty((next_action_arr.shape[0], 1))
            next_max_q_arr = np.empty((next_action_arr.shape[0], 1))
            for i in range(reward_value_arr.shape[0]):

                reward_value_arr[i] = self.observe_reward_value(state_arr, next_action_arr[i])

                next_next_action_arr = self.extract_possible_actions(next_action_arr[i])
                next_max_q_arr[i] = self.__function_approximator.inference_q(next_next_action_arr).max()

            action_arr, predicted_q = self.select_action(next_action_arr, predicted_q_arr)

            real_q_arr = self.update_q(
                predicted_q_arr,
                reward_value_arr,
                next_max_q_arr
            )

            real_q = real_q_arr[np.where(predicted_q_arr == predicted_q)[0][0]]
            if self.__q_logs_arr.shape[0] > 0:
                self.__q_logs_arr = np.r_[
                    self.__q_logs_arr,
                    np.array([predicted_q, real_q]).reshape(1, 2)
                ]
            else:
                self.__q_logs_arr = np.array([predicted_q, real_q]).reshape(1, 2)

            self.learn_q(predicted_q_arr, real_q_arr)

            state_arr = self.update_state(state_arr, action_arr)

            self.t += 1

            end_flag = self.check_the_end_flag(state_arr)
            if end_flag is True:
                break

Learning and searching the optimal solution.

Args:
state_arr:      `np.ndarray` of initial state.
limit:          The maximum number of iterative updates based on value iteration algorithms.


def __init__(self, group_key_start=1):
    self._group_key = group_key_start
    self._instance_key_table = {}
    self._lock = threading.Lock()
    self._known_groups = {}

Initializes the object.

Args:
group_key_start: the starting integer of group key.


def _serialize_tensor_like_io(value, debug_path: Optional[str]=None, use_repr: bool=True, path_to_value: Optional[str]=None):
    torch.set_printoptions(sci_mode=True)
    if use_repr:
        value_out = _repr_to_list(value)
    elif path_to_value:
        if not path_to_value.endswith('.safetensors'):
            path_to_value += '.safetensors'
        filepath = os.path.join(debug_path, path_to_value) if debug_path else path_to_value
        save_file({'data': value.contiguous().detach().cpu()}, filepath)
        value_out = f'./{path_to_value}'
    else:
        raise ValueError(f'use_repr={use_repr!r} and path_to_value={path_to_value!r} cannot both be falsy.')
    out = {'shape': repr(value.shape), 'dtype': repr(value.dtype), 'value': value_out}
    if value.dtype in {torch.float16, torch.float32, torch.bfloat16}:
        out.update({'mean': _sanitize_repr_for_diff(repr(value.mean())), 'std': _sanitize_repr_for_diff(repr(value.std())), 'min': _sanitize_repr_for_diff(repr(value.min())), 'max': _sanitize_repr_for_diff(repr(value.max()))})
    return out

Converts Tensors and DTensors to a JSON-serializable dictionary representation.

Args:
value: Any Python object, often including torch Tensors, lists, dicts, etc.
debug_path (`str`, *optional*, defaults to `None`): Directory to dump debug JSON and SafeTensors files.
use_repr (bool, *optional*, defaults to `True`): Whether to save a `repr()`-ized version of the tensor as the
`value` property in the asscoiated FULL_TENSORS.json file, or to store the full tensors in separate
SafeTensors file and store the relative path to that file in the `value` property in the dictionary.
path_to_value (`str`, *optional*, defaults to `None`): The file name for the SafeTensors file holding the full
tensor value if `use_repr=False`.

Returns:
A nested Python structure (list, dict, or sanitized string) that is safe to json.dump.


def _QueryHash(self, nsrl_socket, digest):

    try:
      query = 'QUERY {0:s}\n'.format(digest).encode('ascii')
    except UnicodeDecodeError:
      logger.error('Unable to encode digest: {0!s} to ASCII.'.format(digest))
      return False

    response = None

    try:
      nsrl_socket.sendall(query)
      response = nsrl_socket.recv(self._RECEIVE_BUFFER_SIZE)

    except socket.error as exception:
      logger.error('Unable to query nsrlsvr with error: {0!s}.'.format(
          exception))

    if not response:
      return False

    response = response.strip()

    return response == b'OK 1'

Queries nsrlsvr for a specific hash.

Args:
nsrl_socket (socket._socketobject): socket of connection to nsrlsvr.
digest (str): hash to look up.

Returns:
bool: True if the hash was found, False if not or None on error.


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

        super(JLinkDeviceInfo, self).__init__(*args, **kwargs)
        self.SizeofStruct = ctypes.sizeof(self)

Initializes the instance.

Populates the ``.SizeofStruct`` parameter to the size of the instance.

Args:
self (JLinkDeviceInfo): the ``JLinkDeviceInfo`` instance
args: list of arguments
kwargs: key-word arguments dictionary

Returns:
``None``


def open_channel_url(channel, staging=False):

    return OPEN_CHANNEL_URL.format(domain=DOMAIN, channel_id=channel, access='staging' if staging or STAGE else 'edit')

open_channel_url: returns url to uploaded channel
Args:
channel (str): channel id of uploaded channel
Returns: string url to open channel


def condition_details_has_owner(condition_details, owner):

    if 'subconditions' in condition_details:
        result = condition_details_has_owner(condition_details['subconditions'], owner)
        if result:
            return True

    elif isinstance(condition_details, list):
        for subcondition in condition_details:
            result = condition_details_has_owner(subcondition, owner)
            if result:
                return True
    else:
        if 'public_key' in condition_details \
                and owner == condition_details['public_key']:
            return True
    return False

Check if the public_key of owner is in the condition details
as an Ed25519Fulfillment.public_key

Args:
condition_details (dict): dict with condition details
owner (str): base58 public key of owner

Returns:
bool: True if the public key is found in the condition details, False otherwise


def random( self ):

        j = np.searchsorted( self.cumulative_probabilities(), random.random() )
        return self.jumps[ j ]

Select a jump at random with appropriate relative probabilities.

Args:
None

Returns:
(Jump): The randomly selected Jump.


def get_functions_overridden_by(self, function):

        candidates = [c.functions_not_inherited for c in self.inheritance]
        candidates = [candidate for sublist in candidates for candidate in sublist]
        return [f for f in candidates if f.full_name == function.full_name]

Return the list of functions overriden by the function
Args:
(core.Function)
Returns:
list(core.Function)


def pipe(engine, format, data, renderer=None, formatter=None, quiet=False):
    (cmd, _) = command(engine, format, None, renderer, formatter)
    (out, _) = run(cmd, input=data, capture_output=True, check=True, quiet=quiet)
    return out

Return ``data`` piped through Graphviz ``engine`` into ``format``.

Args:
engine: The layout commmand used for rendering (``'dot'``, ``'neato'``, ...).
format: The output format used for rendering (``'pdf'``, ``'png'``, ...).
data: The binary (encoded) DOT source string to render.
renderer: The output renderer used for rendering (``'cairo'``, ``'gd'``, ...).
formatter: The output formatter used for rendering (``'cairo'``, ``'gd'``, ...).
quiet (bool): Suppress ``stderr`` output.
Returns:
Binary (encoded) stdout of the layout command.
Raises:
ValueError: If ``engine``, ``format``, ``renderer``, or ``formatter`` are not known.
graphviz.RequiredArgumentError: If ``formatter`` is given but ``renderer`` is None.
graphviz.ExecutableNotFound: If the Graphviz executable is not found.
subprocess.CalledProcessError: If the exit status is non-zero.


def create_position_ids_from_input_ids(input_ids, padding_idx):
    mask = input_ids.ne(padding_idx).int()
    incremental_indices = torch.cumsum(mask, dim=1).type_as(mask) * mask
    return incremental_indices.long() + padding_idx

Replace non-padding symbols with their position numbers. Position numbers begin at padding_idx+1. Padding symbols
are ignored. This is modified from fairseq's `utils.make_positions`.

Args:
x: torch.Tensor x:

Returns: torch.Tensor


def get_layer_vis_square(data,
                         allow_heatmap=True,
                         normalize=True,
                         min_img_dim=100,
                         max_width=1200,
                         channel_order='RGB',
                         colormap='jet',
                         ):

    if channel_order not in ['RGB', 'BGR']:
        raise ValueError('Unsupported channel_order %s' % channel_order)
    if data.ndim == 1:

        data = data[:, np.newaxis, np.newaxis]
    elif data.ndim == 2:

        data = data.reshape((data.shape[0] * data.shape[1], 1, 1))
    elif data.ndim == 3:
        if data.shape[0] == 3:

            if channel_order == 'BGR':
                data = data[[2, 1, 0], ...]
            data = data.transpose(1, 2, 0)
            data = data[np.newaxis, ...]
        else:

            pass
    elif data.ndim == 4:
        if data.shape[0] == 3:

            data = data.transpose(1, 2, 3, 0)
            if channel_order == 'BGR':
                data = data[:, :, :, [2, 1, 0]]
        elif data.shape[1] == 3:

            data = data.transpose(0, 2, 3, 1)
            if channel_order == 'BGR':
                data = data[:, :, :, [2, 1, 0]]
        else:

            data = data.reshape((data.shape[0] * data.shape[1], data.shape[2], data.shape[3]))
    else:
        raise RuntimeError('unrecognized data shape: %s' % (data.shape,))

    return get_layer_vis_square_raw(data,
                         allow_heatmap,
                         normalize,
                         min_img_dim,
                         max_width,
                         colormap,
                         )

Returns a vis_square for the given layer data
Arguments:
data -- a np.ndarray
Keyword arguments:
allow_heatmap -- if True, convert single channel images to heatmaps
normalize -- whether to normalize the data when visualizing
max_width -- maximum width for the vis_square


def MakeHistFromList(t, name=''):
    hist = Hist(name=name)
    [hist.Incr(x) for x in t]
    return hist

Makes a histogram from an unsorted sequence of values.

Args:
t: sequence of numbers
name: string name for this histogram

Returns:
Hist object


async def get_ticket(self, request):

        session = await get_session(request)
        return session.get(self.cookie_name)

Called to return the ticket for a request.

Args:
request: aiohttp Request object.

Returns:
A ticket (string like) object, or None if no ticket is available
for the passed request.


def system_repertoire_distance(r1, r2):
    if (config.MEASURE in measures.asymmetric()):
        raise ValueError('{} is asymmetric and cannot be used as a system-level irreducibility measure.'.format(config.MEASURE))
    return measures[config.MEASURE](r1, r2)

Compute the distance between two repertoires of a system.

Args:
r1 (np.ndarray): The first repertoire.
r2 (np.ndarray): The second repertoire.

Returns:
float: The distance between ``r1`` and ``r2``.


def VerifyStructure(self, parser_mediator, line):
    return max([parser.matches(line) for (_, parser) in self.LINE_STRUCTURES])

Verifies that this is an apache access log file.

Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
line (str): line from the text file.

Returns:
bool: True if this is the correct parser, False otherwise.


def __init__(self, napp_path, tpl_path):

        self._napp_path = napp_path
        self._template = tpl_path / 'openapi.yml.template'
        self._api_file = napp_path / 'openapi.yml'

        metadata = napp_path / 'kytos.json'
        self._napp = NApp.create_from_json(metadata)

        self._summary = None
        self._description = None

        self._paths = {}

Instantiate an OpenAPI object.

Args:
napp_path (string): Napp directory
tlp_path (string): File name from template


def build(self, text, matrix, skim_depth=10, d_weights=False):

        for anchor in bar(matrix.keys):

            n1 = text.unstem(anchor)

            pairs = matrix.anchored_pairs(anchor).items()
            for term, weight in list(pairs)[:skim_depth]:

                if d_weights: weight = 1-weight

                n2 = text.unstem(term)

                self.graph.add_edge(n1, n2, weight=float(weight))

1. For each term in the passed matrix, score its KDE similarity with
all other indexed terms.

2. With the ordered stack of similarities in hand, skim off the top X
pairs and add them as edges.

Args:
text (Text): The source text instance.
matrix (Matrix): An indexed term matrix.
skim_depth (int): The number of siblings for each term.
d_weights (bool): If true, give "close" words low edge weights.


def __response_message_descriptor(self, message_type, method_id):

    descriptor = {'200': {'description': 'A successful response'}}

    if message_type != message_types.VoidMessage():
      self.__parser.add_message(message_type.__class__)
      self.__response_schema[method_id] = self.__parser.ref_for_message_type(
          message_type.__class__)
      descriptor['200']['schema'] = {'$ref': '
          self.__response_schema[method_id])}

    return dict(descriptor)

Describes the response.

Args:
message_type: messages.Message class, The message to describe.
method_id: string, Unique method identifier (e.g. 'myapi.items.method')

Returns:
Dictionary describing the response.


def MakeSuiteFromList(t, name=''):

    hist = MakeHistFromList(t)
    d = hist.GetDict()
    return MakeSuiteFromDict(d)

Makes a suite from an unsorted sequence of values.

Args:
t: sequence of numbers
name: string name for this suite

Returns:
Suite object


def get_course_duration(self, obj):

        duration = obj.end - obj.start if obj.start and obj.end else None
        if duration:
            return strfdelta(duration, '{W} weeks {D} days.')
        return ''

Get course's duration as a timedelta.

Arguments:
obj (CourseOverview): CourseOverview object

Returns:
(timedelta): Duration of a course.


def next_trials(self):
    trials = []
    for trial in self._trial_generator:
        if (trial is None):
            return trials
        trials += [trial]
    self._finished = True
    return trials

Provides a batch of Trial objects to be queued into the TrialRunner.

A batch ends when self._trial_generator returns None.

Returns:
trials (list): Returns a list of trials.


def remove(self, *l):

        for a in flatten(l):
            self._remove([self.Inner(a)], self.l)

remove inner from outer

Args:
*l element that is passes into Inner init


def random_data(line_count=1, chars_per_line=80):

    divide_lines = chars_per_line * line_count
    return '\n'.join(random_line_data(chars_per_line) for x in range(int(divide_lines / chars_per_line)))

Function to creates lines of random string data
Args:
line_count: An integer that says how many lines to return
chars_per_line: An integer that says how many characters per line to return

Returns:
A String


def get_response(response: Dict[str, Any]) -> JSONRPCResponse:

    if "error" in response:
        return ErrorResponse(**response)
    return SuccessResponse(**response)

Converts a deserialized response into a JSONRPCResponse object.

The dictionary be either an error or success response, never a notification.

Args:
response: Deserialized response dictionary. We can assume the response is valid
JSON-RPC here, since it passed the jsonschema validation.


def check_list_type(objects, allowed_type, name, allow_none=True):

  if objects is None:
    if not allow_none:
      raise TypeError('%s is None, which is not allowed.' % name)
    return objects
  if not isinstance(objects, (tuple, list)):
    raise TypeError('%s is not a list.' % name)
  if not all(isinstance(i, allowed_type) for i in objects):
    type_list = sorted(list(set(type(obj) for obj in objects)))
    raise TypeError('%s contains types that don\'t match %s: %s' %
                    (name, allowed_type.__name__, type_list))
  return objects

Verify that objects in list are of the allowed type or raise TypeError.

Args:
objects: The list of objects to check.
allowed_type: The allowed type of items in 'settings'.
name: Name of the list of objects, added to the exception.
allow_none: If set, None is also allowed.

Raises:
TypeError: if object is not of the allowed type.

Returns:
The list of objects, for convenient use in assignment.


def __ne__(self, other):

        if isinstance(other, DocumentReference):
            return self._client != other._client or self._path != other._path
        else:
            return NotImplemented

Inequality check against another instance.

Args:
other (Any): A value to compare against.

Returns:
Union[bool, NotImplementedType]: Indicating if the values are
not equal.


def _g(self, z):
    return (np.exp(np.multiply((- self.theta), z)) - 1)

Helper function to solve Frank copula.

This functions encapsulates :math:`g_z = e^{-\\theta z} - 1` used on Frank copulas.

Argument:
z: np.ndarray

Returns:
np.ndarray


def plots_html_page(query_module):
    template = jenv.get_template('analysis.html')
    context = dict(extended=config.EXTENDED)
    cl = client.get_client()
    session = cl.create_session()
    seaborn.set_style('whitegrid')
    decade_df = query_module.decade_query()
    pix_size = pixels_to_inches((600, 400))
    ax = seaborn.lmplot(x='decade', y='area', data=decade_df, size=pix_size[1], aspect=(pix_size[0] / pix_size[1]), scatter_kws={'s': 30, 'alpha': 0.3})
    ax.set(xlabel='Decade', ylabel='Area, m^2')
    context['area_by_decade_svg'] = fig_to_svg(plt.gcf())
    plt.close('all')
    if config.EXTENDED:
        gender_df = query_module.gender_query()
        pix_size = pixels_to_inches((600, 400))
        g = seaborn.FacetGrid(gender_df, hue='gender', margin_titles=True, size=pix_size[1], aspect=(pix_size[0] / pix_size[1]))
        bins = np.linspace(0, 5, 30)
        g.map(plt.hist, 'area', bins=bins, lw=0, alpha=0.5, normed=True)
        g.axes[(0, 0)].set_xlabel('Area, m^2')
        g.axes[(0, 0)].set_ylabel('Percentage of paintings')
        context['area_by_gender_svg'] = fig_to_svg(plt.gcf())
        plt.close('all')
    out_file = path.join(out_dir, 'analysis.html')
    html_content = template.render(**context)
    with open(out_file, 'w') as f:
        f.write(html_content)
    plt.close('all')
    session.close()

Generate analysis output as html page

Args:
query_module (module): module to use for querying data for the
desired model/pipeline variant, e.g. leonardo.standard.queries


def as_objective(obj):

  if isinstance(obj, Objective):
    return obj
  elif callable(obj):
    return obj
  elif isinstance(obj, str):
    layer, n = obj.split(":")
    layer, n = layer.strip(), int(n)
    return channel(layer, n)

Convert obj into Objective class.

Strings of the form "layer:n" become the Objective channel(layer, n).
Objectives are returned unchanged.

Args:
obj: string or Objective.

Returns:
Objective


def add_token(self, token):

        token = self.process_token(token)
        self._token_count.update([token])

Add token to vocabulary.

Args:
token (str): token to add.


def _parse_services(self, service_config: dict, service_name: str, service_list: dict) -> dict:
    for (key, value) in service_list['services'][service_name].items():
        service_config[key] = value
        if ('command' in key):
            key = 'args'
            service_config['args'] = value
            service_config.pop('command')
        if ('ports' in key):
            endpoint_spec = self._parse_ports(value)
            service_config['endpoint_spec'] = endpoint_spec
            service_config.pop('ports')
        if ('volumes' in key):
            volume_spec = self._parse_volumes(value)
            service_config['mounts'] = volume_spec
            service_config.pop('volumes')
        if ('deploy' in key):
            self._parse_deploy(value, service_config)
            service_config.pop('deploy')
        if ('networks' in key):
            network_spec = self._parse_networks(service_list)
            service_config['networks'] = network_spec
        if ('logging' in key):
            self._parse_logging(value, service_config)
            service_config.pop('logging')
        if ('environment' in key):
            service_config['env'] = value
            service_config.pop('environment')
    return service_config

Parse the docker compose file.

Args:
service_config (dict): Service configurations from the compose file
service_name (string): Name of the services
service_list (dict): Service configuration list

Returns:
dict, service specifications extracted from the compose file


def track_storms(storm_objects, times, distance_components, distance_maxima, distance_weights, tracked_objects=None):
    obj_matcher = ObjectMatcher(distance_components, distance_weights, distance_maxima)
    if (tracked_objects is None):
        tracked_objects = []
    for (t, time) in enumerate(times):
        past_time_objects = []
        for obj in tracked_objects:
            if (obj.end_time == (time - obj.step)):
                past_time_objects.append(obj)
        if (len(past_time_objects) == 0):
            tracked_objects.extend(storm_objects[t])
        elif ((len(past_time_objects) > 0) and (len(storm_objects[t]) > 0)):
            assignments = obj_matcher.match_objects(past_time_objects, storm_objects[t], times[(t - 1)], times[t])
            unpaired = list(range(len(storm_objects[t])))
            for pair in assignments:
                past_time_objects[pair[0]].extend(storm_objects[t][pair[1]])
                unpaired.remove(pair[1])
            if (len(unpaired) > 0):
                for up in unpaired:
                    tracked_objects.append(storm_objects[t][up])
    return tracked_objects

Given the output of extract_storm_objects, this method tracks storms through time and merges individual
STObjects into a set of tracks.

Args:
storm_objects: list of list of STObjects that have not been tracked.
times: List of times associated with each set of STObjects
distance_components: list of function objects that make up components of distance function
distance_maxima: array of maximum values for each distance for normalization purposes
distance_weights: weight given to each component of the distance function. Should add to 1.
tracked_objects: List of STObjects that have already been tracked.
Returns:
tracked_objects:


def select_action(self, next_action_arr, next_q_arr):

        key_arr = self.select_action_key(next_action_arr, next_q_arr)
        return next_action_arr[key_arr], next_q_arr[key_arr]

Select action by Q(state, action).

Args:
next_action_arr:        `np.ndarray` of actions.
next_q_arr:             `np.ndarray` of Q-Values.

Retruns:
Tuple(`np.ndarray` of action., Q-Value)


def template_string(task: Task, template: str, jinja_filters: FiltersDict=None, **kwargs: Any) -> Result:
    jinja_filters = (jinja_filters or {} or task.nornir.config.jinja2.filters)
    text = jinja_helper.render_from_string(template=template, host=task.host, jinja_filters=jinja_filters, **kwargs)
    return Result(host=task.host, result=text)

Renders a string with jinja2. All the host data is available in the template

Arguments:
template (string): template string
jinja_filters (dict): jinja filters to enable. Defaults to nornir.config.jinja2.filters
**kwargs: additional data to pass to the template

Returns:
Result object with the following attributes set:
* result (``string``): rendered string


def locate_module(module_id: str, module_type: str = None):

    entry_point = None

    if module_type:
        entry_point = 'ehforwarderbot.%s' % module_type

    module_id = module_id.split('

    if entry_point:
        for i in pkg_resources.iter_entry_points(entry_point):
            if i.name == module_id:
                return i.load()

    return pydoc.locate(module_id)

Locate module by module ID

Args:
module_id: Module ID
module_type: Type of module, one of ``'master'``, ``'slave'`` and ``'middleware'``


def verify_account(self, email_address):

        request = self._get_request()
        resp = request.post(self.ACCOUNT_VERIFY_URL, {
            'email_address': email_address
        })
        return ('account' in resp)

Verify whether a HelloSign Account exists

Args:

email_address (str): Email address for the account to verify

Returns:
True or False


def install_package(self, name, index=None, force=False, update=False):

        cmd = 'install'
        if force:

            cmd = '{0} {1}'.format(cmd, '--force-reinstall')

        if update:

            cmd = '{0} {1}'.format(cmd, '--update')

        if index:

            cmd = '{0} {1}'.format(cmd, '--index-url {0}'.format(index))

        self.pip('{0} {1}'.format(cmd, name))

Install a given package.

Args:
name (str): The package name to install. This can be any valid
pip package specification.
index (str): The URL for a pypi index to use.
force (bool): For the reinstall of packages during updates.
update (bool): Update the package if it is out of date.


def receive(self, event_type, signature, data_str):
    if (not self.validate_signature(signature, data_str)):
        raise HelpScoutSecurityException('The signature provided by this request was invalid.')
    return HelpScoutWebHookEvent(event_type=event_type, record=json.loads(data_str))

Receive a web hook for the event and signature.

Args:
event_type (str): Name of the event that was received (from the
request ``X-HelpScout-Event`` header).
signature (str): The signature that was received, which serves as
authentication (from the request ``X-HelpScout-Signature``
header).
data_str (str): The raw data that was posted by HelpScout
to the web hook. This must be the raw string, because if it
is parsed with JSON it will lose its ordering and not pass
signature validation.

Raises:
helpscout.exceptions.HelpScoutSecurityException: If an invalid
signature is provided, and ``raise_if_invalid`` is ``True``.

Returns:
helpscout.web_hook.WebHookEvent: The authenticated web hook
request.


def get_energy_relax_structure_buckingham(structure, gulp_cmd='gulp', keywords=('optimise', 'conp'), valence_dict=None):
    gio = GulpIO()
    gc = GulpCaller(gulp_cmd)
    gin = gio.buckingham_input(structure, keywords, valence_dict=valence_dict)
    gout = gc.run(gin)
    energy = gio.get_energy(gout)
    relax_structure = gio.get_relaxed_structure(gout)
    return (energy, relax_structure)

Relax a structure and compute the energy using Buckingham potential.

Args:
structure: pymatgen.core.structure.Structure
gulp_cmd: GULP command if not in standard place
keywords: GULP first line keywords
valence_dict: {El: valence}. Needed if the structure is not charge
neutral.


def read(self, length, timeout=None):
    data = b''
    while True:
        if (timeout is not None):
            (rlist, _, _) = select.select([self._fd], [], [], timeout)
            if (self._fd not in rlist):
                break
        try:
            data += os.read(self._fd, (length - len(data)))
        except OSError as e:
            raise SerialError(e.errno, ('Reading serial port: ' + e.strerror))
        if (len(data) == length):
            break
    return data

Read up to `length` number of bytes from the serial port with an
optional timeout.

`timeout` can be positive for a timeout in seconds, 0 for a
non-blocking read, or negative or None for a blocking read that will
block until `length` number of bytes are read. Default is a blocking
read.

For a non-blocking or timeout-bound read, read() may return data whose
length is less than or equal to the requested length.

Args:
length (int): length in bytes.
timeout (int, float, None): timeout duration in seconds.

Returns:
bytes: data read.

Raises:
SerialError: if an I/O or OS error occurs.


def CreateTaskStorage(self, task):

    if self._storage_type != definitions.STORAGE_TYPE_SESSION:
      raise IOError('Unsupported storage type.')

    storage_file_path = self._GetTaskStorageFilePath(task)
    return self._CreateTaskStorageWriter(storage_file_path, task)

Creates a task storage.

The task storage is used to store attributes created by the task.

Args:
task(Task): task.

Returns:
StorageWriter: storage writer.

Raises:
IOError: if the storage type is not supported.
OSError: if the storage type is not supported.


def __init__(self, host: str, port: int, time_to_live: Union[int, timedelta], *, request_coder: Optional[coders.Coder], response_coder: Optional[coders.Coder], kwargs: Optional[Dict[str, Any]]=None, source_caller: Optional[Caller]=None, mode: _RedisMode):
    self.host, self.port = (host, port)
    self.time_to_live = time_to_live
    self.request_coder = request_coder
    self.response_coder = response_coder
    self.kwargs = kwargs
    self.source_caller = source_caller
    self.mode = mode

Args:
host (str): The hostname or IP address of the Redis server.
port (int): The port number of the Redis server.
time_to_live: `(Union[int, timedelta])` The time-to-live (TTL) for
records stored in Redis. Provide an integer (in seconds) or a
`datetime.timedelta` object.
request_coder: (Optional[`coders.Coder`]) coder for requests stored
in Redis.
response_coder: (Optional[`coders.Coder`]) coder for decoding responses
received from Redis.
kwargs: Optional(Dict[str, Any]) additional keyword arguments that
are required to connect to your redis server. Same as `redis.Redis()`.
source_caller: (Optional[`Caller`]): The source caller using this Redis
cache in case of fetching the cache request to store in Redis.
mode: `_RedisMode` An enum type specifying the operational mode of
the `_RedisCaller`.


def get_section_by_name(self, section_name):
    sections = self.unravel_sections(self.get_sections())
    for section in sections:
        if (section['name'] == section_name):
            return (section['groupId'], section)
    return (None, None)

Get a section by its name.

Get a list of sections for a given gradebook,
specified by a gradebookid.

Args:
section_name (str): The section's name.

Raises:
requests.RequestException: Exception connection error
ValueError: Unable to decode response content

Returns:
tuple: tuple of group id, and section dictionary

An example return value is:

.. code-block:: python

(
1327565,
{
u'editable': True,
u'groupId': 1327565,
u'groupingScheme': u'Recitation',
u'members': None,
u'name': u'r01',
u'shortName': u'r01',
u'staffs': None
}
)


def generate_message_doc(message_descriptor, locations, path, name_prefix=''):

    prefixed_name = name_prefix + message_descriptor.name
    print(make_subsection(prefixed_name))
    location = locations[path]
    if location.HasField('leading_comments'):
        print(textwrap.dedent(location.leading_comments))

    row_tuples = []
    for field_index, field in enumerate(message_descriptor.field):
        field_location = locations[path + (2, field_index)]
        if field.type not in [11, 14]:
            type_str = TYPE_TO_STR[field.type]
        else:
            type_str = make_link(field.type_name.lstrip('.'))
        row_tuples.append((
            make_code(field.name),
            field.number,
            type_str,
            LABEL_TO_STR[field.label],
            textwrap.fill(get_comment_from_location(field_location), INFINITY),
        ))
    print_table(('Field', 'Number', 'Type', 'Label', 'Description'),
                row_tuples)

    nested_types = enumerate(message_descriptor.nested_type)
    for index, nested_message_desc in nested_types:
        generate_message_doc(nested_message_desc, locations,
                             path + (3, index),
                             name_prefix=prefixed_name + '.')

    for index, nested_enum_desc in enumerate(message_descriptor.enum_type):
        generate_enum_doc(nested_enum_desc, locations, path + (4, index),
                          name_prefix=prefixed_name + '.')

Generate docs for message and nested messages and enums.

Args:
message_descriptor: descriptor_pb2.DescriptorProto instance for message
to generate docs for.
locations: Dictionary of location paths tuples to
descriptor_pb2.SourceCodeInfo.Location instances.
path: Path tuple to the message definition.
name_prefix: Optional prefix for this message's name.


def cancel(self, job_ids):
    statuses = []
    for job_id in job_ids:
        try:
            self.delete_instance(job_id)
            statuses.append(True)
            self.provisioned_blocks -= 1
        except Exception:
            statuses.append(False)
    return statuses

Cancels the resources identified by the job_ids provided by the user.

Args:
- job_ids (list): A list of job identifiers

Returns:
- A list of status from cancelling the job which can be True, False

Raises:
- ExecutionProviderException or its subclasses


def get_losses_for(self, inputs):
    warnings.warn('`layer.get_losses_for` is deprecated and will be removed in a future version. Please use `layer.losses` instead.')
    return self.losses

Deprecated, do NOT use!

Retrieves losses relevant to a specific set of inputs.

Args:
inputs: Input tensor or list/tuple of input tensors.

Returns:
List of loss tensors of the layer that depend on `inputs`.


def _verify_output(self, submission_type):
    result = True
    if (submission_type == 'defense'):
        try:
            image_classification = load_defense_output(os.path.join(self._sample_output_dir, 'result.csv'))
            expected_keys = [IMAGE_NAME_PATTERN.format(i) for i in range(BATCH_SIZE)]
            if (set(image_classification.keys()) != set(expected_keys)):
                logging.error('Classification results are not saved for all images')
                result = False
        except IOError as e:
            logging.error('Failed to read defense output file: %s', e)
            result = False
    else:
        for i in range(BATCH_SIZE):
            image_filename = os.path.join(self._sample_output_dir, IMAGE_NAME_PATTERN.format(i))
            try:
                img = np.array(Image.open(image_filename).convert('RGB'))
                if (list(img.shape) != [299, 299, 3]):
                    logging.error('Invalid image size %s for image %s', str(img.shape), image_filename)
                    result = False
            except IOError as e:
                result = False
    return result

Verifies correctness of the submission output.

Args:
submission_type: type of the submission

Returns:
True if output looks valid


def dumpfile(item, path):

    with io.open(path, 'wb') as fd:
        fd.write(en(item))

Dump an object to a file by path.

Args:
item (object): The object to serialize.
path (str): The file path to save.

Returns:
None


def squared_hinge(y_true, y_pred):
    y_pred = ops.convert_to_tensor(y_pred)
    y_true = ops.cast(y_true, y_pred.dtype)
    y_true = convert_binary_labels_to_hinge(y_true)
    return ops.mean(ops.square(ops.maximum(1.0 - y_true * y_pred, 0.0)), axis=-1)

Computes the squared hinge loss between `y_true` & `y_pred`.

Formula:

```python
loss = mean(square(maximum(1 - y_true * y_pred, 0)), axis=-1)
```

Args:
y_true: The ground truth values. `y_true` values are expected to be -1
or 1. If binary (0 or 1) labels are provided we will convert them
to -1 or 1 with shape = `[batch_size, d0, .. dN]`.
y_pred: The predicted values with shape = `[batch_size, d0, .. dN]`.

Returns:
Squared hinge loss values with shape = `[batch_size, d0, .. dN-1]`.

Example:

>>> y_true = np.random.choice([-1, 1], size=(2, 3))
>>> y_pred = np.random.random(size=(2, 3))
>>> loss = keras.losses.squared_hinge(y_true, y_pred)


def install(name, dst, capture_error=False):

    if dst not in sys.path:
        sys.path.insert(0, dst)

    entrypoint_type = _entry_point_type.get(dst, name)
    if entrypoint_type is _entry_point_type.PYTHON_PACKAGE:
        _modules.install(dst, capture_error)
    if entrypoint_type is _entry_point_type.COMMAND:
        os.chmod(os.path.join(dst, name), 511)

Install the user provided entry point to be executed as follow:
- add the path to sys path
- if the user entry point is a command, gives exec permissions to the script

Args:
name (str): name of the script or module.
dst (str): path to directory with the script or module.
capture_error (bool): Default false. If True, the running process captures the
stderr, and appends it to the returned Exception message in case of errors.


def _confirm_overwrite(filename):
    message = '{}Would you like to overwrite the contents of {} (y/[n])? '.format(c.Fore.MAGENTA, filename)
    response = raw_input(message)
    response = response.lower()
    if (response in ['y', 'yes']):
        return True
    return False

Confirm overwrite of template files.

Make sure the user would like to continue downloading a file which will overwrite a file
in the current directory.

Args:
filename (str): The name of the file to overwrite.

Returns:
bool: True if the user specifies a "yes" response.


def log_error(self, msg):
    if self.__logger:
        self.__logger.error(msg)
    raise RuntimeError(msg)

Log an error and raise an exception.

Args:
msg: Error message to log.

Raises:
RuntimeError: With the message.


def Process(self, parser_mediator, root_item=None, **kwargs):

    super(DefaultOLECFPlugin, self).Process(parser_mediator, **kwargs)

    if not root_item:
      raise ValueError('Root item not set.')

    if not self._ParseItem(parser_mediator, root_item):
      event_data = OLECFItemEventData()
      event_data.name = root_item.name
      event_data.offset = 0
      event_data.size = root_item.size

      date_time = dfdatetime_semantic_time.SemanticTime('Not set')
      event = time_events.DateTimeValuesEvent(
          date_time, definitions.TIME_DESCRIPTION_CREATION)
      parser_mediator.ProduceEventWithEventData(event, event_data)

Parses an OLECF file.

Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
root_item (Optional[pyolecf.item]): root item of the OLECF file.

Raises:
ValueError: If the root item is not set.