def contains(self, key):

    try:
      self._api.objects_get(self._bucket, key)
    except datalab.utils.RequestException as e:
      if e.status == 404:
        return False
      raise e
    except Exception as e:
      raise e
    return True

Checks if the specified item exists.

Args:
key: the key of the item to lookup.
Returns:
True if the item exists; False otherwise.
Raises:
Exception if there was an error requesting information about the item.


def save_output_in_cache(name, filename, output):
    cache_filename = _get_cache_filename(name, filename)
    with _open_for_write(cache_filename) as f:
        f.write(output)

Saves output in the cache location.

Args:
name: string: name of the linter.
filename: string: path of the filename for which we are saving the output.
output: string: full output (not yet filetered) of the lint command.


def write_chunks(self, data, start, step, count) -> None:

        self.mglo.write_chunks(data, start, step, count)

Split data to count equal parts.

Write the chunks using offsets calculated from start, step and stop.

Args:
data (bytes): The data.
start (int): First offset.
step (int): Offset increment.
count (int): The number of offsets.


def AddWarning(self, warning):
    self._RaiseIfNotWritable()
    warning = self._PrepareAttributeContainer(warning)
    self._warnings.append(warning)
    self.number_of_warnings += 1

Adds a warnings.

Args:
warning (ExtractionWarning): warning.

Raises:
IOError: when the storage writer is closed.
OSError: when the storage writer is closed.


def clear_caches(self, hard=False):
    from rez.package_repository import package_repository_manager
    from rez.utils.memcached import memcached_client
    package_repository_manager.clear_caches()
    if hard:
        with memcached_client() as client:
            client.flush()

Clear all caches in Rez.

Rez caches package contents and iteration during a python session. Thus
newly released packages, and changes to existing packages, may not be
picked up. You need to clear the cache for these changes to become
visible.

Args:
hard (bool): Perform a 'hard' cache clear. This just means that the
memcached cache is also cleared. Generally this is not needed -
this option is for debugging purposes.


def random_set_distribution(rnd: Optional[tcod.random.Random], dist: int) -> None:
    lib.TCOD_random_set_distribution((rnd.random_c if rnd else ffi.NULL), dist)

Change the distribution mode of a random number generator.

Args:
rnd (Optional[Random]): A Random instance, or None to use the default.
dist (int): The distribution mode to use.  Should be DISTRIBUTION_*.


def package_releases(self, project_name):
    try:
        return self._connection.package_releases(project_name)
    except Exception as err:
        raise PyPIClientError(err)

Retrieve the versions from PyPI by ``project_name``.

Args:
project_name (str): The name of the project we wish to retrieve
the versions of.

Returns:
list: Of string versions.


def exists(self, filename):

        result = True
        for repo in self._children:
            if not repo.exists(filename):
                result = False
        return result

Report whether a file exists on all distribution points.

Determines file type by extension.

Args:
filename: Filename you wish to check. (No path! e.g.:
"AdobeFlashPlayer-14.0.0.176.pkg")

Returns:
Boolean


def FindStartOfExpressionInLine(line, endpos, stack):
    i = endpos
    while (i >= 0):
        char = line[i]
        if (char in ')]}'):
            stack.append(char)
        elif (char == '>'):
            if ((i > 0) and ((line[(i - 1)] == '-') or Match('\\s>=\\s', line[(i - 1):]) or Search('\\boperator\\s*$', line[0:i]))):
                i -= 1
            else:
                stack.append('>')
        elif (char == '<'):
            if ((i > 0) and (line[(i - 1)] == '<')):
                i -= 1
            elif (stack and (stack[(- 1)] == '>')):
                stack.pop()
                if (not stack):
                    return (i, None)
        elif (char in '([{'):
            while (stack and (stack[(- 1)] == '>')):
                stack.pop()
            if (not stack):
                return ((- 1), None)
            if (((char == '(') and (stack[(- 1)] == ')')) or ((char == '[') and (stack[(- 1)] == ']')) or ((char == '{') and (stack[(- 1)] == '}'))):
                stack.pop()
                if (not stack):
                    return (i, None)
            else:
                return ((- 1), None)
        elif (char == ';'):
            while (stack and (stack[(- 1)] == '>')):
                stack.pop()
            if (not stack):
                return ((- 1), None)
        i -= 1
    return ((- 1), stack)

Find position at the matching start of current expression.

This is almost the reverse of FindEndOfExpressionInLine, but note
that the input position and returned position differs by 1.

Args:
line: a CleansedLines line.
endpos: start searching at this position.
stack: nesting stack at endpos.

Returns:
On finding matching start: (index at matching start, None)
On finding an unclosed expression: (-1, None)
Otherwise: (-1, new stack at beginning of this line)


def upgrade_name(self, user_):
    if (user_.name_type > self.name_type):
        self.full_name = user_.full_name
        self.first_name = user_.first_name
        self.name_type = user_.name_type
        logger.debug('Added %s name to User "%s": %s', self.name_type.name.lower(), self.full_name, self)

Upgrade name type of this user.

Google Voice participants often first appear with no name at all, and
then get upgraded unpredictably to numbers ("+12125551212") or names.

Args:
user_ (~hangups.user.User): User to upgrade with.


def _CreateDynamicDisplayAdSettings(media_service, opener):

  image = _CreateImage(media_service, opener, 'https:

  logo = {
      'type': 'IMAGE',
      'mediaId': image['mediaId'],
      'xsi_type': 'Image'
  }

  dynamic_settings = {
      'landscapeLogoImage': logo,
      'pricePrefix': 'as low as',
      'promoText': 'Free shipping!',
      'xsi_type': 'DynamicSettings',
  }

  return dynamic_settings

Creates settings for dynamic display ad.

Args:
media_service: a SudsServiceProxy instance for AdWords's MediaService.
opener: an OpenerDirector instance.

Returns:
The dynamic display ad settings.


def run(self, sensor_graph, model):

        for node, inputs, outputs in sensor_graph.iterate_bfs():
            if node.num_inputs != 1:
                continue

            input_a, trigger_a = node.inputs[0]
            if input_a.selector.match_type not in [DataStream.InputType, DataStream.UnbufferedType]:
                continue

            if not isinstance(trigger_a, InputTrigger):
                continue

            if trigger_a.comp_string != u'==':
                continue

            if not trigger_a.use_count:
                continue

            if trigger_a.reference != 1:
                continue

            node.inputs[0] = (input_a, TrueTrigger())

Run this optimization pass on the sensor graph

If necessary, information on the device model being targeted
can be found in the associated model argument.

Args:
sensor_graph (SensorGraph): The sensor graph to optimize
model (DeviceModel): The device model we're using


def ekm_log(logstr, priority=3):
    if (priority <= ekmmeters_log_level):
        dt = datetime.datetime
        stamp = datetime.datetime.now().strftime('%Y-%m-%d %H:%M.%f')
        ekmmeters_log_func(((('[EKM Meter Debug Message: ' + stamp) + '] -> ') + logstr))
    pass

Send string to module level log

Args:
logstr (str): string to print.
priority (int): priority, supports 3 (default) and 4 (special).


def get_uuid_string(low=None, high=None, **x):
    if ((low is None) or (high is None)):
        return None
    x = ''.join([parse_part(low), parse_part(high)])
    return '-'.join([x[:8], x[8:12], x[12:16], x[16:20], x[20:32]])

This method parses a UUID protobuf message type from its component
'high' and 'low' longs into a standard formatted UUID string

Args:
x (dict): containing keys, 'low' and 'high' corresponding to the UUID
protobuf message type

Returns:
str: UUID formatted string


def _IsHelpShortcut(component_trace, remaining_args):
    show_help = False
    if remaining_args:
        target = remaining_args[0]
        if target in ('-h', '--help'):
            component = component_trace.GetResult()
            if inspect.isclass(component) or inspect.isroutine(component):
                fn_spec = inspectutils.GetFullArgSpec(component)
                _, remaining_kwargs, _ = _ParseKeywordArgs(remaining_args, fn_spec)
                show_help = target in remaining_kwargs
            else:
                members = dict(inspect.getmembers(component))
                show_help = target not in members
    if show_help:
        component_trace.show_help = True
        command = f'{component_trace.GetCommand()} -- --help'
        print(f'INFO: Showing help with the command {shlex.quote(command)}.\n', file=sys.stderr)
    return show_help

Determines if the user is trying to access help without '--' separator.

For example, mycmd.py --help instead of mycmd.py -- --help.

Args:
component_trace: (FireTrace) The trace for the Fire command.
remaining_args: List of remaining args that haven't been consumed yet.
Returns:
True if help is requested, False otherwise.


def update(self, **kwargs):

        return self.__class__(self.resource.update(kwargs),
                              self.client,
                              wallet=self.wallet)

Update the Account resource with specified content.

Args:
name (str): Human-readable name for the account

Returns: the updated Account object.


def decrypt(self, ciphertext):

        plaintext = self._rx_tinh.dec(ciphertext)
        if plaintext is None:
            logger.error('Message decryption failure')
            raise s_exc.CryptoErr(mesg='Message decryption failure')

        seqn = next(self._rx_sn)

        sn, mesg = s_msgpack.un(plaintext)
        if sn != seqn:
            logger.error('Message out of sequence: got %d expected %d', sn, seqn)
            raise s_exc.CryptoErr(mesg='Message out of sequence', expected=seqn, got=sn)

        return mesg

Decrypt a message, validating its sequence number is as we expect.

Args:
ciphertext (bytes): The message to decrypt and verify.

Returns:
mesg: A mesg.

Raises:
s_exc.CryptoErr: If the message decryption fails or the sequence number was unexpected.


def mix(self, ca, cb, xb):

        r = (1 - xb) * ca.red + xb * cb.red
        g = (1 - xb) * ca.green + xb * cb.green
        b = (1 - xb) * ca.blue + xb * cb.blue
        a = (1 - xb) * ca.alpha + xb * cb.alpha
        return gdk.RGBA(red=r, green=g, blue=b, alpha=a)

Mix colors.

Args:
ca (gdk.RGBA): first color
cb (gdk.RGBA): second color
xb (float): between 0.0 and 1.0

Return:
gdk.RGBA: linear interpolation between ca and cb,
0 or 1 return the unaltered 1st or 2nd color respectively,
as in CSS.


def prepare_run_debug_urls(self, fetches, feed_dict):

Abstract method to be implemented by concrete subclasses.

This method prepares the run-specific debug URL(s).

Args:
fetches: Same as the `fetches` argument to `Session.run()`
feed_dict: Same as the `feed_dict` argument to `Session.run()`

Returns:
debug_urls: (`str` or `list` of `str`) Debug URLs to be used in
this `Session.run()` call.


def cmvn(vec, variance_normalization=False):

    eps = 2**-30
    rows, cols = vec.shape

    norm = np.mean(vec, axis=0)
    norm_vec = np.tile(norm, (rows, 1))

    mean_subtracted = vec - norm_vec

    if variance_normalization:
        stdev = np.std(mean_subtracted, axis=0)
        stdev_vec = np.tile(stdev, (rows, 1))
        output = mean_subtracted / (stdev_vec + eps)
    else:
        output = mean_subtracted

    return output

This function is aimed to perform global cepstral mean and
variance normalization (CMVN) on input feature vector "vec".
The code assumes that there is one observation per row.

Args:
vec (array): input feature matrix
(size:(num_observation,num_features))
variance_normalization (bool): If the variance
normilization should be performed or not.

Return:
array: The mean(or mean+variance) normalized feature vector.


def max_cation_removal(self):
    oxid_pot = sum([((Element(spec.symbol).max_oxidation_state - spec.oxi_state) * self.comp[spec]) for spec in self.comp if is_redox_active_intercalation(Element(spec.symbol))])
    oxid_limit = (oxid_pot / self.cation_charge)
    num_cation = self.comp[Specie(self.cation.symbol, self.cation_charge)]
    return min(oxid_limit, num_cation)

Maximum number of cation A that can be removed while maintaining charge-balance.

Returns:
integer amount of cation. Depends on cell size (this is an 'extrinsic' function!)


def __init__(self, scope, parent):

        CodeControlFlow.__init__(self, scope, parent, 'if')
        self.else_body = CodeBlock(scope, self, explicit=False)

Constructor for conditionals.

Args:
scope (CodeEntity): The program scope where this object belongs.
parent (CodeEntity): This object's parent in the program tree.


def Get(self, path, follow_symlink = True):

    key = self._Key(path=path, follow_symlink=follow_symlink)
    try:
      return self._cache[key]
    except KeyError:
      value = Stat.FromPath(path, follow_symlink=follow_symlink)
      self._cache[key] = value

      if not follow_symlink and not value.IsSymlink():
        self._cache[self._Key(path=path, follow_symlink=True)] = value

      return value

Stats given file or returns a cached result if available.

Args:
path: A path to the file to perform `stat` on.
follow_symlink: True if `stat` of a symlink should be returned instead of
a file that it points to. For non-symlinks this setting has no effect.

Returns:
`Stat` object corresponding to the given path.


def user_agent(self, text, **kwargs):
    indicator_obj = UserAgent(text, **kwargs)
    return self._indicator(indicator_obj)

Add User Agent data to Batch object

Args:
text (str): The value for this Indicator.
confidence (str, kwargs): The threat confidence for this Indicator.
date_added (str, kwargs): The date timestamp the Indicator was created.
last_modified (str, kwargs): The date timestamp the Indicator was last modified.
rating (str, kwargs): The threat rating for this Indicator.
xid (str, kwargs): The external id for this Indicator.

Returns:
obj: An instance of UserAgent.


def _create_dataset_reader(dataset_creator, filenames, num_parallel_reads=None, name=None):

    def read_one_file(filename):
        filename = ops.convert_to_tensor(filename, dtypes.string, name='filename')
        return dataset_creator(filename)
    if num_parallel_reads is None:
        return filenames.flat_map(read_one_file, name=name)
    elif num_parallel_reads == dataset_ops.AUTOTUNE:
        return filenames.interleave(read_one_file, num_parallel_calls=num_parallel_reads, name=name)
    else:
        return ParallelInterleaveDataset(filenames, read_one_file, cycle_length=num_parallel_reads, block_length=1, sloppy=False, buffer_output_elements=None, prefetch_input_elements=None, name=name)

Creates a dataset that reads the given files using the given reader.

Args:
dataset_creator: A function that takes in a single file name and returns a
dataset.
filenames: A `tf.data.Dataset` containing one or more filenames.
num_parallel_reads: The number of parallel reads we should do.
name: (Optional.) A name for the tf.data operation.

Returns:
A `Dataset` that reads data from `filenames`.


def select_best_paths(examples):

    possible_paths = {}

    for example in examples:
        dom = _create_dom(example["html"])
        matching_elements = _match_elements(dom, example["vars"])

        for key, match in matching_elements.items():
            if key not in possible_paths:
                possible_paths[key] = _collect_paths(match)

    for example in examples:
        dom = _create_dom(example["html"])
        matching_elements = _match_elements(dom, example["vars"])

        for key, paths in possible_paths.items():
            if key not in matching_elements:
                continue

            possible_paths[key] = filter(
                lambda path: _is_working_path(
                    dom,
                    path,
                    matching_elements[key]
                ),
                paths
            )

    priorities = [
        "find",
        "left_neighbour_tag",
        "right_neighbour_tag",
        "wfind",
        "match",
        "Chained"
    ]
    priorities = dict(map(lambda x: (x[1], x[0]), enumerate(priorities)))

    for key in possible_paths.keys():
        possible_paths[key] = list(sorted(
            possible_paths[key],
            key=lambda x: priorities.get(x.call_type, 100)
        ))

    return possible_paths

Process `examples`, select only paths that works for every example. Select
best paths with highest priority.

Args:
examples (dict): Output from :func:`.read_config`.

Returns:
list: List of :class:`.PathCall` and :class:`.Chained` objects.


def section(title, element_list):
    sect = {'Type': 'Section', 'Title': title}
    if isinstance(element_list, list):
        sect['Elements'] = element_list
    else:
        sect['Elements'] = [element_list]
    return sect

Returns a dictionary representing a new section.  Sections
contain a list of elements that are displayed separately from
the global elements on the page.

Args:
title: The title of the section to be displayed
element_list: The list of elements to display within the section

Returns:
A dictionary with metadata specifying that it is to be rendered as
a section containing multiple elements


def send(self, request):
    self._connection.connection.rpush(self._request_key, pickle.dumps(request))
    resp_key = '{}:{}'.format(SIGNAL_REDIS_PREFIX, request.uid)
    while True:
        if (self._connection.polling_time > 0.0):
            sleep(self._connection.polling_time)
        response_data = self._connection.connection.get(resp_key)
        if (response_data is not None):
            self._connection.connection.delete(resp_key)
            break
    return pickle.loads(response_data)

Send a request to the server and wait for its response.

Args:
request (Request): Reference to a request object that is sent to the server.

Returns:
Response: The response from the server to the request.


def _print_if_not_none(obj):
    if obj is not None:
        print(repr(obj))

Print like a notebook: Show the repr if the object is not None.

`_patch_compile` Uses this on the final expression in each cell.

This way the outputs feel like notebooks.

Args:
obj: the object to print.


def HandleExceptionsAndRebuildHttpConnections(retry_args):
    retry_after = None
    if isinstance(retry_args.exc, (http_client.BadStatusLine, http_client.IncompleteRead, http_client.ResponseNotReady)):
        logging.debug('Caught HTTP error %s, retrying: %s', type(retry_args.exc).__name__, retry_args.exc)
    elif isinstance(retry_args.exc, socket.error):
        logging.debug('Caught socket error, retrying: %s', retry_args.exc)
    elif isinstance(retry_args.exc, socket.gaierror):
        logging.debug('Caught socket address error, retrying: %s', retry_args.exc)
    elif isinstance(retry_args.exc, socket.timeout):
        logging.debug('Caught socket timeout error, retrying: %s', retry_args.exc)
    elif isinstance(retry_args.exc, httplib2.ServerNotFoundError):
        logging.debug('Caught server not found error, retrying: %s', retry_args.exc)
    elif isinstance(retry_args.exc, ValueError):
        logging.debug('Response content was invalid (%s), retrying', retry_args.exc)
    elif (isinstance(retry_args.exc, TokenRefreshError) and hasattr(retry_args.exc, 'status') and ((retry_args.exc.status == TOO_MANY_REQUESTS) or (retry_args.exc.status >= 500))):
        logging.debug('Caught transient credential refresh error (%s), retrying', retry_args.exc)
    elif isinstance(retry_args.exc, exceptions.RequestError):
        logging.debug('Request returned no response, retrying')
    elif isinstance(retry_args.exc, exceptions.BadStatusCodeError):
        logging.debug('Response returned status %s, retrying', retry_args.exc.status_code)
    elif isinstance(retry_args.exc, exceptions.RetryAfterError):
        logging.debug('Response returned a retry-after header, retrying')
        retry_after = retry_args.exc.retry_after
    else:
        raise retry_args.exc
    RebuildHttpConnections(retry_args.http)
    logging.debug('Retrying request to url %s after exception %s', retry_args.http_request.url, retry_args.exc)
    time.sleep((retry_after or util.CalculateWaitForRetry(retry_args.num_retries, max_wait=retry_args.max_retry_wait)))

Exception handler for http failures.

This catches known failures and rebuilds the underlying HTTP connections.

Args:
retry_args: An ExceptionRetryArgs tuple.


def __init__(self, saved_model_handler, checkpoint_variables_path,
               check_collections=True):

    check_unique_tags(saved_model_handler.get_tags())
    if check_collections:
      check_collections_are_supported(
          saved_model_handler, _SUPPORTED_COLLECTIONS)
    self._saved_model_handler = saved_model_handler
    self._checkpoint_variables_path = checkpoint_variables_path
    self._module_attachments = {
        tags: saved_model_handler.get_attached_bytes_map(tags)
        for tags in saved_model_handler.get_tags()}

Private constructor.

Args:
saved_model_handler: SavedModelHandler backing up this Module definition.
checkpoint_variables_path: An optional string to the checkpoint where this
Module variables are checkpointed. If given the variables initializers
are overridden to load from it.
check_collections: Whether to check collections are supported.

Raises:
ValueError: if SavedModel contains any unexpected value.


def download_and_verify(url, md5sum, fname=None, chunk_size=1024, clobber=False, verbose=True):
    if (fname is None):
        fname = url.split('/')[(- 1)]
    if ((not clobber) and os.path.isfile(fname)):
        print('Checking existing file to see if MD5 sum matches ...')
        md5_existing = get_md5sum(fname, chunk_size=chunk_size)
        if (md5_existing == md5sum):
            print('File exists. Not overwriting.')
            return fname
    dir_name = os.path.dirname(fname)
    if (not os.path.exists(dir_name)):
        os.makedirs(dir_name)
    sig = hashlib.md5()
    if verbose:
        print('Downloading {} ...'.format(url))
    if (url.startswith('http:
        with contextlib.closing(requests.get(url, stream=True)) as r:
            try:
                r.raise_for_status()
            except requests.exceptions.HTTPError as error:
                print('Error connecting to URL: "{}"'.format(url))
                print(r.text)
                raise error
            with open(fname, 'wb') as f:
                content_length = r.headers.get('content-length')
                if (content_length is not None):
                    content_length = int(content_length)
                bar = FileTransferProgressBar(content_length)
                for (k, chunk) in enumerate(r.iter_content(chunk_size=chunk_size)):
                    f.write(chunk)
                    sig.update(chunk)
                    if verbose:
                        bar_val = (chunk_size * (k + 1))
                        if (content_length is not None):
                            bar_val = min(bar_val, content_length)
                        bar.update(bar_val)
    else:
        with contextlib.closing(urlopen(url)) as r:
            content_length = r.headers.get('content-length')
            if (content_length is not None):
                content_length = int(content_length)
            bar = FileTransferProgressBar(content_length)
            with open(fname, 'wb') as f:
                k = 0
                while True:
                    chunk = r.read(chunk_size)
                    if (not chunk):
                        break
                    f.write(chunk)
                    sig.update(chunk)
                    if verbose:
                        k += 1
                        bar_val = (chunk_size * k)
                        if (content_length is not None):
                            bar_val = min(bar_val, content_length)
                        bar.update(bar_val)
    if (sig.hexdigest() != md5sum):
        raise DownloadError((('The MD5 sum of the downloaded file is incorrect.\n' + '  download: {}\n'.format(sig.hexdigest())) + '  expected: {}\n'.format(md5sum)))
    return fname

Download a file and verify the MD5 sum.

Args:
url (str): The URL to download.
md5sum (str): The expected MD5 sum.
fname (Optional[str]): The filename to store the downloaded file in.
If `None`, infer the filename from the URL. Defaults to `None`.
chunk_size (Optional[int]): Process in chunks of this size (in Bytes).
Defaults to 1024.
clobber (Optional[bool]): If `True`, any existing, identical file will
be overwritten. If `False`, the MD5 sum of any existing file with
the destination filename will be checked. If the MD5 sum does not
match, the existing file will be overwritten. Defaults to `False`.
verbose (Optional[bool]): If `True` (the default), then a progress bar
will be shownd during downloads.

Returns:
The filename the URL was downloaded to.

Raises:
DownloadError: The MD5 sum of the downloaded file does not match
`md5sum`.
requests.exceptions.HTTPError: There was a problem connecting to the
URL.


def _fulfill(self, bits, ignore_nonpromised_bits=False):
    if self._allsubsfulfilled():
        if (not self._components):
            if ignore_nonpromised_bits:
                self._value = bits[self._bitstartselective:(self._bitstartselective + self._bitlength)]
            else:
                self._value = bits[self._bitstart:self._bitend]
        else:
            self._value = self._components[0][0]._value
            for (sub, offset) in self._components[1:]:
                self._value += sub._value
        if (self._parent is not None):
            self._parent._fulfill(None)

Supply the promise with the bits from its associated primitive's execution.

The fulfillment process must walk the promise chain backwards
until it reaches the original promise and can supply the final
value.

The data that comes in can either be all a bit read for every
bit written by the associated primitive, or (if the primitive
supports it), only the bits that are used by promises. The
ignore_nonpromised_bits flag specifies which format the
incoming data is in.

Args:
bits: A bitarray (or compatible) containing the data read from the jtag controller's TDO pin.
ignore_nonpromised_bits: A boolean specifying if only promised bits are being returned (and thus the 2nd index of the promise must be used for slicing the incoming data).


def rotate_texture(texture, rotation, x_offset=0.5, y_offset=0.5):
    (x, y) = texture
    x = (x.copy() - x_offset)
    y = (y.copy() - y_offset)
    angle = np.radians(rotation)
    x_rot = ((x * np.cos(angle)) + (y * np.sin(angle)))
    y_rot = ((x * (- np.sin(angle))) + (y * np.cos(angle)))
    return ((x_rot + x_offset), (y_rot + y_offset))

Rotates the given texture by a given angle.

Args:
texture (texture): the texture to rotate
rotation (float): the angle of rotation in degrees
x_offset (float): the x component of the center of rotation (optional)
y_offset (float): the y component of the center of rotation (optional)

Returns:
texture: A texture.


def dominator_tree_to_dot(self, filename):

        def description(node):
            desc ='{}\n'.format(node)
            desc += 'id: {}'.format(node.node_id)
            if node.dominance_frontier:
                desc += '\ndominance frontier: {}'.format([n.node_id for n in node.dominance_frontier])
            return desc
        with open(filename, 'w', encoding='utf8') as f:
            f.write('digraph{\n')
            for node in self.nodes:
                f.write('{}[label="{}"];\n'.format(node.node_id, description(node)))
                if node.immediate_dominator:
                    f.write('{}->{};\n'.format(node.immediate_dominator.node_id, node.node_id))

            f.write("}\n")

Export the dominator tree of the function to a dot file
Args:
filename (str)


def upload(self, local_fn: str, remote_fn: str='', dont_overwrite: bool=False):
    raise NotImplementedError()

Uploads given file to the task. If remote_fn is not specified, dumps it
into task current directory with the same name.

Args:
local_fn: location of file locally
remote_fn: location of file on task
dont_overwrite: if True, will be no-op if target file exists


def ng(self, wavelength):
    return (self.n(wavelength) - ((wavelength * 1e-09) * self.nDer1(wavelength)))

The group index with respect to wavelength.

Args:
wavelength (float, list, None): The wavelength(s) the group
index will be evaluated at.

Returns:
float, list: The group index at the target wavelength(s).


def get_contact(self, jid):

        try:
            return self.get_contacts()[jid.bare()]
        except KeyError:
            raise ContactNotFound
        except AttributeError:
            raise AttributeError("jid must be an aioxmpp.JID object")

Returns a contact

Args:
jid (aioxmpp.JID): jid of the contact

Returns:
dict: the roster of contacts


def receiveds_not_parsed(receiveds):

    log.debug("Receiveds for this email are not parsed")

    output = []
    counter = Counter()

    for i in receiveds[::-1]:
        j = {"raw": i.strip()}
        j["hop"] = counter["hop"] + 1
        counter["hop"] += 1
        output.append(j)
    else:
        return output

If receiveds are not parsed, makes a new structure with raw
field. It's useful to have the same structure of receiveds
parsed.

Args:
receiveds (list): list of raw receiveds headers

Returns:
a list of not parsed receiveds headers with first hop in first position


def _binary_op(cls,
            x: 'TensorFluent',
            y: 'TensorFluent',
            op: Callable[[tf.Tensor, tf.Tensor], tf.Tensor],
            dtype: tf.DType) -> 'TensorFluent':

        s1 = x.scope.as_list()
        s2 = y.scope.as_list()
        scope, perm1, perm2 = TensorFluentScope.broadcast(s1, s2)
        if x.batch and perm1 != []:
            perm1 = [0] + [p+1 for p in perm1]
        if y.batch and perm2 != []:
            perm2 = [0] + [p+1 for p in perm2]
        x = x.transpose(perm1)
        y = y.transpose(perm2)

        reshape1, reshape2 = TensorFluentShape.broadcast(x.shape, y.shape)
        if reshape1 is not None:
            x = x.reshape(reshape1)
        if reshape2 is not None:
            y = y.reshape(reshape2)

        x = x.cast(dtype)
        y = y.cast(dtype)

        t = op(x.tensor, y.tensor)

        batch = x.batch or y.batch

        return TensorFluent(t, scope, batch=batch)

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

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

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


def exec_resize(self, exec_id, height=None, width=None):

        if isinstance(exec_id, dict):
            exec_id = exec_id.get('Id')

        params = {'h': height, 'w': width}
        url = self._url("/exec/{0}/resize", exec_id)
        res = self._post(url, params=params)
        self._raise_for_status(res)

Resize the tty session used by the specified exec command.

Args:
exec_id (str): ID of the exec instance
height (int): Height of tty session
width (int): Width of tty session


def Process(self, parser_mediator, plist_name, top_level, **kwargs):
    if (not plist_name.startswith(self.PLIST_PATH)):
        raise errors.WrongPlistPlugin(self.NAME, plist_name)
    super(AppleAccountPlugin, self).Process(parser_mediator, plist_name=self.PLIST_PATH, top_level=top_level)

Check if it is a valid Apple account plist file name.

Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
plist_name (str): name of the plist.
top_level (dict[str, object]): plist top-level key.


def to_gzipped_file(data, out=None):

    if not out:
        out = StringIO.StringIO()

    with gzip.GzipFile(fileobj=out, mode="w") as f:
        f.write(data)

    out.seek(0)
    return out

Pack `data` to GZIP and write them to `out`. If `out` is not defined,
:mod:`stringio` is used.

Args:
data (obj): Any packable data (str / unicode / whatever).
out (file, default None): Optional opened file handler.

Returns:
obj: File handler with packed data seeked at the beginning.


def trace_region(self, region_index):
    cmd = enums.JLinkTraceCommand.GET_REGION_PROPS_EX
    region = structs.JLinkTraceRegion()
    region.RegionIndex = int(region_index)
    res = self._dll.JLINKARM_TRACE_Control(cmd, ctypes.byref(region))
    if (res == 1):
        raise errors.JLinkException('Failed to get trace region.')
    return region

Retrieves the properties of a trace region.

Args:
self (JLink): the ``JLink`` instance.
region_index (int): the trace region index.

Returns:
An instance of ``JLinkTraceRegion`` describing the specified region.


def create_dummy_func(func, dependency):
    assert (not building_rtfd())
    if isinstance(dependency, (list, tuple)):
        dependency = ','.join(dependency)

    def _dummy(*args, **kwargs):
        raise ImportError("Cannot import '{}', therefore '{}' is not available".format(dependency, func))
    return _dummy

When a dependency of a function is not available, create a dummy function which throws ImportError when used.

Args:
func (str): name of the function.
dependency (str or list[str]): name(s) of the dependency.

Returns:
function: a function object


def trigger_if_changed(self, obj, old):

        new_value = self.__get__(obj, obj.__class__)
        if not self.property.matches(old, new_value):
            self._trigger(obj, old, new_value)

Send a change event notification if the property is set to a
value is not equal to ``old``.

Args:
obj (HasProps)
The object the property is being set on.

old (obj) :
The previous value of the property to compare

Returns:
None


def get_num_bytes(self, batch: Sequence[numpy.ndarray]) -> int:
    return sum((np_array.itemsize for np_array in batch))

Returns:
The number of bytes of data for a batch.


def _atleast_nd(n, new_shape, *arys):

    def f(x):
        x = asarray(x)
        return asarray(np_utils.cond(np_utils.greater(n, array_ops.rank(x)), lambda: reshape(x, new_shape(n, array_ops.shape(x))), lambda: x))
    arys = list(map(f, arys))
    if len(arys) == 1:
        return arys[0]
    else:
        return arys

Reshape arrays to be at least `n`-dimensional.

Args:
n: The minimal rank.
new_shape: a function that takes `n` and the old shape and returns the
desired new shape.
*arys: ndarray(s) to be reshaped.

Returns:
The reshaped array(s).


def process(self, element, model_state=beam.DoFn.StateParam(BIRCH_MODEL_SPEC), collected_docs_state=beam.DoFn.StateParam(DATA_ITEMS_SPEC), collected_embeddings_state=beam.DoFn.StateParam(EMBEDDINGS_SPEC), update_counter_state=beam.DoFn.StateParam(UPDATE_COUNTER_SPEC), *args, **kwargs):
    clustering = model_state.read() or Birch(n_clusters=None, threshold=0.7)
    collected_documents = collected_docs_state.read() or {}
    collected_embeddings = collected_embeddings_state.read() or {}
    update_counter = update_counter_state.read() or Counter()
    _, doc = element
    doc_id = doc['id']
    embedding_vector = doc['embedding']
    collected_embeddings[doc_id] = embedding_vector
    collected_documents[doc_id] = {'id': doc_id, 'text': doc['text']}
    update_counter = len(collected_documents)
    clustering.partial_fit(np.atleast_2d(embedding_vector))
    cluster_labels = clustering.predict(np.array(list(collected_embeddings.values())))
    model_state.write(clustering)
    collected_docs_state.write(collected_documents)
    collected_embeddings_state.write(collected_embeddings)
    update_counter_state.write(update_counter)
    yield {'labels': cluster_labels, 'docs': collected_documents, 'id': list(collected_embeddings.keys()), 'counter': update_counter}

Takes the embedding of a document and updates the clustering model

Args:
element: The input element to be processed.
model_state: This is the state of the clustering model. It is a stateful parameter,
which means that it will be updated after each call to the process function.
collected_docs_state: This is a stateful dictionary that stores the documents that
have been processed so far.
collected_embeddings_state: This is a dictionary of document IDs and their embeddings.
update_counter_state: This is a counter that keeps track of how many documents have been
processed.


def lresolve(self, path):

        path = make_string_path(path)
        if path == self.root.name:

            return self.root

        path = self._path_without_trailing_separators(path)
        path = self._original_path(path)

        parent_directory, child_name = self.splitpath(path)
        if not parent_directory:
            parent_directory = self.cwd
        try:
            parent_obj = self.resolve(parent_directory)
            assert parent_obj
            if not isinstance(parent_obj, FakeDirectory):
                if not self.is_windows_fs and isinstance(parent_obj, FakeFile):
                    self.raise_io_error(errno.ENOTDIR, path)
                self.raise_io_error(errno.ENOENT, path)
            return parent_obj.get_entry(child_name)
        except KeyError:
            self.raise_io_error(errno.ENOENT, path)

Search for the specified object, resolving only parent links.

This is analogous to the stat/lstat difference.  This resolves links
*to* the object but not of the final object itself.

Args:
path: Specifies target FakeFile object to retrieve.

Returns:
The FakeFile object corresponding to path.

Raises:
IOError: if the object is not found.


def export(export_path, vocabulary, embeddings, num_oov_buckets, preprocess_text):
    tmpdir = tempfile.mkdtemp()
    vocabulary_file = os.path.join(tmpdir, 'tokens.txt')
    with tf.gfile.GFile(vocabulary_file, 'w') as f:
        f.write('\n'.join(vocabulary))
    vocab_size = len(vocabulary)
    embeddings_dim = embeddings.shape[1]
    spec = make_module_spec(vocabulary_file, vocab_size, embeddings_dim, num_oov_buckets, preprocess_text)
    try:
        with tf.Graph().as_default():
            m = hub.Module(spec)
            p_embeddings = tf.placeholder(tf.float32)
            load_embeddings = tf.assign(m.variable_map[EMBEDDINGS_VAR_NAME], p_embeddings)
            with tf.Session() as sess:
                sess.run([load_embeddings], feed_dict={p_embeddings: embeddings})
                m.export(export_path, sess)
    finally:
        shutil.rmtree(tmpdir)

Exports a TF-Hub module that performs embedding lookups.

Args:
export_path: Location to export the module.
vocabulary: List of the N tokens in the vocabulary.
embeddings: Numpy array of shape [N+K,M] the first N rows are the
M dimensional embeddings for the respective tokens and the next K
rows are for the K out-of-vocabulary buckets.
num_oov_buckets: How many out-of-vocabulary buckets to add.
preprocess_text: Whether to preprocess the input tensor by removing
punctuation and splitting on spaces.


def where(self, cond, other, **kwargs):
    assert isinstance(cond, type(self)), 'Must have the same DataManager subclass to perform this operation'
    if isinstance(other, type(self)):

        def where_builder_first_pass(cond, other, **kwargs):
            return cond.where(cond, other, **kwargs)

        def where_builder_second_pass(df, new_other, **kwargs):
            return df.where(new_other.eq(True), new_other, **kwargs)
        first_pass = cond._inter_manager_operations(other, 'left', where_builder_first_pass)
        final_pass = self._inter_manager_operations(first_pass, 'left', where_builder_second_pass)
        return self.__constructor__(final_pass.data, self.index, self.columns)
    else:
        axis = kwargs.get('axis', 0)
        if isinstance(other, pandas.Series):
            other.index = pandas.RangeIndex(len(other.index))

        def where_builder_series(df, cond):
            if (axis == 0):
                df.index = pandas.RangeIndex(len(df.index))
                cond.index = pandas.RangeIndex(len(cond.index))
            else:
                df.columns = pandas.RangeIndex(len(df.columns))
                cond.columns = pandas.RangeIndex(len(cond.columns))
            return df.where(cond, other, **kwargs)
        (reindexed_self, reindexed_cond, a) = self.copartition(axis, cond, 'left', False)
        reindexed_cond = reindexed_cond[0]
        new_data = reindexed_self.inter_data_operation(axis, (lambda l, r: where_builder_series(l, r)), reindexed_cond)
        return self.__constructor__(new_data, self.index, self.columns)

Gets values from this manager where cond is true else from other.

Args:
cond: Condition on which to evaluate values.

Returns:
New DataManager with updated data and index.


def setup_sdk_logging(logfile=None, loglevel=logging.INFO):

    logging.root.setLevel(logging.DEBUG)
    logging.root.addHandler(logging.NullHandler())
    if logfile:
        fh = logging.FileHandler(logfile)
        fh.setLevel(loglevel)
        fh.setFormatter(get_default_log_formatter())
        logging.root.addHandler(fh)

Setup a NullHandler to the root logger. If ``logfile`` is passed,
additionally add a FileHandler in ``loglevel`` level.

Args:
logfile(str): A path to setup a log file.
loglevel(int): :mod:`logging` log level.

Returns:
None


def get_number_of_image_tokens(self, height: int, width: int, images_kwargs=None):
    min_patches = images_kwargs.get('min_patches', None) or self.min_patches
    max_patches = images_kwargs.get('max_patches', None) or self.max_patches
    patch_size = images_kwargs.get('size', None) or self.size
    crop_to_patches = images_kwargs.get('crop_to_patches', None) or self.crop_to_patches
    num_patches = 1
    if crop_to_patches and max_patches > 1:
        num_columns, num_rows = get_optimal_tiled_canvas((height, width), (patch_size['height'], patch_size['width']), min_patches, max_patches)
        num_patches += num_columns * num_rows
    return num_patches

A utility that returns number patches for a given image size.

Args:
height (`int`):
Height of the input image.
width (`int`):
Width of the input image.
images_kwargs (`dict`, *optional*)
Any kwargs to override defaults of the image processor.
Returns:
`int`: Number of patches per image.


def build_input(data, batch_size, dataset, train):

    image_size = 32
    depth = 3
    num_classes = 10 if dataset == "cifar10" else 100
    images, labels = data
    num_samples = images.shape[0] - images.shape[0] % batch_size
    dataset = tf.contrib.data.Dataset.from_tensor_slices(
        (images[:num_samples], labels[:num_samples]))

    def map_train(image, label):
        image = tf.image.resize_image_with_crop_or_pad(image, image_size + 4,
                                                       image_size + 4)
        image = tf.random_crop(image, [image_size, image_size, 3])
        image = tf.image.random_flip_left_right(image)
        image = tf.image.per_image_standardization(image)
        return (image, label)

    def map_test(image, label):
        image = tf.image.resize_image_with_crop_or_pad(image, image_size,
                                                       image_size)
        image = tf.image.per_image_standardization(image)
        return (image, label)

    dataset = dataset.map(map_train if train else map_test)
    dataset = dataset.batch(batch_size)
    dataset = dataset.repeat()
    if train:
        dataset = dataset.shuffle(buffer_size=16 * batch_size)
    images, labels = dataset.make_one_shot_iterator().get_next()
    images = tf.reshape(images, [batch_size, image_size, image_size, depth])
    labels = tf.reshape(labels, [batch_size, 1])
    indices = tf.reshape(tf.range(0, batch_size, 1), [batch_size, 1])
    labels = tf.sparse_to_dense(
        tf.concat([indices, labels], 1),
        [batch_size, num_classes], 1.0, 0.0)

    assert len(images.get_shape()) == 4
    assert images.get_shape()[0] == batch_size
    assert images.get_shape()[-1] == 3
    assert len(labels.get_shape()) == 2
    assert labels.get_shape()[0] == batch_size
    assert labels.get_shape()[1] == num_classes
    if not train:
        tf.summary.image("images", images)
    return images, labels

Build CIFAR image and labels.

Args:
data_path: Filename for cifar10 data.
batch_size: Input batch size.
train: True if we are training and false if we are testing.

Returns:
images: Batches of images of size
[batch_size, image_size, image_size, 3].
labels: Batches of labels of size [batch_size, num_classes].

Raises:
ValueError: When the specified dataset is not supported.


def _GetSerializedAttributeContainerList(self, container_type):

    container_list = self._serialized_attribute_containers.get(
        container_type, None)
    if not container_list:
      container_list = SerializedAttributeContainerList()
      self._serialized_attribute_containers[container_type] = container_list

    return container_list

Retrieves a serialized attribute container list.

Args:
container_type (str): attribute container type.

Returns:
SerializedAttributeContainerList: serialized attribute container list.


def _generate_graph_dicts(self):
    transforms = self._pipeline_proto.components.transforms
    vertex_dict = collections.defaultdict(dict)
    edge_dict = collections.defaultdict(dict)
    self._edge_to_vertex_pairs = collections.defaultdict(list)
    for _, transform in self._top_level_transforms():
        vertex_dict[self._decorate(transform.unique_name)] = {}
        for pcoll_id in transform.outputs.values():
            pcoll_node = None
            if self._pipeline_instrument:
                cacheable = self._pipeline_instrument.cacheables.get(pcoll_id)
                pcoll_node = cacheable.var if cacheable else None
            if not pcoll_node:
                pcoll_node = 'pcoll%s' % (hash(pcoll_id) % 10000)
                vertex_dict[pcoll_node] = {'shape': 'circle', 'label': ''}
            else:
                vertex_dict[pcoll_node] = {'shape': 'circle'}
            if pcoll_id not in self._consumers:
                self._edge_to_vertex_pairs[pcoll_id].append((self._decorate(transform.unique_name), pcoll_node))
                edge_dict[self._decorate(transform.unique_name), pcoll_node] = {}
            else:
                for consumer in self._consumers[pcoll_id]:
                    producer_name = self._decorate(transform.unique_name)
                    consumer_name = self._decorate(transforms[consumer].unique_name)
                    self._edge_to_vertex_pairs[pcoll_id].append((producer_name, pcoll_node))
                    edge_dict[producer_name, pcoll_node] = {}
                    self._edge_to_vertex_pairs[pcoll_id].append((pcoll_node, consumer_name))
                    edge_dict[pcoll_node, consumer_name] = {}
    return (vertex_dict, edge_dict)

From pipeline_proto and other info, generate the graph.

Returns:
vertex_dict: (Dict[str, Dict[str, str]]) vertex mapped to attributes.
edge_dict: (Dict[(str, str), Dict[str, str]]) vertex pair mapped to the
edge's attribute.


def __init__(self, location=None, **kwargs):

    parent = None
    if 'parent' in kwargs:
      parent = kwargs['parent']
      del kwargs['parent']

    if parent:
      raise ValueError('Parent value set.')

    super(FakePathSpec, self).__init__(
        location=location, parent=parent, **kwargs)

Initializes a path specification.

Note that the fake path specification cannot have a parent.

Args:
location (Optional[str]): location e.g. /opt/dfvfs.

Raises:
ValueError: when parent is set.


def nic_a_c(msg):

    tc = typecode(msg)

    if tc != 31:
        raise RuntimeError("%s: Not a status operation message, expecting TC = 31" % msg)

    msgbin = common.hex2bin(msg)
    nic_a = int(msgbin[75])
    nic_c = int(msgbin[51])

    return nic_a, nic_c

Obtain NICa/c, navigation integrity category supplements a and c

Args:
msg (string): 28 bytes hexadecimal message string

Returns:
(int, int): NICa and NICc number (0 or 1)


def _project_single_observable(self, **kwargs: Dict[str, Any]) -> Hist:

        assert isinstance(self.output_attribute_name, str)

        output_hist, projection_name, projection_name_args, = self._project_observable(
            input_key = "single_observable",
            input_observable = self.observable_to_project_from,
            **kwargs,
        )

        output_hist_args = projection_name_args
        output_hist_args.update({
            "output_hist": output_hist,
            "projection_name": projection_name
        })

        output_hist = self.output_hist(**output_hist_args)

        if not hasattr(self.output_observable, self.output_attribute_name):
            raise ValueError(f"Attempted to assign hist to non-existent attribute {self.output_attribute_name} of object {self.output_observable}. Check the attribute name!")

        setattr(self.output_observable, self.output_attribute_name, output_hist)

        return output_hist

Driver function for projecting and storing a single observable.

Args:
kwargs (dict): Additional named args to be passed to projection_name(...) and output_key_name(...)
Returns:
The projected histogram. The histogram is also stored in the output specified by ``output_observable``.


def _auto_kpath_labels(kpt_list):

        label_i = 1
        kpt_labels = {}
        for kpt in chain(*kpt_list):
            if tuple(kpt) in kpt_labels:
                continue
            else:
                kpt_labels.update({tuple(kpt): '({})'.format(label_i)})
                label_i += 1

        kpath_labels = [[kpt_labels[tuple(kpt)] for kpt in segment]
                        for segment in kpt_list]

        return kpath_labels

Get a default set of labels (1), (2), (3)... for a k-point path

Repeated points will be identified and the labels re-used.

Args:
kpt_list (list): Nested list representing k-point path segments,
e.g.::

[[[0., 0., 0.], [0., 0., 0.5], [0., 0.5, 0.5]],
[[0.5, 0.5, 0.], [0., 0., 0.]]]

Returns:
list: Corresponding nested list of labels, e.g.::

[['(1)', '(2)', '(3)'], ['(4)', '(1)']]


def get_high_accuracy_voronoi_nodes(structure, rad_dict, probe_rad=0.1):
    with ScratchDir('.'):
        name = 'temp_zeo1'
        zeo_inp_filename = (name + '.cssr')
        ZeoCssr(structure).write_file(zeo_inp_filename)
        rad_flag = True
        rad_file = (name + '.rad')
        with open(rad_file, 'w+') as fp:
            for el in rad_dict.keys():
                print('{} {}'.format(el, rad_dict[el].real), file=fp)
        atmnet = AtomNetwork.read_from_CSSR(zeo_inp_filename, rad_flag=rad_flag, rad_file=rad_file)
        red_ha_vornet = prune_voronoi_network_close_node(atmnet)
        red_ha_vornet.analyze_writeto_XYZ(name, probe_rad, atmnet)
        voro_out_filename = (name + '_voro.xyz')
        voro_node_mol = ZeoVoronoiXYZ.from_file(voro_out_filename).molecule
    species = (['X'] * len(voro_node_mol.sites))
    coords = []
    prop = []
    for site in voro_node_mol.sites:
        coords.append(list(site.coords))
        prop.append(site.properties['voronoi_radius'])
    lattice = Lattice.from_lengths_and_angles(structure.lattice.abc, structure.lattice.angles)
    vor_node_struct = Structure(lattice, species, coords, coords_are_cartesian=True, to_unit_cell=True, site_properties={'voronoi_radius': prop})
    return vor_node_struct

Analyze the void space in the input structure using high accuracy
voronoi decomposition.
Calls Zeo++ for Voronoi decomposition.

Args:
structure: pymatgen.core.structure.Structure
rad_dict (optional): Dictionary of radii of elements in structure.
If not given, Zeo++ default values are used.
Note: Zeo++ uses atomic radii of elements.
For ionic structures, pass rad_dict with ionic radii
probe_rad (optional): Sampling probe radius in Angstroms.
Default is 0.1 A

Returns:
voronoi nodes as pymatgen.core.structure.Strucutre within the
unit cell defined by the lattice of input structure
voronoi face centers as pymatgen.core.structure.Strucutre within the
unit cell defined by the lattice of input structure


def cost(self):
    total = 0.0
    for (family, rules) in self._excludes.iteritems():
        cost = sum((x.cost() for x in rules))
        if family:
            cost = (cost / float(10))
        total += cost
    return total

Get the approximate cost of this filter.

Cost is the total cost of the exclusion rules in this filter. The cost
of family-specific filters is divided by 10.

Returns:
float: The approximate cost of the filter.


def hardware_info(self, mask=4294967295):
    buf = (ctypes.c_uint32 * 32)()
    res = self._dll.JLINKARM_GetHWInfo(mask, ctypes.byref(buf))
    if (res != 0):
        raise errors.JLinkException(res)
    return list(buf)

Returns a list of 32 integer values corresponding to the bitfields
specifying the power consumption of the target.

The values returned by this function only have significance if the
J-Link is powering the target.

The words, indexed, have the following significance:
0. If ``1``, target is powered via J-Link.
1. Overcurrent bitfield:
0: No overcurrent.
1: Overcurrent happened.  2ms @ 3000mA
2: Overcurrent happened.  10ms @ 1000mA
3: Overcurrent happened.  40ms @ 400mA
2. Power consumption of target (mA).
3. Peak of target power consumption (mA).
4. Peak of target power consumption during J-Link operation (mA).

Args:
self (JLink): the ``JLink`` instance
mask (int): bit mask to decide which hardware information words are
returned (defaults to all the words).

Returns:
List of bitfields specifying different states based on their index
within the list and their value.

Raises:
JLinkException: on hardware error.


def _match_greedily(reaction, compound_formula, score_func):

    uninstantiated_left, uninstantiated_right = _reaction_to_dicts(reaction)

    def compound_instances(uninstantiated):
        instances = []
        for compound, value in iteritems(uninstantiated):
            if value > 0:
                f = compound_formula[compound.name]
                instances.append(_CompoundInstance(compound, value, f))

        for inst in instances:
            uninstantiated[inst.compound] -= 1

        return instances

    def instantiate(uninstantiated, compound):
        n = uninstantiated[compound]
        if n > 0:
            f = compound_formula[compound.name]
            inst = _CompoundInstance(compound, n, f)
            uninstantiated[compound] -= 1
            return inst

        return None

    left = compound_instances(uninstantiated_left)
    right = compound_instances(uninstantiated_right)
    instances = left + right

    pairs = {}
    for inst1, inst2 in product(left, right):
        result = score_func(inst1, inst2)
        if result is not None:
            pairs[inst1, inst2] = result

    def inst_pair_sort_key(entry):

        (inst1, inst2), score = entry
        c1, c2 = inst1.compound, inst2.compound
        same_compound = c1.name == c2.name and c1.compartment != c2.compartment
        return same_compound, score, c1.name, c2.name

    transfer = {}
    while len(pairs) > 0:
        (inst1, inst2), _ = max(iteritems(pairs), key=inst_pair_sort_key)
        common = inst1.formula & inst2.formula

        key = (inst1.compound, inst1.index), (inst2.compound, inst2.index)
        if key not in transfer:
            transfer[key] = Formula()
        transfer[key] |= common

        for inst in (inst1, inst2):
            inst.formula -= common

        to_insert = set()

        inst = instantiate(uninstantiated_left, inst1.compound)
        if inst is not None:
            left.append(inst)
            instances.append(inst)
            to_insert.add(inst)

        inst = instantiate(uninstantiated_right, inst2.compound)
        if inst is not None:
            right.append(inst)
            instances.append(inst)
            to_insert.add(inst)

        to_update = {inst1, inst2}

        to_delete = set()
        for inst1, inst2 in pairs:
            if inst1 in to_update or inst2 in to_update:
                if len(inst1.formula) > 0 and len(inst2.formula) > 0:
                    result = score_func(inst1, inst2)
                    if result is None:
                        to_delete.add((inst1, inst2))
                    else:
                        pairs[inst1, inst2] = result
                else:
                    to_delete.add((inst1, inst2))

        for pair in to_delete:
            del pairs[pair]

        for inst1, inst2 in product(left, right):
            if inst1 in to_insert or inst2 in to_insert:
                result = score_func(inst1, inst2)
                if result is not None:
                    pairs[inst1, inst2] = result

    balance = {}
    for inst in instances:
        if len(inst.formula) > 0:
            key = inst.compound, inst.index
            balance[key] = inst.formula

    return transfer, balance

Match compounds greedily based on score function.

Args:
reaction: Reaction equation :class:`psamm.reaction.Reaction`.
compound_formula: Dictionary mapping compound IDs to
:class:`psamm.formula.Formula`. Formulas must be flattened.
score_func: Function that takes two :class:`_CompoundInstance` and
returns the score.


def set_data(self, data={}, datetime_fields=[]):

        if datetime_fields:
            for field in datetime_fields:
                if field in data:
                    data[field] = self._parse_datetime(data[field])

        super(CampfireEntity, self).set_data(data)

Set entity data

Args:
data (dict): Entity data
datetime_fields (array): Fields that should be parsed as datetimes


def path_new_using_map(
    m: tcod.map.Map, dcost: float = 1.41
) -> tcod.path.AStar:

    return tcod.path.AStar(m, dcost)

Return a new AStar using the given Map.

Args:
m (Map): A Map instance.
dcost (float): The path-finding cost of diagonal movement.
Can be set to 0 to disable diagonal movement.
Returns:
AStar: A new AStar instance.


def _find_furious_yaml(start, checked):
    directory = start
    while (directory not in checked):
        checked.add(directory)
        for fs_yaml_name in FURIOUS_YAML_NAMES:
            yaml_path = os.path.join(directory, fs_yaml_name)
            if os.path.exists(yaml_path):
                return yaml_path
        directory = os.path.dirname(directory)
    return None

Traverse the directory tree identified by start
until a directory already in checked is encountered or the path
of furious.yaml is found.

Checked is present both to make the loop termination easy
to reason about and so the same directories do not get
rechecked

Args:
start: the path to start looking in and work upward from
checked: the set of already checked directories

Returns:
the path of the furious.yaml file or None if it is not found


def insert(self, start_time: int, schedule: ScheduleComponent) -> 'ScheduleComponent':
    return ops.insert(self, start_time, schedule)

Return a new schedule with `schedule` inserted within `self` at `start_time`.

Args:
start_time: time to be inserted
schedule: schedule to be inserted


def limit(self, count):
    return self.__class__(self._parent, projection=self._projection, field_filters=self._field_filters, orders=self._orders, limit=count, offset=self._offset, start_at=self._start_at, end_at=self._end_at)

Limit a query to return a fixed number of results.

If the current query already has a limit set, this will overwrite it.

Args:
count (int): Maximum number of documents to return that match
the query.

Returns:
~.firestore_v1beta1.query.Query: A limited query. Acts as a
copy of the current query, modified with the newly added
"limit" filter.


def move(self, destination):

        self.relocate(destination)
        shutil.move(self.path, destination)
        self._path = destination

Reconfigure and move the virtual environment to another path.

Args:
destination (str): The target path of the virtual environment.

Note:
Unlike `relocate`, this method *will* move the virtual to the
given path.


async def send_message(
        self, request: str, response_expected: bool, **kwargs: Any
    ) -> Response:

        await self.socket.send(request)
        if response_expected:
            response_text = await self.socket.recv()
            return Response(response_text)
        return Response("")

Transport the message to the server and return the response.

Args:
request: The JSON-RPC request string.
response_expected: Whether the request expects a response.

Returns:
A Response object.


def apply_default_prefetch(input_source_or_dataflow, trainer):

    if not isinstance(input_source_or_dataflow, InputSource):

        if type(trainer) == SimpleTrainer:
            input = FeedInput(input_source_or_dataflow)
        else:
            logger.info("Automatically applying QueueInput on the DataFlow.")
            input = QueueInput(input_source_or_dataflow)
    else:
        input = input_source_or_dataflow
    if hasattr(trainer, 'devices'):
        towers = trainer.devices
        if len(towers) > 1:

            assert not isinstance(trainer, SimpleTrainer)

            if isinstance(input, FeedfreeInput) and \
               not isinstance(input, (StagingInput, DummyConstantInput)):
                logger.info("Automatically applying StagingInput on the DataFlow.")
                input = StagingInput(input)
    return input

Apply a set of default rules to make a fast :class:`InputSource`.

Args:
input_source_or_dataflow(InputSource | DataFlow):
trainer (Trainer):

Returns:
InputSource


def send_email_message(self, recipient, subject, html_message, text_message, sender_email, sender_name):
    if (not current_app.testing):
        try:
            from sendgrid.helpers.mail import Email, Content, Substitution, Mail
            from_email = Email(sender_email, sender_name)
            to_email = Email(recipient)
            text_content = Content('text/plain', text_message)
            html_content = Content('text/html', html_message)
            mail = Mail(from_email, subject, to_email, text_content)
            mail.add_content(html_content)
            response = self.sg.client.mail.send.post(request_body=mail.get())
            print(response.status_code)
            print(response.body)
            print(response.headers)
        except ImportError:
            raise ConfigError(SENDGRID_IMPORT_ERROR_MESSAGE)
        except Exception as e:
            print(e)
            print(e.body)
            raise

Send email message via sendgrid-python.

Args:
recipient: Email address or tuple of (Name, Email-address).
subject: Subject line.
html_message: The message body in HTML.
text_message: The message body in plain text.


def get_iso3_country_code(cls, country, use_live=True, exception=None):
    countriesdata = cls.countriesdata(use_live=use_live)
    countryupper = country.upper()
    len_countryupper = len(countryupper)
    if (len_countryupper == 3):
        if (countryupper in countriesdata['countries']):
            return countryupper
    elif (len_countryupper == 2):
        iso3 = countriesdata['iso2iso3'].get(countryupper)
        if (iso3 is not None):
            return iso3
    iso3 = countriesdata['countrynames2iso3'].get(countryupper)
    if (iso3 is not None):
        return iso3
    for candidate in cls.expand_countryname_abbrevs(countryupper):
        iso3 = countriesdata['countrynames2iso3'].get(candidate)
        if (iso3 is not None):
            return iso3
    if (exception is not None):
        raise exception
    return None

Get ISO3 code for cls. Only exact matches or None are returned.

Args:
country (str): Country for which to get ISO3 code
use_live (bool): Try to get use latest data from web rather than file in package. Defaults to True.
exception (Optional[ExceptionUpperBound]): An exception to raise if country not found. Defaults to None.

Returns:
Optional[str]: ISO3 country code or None


def mkdir_p(path_to_dir):

    try:
        os.makedirs(path_to_dir)
    except OSError as e:
        if e.errno == EEXIST and os.path.isdir(path_to_dir):
            logger.debug(
                "Directory %s already exists. Skipping." % path_to_dir)
        else:
            raise e

Make directory(ies).

This function behaves like mkdir -p.

Args:
path_to_dir (:obj:`str`): Path to the directory to make.


def can_file_be_synced_on_current_platform(path):
    can_be_synced = True
    fullpath = os.path.join(os.environ['HOME'], path)
    library_path = os.path.join(os.environ['HOME'], 'Library/')
    if (platform.system() == constants.PLATFORM_LINUX):
        if fullpath.startswith(library_path):
            can_be_synced = False
    return can_be_synced

Check if the given path can be synced locally.

Check if it makes sense to sync the file at the given path on the current
platform.
For now we don't sync any file in the ~/Library folder on GNU/Linux.
There might be other exceptions in the future.

Args:
(str): Path to the file or folder to check. If relative, prepend it
with the home folder.
'abc' becomes '~/abc'
'/def' stays '/def'

Returns:
(bool): True if given file can be synced


def __init__(self, details):

		if not isinstance(details, dict):
			raise ValueError('details in ' + self.__class__.__name__ + '.' + sys._getframe().f_code.co_name + ' must be a dict')

		self._nodes = {}
		self._requires = {}

		for k in tuple(details.keys()):

			if _standardField.match(k):

				if isinstance(details[k], _NodeInterface):

					self._nodes[k] = details[k]

				else:
					self._nodes[k] = _child(details[k])

				del details[k]

		if '__require__' in details:
			self.requires(details['__require__'])
			del details['__require__']

		super(Parent, self).__init__(details, 'Parent')

Constructor

Initialises the instance

Arguments:
details {dict} -- Details describing the type of values allowed for
the node

Raises:
ValueError

Returns:
Parent


def execute(self):

        self.generate_workflow_description()

        if self.batch_values:
            self.id = self.workflow.launch_batch_workflow(self.definition)

        else:
            self.id = self.workflow.launch(self.definition)

        return self.id

Execute the workflow.

Args:
None

Returns:
Workflow_id


def _ParseDLSPageHeader(self, file_object, page_offset):

    page_header_map = self._GetDataTypeMap('dls_page_header')

    try:
      page_header, page_size = self._ReadStructureFromFileObject(
          file_object, page_offset, page_header_map)
    except (ValueError, errors.ParseError) as exception:
      raise errors.ParseError(
          'Unable to parse page header at offset: 0x{0:08x} '
          'with error: {1!s}'.format(page_offset, exception))

    if page_header.signature not in self._DLS_SIGNATURES:
      raise errors.UnableToParseFile(
          'Unsupported page header signature at offset: 0x{0:08x}'.format(
              page_offset))

    return page_header, page_size

Parses a DLS page header from a file-like object.

Args:
file_object (file): file-like object to read the header from.
page_offset (int): offset of the start of the page header, relative
to the start of the file.

Returns:
tuple: containing:

dls_page_header: parsed record structure.
int: header size.

Raises:
ParseError: when the header cannot be parsed.


def parse_signed_request(self, signed_request):

    def _b64_normalize(s):
        appendix = ('=' * (4 - (len(s) % 4)))
        return (s.replace('-', '+').replace('_', '/') + appendix)
    sr = str(signed_request)
    logging.info(('parse signed request: %s' % sr))
    (enc_sig, enc_payload) = sr.split('.', 1)
    sig = base64.b64decode(_b64_normalize(enc_sig))
    data = _parse_json(base64.b64decode(_b64_normalize(enc_payload)))
    if (data['algorithm'] != u'HMAC-SHA256'):
        return None
    expected_sig = hmac.new(self.client_secret, enc_payload, hashlib.sha256).digest()
    if (expected_sig == sig):
        data.user_id = data.uid = data.get('user_id', None)
        data.access_token = data.get('oauth_token', None)
        expires = data.get('expires', None)
        if expires:
            data.expires = data.expires_in = (time.time() + expires)
        return data
    return None

parse signed request when using in-site app.

Returns:
dict object like { 'uid': 12345, 'access_token': 'ABC123XYZ', 'expires': unix-timestamp },
or None if parse failed.


def _parse_response(self, respond):
    mobj = self._max_qubit_error_re.match(respond.text)
    if mobj:
        raise RegisterSizeError('device register size must be <= {}'.format(mobj.group(1)))
    return True

parse text of response for HTTP errors

This parses the text of the response to decide whether to
retry request or raise exception. At the moment this only
detects an exception condition.

Args:
respond (Response): requests.Response object

Returns:
bool: False if the request should be retried, True
if not.

Raises:
RegisterSizeError


def _build_state_value(request_handler, user):
    uri = request_handler.request.url
    token = xsrfutil.generate_token(xsrf_secret_key(), user.user_id(), action_id=str(uri))
    return ((uri + ':') + token)

Composes the value for the 'state' parameter.

Packs the current request URI and an XSRF token into an opaque string that
can be passed to the authentication server via the 'state' parameter.

Args:
request_handler: webapp.RequestHandler, The request.
user: google.appengine.api.users.User, The current user.

Returns:
The state value as a string.


def CreateShoppingCampaign(client, budget_id, merchant_id):
    campaign_service = client.GetService('CampaignService', 'v201809')
    campaign = {'name': ('Shopping campaign
    campaign_operations = [{'operator': 'ADD', 'operand': campaign}]
    campaign = campaign_service.mutate(campaign_operations)['value'][0]
    print(('Campaign with name "%s" and ID "%s" was added.' % (campaign['name'], campaign['id'])))
    return campaign

Creates a shopping campaign with the given budget and merchant IDs.

Args:
client: an AdWordsClient instance.
budget_id: the str ID of the budget to be associated with the shopping
campaign.
merchant_id: the str ID of the merchant account to be associated with the
shopping campaign.

Returns:
The created Shopping Campaign as a sudsobject.


def get_children(decider, root):

    collected = []

    def follow(elem):

        if elem in collected:
            return

        cls = elem.__class__

        if hasattr(cls, '_tx_attrs') and decider(elem):
            collected.append(elem)

        if hasattr(cls, '_tx_attrs'):
            for attr_name, attr in cls._tx_attrs.items():

                if attr.cont:
                    if attr.mult in (MULT_ONE, MULT_OPTIONAL):
                        new_elem = getattr(elem, attr_name)
                        if new_elem:
                            follow(new_elem)
                    else:
                        new_elem_list = getattr(elem, attr_name)
                        if new_elem_list:
                            for new_elem in new_elem_list:
                                follow(new_elem)

    follow(root)
    return collected

Returns a list of all model elements of type 'typ' starting from model
element 'root'. The search process will follow containment links only.
Non-containing references shall not be followed.

Args:
decider(obj): a callable returning True if the object is of interest.
root (model object): Python model object which is the start of the
search process.


def create_summary_metadata(display_name, description):
    content = plugin_data_pb2.ImagePluginData(version=PROTO_VERSION)
    metadata = summary_pb2.SummaryMetadata(display_name=display_name, summary_description=description, plugin_data=summary_pb2.SummaryMetadata.PluginData(plugin_name=PLUGIN_NAME, content=content.SerializeToString()))
    return metadata

Create a `summary_pb2.SummaryMetadata` proto for image plugin data.

Returns:
A `summary_pb2.SummaryMetadata` protobuf object.


def set_pair(self, term1, term2, value, **kwargs):

        key = self.key(term1, term2)
        self.keys.update([term1, term2])
        self.pairs[key] = value

Set the value for a pair of terms.

Args:
term1 (str)
term2 (str)
value (mixed)


def sender(self, jid: str):
    if ((jid is not None) and (not isinstance(jid, str))):
        raise TypeError("'sender' MUST be a string")
    self._sender = (aioxmpp.JID.fromstr(jid) if (jid is not None) else None)

Set jid of the sender

Args:
jid (str): jid of the sender


def make_rc(base_cfg, target_filename, additions=None, replacements=None):
    if (additions is None):
        additions = {}
    if (replacements is None):
        replacements = {}
    new_cfg = six.moves.configparser.ConfigParser()
    new_cfg._sections = copy.deepcopy(base_cfg._sections)
    new_sections = new_cfg._sections
    for (section, opts) in additions.items():
        curr_section = new_sections.setdefault(section, collections.OrderedDict())
        for (opt, opt_val) in opts.items():
            curr_val = curr_section.get(opt)
            if (curr_val is None):
                msg = _MISSING_OPTION_ADDITION.format(opt)
                raise KeyError(msg)
            curr_val = curr_val.rstrip(',')
            opt_val = _transform_opt(opt_val)
            curr_section[opt] = ('%s, %s' % (curr_val, opt_val))
    for (section, opts) in replacements.items():
        curr_section = new_sections.setdefault(section, collections.OrderedDict())
        for (opt, opt_val) in opts.items():
            curr_val = curr_section.get(opt)
            if (curr_val is None):
                msg = _MISSING_OPTION_REPLACE.format(opt)
                print(msg, file=sys.stderr)
            opt_val = _transform_opt(opt_val)
            curr_section[opt] = ('%s' % (opt_val,))
    with open(target_filename, 'w') as file_obj:
        new_cfg.write(file_obj)

Combines a base rc and additions into single file.

Args:
base_cfg (ConfigParser.ConfigParser): The configuration we are
merging into.
target_filename (str): The filename where the new configuration
will be saved.
additions (dict): (Optional) The values added to the configuration.
replacements (dict): (Optional) The wholesale replacements for
the new configuration.

Raises:
KeyError: if one of the additions or replacements does not
already exist in the current config.


def add_edge(self, ind_node, dep_node):

        graph = self.graph
        if ind_node not in graph:
            raise KeyError('independent node %s does not exist' % ind_node)
        if dep_node not in graph:
            raise KeyError('dependent node %s does not exist' % dep_node)
        test_graph = deepcopy(graph)
        test_graph[ind_node].add(dep_node)
        test_dag = DAG()
        test_dag.graph = test_graph
        is_valid, message = test_dag.validate()
        if is_valid:
            graph[ind_node].add(dep_node)
        else:
            raise DAGValidationError(message)

Add an edge (dependency) between the specified nodes.

Args:
ind_node (str): The independent node to add an edge to.
dep_node (str): The dependent node that has a dependency on the
ind_node.

Raises:
KeyError: Either the ind_node, or dep_node do not exist.
DAGValidationError: Raised if the resulting graph is invalid.


def inner_dim_sizes(self):
    return self._inner_dim_sizes

The inner dimension sizes for this shape.

Returns:
A 1-D integer `Tensor`.


def _big_endian_int(bits: np.ndarray) -> int:

    result = 0
    for e in bits:
        result <<= 1
        if e:
            result |= 1
    return result

Returns the big-endian integer specified by the given bits.

For example, [True, False, False, True, False] becomes binary 10010 which
is 18 in decimal.

Args:
bits: Descending bits of the integer, with the 1s bit at the end.

Returns:
The integer.


def reshape_by_blocks(x, x_shape, memory_block_size):

  x = tf.reshape(x, [
      x_shape[0], x_shape[1], x_shape[2]
      memory_block_size, x_shape[3]
  ])
  return x

Reshapes input by splitting its length over blocks of memory_block_size.

Args:
x: a Tensor with shape [batch, heads, length, depth]
x_shape: tf.TensorShape of x.
memory_block_size: Integer which divides length.

Returns:
Tensor with shape
[batch, heads, length // memory_block_size, memory_block_size, depth].


def pearson(logu, name=None):
    with tf.compat.v1.name_scope(name, 'pearson', [logu]):
        logu = tf.convert_to_tensor(value=logu, name='logu')
        return tf.square(tf.math.expm1(logu))

The Pearson Csiszar-function in log-space.

A Csiszar-function is a member of,

```none
F = { f:R_+ to R : f convex }.
```

The Pearson Csiszar-function is:

```none
f(u) = (u - 1)**2
```

Warning: this function makes non-log-space calculations and may therefore be
numerically unstable for `|logu| >> 0`.

Args:
logu: `float`-like `Tensor` representing `log(u)` from above.
name: Python `str` name prefixed to Ops created by this function.

Returns:
pearson_of_u: `float`-like `Tensor` of the Csiszar-function evaluated at
`u = exp(logu)`.


class BufferedSlidingQuantileTracker(BufferedQuantileTracker):

    def __init__(self, window_size, q):
        super().__init__(window_mode=WindowMode.SLIDING, q=q, window_size=window_size)

Sliding window quantile tracker using a sorted list for quantile
calculation.

Warning:
Maintains a sorted list of values within the sliding window to calculate
the specified quantile. Memory consumption is bounded by the window size
but can still be significant for large windows.

Args:
window_size: The size of the sliding window.
q: The quantile to calculate, a float between 0 and 1 (inclusive).


def FormatTime(fmt, stime=None):
    precondition.AssertType(fmt, str)
    precondition.AssertOptionalType(stime, time.struct_time)
    if (stime is None):
        strftime = time.strftime
    else:
        strftime = (lambda fmt: time.strftime(fmt, stime))
    if PY2:
        return strftime(fmt.encode('ascii')).decode('ascii')
    else:
        return strftime(fmt)

A compatibility wrapper for the `strftime` function.

It is guaranteed to always take unicode string as an argument and return an
unicode string as a result.

Args:
fmt: A format string specifying formatting of the output.
stime: A time representation as returned by `gmtime` or `localtime`.

Returns:
A human-readable representation of `stime`.


def post_comment(self, sharekey=None, comment=None):

        endpoint = '/api/sharedfile/{0}/comments'.format(sharekey)

        post_data = {'body': comment}

        data = self._make_request("POST", endpoint=endpoint, data=post_data)
        return Comment.NewFromJSON(data)

Post a comment on behalf of the current user to the
SharedFile with the given sharekey.

Args:
sharekey (str): Sharekey of the SharedFile to which you'd like
to post a comment.
comment (str): Text of the comment to post.

Returns:
Comment object.


def __init__(self, scope, parent, name, result, paren=False):

        CodeExpression.__init__(self, scope, parent, name, result, paren)
        self.full_name = name
        self.arguments = ()
        self.method_of = None
        self.reference = None

Constructor for function calls.

Args:
scope (CodeEntity): The program scope where this object belongs.
parent (CodeEntity): This object's parent in the program tree.
name (str): The name of the function in the program.
result (str): The return type of the expression in the program.

Kwargs:
paren (bool): Whether the expression is enclosed in parentheses.


def to_string(self, verbose=0, title=None, **kwargs):

        from pprint import pformat
        s = pformat(self, **kwargs)
        if title is not None:
            return "\n".join([marquee(title, mark="="), s])
        return s

String representation. kwargs are passed to `pprint.pformat`.

Args:
verbose: Verbosity level
title: Title string.


def update_data(self, index, data):

        datapack = self.built_embed.to_dict()["fields"][index]
        self.built_embed.set_field_at(index, name=datapack["name"], value=data, inline=datapack["inline"])

Updates a particular datapack's data

Args:
index (int): The index of the datapack
data (str): The new value to set for this datapack


def get_rot_mats(self) -> torch.Tensor:
    if self._rot_mats is not None:
        return self._rot_mats
    elif self._quats is not None:
        return quat_to_rot(self._quats)
    else:
        raise ValueError('Both rotations are None')

Returns the underlying rotation as a rotation matrix tensor.

Returns:
The rotation as a rotation matrix tensor


def add_child(self, child):

        if not isinstance(child, Node):
            raise TypeError("child must be a Node")
        self.children.append(child); child.parent = self

Add child to ``Node`` object

Args:
``child`` (``Node``): The child ``Node`` to be added


def project(self, n):

        n = get_uvec(n)
        return self.einsum_sequence([n] * self.rank)

Convenience method for projection of a tensor into a
vector.  Returns the tensor dotted into a unit vector
along the input n.

Args:
n (3x1 array-like): direction to project onto

Returns (float):
scalar value corresponding to the projection of
the tensor into the vector


def dense_message_pass(node_states, edge_matrices):

  batch_size, num_nodes, node_dim = common_layers.shape_list(node_states)

  h_flat = tf.reshape(
      node_states, [batch_size, num_nodes * node_dim, 1], name="h_flat")

  messages = tf.reshape(
      tf.matmul(edge_matrices, h_flat), [batch_size * num_nodes, node_dim],
      name="messages_matmul")

  message_bias = tf.get_variable("message_bias", shape=node_dim)
  messages = messages + message_bias
  messages = tf.reshape(messages, [batch_size, num_nodes, node_dim])
  return messages

Computes a_t from h_{t-1}, see bottom of page 3 in the paper.

Args:
node_states: [B, L, D] tensor (h_{t-1})
edge_matrices (tf.float32): [B, L*D, L*D]

Returns:
messages (tf.float32): [B, L, D] For each pair
of nodes in the graph a message is sent along both the incoming and
outgoing edge.


def ms_to_str(ms, fractions=False):

    sgn = "-" if ms < 0 else ""
    h, m, s, ms = ms_to_times(abs(ms))
    if fractions:
        return sgn + "{:01d}:{:02d}:{:02d}.{:03d}".format(h, m, s, ms)
    else:
        return sgn + "{:01d}:{:02d}:{:02d}".format(h, m, s)

Prettyprint milliseconds to [-]H:MM:SS[.mmm]

Handles huge and/or negative times. Non-negative times with ``fractions=True``
are matched by :data:`pysubs2.time.TIMESTAMP`.

Arguments:
ms: Number of milliseconds (int, float or other numeric class).
fractions: Whether to print up to millisecond precision.

Returns:
str


def correct_dihedral(self, construction_table,
                         use_lookup=None):

        if use_lookup is None:
            use_lookup = settings['defaults']['use_lookup']

        problem_index = self.check_dihedral(construction_table)
        bond_dict = self._give_val_sorted_bond_dict(use_lookup=use_lookup)
        c_table = construction_table.copy()
        for i in problem_index:
            loc_i = c_table.index.get_loc(i)
            b, a, problem_d = c_table.loc[i, ['b', 'a', 'd']]
            try:
                c_table.loc[i, 'd'] = (bond_dict[a] - {b, a, problem_d}
                                       - set(c_table.index[loc_i:]))[0]
            except IndexError:
                visited = set(c_table.index[loc_i:]) | {b, a, problem_d}
                tmp_bond_dict = OrderedDict([(j, bond_dict[j] - visited)
                                             for j in bond_dict[problem_d]])
                found = False
                while tmp_bond_dict and not found:
                    new_tmp_bond_dict = OrderedDict()
                    for new_d in tmp_bond_dict:
                        if new_d in visited:
                            continue
                        angle = self.get_angle_degrees([b, a, new_d])[0]
                        if 5 < angle < 175:
                            found = True
                            c_table.loc[i, 'd'] = new_d
                        else:
                            visited.add(new_d)
                            for j in tmp_bond_dict[new_d]:
                                new_tmp_bond_dict[j] = bond_dict[j] - visited
                    tmp_bond_dict = new_tmp_bond_dict
                if not found:
                    other_atoms = c_table.index[:loc_i].difference({b, a})
                    molecule = self.get_distance_to(origin=i, sort=True,
                                                    other_atoms=other_atoms)
                    k = 0
                    while not found and k < len(molecule):
                        new_d = molecule.index[k]
                        angle = self.get_angle_degrees([b, a, new_d])[0]
                        if 5 < angle < 175:
                            found = True
                            c_table.loc[i, 'd'] = new_d
                        k = k + 1
                    if not found:
                        message = ('The atom with index {} has no possibility '
                                   'to get nonlinear reference atoms'.format)
                        raise UndefinedCoordinateSystem(message(i))
        return c_table

Reindexe the dihedral defining atom if linear reference is used.

Uses :meth:`~Cartesian.check_dihedral` to obtain the problematic
indices.

Args:
construction_table (pd.DataFrame):
use_lookup (bool): Use a lookup variable for
:meth:`~chemcoord.Cartesian.get_bonds`. The default is
specified in ``settings['defaults']['use_lookup']``

Returns:
pd.DataFrame: Appropiately renamed construction table.


def init_with_validation(cls, function, arguments):
    func = FUNCTIONS[function]
    args = []
    for (arg, arg_type) in zip(arguments, func.args):
        if arg_type.values:
            if isinstance(arg, six.string_types):
                try:
                    args.append([arg_type.values[arg]])
                except KeyError:
                    raise KeyError(('Unknown argument value: %s, valid values: %s' % (arg, [v.name for v in arg_type.values])))
            else:
                if isinstance(arg, (list, tuple)):
                    arg = arg[0]
                try:
                    args.append([arg_type.values(arg)])
                except ValueError:
                    raise ValueError(('Unknown argument value: %s, valid values: %s' % (arg, list(arg_type.values))))
        elif isinstance(arg, int):
            args.append([arg])
        else:
            args.append(list(arg))
    return cls(func.id, args)

Return a `FunctionCall` given some validation for the function and args.

Args:
function: A function name or id, to be converted into a function id enum.
arguments: An iterable of function arguments. Arguments that are enum
types can be passed by name. Arguments that only take one value (ie
not a point) don't need to be wrapped in a list.

Returns:
A new `FunctionCall` instance.

Raises:
KeyError: if the enum name doesn't exist.
ValueError: if the enum id doesn't exist.


def get_release_date(pdb_id):
    pdb_id = pdb_id.upper()
    if (pdb_id not in _property_table().index):
        raise ValueError('PDB ID not in property table')
    else:
        release_date = _property_table().ix[(pdb_id, 'releaseDate')]
        if pd.isnull(release_date):
            log.debug('{}: no release date available')
            release_date = None
    return release_date

Quick way to get the release date of a PDB ID using the table of results from the REST service

Returns None if the release date is not available.

Returns:
str: Organism of a PDB ID


def GetConsensusAddress(validators):

        vlen = len(validators)
        script = Contract.CreateMultiSigRedeemScript(vlen - int((vlen - 1) / 3), validators)
        return Crypto.ToScriptHash(script)

Get the script hash of the consensus node.

Args:
validators (list): of Ellipticcurve.ECPoint's

Returns:
UInt160:


def fit(self, mol1, mol2):
    return (self.get_rmsd(mol1, mol2) < self._tolerance)

Fit two molecules.

Args:
mol1: First molecule. OpenBabel OBMol or pymatgen Molecule object
mol2: Second molecule. OpenBabel OBMol or pymatgen Molecule object

Returns:
A boolean value indicates whether two molecules are the same.


def get_nsx_controller(self):

        urn = "urn:brocade.com:mgmt:brocade-tunnels"
        config = ET.Element("config")
        ET.SubElement(config, "nsx-controller", xmlns=urn)
        output = self._callback(config, handler='get_config')
        result = {}
        element = ET.fromstring(str(output))
        for controller in element.iter('{%s}nsx-controller'%urn):
            result['name'] = controller.find('{%s}name'%urn).text
            isactivate = controller.find('{%s}activate'%urn)
            if isactivate is None:
                result['activate'] = False
            else:
                result['activate'] = True
            connection = controller.find('{%s}connection-addr'%urn)
            if connection is None:
                result['port'] = None
                result['address'] = None
            else:
                result['port'] = connection.find('{%s}port'%urn).text
                address = connection.find('{%s}address'%urn)
                if address is None:
                    result['address'] = None
                else:
                    result['address'] = address.text

        return result

Get/Set nsx controller name

Args:
name: (str) :   Name of the nsx-controller
callback (function): A function executed upon completion of the
method.

Returns: Return dictionary containing nsx-controller information.
Returns blank dict if no nsx-controller is configured.

Raises: None


def GetRelativePathForPathSpec(cls, path_spec, mount_path=None):
    if (not path_spec):
        return None
    location = getattr(path_spec, 'location', None)
    if ((not location) and path_spec.HasParent()):
        location = getattr(path_spec.parent, 'location', None)
    if (not location):
        return None
    data_stream = getattr(path_spec, 'data_stream', None)
    if data_stream:
        location = '{0:s}:{1:s}'.format(location, data_stream)
    if (path_spec.type_indicator != dfvfs_definitions.TYPE_INDICATOR_OS):
        return location
    if (mount_path and location.startswith(mount_path)):
        location = location[len(mount_path):]
    return location

Retrieves the relative path of a path specification.

If a mount path is defined the path will be relative to the mount point,
otherwise the path is relative to the root of the file system that is used
by the path specification.

Args:
path_spec (dfvfs.PathSpec): path specification.
mount_path (Optional[str]): path where the file system that is used
by the path specification is mounted, such as "/mnt/image". The
mount path will be stripped from the absolute path defined by
the path specification.

Returns:
str: relative path or None.


def read_binary_array(self, key, b64decode=True, decode=False):

        data = None
        if key is not None:
            data = self.db.read(key.strip())
            if data is not None:
                data_decoded = []
                for d in json.loads(data, object_pairs_hook=OrderedDict):
                    if b64decode:

                        dd = base64.b64decode(d)
                        if decode:

                            try:
                                dd = dd.decode('utf-8')
                            except UnicodeDecodeError:

                                dd = dd.decode('latin-1')
                        data_decoded.append(dd)
                    else:

                        data_decoded.append(d)
                data = data_decoded
        else:
            self.tcex.log.warning(u'The key field was None.')
        return data

Read method of CRUD operation for binary array data.

Args:
key (string): The variable to read from the DB.
b64decode (bool): If true the data will be base64 decoded.
decode (bool): If true the data will be decoded to a String.

Returns:
(list): Results retrieved from DB.


def _get_connection(self, cluster):

        if 'connection' not in cluster:
            cluster['connection'] = self._connection_class(
                socketTimeoutMS=self._network_timeout,
                w=1,
                j=self.j,
                **cluster['params'])

        return cluster['connection']

Return a connection to a Cluster.

Return a MongoClient or a MongoReplicaSetClient for the given Cluster.
This is done in a lazy manner (if there is already a Client connected to
the Cluster, it is returned and no other Client is created).

Args:
cluster: A dict containing information about a cluster.

Returns:
A MongoClient or MongoReplicaSetClient instance connected to the
desired cluster


def get_root_dir(self):
    if os.path.isdir(self.root_path):
        return self.root_path
    else:
        return os.path.dirname(self.root_path)

Retrieve the absolute path to the root directory of this data source.

Returns:
str: absolute path to the root directory of this data source.


def expand_valid_values(valid_values):

        if '${GROUP_TYPES}' in valid_values:
            valid_values.remove('${GROUP_TYPES}')
            valid_values.extend(
                [
                    'Adversary',
                    'Campaign',
                    'Document',
                    'Email',
                    'Event',
                    'Incident',
                    'Intrusion Set',
                    'Signature',
                    'Task',
                    'Threat',
                ]
            )
        elif '${OWNERS}' in valid_values:
            valid_values.remove('${OWNERS}')
            valid_values.append('')
        elif '${USERS}' in valid_values:
            valid_values.remove('${USERS}')
            valid_values.append('')
        return valid_values

Expand supported playbook variables to their full list.

Args:
valid_values (list): The list of valid values for Choice or MultiChoice inputs.

Returns:
List: An expanded list of valid values for Choice or MultiChoice inputs.


def start(self, channel=None):

        super(EmulatedDevice, self).start(channel)
        self.emulator.start()

Start this emulated device.

This triggers the controller to call start on all peripheral tiles in
the device to make sure they start after the controller does and then
it waits on each one to make sure they have finished initializing
before returning.

Args:
channel (IOTilePushChannel): the channel with a stream and trace
routine for streaming and tracing data through a VirtualInterface


def distance_tt_point(a, b):

    return math.sqrt((b.lat-a.lat)**2 + (b.lon-a.lon)**2)

Euclidean distance between two (tracktotrip) points

Args:
a (:obj:`Point`)
b (:obj:`Point`)
Returns:
float


def list_lb_nat_rules(access_token, subscription_id, resource_group, lb_name):
    endpoint = ''.join([get_rm_endpoint(), '/subscriptions/', subscription_id, '/resourceGroups/', resource_group, '/providers/Microsoft.Network/loadBalancers/', lb_name, 'inboundNatRules?api-version=', NETWORK_API])
    return do_get(endpoint, access_token)

List the inbound NAT rules for a load balancer.

Args:
access_token (str): A valid Azure authentication token.
subscription_id (str): Azure subscription id.
resource_group (str): Azure resource group name.
lb_name (str): Name of the load balancer.

Returns:
HTTP response. JSON body of load balancer NAT rules.


def from_text_audio_configs(cls, text_config: ClapTextConfig, audio_config: ClapAudioConfig, **kwargs):
    return cls(text_config=text_config.to_dict(), audio_config=audio_config.to_dict(), **kwargs)

Instantiate a [`ClapConfig`] (or a derived class) from clap text model configuration and clap audio model
configuration.

Returns:
[`ClapConfig`]: An instance of a configuration object


def SerializeUnsigned(self, writer):

        writer.WriteByte(self.Type)
        writer.WriteByte(self.Version)
        self.SerializeExclusiveData(writer)

        if len(self.Attributes) > self.MAX_TX_ATTRIBUTES:
            raise Exception("Cannot have more than %s transaction attributes" % self.MAX_TX_ATTRIBUTES)

        writer.WriteSerializableArray(self.Attributes)
        writer.WriteSerializableArray(self.inputs)
        writer.WriteSerializableArray(self.outputs)

Serialize object.

Args:
writer (neo.IO.BinaryWriter):


def _factored_dims(self, shape):

    if not self._factored or shape.ndims < 2:
      return None
    sorted_dims = sorted(shape.dims, key=lambda d: -d.size)
    if sorted_dims[1].size < self._min_dim_size_to_factor:
      return None
    return sorted_dims[:2]

Should we use a factored second moment estimator.

Based on the shape of the variable.
If we factor the accumulator, then this function returns a list of two
mtf.Dimensions to reduce over.  We always pick the two largest dimensions.
If there are not two dimensions of size >= min_dim_size_to_factor, then we
do not factor.

Args:
shape: a Shape
Returns:
either a list of 2 Dimensions or None


Iterator for different convolution shapes, strides and explicit paddings.

compute_gradient_error() is very expensive. So the configs should be
relatively small.

Returns:
List of tuples (input_size, filter_size, out_size, stride, padding,
dilations), the depthwise convolution parameters.


def ioa(boxes1, boxes2):

  intersect = intersection(boxes1, boxes2)
  inv_areas = np.expand_dims(1.0 / area(boxes2), axis=0)
  return intersect * inv_areas

Computes pairwise intersection-over-area between box collections.

Intersection-over-area (ioa) between two boxes box1 and box2 is defined as
their intersection area over box2's area. Note that ioa is not symmetric,
that is, IOA(box1, box2) != IOA(box2, box1).

Args:
boxes1: a numpy array with shape [N, 4] holding N boxes.
boxes2: a numpy array with shape [M, 4] holding N boxes.

Returns:
a numpy array with shape [N, M] representing pairwise ioa scores.


def run_inference(self, batch, model, inference_args=None):
    _validate_inference_args(inference_args)
    vectorized_batch = np.vstack(batch)
    predictions = hdbscan.approximate_predict(model, vectorized_batch)
    return [PredictionResult(x, y) for x, y in zip(batch, predictions)]

Runs inferences on a batch of numpy arrays.

Args:
batch: A sequence of examples as numpy arrays. They should
be single examples.
model: A numpy model or pipeline. Must implement predict(X).
Where the parameter X is a numpy array.
inference_args: Any additional arguments for an inference.

Returns:
An Iterable of type PredictionResult.