def connected_emulators(self, host=enums.JLinkHost.USB):

        res = self._dll.JLINKARM_EMU_GetList(host, 0, 0)
        if res < 0:
            raise errors.JLinkException(res)

        num_devices = res
        info = (structs.JLinkConnectInfo * num_devices)()
        num_found = self._dll.JLINKARM_EMU_GetList(host, info, num_devices)
        if num_found < 0:
            raise errors.JLinkException(num_found)

        return list(info)[:num_found]

Returns a list of all the connected emulators.

Args:
self (JLink): the ``JLink`` instance
host (int): host type to search (default: ``JLinkHost.USB``)

Returns:
List of ``JLinkConnectInfo`` specifying the connected emulators.

Raises:
JLinkException: if fails to enumerate devices.


def ragged_cumsum(x: ragged_tensor.Ragged, axis: int=0, exclusive: bool=False, reverse: bool=False, name: typing.Optional[str]=None):
    with ops.name_scope(name, 'RaggedCumSum', [x, axis, exclusive, reverse]):
        axis = array_ops.get_positive_axis(axis, x.shape.rank, ndims_name='rank')
        if axis == x.ragged_rank:
            last_rp = x._nested_row_partitions[-1]
            return x.with_flat_values(_cumsum_flat_values_at_ragged_rank(last_rp, x.flat_values, exclusive=exclusive, reverse=reverse))
        elif axis > x.ragged_rank:
            new_axis = axis - x.ragged_rank
            cumsum_bound = functools.partial(math_ops.cumsum, axis=new_axis, exclusive=exclusive, reverse=reverse)
            return ragged_functional_ops.map_flat_values(cumsum_bound, x)
        else:
            dense_version = x.to_tensor()
            result = math_ops.cumsum(dense_version, axis, exclusive=exclusive, reverse=reverse, name=name)
            return ragged_tensor.RaggedTensor.from_tensor(result, lengths=x.nested_row_lengths())

Calculate math_ops.cumsum for a RaggedTensor.

Given a ragged tensor `x`, the `result` is a ragged tensor with the same
shape. One can calculate the value of `result[i_1...i_k]` as follows:
```
dense_result=tf.math.cumsum(rt.to_tensor(), axis=axis, exclusive=exclusive,
reverse=reverse)
result[i_1...i_k]=dense_result[i_1...i_k]
```

Args:
x: the original ragged tensor to sum.
axis: the axis along which to sum, can range -rank<=axis<rank.
exclusive: is the sum exclusive or inclusive? If True, then result[0]=0.
If False, then result[0]=x[0].
reverse: If True, sum from back to front.
name: the name of the op.
Returns:
the cumulative sum.


def CreateSession(cls, artifact_filter_names=None, command_line_arguments=None, debug_mode=False, filter_file_path=None, preferred_encoding='utf-8', preferred_time_zone=None, preferred_year=None):
    session = sessions.Session()
    session.artifact_filters = artifact_filter_names
    session.command_line_arguments = command_line_arguments
    session.debug_mode = debug_mode
    session.filter_file = filter_file_path
    session.preferred_encoding = preferred_encoding
    session.preferred_time_zone = preferred_time_zone
    session.preferred_year = preferred_year
    return session

Creates a session attribute container.

Args:
artifact_filter_names (Optional[list[str]]): names of artifact definitions
that are used for filtering file system and Windows Registry
key paths.
command_line_arguments (Optional[str]): the command line arguments.
debug_mode (bool): True if debug mode was enabled.
filter_file_path (Optional[str]): path to a file with find specifications.
preferred_encoding (Optional[str]): preferred encoding.
preferred_time_zone (Optional[str]): preferred time zone.
preferred_year (Optional[int]): preferred year.

Returns:
Session: session attribute container.


def set_status(self, on, switch=1):

        if isinstance(switch, int):
            switch = str(switch)
        payload = self.generate_payload(SET, {switch:on})

        data = self._send_receive(payload)
        log.debug('set_status received data=%r', data)

        return data

Set status of the device to 'on' or 'off'.

Args:
on(bool):  True for 'on', False for 'off'.
switch(int): The switch to set


def draw_lines(self, *points):

        point_array = ffi.new('SDL_Point[]', len(points))
        for i, p in enumerate(points):
            point_array[i] = p._ptr[0]
        check_int_err(lib.SDL_RenderDrawLines(self._ptr, point_array, len(points)))

Draw a series of connected lines on the current rendering target.

Args:
*points (Point): The points along the lines.

Raises:
SDLError: If an error is encountered.


def handle_event(self, event_handler, event_name, user_args, event_timeout=None, cond=None, cond_timeout=None):
    worker = self.executor.submit(self._handle, event_handler, event_name, user_args, event_timeout, cond, cond_timeout)
    return worker

Handle events that don't have registered handlers

In a new thread, poll one event of specified type from its queue and
execute its handler. If no such event exists, the thread waits until
one appears.

Args:
event_handler: Handler for the event, which should take at least
one argument - the event json object.
event_name: Name of the event to be handled.
user_args: User arguments for the handler; to be passed in after
the event json.
event_timeout: Number of seconds to wait for the event to come.
cond: A condition to wait on before executing the handler. Should
be a threading.Event object.
cond_timeout: Number of seconds to wait before the condition times
out. Never times out if None.

Returns:
A concurrent.Future object associated with the handler.
If blocking call worker.result() is triggered, the handler
needs to return something to unblock.


def get_header(message, name):

    header = message.get(name)
    log.debug("Getting header {!r}: {!r}".format(name, header))
    if header:
        return decode_header_part(header)
    return six.text_type()

Gets an email.message.Message and a header name and returns
the mail header decoded with the correct charset.

Args:
message (email.message.Message): email message object
name (string): header to get

Returns:
decoded header


def suggestions(self, word):

    suggestions = set(self._misspelling_dict.get(word, [])).union(
        set(self._misspelling_dict.get(word.lower(), [])))
    return sorted([same_case(source=word, destination=w)
                   for w in suggestions])

Returns a list of suggestions for a misspelled word.

Args:
word: The word to check.

Returns:
List of zero or more suggested replacements for word.


def dumps(o, encoder=None):

    retval = ""
    if encoder is None:
        encoder = TomlEncoder(o.__class__)
    addtoretval, sections = encoder.dump_sections(o, "")
    retval += addtoretval
    while sections:
        newsections = encoder.get_empty_table()
        for section in sections:
            addtoretval, addtosections = encoder.dump_sections(
                sections[section], section)

            if addtoretval or (not addtoretval and not addtosections):
                if retval and retval[-2:] != "\n\n":
                    retval += "\n"
                retval += "[" + section + "]\n"
                if addtoretval:
                    retval += addtoretval
            for s in addtosections:
                newsections[section + "." + s] = addtosections[s]
        sections = newsections
    return retval

Stringifies input dict as toml

Args:
o: Object to dump into toml

preserve: Boolean parameter. If true, preserve inline tables.

Returns:
String containing the toml corresponding to dict


def __init__(self, section):

        self.section = section
        super().__init__('invalid section name: {}'.format(section))

Initialization of instances:

Args:
section (str): invalid section name.

Attributes:
section (str): invalid section name.


def color_string(self, x):

        diff_str = ""
        color = "black"

        if len(x) == 2 and self.compare_file is not None:
            difference = x[0] - x[1]
            if difference:
                color, sign = ('green', '-') if difference < 0 else ('red', '+')
                diff_str = '{}{}'.format(sign, self.format_measure(difference))
        return [self.format_measure(x[0]), [diff_str, color]]

Return a string formatted delta for the values in x.

Args:
x: 2-item list of integers (representing number of calls) or
2-item list of floats (representing seconds of runtime).

Returns:
A list with [formatted x[0], [color, formatted delta]], where
color reflects whether x[1] is lower, greater, or the same as
x[0].


def CheckSectionSpacing(filename, clean_lines, class_info, linenum, error):
    if (((class_info.last_line - class_info.starting_linenum) <= 24) or (linenum <= class_info.starting_linenum)):
        return
    matched = Match('\\s*(public|protected|private):', clean_lines.lines[linenum])
    if matched:
        prev_line = clean_lines.lines[(linenum - 1)]
        if ((not IsBlankLine(prev_line)) and (not Search('\\b(class|struct)\\b', prev_line)) and (not Search('\\\\$', prev_line))):
            end_class_head = class_info.starting_linenum
            for i in range(class_info.starting_linenum, linenum):
                if Search('\\{\\s*$', clean_lines.lines[i]):
                    end_class_head = i
                    break
            if (end_class_head < (linenum - 1)):
                error(filename, linenum, 'whitespace/blank_line', 3, ('"%s:" should be preceded by a blank line' % matched.group(1)))

Checks for additional blank line issues related to sections.

Currently the only thing checked here is blank line before protected/private.

Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
class_info: A _ClassInfo objects.
linenum: The number of the line to check.
error: The function to call with any errors found.


def create_module_file(txt, directory):
    name = nonpresent_module_filename()
    path = os.path.join(directory, name)
    with open(path, 'w') as fh:
        fh.write(txt)
    return path

Create a file in the given directory with
a valid module name populated with the given txt.

Returns:
A path to the file


def generate_encodeable_characters(characters: Iterable[str],
                                   encodings: Iterable[str]) -> Iterable[str]:

    for c in characters:
        for encoding in encodings:
            try:
                c.encode(encoding)
                yield c
            except UnicodeEncodeError:
                pass

Generates the subset of 'characters' that can be encoded by 'encodings'.

Args:
characters: The characters to check for encodeability e.g. 'abcd'.
encodings: The encodings to check against e.g. ['cp1252', 'iso-8859-5'].

Returns:
The subset of 'characters' that can be encoded using one of the provided
encodings.


def __init__(self,
               make_distribution_fn,
               convert_to_tensor_fn=tfd.Distribution.sample,
               **kwargs):

    if isinstance(make_distribution_fn, six.string_types):

      make_distribution_fn = _deserialize_function(make_distribution_fn)

    convert_to_tensor_fn = _get_convert_to_tensor_fn(convert_to_tensor_fn)

    kwargs.pop('function', None)

    def _fn(*fargs, **fkwargs):

      d = make_distribution_fn(*fargs, **fkwargs)
      value_is_seq = isinstance(d.dtype, collections.Sequence)
      maybe_composite_convert_to_tensor_fn = (
          (lambda d: tensor_tuple.TensorTuple(convert_to_tensor_fn(d)))
          if value_is_seq else convert_to_tensor_fn)
      distribution = dtc._TensorCoercible(
          distribution=d,
          convert_to_tensor_fn=maybe_composite_convert_to_tensor_fn)

      value = distribution._value()

      value._tfp_distribution = distribution

      if value_is_seq:
        value.shape = value[-1].shape
        value.get_shape = value[-1].get_shape
        value.dtype = value[-1].dtype
        distribution.shape = value[-1].shape
        distribution.get_shape = value[-1].get_shape
      else:
        distribution.shape = value.shape
        distribution.get_shape = value.get_shape
      return distribution, value

    super(DistributionLambda, self).__init__(_fn, **kwargs)

    self._make_distribution_fn = make_distribution_fn
    self._convert_to_tensor_fn = convert_to_tensor_fn

    self._enter_dunder_call = False

Create a `DistributionLambda` Keras layer.

Args:
make_distribution_fn: Python `callable` that takes previous layer outputs
and returns a `tfd.Distribution` instance.
convert_to_tensor_fn: Python `callable` that takes a `tfd.Distribution`
instance and returns a `tf.Tensor`-like object. For examples, see
`class` docstring.
Default value: `tfd.Distribution.sample`.
**kwargs: Additional keyword arguments passed to `tf.keras.Layer`.


def padFrameRange(frange, zfill):

    def _do_pad(match):
        '\n            Substitutes padded for unpadded frames.\n            '
        result = list(match.groups())
        result[1] = pad(result[1], zfill)
        if result[4]:
            result[4] = pad(result[4], zfill)
        return ''.join((i for i in result if i))
    return PAD_RE.sub(_do_pad, frange)

Return the zero-padded version of the frame range string.

Args:
frange (str): a frame range to test
zfill (int):

Returns:
str:


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

        if self.single_observable_projection:
            return self._project_single_observable(**kwargs)
        else:
            return self._project_dict(**kwargs)

Perform the requested projection(s).

Note:
All cuts on the original histograms will be reset when this function is completed.

Args:
kwargs (dict): Additional named args to be passed to projection_name(...) and output_key_name(...)
Returns:
The projected histogram(s). The projected histograms are also stored in ``output_observable``.


def UpdateNumberOfEvents(
      self, number_of_consumed_events, number_of_produced_events):

    consumed_events_delta = 0
    if number_of_consumed_events is not None:
      if number_of_consumed_events < self.number_of_consumed_events:
        raise ValueError(
            'Number of consumed events smaller than previous update.')

      consumed_events_delta = (
          number_of_consumed_events - self.number_of_consumed_events)

      self.number_of_consumed_events = number_of_consumed_events
      self.number_of_consumed_events_delta = consumed_events_delta

    produced_events_delta = 0
    if number_of_produced_events is not None:
      if number_of_produced_events < self.number_of_produced_events:
        raise ValueError(
            'Number of produced events smaller than previous update.')

      produced_events_delta = (
          number_of_produced_events - self.number_of_produced_events)

      self.number_of_produced_events = number_of_produced_events
      self.number_of_produced_events_delta = produced_events_delta

    return consumed_events_delta > 0 or produced_events_delta > 0

Updates the number of events.

Args:
number_of_consumed_events (int): total number of events consumed by
the process.
number_of_produced_events (int): total number of events produced by
the process.

Returns:
bool: True if either number of events has increased.

Raises:
ValueError: if the consumed or produced number of events is smaller
than the value of the previous update.


def get_list(self, id, name=None):
    return self.create_list(dict(id=id, name=name))

Get a list

Returns:
List: The list with the given `id`


def set_pattern_actual_step(self, patternnumber, value):
    _checkPatternNumber(patternnumber)
    _checkStepNumber(value)
    address = _calculateRegisterAddress('actualstep', patternnumber)
    self.write_register(address, value, 0)

Set the 'actual step' parameter for a given pattern.

Args:
* patternnumber (integer): 0-7
* value (integer): 0-7


def dump(voevent, file, pretty_print=True, xml_declaration=True):
    file.write(dumps(voevent, pretty_print, xml_declaration))

Writes the voevent to the file object.

e.g.::

with open('/tmp/myvoevent.xml','wb') as f:
voeventparse.dump(v, f)

Args:
voevent(:class:`Voevent`): Root node of the VOevent etree.
file (io.IOBase): An open (binary mode) file object for writing.
pretty_print
pretty_print(bool): See :func:`dumps`
xml_declaration(bool): See :func:`dumps`


def from_ops(*operations: ops.OP_TREE,
                 strategy: InsertStrategy = InsertStrategy.EARLIEST,
                 device: devices.Device = devices.UnconstrainedDevice
                 ) -> 'Circuit':

        result = Circuit(device=device)
        result.append(operations, strategy)
        return result

Creates an empty circuit and appends the given operations.

Args:
operations: The operations to append to the new circuit.
strategy: How to append the operations.
device: Hardware that the circuit should be able to run on.

Returns:
The constructed circuit containing the operations.


def concat(values, axis, name: str='concat'):
    if name is None:
        name = 'concat'
    _assert_concat_compatible_structured_tensors(values)

    def leaf_op(values):
        return array_ops.concat(values, axis)
    axis = array_ops.get_positive_axis(axis, values[0].rank)
    with ops.name_scope(name, 'StructuredConcat', values):
        return _extend_op(values, leaf_op)

tf.concat for structured tensors.

Does not support (yet) checks on illegal axis values, et cetera.

Args:
values: a sequence of StructuredTensors.
axis: an axis to concatenate upon.
name: the name of the op(s).

Returns:
the params reorganized according to indices.


def get_variation_for_experiment(self, experiment_id):

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

Helper method to retrieve variation ID for given experiment.

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

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


def delete_direct(self, addresses):

        with self._lock:
            for address in addresses:
                self._validate_write(address)
                if address in self._state:
                    self._state[address].set_deleted()
                else:
                    fut = _ContextFuture(address=address)
                    self._state[address] = fut
                    fut.set_deleted()

Called in the context manager's delete method to either
mark an entry for deletion , or create a new future and immediately
set it for deletion in the future.

Args:
address_list (list of str): The unique full addresses.

Raises:
AuthorizationException


def process_alias_export_namespace(namespace):

    namespace.export_path = os.path.abspath(namespace.export_path)
    if os.path.isfile(namespace.export_path):
        raise CLIError(FILE_ALREADY_EXISTS_ERROR.format(namespace.export_path))

    export_path_dir = os.path.dirname(namespace.export_path)
    if not os.path.isdir(export_path_dir):
        os.makedirs(export_path_dir)

    if os.path.isdir(namespace.export_path):
        namespace.export_path = os.path.join(namespace.export_path, ALIAS_FILE_NAME)

Validate input arguments when the user invokes 'az alias export'.

Args:
namespace: argparse namespace object.


def of(cls, key: SearchKey, params: SearchParams) -> 'SearchCriteria':

        key_name = key.value
        if key_name in params.disabled:
            raise SearchNotAllowed(key_name)
        elif key.inverse:
            return InverseSearchCriteria(key.not_inverse, params)
        elif key_name == b'SEQSET':
            return SequenceSetSearchCriteria(key.filter_sequence_set, params)
        elif key_name == b'KEYSET':
            return SearchCriteriaSet(key.filter_key_set, params)
        elif key_name == b'ALL':
            return AllSearchCriteria(params)
        elif key_name == b'OR':
            left_key, right_key = key.filter_key_or
            return OrSearchCriteria(left_key, right_key, params)
        elif key_name == b'ANSWERED':
            return HasFlagSearchCriteria(Answered, True, params)
        elif key_name == b'UNANSWERED':
            return HasFlagSearchCriteria(Answered, False, params)
        elif key_name == b'DELETED':
            return HasFlagSearchCriteria(Deleted, True, params)
        elif key_name == b'UNDELETED':
            return HasFlagSearchCriteria(Deleted, False, params)
        elif key_name == b'DRAFT':
            return HasFlagSearchCriteria(Draft, True, params)
        elif key_name == b'UNDRAFT':
            return HasFlagSearchCriteria(Draft, False, params)
        elif key_name == b'FLAGGED':
            return HasFlagSearchCriteria(Flagged, True, params)
        elif key_name == b'UNFLAGGED':
            return HasFlagSearchCriteria(Flagged, False, params)
        elif key_name == b'RECENT':
            return HasFlagSearchCriteria(Recent, True, params)
        elif key_name == b'OLD':
            return HasFlagSearchCriteria(Recent, False, params)
        elif key_name == b'SEEN':
            return HasFlagSearchCriteria(Seen, True, params)
        elif key_name == b'UNSEEN':
            return HasFlagSearchCriteria(Seen, False, params)
        elif key_name == b'KEYWORD':
            return HasFlagSearchCriteria(key.filter_flag, True, params)
        elif key_name == b'UNKEYWORD':
            return HasFlagSearchCriteria(key.filter_flag, False, params)
        elif key_name == b'NEW':
            return NewSearchCriteria(params)
        elif key_name == b'BEFORE':
            return DateSearchCriteria(key.filter_datetime, '<', params)
        elif key_name == b'ON':
            return DateSearchCriteria(key.filter_datetime, '=', params)
        elif key_name == b'SINCE':
            return DateSearchCriteria(key.filter_datetime, '>=', params)
        elif key_name == b'SENTBEFORE':
            return HeaderDateSearchCriteria(key.filter_datetime, '<', params)
        elif key_name == b'SENTON':
            return HeaderDateSearchCriteria(key.filter_datetime, '=', params)
        elif key_name == b'SENTSINCE':
            return HeaderDateSearchCriteria(key.filter_datetime, '>=', params)
        elif key_name == b'SMALLER':
            return SizeSearchCriteria(key.filter_int, '<', params)
        elif key_name == b'LARGER':
            return SizeSearchCriteria(key.filter_int, '>', params)
        elif key_name in (b'BCC', b'CC', b'FROM', b'SUBJECT', b'TO'):
            return EnvelopeSearchCriteria(key_name, key.filter_str, params)
        elif key_name == b'HEADER':
            name, value = key.filter_header
            return HeaderSearchCriteria(name, value, params)
        elif key_name in (b'BODY', b'TEXT'):
            return BodySearchCriteria(key.filter_str, params)
        raise SearchNotAllowed(key_name)

Factory method for producing a search criteria sub-class from a
search key.

Args:
key: The search key defining the criteria.
params: The parameters that may be used by some searches.


def hpo_diseases(username, password, hpo_ids, p_value_treshold=1):
    try:
        results = query_phenomizer.query(username, password, *hpo_ids)
        diseases = [result for result in results if (result['p_value'] <= p_value_treshold)]
        return diseases
    except SystemExit:
        return None

Return the list of HGNC symbols that match annotated HPO terms.

Args:
username (str): username to use for phenomizer connection
password (str): password to use for phenomizer connection

Returns:
query_result: a generator of dictionaries on the form
{
'p_value': float,
'disease_source': str,
'disease_nr': int,
'gene_symbols': list(str),
'description': str,
'raw_line': str
}


def ucast_ip(ip_addr, return_tuple=True):

    regex_ucast_ip = __re.compile("^((22[0-3])|(2[0-1][0-9])|(1[0-9][0-9])|([1-9]?[0-9]))\.((25[0-5])|(2[0-4][0-9])|(1[0-9][0-9])|([1-9]?[0-9]))\.((25[0-5])|(2[0-4][0-9])|(1[0-9][0-9])|([1-9]?[0-9]))\.((25[0-5])|(2[0-4][0-9])|(1[0-9][0-9])|([1-9]?[0-9]))$")
    if return_tuple:
        while not regex_ucast_ip.match(ip_addr):
            print("Not a good unicast IP.")
            print("Please try again.")
            ip_addr = input("Please enter a unicast IP address in the following format x.x.x.x: ")
        return ip_addr
    elif not return_tuple:
        if not regex_ucast_ip.match(ip_addr):
            return False
        else:
            return True

Function to check if a address is unicast
Args:
ip_addr: Unicast IP address in the following format 192.168.1.1
return_tuple: Set to True it returns a IP, set to False returns True or False

Returns: see return_tuple for return options


def _rpc(self, method, *args):

        with self._lock:
            apiid = next(self._counter)
            data = {'id': apiid, 'method': method, 'params': args}
            request = json.dumps(data)
            self._client_send(request)
            response = self._client_receive()
        if not response:
            raise ProtocolError(self._ad,
                                ProtocolError.NO_RESPONSE_FROM_SERVER)
        result = json.loads(str(response, encoding='utf8'))
        if result['error']:
            raise ApiError(self._ad, result['error'])
        if result['id'] != apiid:
            raise ProtocolError(self._ad, ProtocolError.MISMATCHED_API_ID)
        if result.get('callback') is not None:
            if self._event_client is None:
                self._event_client = self._start_event_client()
            return callback_handler.CallbackHandler(
                callback_id=result['callback'],
                event_client=self._event_client,
                ret_value=result['result'],
                method_name=method,
                ad=self._ad)
        return result['result']

Sends an rpc to the app.

Args:
method: str, The name of the method to execute.
args: any, The args of the method.

Returns:
The result of the rpc.

Raises:
ProtocolError: Something went wrong with the protocol.
ApiError: The rpc went through, however executed with errors.


def __cloudflare_list_zone_records(self, *, account, zoneID, **kwargs):
    done = False
    records = {}
    page = 1
    while (not done):
        kwargs['page'] = page
        response = self.__cloudflare_request(account=account, path='/zones/{}/dns_records'.format(zoneID), args=kwargs)
        info = response['result_info']
        if (('total_pages' not in info) or (page >= info['total_pages'])):
            done = True
        else:
            page += 1
        for record in response['result']:
            if (record['name'] in records):
                records[record['name']]['value'] = sorted((records[record['name']]['value'] + [record['content']]))
            else:
                records[record['name']] = {'name': record['name'], 'value': sorted([record['content']]), 'type': record['type']}
    return list(records.values())

Helper function to list all records on a CloudFlare DNS Zone. Returns a `dict` containing the records and
their information.

Args:
account (:obj:`CloudFlareAccount`): A CloudFlare Account object
zoneID (`int`): Internal CloudFlare ID of the DNS zone
**kwargs (`dict`): Additional arguments to be consumed by the API endpoint

Returns:
:obj:`dict` of `str`: `dict`


def run(func, options, args=(), kwargs={}, host='localhost', port=8000):
    run_stats = run_profilers((func, args, kwargs), options)
    result = None
    for prof in run_stats:
        if (not result):
            result = run_stats[prof]['result']
        del run_stats[prof]['result']
    post_data = gzip.compress(json.dumps(run_stats).encode('utf-8'))
    urllib.request.urlopen(('http:
    return result

Runs profilers on a function.

Args:
func: A Python function.
options: A string with profilers configuration (i.e. 'cmh').
args: func non-keyword arguments.
kwargs: func keyword arguments.
host: Host name to send collected data.
port: Port number to send collected data.

Returns:
A result of func execution.


def _pool(inputs, initial_value, reduce_fn, pool_size, strides=None, padding='valid'):
    if padding not in ('same', 'valid'):
        raise ValueError(f"Invalid padding '{padding}', must be 'same' or 'valid'.")
    padding = padding.upper()
    return lax.reduce_window(inputs, initial_value, reduce_fn, pool_size, strides, padding)

Helper function to define pooling functions.

Args:
inputs: input data of shape `N+2`.
initial_value: the initial value for the reduction.
reduce_fn: a reduce function of the form `(T, T) -> T`.
pool_size: a sequence of `N` integers, representing the window size to
reduce over.
strides: a sequence of `N` integers, representing the inter-window
strides (default: `(1, ..., 1)`).
padding: either the string `same` or `valid`.

Returns:
The output of the reduction for each window slice.


def offTagAdd(self, name, func):
    if ('*' in name):
        self.ontagaddglobs.rem(name, func)
        return
    cblist = self.ontagadds.get(name)
    if (cblist is None):
        return
    try:
        cblist.remove(func)
    except ValueError:
        pass

Unregister a callback for tag addition.

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


def _cast_value(self, value):

        if (self.convert_datetimes):
            try:
                date_time = datetime.datetime.fromtimestamp(float(value))
                if datetime.datetime(1970, 1, 1) > date_time:
                    raise ValueError
                else:
                    return date_time

            except ValueError:
                pass

        tests = (int, float, str)
        for test in tests:
            try:
                return test(value)
            except ValueError:
                continue
        return value

Internal method that makes sure every value in dictionary
is properly cast into the correct types, instead of
just treating everything like a string from the csv file.

Args:
value : The value to be casted

Returns:
A casted Value.


def distribute_tensor(tensor, layout):
    if isinstance(tensor, KerasTensor):
        return tensor
    return distribution_lib.distribute_tensor(tensor, layout)

Change the layout of a Tensor value in the jit function execution.

Args:
tensor: a Tensor to change the layout.
layout: `TensorLayout` to be applied on the value.

Returns:
a new value with the specified tensor layout.


def delete(self, id, **kwargs):
    if (id is None):
        path = self.path
    else:
        if (not isinstance(id, int)):
            id = id.replace('/', '%2F')
        path = ('%s/%s' % (self.path, id))
    self.gitlab.http_delete(path, **kwargs)

Delete an object on the server.

Args:
id: ID of the object to delete
**kwargs: Extra options to send to the server (e.g. sudo)

Raises:
GitlabAuthenticationError: If authentication is not correct
GitlabDeleteError: If the server cannot perform the request


Compute the quadratic estimate of the centroid in a 2d-array.

Args:
data (2darray): two dimensional data array

Returns
center (tuple): centroid estimate on the row and column directions,
respectively


def get(self, ID, index='vector-web-s'):

        url = self.get_url % index
        r = self.gbdx_connection.get(url + ID)
        r.raise_for_status()
        return r.json()

Retrieves a vector.  Not usually necessary because searching is the best way to find & get stuff.

Args:
ID (str): ID of the vector object
index (str): Optional.  Index the object lives in.  defaults to 'vector-web-s'

Returns:
record (dict): A dict object identical to the json representation of the catalog record


def forward(self, inputs_embeddings=None, output_attentions=None, output_hidden_states=None, return_dict=None):
    output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
    output_hidden_states = output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
    return_dict = return_dict if return_dict is not None else self.config.use_return_dict
    hidden_states = inputs_embeddings
    encoder_states = () if output_hidden_states else None
    all_attentions = () if output_attentions else None
    projected_features = [self.channel_projection_layers[i](feature) for i, feature in enumerate(hidden_states)]
    for encoder_layer_index, feature_to_project_index in enumerate(self.encoder_projection_indices):
        if output_hidden_states:
            encoder_states = encoder_states + (projected_features[feature_to_project_index],)
        height, width = projected_features[feature_to_project_index].shape[2:]
        src_flatten = projected_features[feature_to_project_index].flatten(2).permute(0, 2, 1)
        if self.training or self.eval_size is None:
            pos_embed = self.build_2d_sincos_position_embedding(width, height, self.encoder_hidden_dim, self.positional_encoding_temperature, device=src_flatten.device, dtype=src_flatten.dtype).to(src_flatten.device, src_flatten.dtype)
        else:
            pos_embed = None
        layer_outputs = self.encoder[encoder_layer_index](src_flatten, pos_embed=pos_embed, output_attentions=output_attentions)
        projected_features[feature_to_project_index] = layer_outputs[0].permute(0, 2, 1).reshape(-1, self.encoder_hidden_dim, height, width).contiguous()
        if output_attentions:
            all_attentions = all_attentions + (layer_outputs[1],)
    if output_hidden_states:
        encoder_states = encoder_states + (projected_features[feature_to_project_index],)
    fpn_feature_maps = [projected_features[-1]]
    for idx in range(len(self.in_channels) - 1, 0, -1):
        feat_high = fpn_feature_maps[0]
        feat_low = projected_features[idx - 1]
        feat_high = self.lateral_convs[len(self.in_channels) - 1 - idx](feat_high)
        fpn_feature_maps[0] = feat_high
        upsample_feat = F.interpolate(feat_high, scale_factor=2.0, mode='nearest')
        fps_map = self.fpn_blocks[len(self.in_channels) - 1 - idx](torch.concat([upsample_feat, feat_low], dim=1))
        fpn_feature_maps.insert(0, fps_map)
    fpn_states = [fpn_feature_maps[0]]
    for idx in range(len(self.in_channels) - 1):
        feat_low = fpn_states[-1]
        feat_high = fpn_feature_maps[idx + 1]
        downsample_feat = self.downsample_convs[idx](feat_low)
        hidden_states = self.pan_blocks[idx](torch.concat([downsample_feat, feat_high.to(downsample_feat.device)], dim=1))
        fpn_states.append(hidden_states)
    if not return_dict:
        return (fpn_states[-1], encoder_states, all_attentions, fpn_states)
    return OmDetTurboEncoderOutput(last_hidden_state=fpn_states[-1], hidden_states=encoder_states, attentions=all_attentions, extracted_states=fpn_states)

Args:
inputs_embeddings (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
Flattened feature map (output of the backbone + projection layers) that is passed to the encoder.
output_attentions (`bool`, *optional*):
Whether or not to return the attentions tensors of all attention layers. See `attentions` under
returned tensors for more detail.
output_hidden_states (`bool`, *optional*):
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
for more detail.
return_dict (`bool`, *optional*):
Whether or not to return a [`~file_utils.ModelOutput`] instead of a plain tuple.


def __init__(self, timestep, natoms, box, data):

        self.timestep = timestep
        self.natoms = natoms
        self.box = box
        self.data = data

Base constructor.

Args:
timestep (int): Current timestep.
natoms (int): Total number of atoms in the box.
box (LammpsBox): Simulation box.
data (pd.DataFrame): Dumped atomic data.


def extend(self, elts):

        elts = elts[:]
        self._in_deque.append(elts)
        event = self._event_for(elts)
        self._event_deque.append(event)
        return event

Adds elts to the tasks.

Args:
elts (Sequence): a iterable of elements that can be appended to the
task's bundle_field.

Returns:
Event: an event that can be used to wait on the response.


def _get_fullname(obj):

        if not hasattr(obj, "__name__"):
            obj = obj.__class__
        if obj.__module__ in ("builtins", "__builtin__"):
            return obj.__name__
        return "{}.{}".format(obj.__module__, obj.__name__)

Get the full name of an object including the module.

Args:
obj: An object.

Returns:
The full class name of the object.


def set_scf_algorithm_and_iterations(self, algorithm="diis",
                                         iterations=50):

        available_algorithms = {"diis", "dm", "diis_dm", "diis_gdm", "gdm",
                                "rca", "rca_diis", "roothaan"}
        if algorithm.lower() not in available_algorithms:
            raise ValueError("Algorithm " + algorithm +
                             " is not available in QChem")
        self.params["rem"]["scf_algorithm"] = algorithm.lower()
        self.params["rem"]["max_scf_cycles"] = iterations

Set algorithm used for converging SCF and max number of SCF iterations.

Args:
algorithm: The algorithm used for converging SCF. (str)
iterations: The max number of SCF iterations. (Integer)


def _finalize_outputs(cls, mapreduce_spec, mapreduce_state):

    if (mapreduce_spec.mapper.output_writer_class() and
        mapreduce_state.result_status == model.MapreduceState.RESULT_SUCCESS):
      mapreduce_spec.mapper.output_writer_class().finalize_job(mapreduce_state)

Finalize outputs.

Args:
mapreduce_spec: an instance of MapreduceSpec.
mapreduce_state: an instance of MapreduceState.


def create_game(self, map_name):

    map_inst = maps.get(map_name)
    map_data = map_inst.data(self._run_config)
    if map_name not in self._saved_maps:
      for controller in self._controllers:
        controller.save_map(map_inst.path, map_data)
      self._saved_maps.add(map_name)

    create = sc_pb.RequestCreateGame(
        local_map=sc_pb.LocalMap(map_path=map_inst.path),
        disable_fog=False)

    for _ in range(self._num_agents):
      create.player_setup.add(type=sc_pb.Participant)

    self._controllers[0].create_game(create)

Create a game for the agents to join.

Args:
map_name: The map to use.


def forward(self, hidden_states: List[torch.Tensor], patch_height=None, patch_width=None) -> List[torch.Tensor]:
    out = []
    for i, hidden_state in enumerate(hidden_states):
        if i not in self.neck_ignore_stages:
            cls_token, hidden_state = (hidden_state[:, 0], hidden_state[:, 1:])
            batch_size, sequence_length, num_channels = hidden_state.shape
            if patch_height is not None and patch_width is not None:
                hidden_state = hidden_state.reshape(batch_size, patch_height, patch_width, num_channels)
            else:
                size = torch_int(sequence_length ** 0.5)
                hidden_state = hidden_state.reshape(batch_size, size, size, num_channels)
            hidden_state = hidden_state.permute(0, 3, 1, 2).contiguous()
            feature_shape = hidden_state.shape
            if self.config.readout_type == 'project':
                hidden_state = hidden_state.flatten(2).permute((0, 2, 1))
                readout = cls_token.unsqueeze(1).expand_as(hidden_state)
                hidden_state = self.readout_projects[i](torch.cat((hidden_state, readout), -1))
                hidden_state = hidden_state.permute(0, 2, 1).reshape(feature_shape)
            elif self.config.readout_type == 'add':
                hidden_state = hidden_state.flatten(2) + cls_token.unsqueeze(-1)
                hidden_state = hidden_state.reshape(feature_shape)
            hidden_state = self.layers[i](hidden_state)
        out.append(hidden_state)
    return out

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


def connect_engine(self):
    try:
        self.connection = self.engine.connect()
        return True
    except sa.exc.OperationalError as opex:
        LOG.fatal("Could not connect to the database. The error was: '%s'", str(opex))
    return False

Establish a connection to the database.

Provides simple error handling for fatal errors.

Returns:
True, if we could establish a connection, else False.


def _ReadStreamDataTypeDefinition(self, definitions_registry, definition_values, definition_name, is_member=False):
    if is_member:
        supported_definition_values = self._SUPPORTED_DEFINITION_VALUES_ELEMENTS_MEMBER_DATA_TYPE
    else:
        supported_definition_values = self._SUPPORTED_DEFINITION_VALUES_ELEMENTS_DATA_TYPE
    return self._ReadElementSequenceDataTypeDefinition(definitions_registry, definition_values, data_types.StreamDefinition, definition_name, supported_definition_values)

Reads a stream data type definition.

Args:
definitions_registry (DataTypeDefinitionsRegistry): data type definitions
registry.
definition_values (dict[str, object]): definition values.
definition_name (str): name of the definition.
is_member (Optional[bool]): True if the data type definition is a member
data type definition.

Returns:
StreamDefinition: stream data type definition.

Raises:
DefinitionReaderError: if the definitions values are missing or if
the format is incorrect.


def write_to_path(self,path,suffix='',format='png',overwrite=False):

        if os.path.exists(path) and overwrite is False: raise ValueError("Error: use ovewrite=True to overwrite images")
        if not os.path.exists(path): os.makedirs(path)
        for i,r in self.iterrows():
            spath = os.path.join(path,r['project_name'],r['sample_name'])
            if not os.path.exists(spath): os.makedirs(spath)
            if suffix == '':
                fname = os.path.join(spath,r['frame_name']+'.'+format)
            else: fname = os.path.join(spath,r['frame_name']+'_'+suffix+'.'+format)
            imageio.imwrite(fname, r['image'],format=format)

Output the data the dataframe's 'image' column to a directory structured by project->sample and named by frame

Args:
path (str): Where to write the directory of images
suffix (str): for labeling the imaages you write
format (str): default 'png' format to write the file
overwrite (bool): default False. if true can overwrite files in the path

Modifies:
Creates path folder if necessary and writes images to path


def get_extrema(self, normalize_rxn_coordinate=True):
    x = np.arange(0, np.max(self.r), 0.01)
    y = (self.spline(x) * 1000)
    scale = (1 if (not normalize_rxn_coordinate) else (1 / self.r[(- 1)]))
    min_extrema = []
    max_extrema = []
    for i in range(1, (len(x) - 1)):
        if ((y[i] < y[(i - 1)]) and (y[i] < y[(i + 1)])):
            min_extrema.append(((x[i] * scale), y[i]))
        elif ((y[i] > y[(i - 1)]) and (y[i] > y[(i + 1)])):
            max_extrema.append(((x[i] * scale), y[i]))
    return (min_extrema, max_extrema)

Returns the positions of the extrema along the MEP. Both local
minimums and maximums are returned.

Args:
normalize_rxn_coordinate (bool): Whether to normalize the
reaction coordinate to between 0 and 1. Defaults to True.

Returns:
(min_extrema, max_extrema), where the extrema are given as
[(x1, y1), (x2, y2), ...].


def install(self, ref, table_name=None, index_columns=None,logger=None):

        try:
            obj_number = ObjectNumber.parse(ref)
            if isinstance(obj_number, TableNumber):
                table = self._library.table(ref)
                connection = self._backend._get_connection()
                return self._backend.install_table(connection, table, logger=logger)
            else:

                raise NotObjectNumberError

        except NotObjectNumberError:

            partition = self._library.partition(ref)
            connection = self._backend._get_connection()

            return self._backend.install(
                connection, partition, table_name=table_name, index_columns=index_columns,
                logger=logger)

Finds partition by reference and installs it to warehouse db.

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


def _fill_from_default(self, default_job_config):
    if (self._job_type != default_job_config._job_type):
        raise TypeError(((('attempted to merge two incompatible job types: ' + repr(self._job_type)) + ', ') + repr(default_job_config._job_type)))
    new_job_config = self.__class__()
    default_job_properties = copy.deepcopy(default_job_config._properties)
    for key in self._properties:
        if (key != self._job_type):
            default_job_properties[key] = self._properties[key]
    default_job_properties[self._job_type].update(self._properties[self._job_type])
    new_job_config._properties = default_job_properties
    return new_job_config

Merge this job config with a default job config.

The keys in this object take precedence over the keys in the default
config. The merge is done at the top-level as well as for keys one
level below the job type.

Arguments:
default_job_config (google.cloud.bigquery.job._JobConfig):
The default job config that will be used to fill in self.

Returns:
google.cloud.bigquery.job._JobConfig A new (merged) job config.


def set_bool(self, location, value):

        element = self._handle_location(location)
        if isinstance(value, basestring):
            value = True if value.upper() == "TRUE" else False
        elif not isinstance(value, bool):
            raise ValueError
        if value is True:
            element.text = "true"
        else:
            element.text = "false"

Set a boolean value.

Casper booleans in XML are string literals of "true" or "false".
This method sets the text value of "location" to the correct
string representation of a boolean.

Args:
location: Element or a string path argument to find()
value: Boolean or string value to set. (Accepts
"true"/"True"/"TRUE"; all other strings are False).


def update_detector(self, detector_id, detector):
    resp = self._put(self._u(self._DETECTOR_ENDPOINT_SUFFIX, detector_id), data=detector)
    resp.raise_for_status()
    return resp.json()

Update an existing detector.

Args:
detector_id (string): the ID of the detector.
detector (object): the detector model object. Will be serialized as
JSON.
Returns:
dictionary of the response (updated detector model).


def commit(self):
    commit_response = self._client._firestore_api.commit(self._client._database_string, self._write_pbs, transaction=None, metadata=self._client._rpc_metadata)
    self._write_pbs = []
    self.write_results = results = list(commit_response.write_results)
    self.commit_time = commit_response.commit_time
    return results

Commit the changes accumulated in this batch.

Returns:
List[google.cloud.proto.firestore.v1beta1.\
write_pb2.WriteResult, ...]: The write results corresponding
to the changes committed, returned in the same order as the
changes were applied to this batch. A write result contains an
``update_time`` field.


def _create_mirrored_tpu_replicated_variables(**kwargs):
    initial_value = kwargs['initial_value']
    with maybe_init_scope():
        initial_value = initial_value() if callable(initial_value) else initial_value
    mirrored_replicated_var_list = []
    for replica_id in range(num_replicas):
        replicated_var_list = []
        for logic_core_id in range(num_cores_per_replica):
            with ops.device(self._tpu_devices[replica_id][logic_core_id]):
                kwargs['initial_value'] = initial_value
                v = next_creator(**kwargs)
            replicated_var_list.append(v)
        replica_name = '{}/r:{}'.format(kwargs['name'], replica_id)
        tpu_replicated_var = tpu_replicated_variable.TPUReplicatedVariable(variables=replicated_var_list, name=replica_name)
        mirrored_replicated_var_list.append(tpu_replicated_var)
    return mirrored_replicated_var_list

Returns a list of `TPUReplicatedVariable`s.

The list consists of `num_replicas` `TPUReplicatedVariable`s and can be
used to initialize a `TPUMirroredVariable`. Each `TPUReplicatedVariable`
contains a list of `tf.Variable`s which are replicated to
`num_cores_per_replica` logical cores to enable XLA SPMD compilation.

Args:
**kwargs: the keyword arguments for creating a variable


def start_entry(self, target, var_id):

        self.in_progress = ConfigEntry(target, var_id, b'')

        if self.data_size - self.data_index < self.in_progress.data_space():
            return Error.DESTINATION_BUFFER_TOO_SMALL

        self.in_progress.data += struct.pack("<H", var_id)
        self.data_index += self.in_progress.data_space()

        return Error.NO_ERROR

Begin a new config database entry.

If there is a current entry in progress, it is aborted but the
data was already committed to persistent storage so that space
is wasted.

Args:
target (SlotIdentifer): The target slot for this config variable.
var_id (int): The config variable ID

Returns:
int: An error code from the global Errors enum.


def _construct_location_to_filter_list(match_query):

    location_to_filters = {}
    for match_traversal in match_query.match_traversals:
        for match_step in match_traversal:
            current_filter = match_step.where_block
            if current_filter is not None:
                current_location = match_step.as_block.location
                location_to_filters.setdefault(current_location, []).append(
                    current_filter)

    return location_to_filters

Return a dict mapping location -> list of filters applied at that location.

Args:
match_query: MatchQuery object from which to extract location -> filters dict

Returns:
dict mapping each location in match_query to a list of
Filter objects applied at that location


def local_conv1d(inputs, kernel, kernel_size, strides, data_format=None):
    output_shape = (kernel.shape[0],)
    return local_conv(inputs, kernel, kernel_size, strides, output_shape, data_format)

Apply 1D conv with un-shared weights.

Args:
inputs: 3D tensor with shape:
(batch_size, steps, input_dim)
if data_format is "channels_last" or
(batch_size, input_dim, steps)
if data_format is "channels_first".
kernel: the unshared weight for convolution,
with shape (output_length, feature_dim, filters).
kernel_size: a tuple of a single integer,
specifying the length of the 1D convolution window.
strides: a tuple of a single integer,
specifying the stride length of the convolution.
data_format: the data format, channels_first or channels_last.

Returns:
A 3d tensor with shape:
(batch_size, output_length, filters)
if data_format='channels_first'
or 3D tensor with shape:
(batch_size, filters, output_length)
if data_format='channels_last'.


def sort_elements_by_child_values(obj_pyxb, child_name_list):
    obj_pyxb.sort(key=(lambda x: [get_auto(getattr(x, n)) for n in child_name_list]))

In-place sort simple or complex elements in a PyXB object by values they contain
in child elements.

Args:
obj_pyxb: PyXB object

child_name_list: list of str
List of element names that are direct children of the PyXB object.


def Lock(fd, path, blocking):
    operation = (fcntl.LOCK_EX if blocking else (fcntl.LOCK_EX | fcntl.LOCK_NB))
    try:
        fcntl.flock(fd, operation)
    except IOError as e:
        if (e.errno == errno.EWOULDBLOCK):
            raise IOError(('Exception locking %s. File already locked.' % path))
        else:
            raise IOError(('Exception locking %s. %s.' % (path, str(e))))

Lock the provided file descriptor.

Args:
fd: int, the file descriptor of the file to lock.
path: string, the name of the file to lock.
blocking: bool, whether the function should return immediately.

Raises:
IOError, raised from flock while attempting to lock a file.


def get_excel_workbook(api_data, result_info_key, identifier_keys):

    cleaned_data = []

    for item_data in api_data:
        result_info = item_data.pop(result_info_key, {})

        cleaned_item_data = {}

        if 'meta' in item_data:
            meta = item_data.pop('meta')
            cleaned_item_data['meta'] = meta

        for key in item_data:
            cleaned_item_data[key] = item_data[key]['result']

        cleaned_item_data[result_info_key] = result_info

        cleaned_data.append(cleaned_item_data)

    data_list = copy.deepcopy(cleaned_data)

    workbook = openpyxl.Workbook()

    write_worksheets(workbook, data_list, result_info_key, identifier_keys)

    return workbook

Generates an Excel workbook object given api_data returned by the Analytics API

Args:
api_data: Analytics API data as a list of dicts (one per identifier)
result_info_key: the key in api_data dicts that contains the data results
identifier_keys: the list of keys used as requested identifiers
(address, zipcode, block_id, etc)

Returns:
raw excel file data


def key_periods(ciphertext, max_key_period):
    if (max_key_period <= 0):
        raise ValueError('max_key_period must be a positive integer')
    key_scores = []
    for period in range(1, (min(max_key_period, len(ciphertext)) + 1)):
        score = abs((ENGLISH_IC - index_of_coincidence(*split_columns(ciphertext, period))))
        key_scores.append((period, score))
    return [p[0] for p in sorted(key_scores, key=(lambda x: x[1]))]

Rank all key periods for ``ciphertext`` up to and including ``max_key_period``

Example:
>>> key_periods(ciphertext, 30)
[2, 4, 8, 3, ...]

Args:
ciphertext (str): The text to analyze
max_key_period (int): The maximum period the key could be

Returns:
Sorted list of keys

Raises:
ValueError: If max_key_period is less than or equal to 0


def pull(self, platform=None):
    (repository, _) = parse_repository_tag(self.image_name)
    return self.collection.pull(repository, tag=self.id, platform=platform)

Pull the image digest.

Args:
platform (str): The platform to pull the image for.
Default: ``None``

Returns:
(:py:class:`Image`): A reference to the pulled image.


def read(self, filename, encoding=None):
    with open(filename, encoding=encoding) as fp:
        self._read(fp, filename)
    self._filename = os.path.abspath(filename)

Read and parse a filename.

Args:
filename (str): path to file
encoding (str): encoding of file, default None


def mean(x, axis=None, keepdims=False):
    if any_symbolic_tensors((x,)):
        return Mean(axis=axis, keepdims=keepdims).symbolic_call(x)
    return backend.numpy.mean(x, axis=axis, keepdims=keepdims)

Compute the arithmetic mean along the specified axes.

Args:
x: Input tensor.
axis: Axis or axes along which the means are computed. The default
is to compute the mean of the flattened tensor.
keepdims: If this is set to `True`, the axes which are reduced are left
in the result as dimensions with size one.

Returns:
Output tensor containing the mean values.


def scheduled_sample_count(ground_truth_x, generated_x, batch_size, scheduled_sample_var):
    num_ground_truth = scheduled_sample_var
    idx = tf.random_shuffle(tf.range(batch_size))
    ground_truth_idx = tf.gather(idx, tf.range(num_ground_truth))
    generated_idx = tf.gather(idx, tf.range(num_ground_truth, batch_size))
    ground_truth_examps = tf.gather(ground_truth_x, ground_truth_idx)
    generated_examps = tf.gather(generated_x, generated_idx)
    output = tf.dynamic_stitch([ground_truth_idx, generated_idx], [ground_truth_examps, generated_examps])
    if isinstance(batch_size, int):
        output.set_shape(([batch_size] + common_layers.shape_list(output)[1:]))
    return output

Sample batch with specified mix of groundtruth and generated data points.

Args:
ground_truth_x: tensor of ground-truth data points.
generated_x: tensor of generated data points.
batch_size: batch size
scheduled_sample_var: number of ground-truth examples to include in batch.
Returns:
New batch with num_ground_truth sampled from ground_truth_x and the rest
from generated_x.


def penalty_satisfaction(response, bqm):
    record = response.record
    label_dict = response.variables.index
    if (len(bqm.info['reduction']) == 0):
        return np.array(([1] * len(record.sample)))
    penalty_vector = np.prod([((record.sample[(:, label_dict[qi])] * record.sample[(:, label_dict[qj])]) == record.sample[(:, label_dict[valdict['product']])]) for ((qi, qj), valdict) in bqm.info['reduction'].items()], axis=0)
    return penalty_vector

Creates a penalty satisfaction list

Given a sampleSet and a bqm object, will create a binary list informing
whether the penalties introduced during degree reduction are satisfied for
each sample in sampleSet

Args:
response (:obj:`.SampleSet`): Samples corresponding to provided bqm

bqm (:obj:`.BinaryQuadraticModel`): a bqm object that contains
its reduction info.

Returns:
:obj:`numpy.ndarray`: a binary array of penalty satisfaction information


def _FormatDescription(self, event):

    date_time_string = timelib.Timestamp.CopyToIsoFormat(
        event.timestamp, timezone=self._output_mediator.timezone)
    timestamp_description = event.timestamp_desc or 'UNKNOWN'

    message, _ = self._output_mediator.GetFormattedMessages(event)
    if message is None:
      data_type = getattr(event, 'data_type', 'UNKNOWN')
      raise errors.NoFormatterFound(
          'Unable to find event formatter for: {0:s}.'.format(data_type))

    description = '{0:s}; {1:s}; {2:s}'.format(
        date_time_string, timestamp_description,
        message.replace(self._DESCRIPTION_FIELD_DELIMITER, ' '))
    return self._SanitizeField(description)

Formats the description.

Args:
event (EventObject): event.

Returns:
str: formatted description field.


def add_layer(self, label, change_layer=True):
    self.layer_stack.insert((self.last_layer() + 1), label)
    if change_layer:
        self.set_current_layer(self.last_layer())
    return None

Add new mesh layer to the end of the stack

Args:
label (str): new label for the mesh layer
change_layer (bool): change to the newly created layer


def plugins(self):
    if (not self.loaded):
        self.load_modules()
    return get_plugins()[self.group]._filter(blacklist=self.blacklist, newest_only=True, type_filter=self.type_filter)

Newest version of all plugins in the group filtered by ``blacklist``

Returns:
dict: Nested dictionary of plugins accessible through dot-notation.

Plugins are returned in a nested dictionary, but can also be accessed through dot-notion.
Just as when accessing an undefined dictionary key with index-notation,
a :py:exc:`KeyError` will be raised if the plugin type or plugin does not exist.

Parent types are always included.
Child plugins will only be included if a valid, non-blacklisted plugin is available.


def export_vms(self, vms_names=None, standalone=False, export_dir='.', compress=False, init_file_name='LagoInitFile', out_format=YAMLOutFormatPlugin(), collect_only=False, with_threads=True):
    return self.virt_env.export_vms(vms_names, standalone, export_dir, compress, init_file_name, out_format, collect_only, with_threads)

Export vm images disks and init file.
The exported images and init file can be used to recreate
the environment.

Args:
vms_names(list of str): Names of the vms to export, if None
export all the vms in the env (default=None)
standalone(bool): If false, export a layered image
(default=False)
export_dir(str): Dir to place the exported images and init file
compress(bool): If True compress the images with xz
(default=False)
init_file_name(str): The name of the exported init file
(default='LagoInitfile')
out_format(:class:`lago.plugins.output.OutFormatPlugin`):
The type of the exported init file (the default is yaml)
collect_only(bool): If True, return only a mapping from vm name
to the disks that will be exported. (default=False)
with_threads(bool): If True, run the export in parallel
(default=True)

Returns
Unless collect_only == True, a mapping between vms' disks.


def get_version(here_path, default_version=DEFAULT_VERSION):
    if ('site-packages' in here_path):
        return _version_from_file(here_path)
    if os.environ.get('TRAVIS_TAG'):
        if (not TEST_MODE):
            return os.environ.get('TRAVIS_TAG').replace('v', '')
        else:
            warnings.warn('Travis detected, but TEST_MODE enabled', exceptions.ProsperVersionTestModeWarning)
    try:
        current_tag = _read_git_tags(default_version=default_version)
    except Exception:
        return _version_from_file(here_path)
    with open(os.path.join(here_path, 'version.txt'), 'w') as v_fh:
        v_fh.write(current_tag)
    return current_tag

tries to resolve version number

Args:
here_path (str): path to project local dir
default_version (str): what version to return if all else fails

Returns:
str: semantic_version information for library


def keyDown(key, pause=None, _pause=True):

    if len(key) > 1:
        key = key.lower()

    _failSafeCheck()
    platformModule._keyDown(key)

    _autoPause(pause, _pause)

Performs a keyboard key press without the release. This will put that
key in a held down state.

NOTE: For some reason, this does not seem to cause key repeats like would
happen if a keyboard key was held down on a text field.

Args:
key (str): The key to be pressed down. The valid names are listed in
KEYBOARD_KEYS.

Returns:
None


def read(self, size):

        now = time.time()
        missing_dt = self._sleep_until - now
        if missing_dt > 0:
            time.sleep(missing_dt)
        self._sleep_until = time.time() + self._sleep_time(size)
        data = (self._wavep.readframes(size)
                if self._wavep
                else self._fp.read(size))

        if not data:
            return b'\x00' * size
        return data

Read bytes from the stream and block until sample rate is achieved.

Args:
size: number of bytes to read from the stream.


def merge_resources(resource1, resource2):
    merged = resource1.copy()
    merged.update(resource2)
    return merged

Updates a copy of resource1 with resource2 values and returns the merged dictionary.

Args:
resource1: original resource
resource2: resource to update resource1

Returns:
dict: merged resource


def get_image_features(self, pixel_values: torch.FloatTensor, pixel_mask: Optional[torch.FloatTensor]=None, vision_feature_layer: int=-1):
    vision_feature_layer = vision_feature_layer if vision_feature_layer is not None else self.config.vision_feature_layer
    patch_attention_mask = self._create_patch_attention_mask(pixel_mask)
    image_outputs = self.vision_tower(pixel_values, patch_attention_mask=patch_attention_mask, output_hidden_states=True)
    image_attn_mask = None
    if patch_attention_mask is not None:
        flattened_mask = patch_attention_mask.flatten(1)
        image_attn_mask = torch.logical_not(flattened_mask)
    selected_image_feature = image_outputs.hidden_states[vision_feature_layer]
    image_features = self.multi_modal_projector(selected_image_feature, attn_mask=image_attn_mask)
    return image_features

Obtains image last hidden states from the vision tower and apply multimodal projection.

Args:
pixel_values (`torch.FloatTensor]` of shape `(batch_size, channels, height, width)`):
The tensors corresponding to the input images.
pixel_mask (`torch.FloatTensor]`, *optional*):
The tensors corresponding to the input image mask.
vision_feature_layer (`Union[int, List[int]]`, *optional*):
The index of the layer to select the vision feature. If multiple indices are provided,
the vision feature of the corresponding indices will be concatenated to form the
vision features.
Returns:
image_features (`torch.Tensor`): Image feature tensor of shape `(num_images, image_length, embed_dim)`).


def __init__(self,
               url,
               params,
               name=None,
               eta=None,
               countdown=None,
               parent=None,
               headers=None):

    self.url = url
    self.name = name
    self.eta = eta
    self.countdown = countdown
    self._headers = {
        "Content-Type": "application/octet-stream",
        self.PAYLOAD_VERSION_HEADER: self.PAYLOAD_VERSION
    }
    if headers:
      self._headers.update(headers)

    payload_str = urllib.urlencode(params)
    compressed_payload = ""
    if len(payload_str) > self.MAX_TASK_PAYLOAD:
      compressed_payload = zlib.compress(payload_str)

    if not compressed_payload:
      self._payload = payload_str

    elif len(compressed_payload) < self.MAX_TASK_PAYLOAD:
      self._payload = self.PAYLOAD_PARAM + compressed_payload
    elif len(compressed_payload) > self.MAX_DB_PAYLOAD:
      raise ValueError(
          "Payload from %s to big to be stored in database: %s" %
          (self.name, len(compressed_payload)))

    else:
      if not parent:
        raise ValueError("Huge tasks should specify parent entity.")

      payload_entity = _HugeTaskPayload(payload=compressed_payload,
                                        parent=parent)
      payload_key = payload_entity.put()
      self._payload = self.PAYLOAD_KEY_PARAM + str(payload_key)

Init.

Args:
url: task url in str.
params: a dict from str to str.
name: task name.
eta: task eta.
countdown: task countdown.
parent: parent entity of huge task's payload.
headers: a dict of headers for the task.

Raises:
ValueError: when payload is too big even for datastore, or parent is
not specified when payload is stored in datastore.


def Serialize(self, writer):

        self.SerializeUnsigned(writer)
        writer.WriteByte(1)
        self.Script.Serialize(writer)

Serialize full object.

Args:
writer (neo.IO.BinaryWriter):


def post_async(self, path, params=None):
    request = Post(self._get_next_id(), path, params)
    request.set_callback(self._q.put)
    future = self._dispatch_request(request)
    return future

Asynchronously calls a function on a child block

Args:
path (list): The path to post to
params (dict): parameters for the call

Returns:
Future: as single Future that will resolve to the result


def __init__(self, channel):

        self.BatchAnnotateImages = channel.unary_unary(
            "/google.cloud.vision.v1p4beta1.ImageAnnotator/BatchAnnotateImages",
            request_serializer=google_dot_cloud_dot_vision__v1p4beta1_dot_proto_dot_image__annotator__pb2.BatchAnnotateImagesRequest.SerializeToString,
            response_deserializer=google_dot_cloud_dot_vision__v1p4beta1_dot_proto_dot_image__annotator__pb2.BatchAnnotateImagesResponse.FromString,
        )
        self.BatchAnnotateFiles = channel.unary_unary(
            "/google.cloud.vision.v1p4beta1.ImageAnnotator/BatchAnnotateFiles",
            request_serializer=google_dot_cloud_dot_vision__v1p4beta1_dot_proto_dot_image__annotator__pb2.BatchAnnotateFilesRequest.SerializeToString,
            response_deserializer=google_dot_cloud_dot_vision__v1p4beta1_dot_proto_dot_image__annotator__pb2.BatchAnnotateFilesResponse.FromString,
        )
        self.AsyncBatchAnnotateImages = channel.unary_unary(
            "/google.cloud.vision.v1p4beta1.ImageAnnotator/AsyncBatchAnnotateImages",
            request_serializer=google_dot_cloud_dot_vision__v1p4beta1_dot_proto_dot_image__annotator__pb2.AsyncBatchAnnotateImagesRequest.SerializeToString,
            response_deserializer=google_dot_longrunning_dot_operations__pb2.Operation.FromString,
        )
        self.AsyncBatchAnnotateFiles = channel.unary_unary(
            "/google.cloud.vision.v1p4beta1.ImageAnnotator/AsyncBatchAnnotateFiles",
            request_serializer=google_dot_cloud_dot_vision__v1p4beta1_dot_proto_dot_image__annotator__pb2.AsyncBatchAnnotateFilesRequest.SerializeToString,
            response_deserializer=google_dot_longrunning_dot_operations__pb2.Operation.FromString,
        )

Constructor.

Args:
channel: A grpc.Channel.


def verify(self, byts, sign):

        try:
            chosen_hash = c_hashes.SHA256()
            hasher = c_hashes.Hash(chosen_hash, default_backend())
            hasher.update(byts)
            digest = hasher.finalize()
            self.publ.verify(sign,
                             digest,
                             c_ec.ECDSA(c_utils.Prehashed(chosen_hash))
                             )
            return True
        except InvalidSignature:
            logger.exception('Error in publ.verify')
            return False

Verify the signature for the given bytes using the ECC
public key.

Args:
byts (bytes): The data bytes.
sign (bytes): The signature bytes.

Returns:
bool: True if the data was verified, False otherwise.


def get_op(self, id: str, **kwargs: str) -> dict:
    path = self._get_path_for_op_id(id)
    return self.get_path(path, kwargs)

Queries the ESI by looking up an operation id.

Endpoints are cached, so calls to this method
for the same op and args will return the data
from the cache instead of making the API call.

Args:
id: operation id
kwargs: data to populate the endpoint's URL variables

Returns:
ESI data


def _UpdateSudoer(self, user, sudoer=False):

    if sudoer:
      self.logger.info('Adding user %s to the Google sudoers group.', user)
      command = self.gpasswd_add_cmd.format(
          user=user, group=self.google_sudoers_group)
    else:
      self.logger.info('Removing user %s from the Google sudoers group.', user)
      command = self.gpasswd_remove_cmd.format(
          user=user, group=self.google_sudoers_group)

    try:
      subprocess.check_call(command.split(' '))
    except subprocess.CalledProcessError as e:
      self.logger.warning('Could not update user %s. %s.', user, str(e))
      return False
    else:
      self.logger.debug('Removed user %s from the Google sudoers group.', user)
      return True

Update sudoer group membership for a Linux user account.

Args:
user: string, the name of the Linux user account.
sudoer: bool, True if the user should be a sudoer.

Returns:
bool, True if user update succeeded.


def dump_values(self, with_defaults=True, dict_cls=dict, flat=False):
    values = dict_cls()
    if flat:
        for (str_path, item) in self.iter_items(recursive=True, key='str_path'):
            if item.has_value:
                if (with_defaults or (not item.is_default)):
                    values[str_path] = item.value
    else:
        for (item_name, item) in self._tree.items():
            if is_config_section(item):
                section_values = item.dump_values(with_defaults=with_defaults, dict_cls=dict_cls)
                if section_values:
                    values[item_name] = section_values
            elif item.has_value:
                if (with_defaults or (not item.is_default)):
                    values[item.name] = item.value
    return values

Export values of all items contained in this section to a dictionary.

Items with no values set (and no defaults set if ``with_defaults=True``) will be excluded.

Returns:
dict: A dictionary of key-value pairs, where for sections values are dictionaries
of their contents.


def get_boards(self, **query_params):
    boards = self.get_boards_json(self.base_uri, query_params=query_params)
    boards_list = []
    for board_json in boards:
        boards_list.append(self.create_board(board_json))
    return boards_list

Get all the boards for this organisation. Returns a list of Board s.

Returns:
list(Board): The boards attached to this organisation


def find_file_in_load_dirs(relpath):
    if relpath.startswith(os.path.sep):
        relpath = relpath.lstrip(os.path.sep)
    for ld in settings.DATA_DIRECTORIES:
        possible_path = os.path.join(ld, relpath)
        if os.path.exists(possible_path):
            return possible_path

If given relative path exists in one of DevAssistant load paths,
return its full path.

Args:
relpath: a relative path, e.g. "assitants/crt/test.yaml"

Returns:
absolute path of the file, e.g. "/home/x/.devassistant/assistanta/crt/test.yaml
or None if file is not found


def execute_rex_code(self, code, filename=None, shell=None, parent_environ=None, **Popen_args):

    def _actions_callback(executor):
        executor.execute_code(code, filename=filename)
    return self.execute_shell(shell=shell, parent_environ=parent_environ, command='', block=False, actions_callback=_actions_callback, **Popen_args)

Run some rex code in the context.

Note:
This is just a convenience form of `execute_shell`.

Args:
code (str): Rex code to execute.
filename (str): Filename to report if there are syntax errors.
shell: Shell type, for eg 'bash'. If None, the current shell type
is used.
parent_environ: Environment to run the shell process in, if None
then the current environment is used.
Popen_args: args to pass to the shell process object constructor.

Returns:
`subprocess.Popen` object for the shell process.


def retry(self, **kwargs):
    path = ('%s/%s/retry' % (self.manager.path, self.get_id()))
    self.manager.gitlab.http_post(path)

Retry the job.

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

Raises:
GitlabAuthenticationError: If authentication is not correct
GitlabJobRetryError: If the job could not be retried


def build_graph(path, term_depth=1000, skim_depth=10,
                d_weights=False, **kwargs):

    click.echo('\nTokenizing text...')
    t = Text.from_file(path)
    click.echo('Extracted %d tokens' % len(t.tokens))

    m = Matrix()

    click.echo('\nIndexing terms:')
    m.index(t, t.most_frequent_terms(term_depth), **kwargs)

    g = Skimmer()

    click.echo('\nGenerating graph:')
    g.build(t, m, skim_depth, d_weights)

    return g

Tokenize a text, index a term matrix, and build out a graph.

Args:
path (str): The file path.
term_depth (int): Consider the N most frequent terms.
skim_depth (int): Connect each word to the N closest siblings.
d_weights (bool): If true, give "close" nodes low weights.

Returns:
Skimmer: The indexed graph.


def MakeSelfExtractingZip(self, payload_data, output_path):
    context = (self.context + ['Client Context'])
    src_zip = zipfile.ZipFile(io.BytesIO(payload_data), mode='r')
    zip_data = io.BytesIO()
    output_zip = zipfile.ZipFile(zip_data, mode='w', compression=zipfile.ZIP_DEFLATED)
    config_file_name = config.CONFIG.Get('ClientBuilder.config_filename', context=context)
    for template_file in src_zip.namelist():
        if (template_file != config_file_name):
            CopyFileInZip(src_zip, template_file, output_zip)
    client_config_content = self.GetClientConfig(context)
    output_zip.writestr(config_file_name, client_config_content.encode('utf-8'), compress_type=zipfile.ZIP_STORED)
    output_zip.comment = (b'$AUTORUN$>%s' % config.CONFIG.Get('ClientBuilder.autorun_command_line', context=context).encode('utf-8'))
    output_zip.close()
    utils.EnsureDirExists(os.path.dirname(output_path))
    with open(output_path, 'wb') as fd:
        stub_data = io.BytesIO()
        unzipsfx_stub = config.CONFIG.Get('ClientBuilder.unzipsfx_stub', context=context)
        stub_raw = open(unzipsfx_stub, 'rb').read()
        if (b'level="requireAdministrator' not in stub_raw):
            raise RuntimeError('Bad unzip binary in use. Not compiled with therequireAdministrator manifest option.')
        stub_data.write(stub_raw)
        SetPeSubsystem(stub_data, console=config.CONFIG.Get('ClientBuilder.console', context=context))
        end_of_file = (zip_data.tell() + stub_data.tell())
        offset_to_rsrc = stub_data.getvalue().find(b'.rsrc')
        stub_data.seek((offset_to_rsrc + 20))
        start_of_rsrc_section = struct.unpack('<I', stub_data.read(4))[0]
        stub_data.seek((offset_to_rsrc + 16))
        stub_data.write(struct.pack('<I', (end_of_file - start_of_rsrc_section)))
        out_data = io.BytesIO()
        out_data.write(stub_data.getvalue())
        out_data.write(zip_data.getvalue())
        fd.write(out_data.getvalue())
    if self.signer:
        self.signer.SignFile(output_path)
    logging.info('Deployable binary generated at %s', output_path)
    return output_path

Repack the installer into the payload.

Args:
payload_data: data payload for zip file
output_path: filename for the zip output

Raises:
RuntimeError: if the ClientBuilder.unzipsfx_stub doesn't require admin.
Returns:
output_path: filename string of zip output file


def combine_heads(self, x):
    with tf.name_scope('combine_heads'):
        batch_size = tf.shape(x)[0]
        length = tf.shape(x)[2]
        x = tf.transpose(x, [0, 2, 1, 3])
        return tf.reshape(x, [batch_size, length, self.hidden_size])

Combine tensor that has been split.

Args:
x: A tensor [batch_size, num_heads, length, hidden_size/num_heads]

Returns:
A tensor with shape [batch_size, length, hidden_size]


def connect_async(self, connection_id, connection_string, callback):

        if callback is not None:
            callback(connection_id, self.id, False, "connect command is not supported in device adapter")

Asynchronously connect to a device

Args:
connection_id (int): A unique identifier that will refer to this connection
connection_string (string): A DeviceAdapter specific string that can be used to connect to
a device using this DeviceAdapter.
callback (callable): A function that will be called when the connection attempt finishes as
callback(connection_id, adapter_id, success: bool, failure_reason: string or None)


def pack_eager_tensors(self, tensors):
    self.ensure_initialized()
    return pywrap_tfe.TFE_Py_PackEagerTensors(self._handle, tensors)

Pack multiple `EagerTensor`s of the same dtype and shape.

Args:
tensors: a list of EagerTensors to pack.

Returns:
A packed EagerTensor.


def objects_delete(self, bucket, key):
    url = (Api._ENDPOINT + (Api._OBJECT_PATH % (bucket, Api._escape_key(key))))
    datalab.utils.Http.request(url, method='DELETE', credentials=self._credentials, raw_response=True)

Deletes the specified object.

Args:
bucket: the name of the bucket.
key: the key of the object within the bucket.
Raises:
Exception if there is an error performing the operation.


def configure(self, sbi_config: str):
    config_dict = json.loads(sbi_config)
    self.debug_stream('SBI configuration:\n%s', json.dumps(config_dict, indent=2))
    try:
        sbi = Subarray(self.get_name()).configure_sbi(config_dict)
    except jsonschema.exceptions.ValidationError as error:
        return json.dumps(dict(path=error.absolute_path.__str__(), schema_path=error.schema_path.__str__(), message=error.message), indent=2)
    except RuntimeError as error:
        return json.dumps(dict(error=str(error)), indent=2)
    return 'Accepted SBI: {}'.format(sbi.id)

Configure an SBI for this subarray.

Args:
sbi_config (str): SBI configuration JSON

Returns:
str,


def prod(x, axis=None, keepdims=False, dtype=None):
    if any_symbolic_tensors((x,)):
        return Prod(axis=axis, keepdims=keepdims, dtype=dtype).symbolic_call(x)
    return backend.numpy.prod(x, axis=axis, keepdims=keepdims, dtype=dtype)

Return the product of tensor elements over a given axis.

Args:
x: Input tensor.
axis: Axis or axes along which a product is performed. The default,
`axis=None`, will compute the product of all elements
in the input tensor.
keepdims: If this is set to `True`, the axes which are reduce
are left in the result as dimensions with size one.
dtype: Data type of the returned tensor.

Returns:
Product of elements of `x` over the given axis or axes.


def _make_model_class(message_type, indexed_fields, **props):
    analyzed = _analyze_indexed_fields(indexed_fields)
    for (field_name, sub_fields) in analyzed.iteritems():
        if (field_name in props):
            raise ValueError(('field name %s is reserved' % field_name))
        try:
            field = message_type.field_by_name(field_name)
        except KeyError:
            raise ValueError(('Message type %s has no field named %s' % (message_type.__name__, field_name)))
        if isinstance(field, messages.MessageField):
            if (not sub_fields):
                raise ValueError(('MessageField %s cannot be indexed, only sub-fields' % field_name))
            sub_model_class = _make_model_class(field.type, sub_fields)
            prop = model.StructuredProperty(sub_model_class, field_name, repeated=field.repeated)
        else:
            if (sub_fields is not None):
                raise ValueError(('Unstructured field %s cannot have indexed sub-fields' % field_name))
            if isinstance(field, messages.EnumField):
                prop = EnumProperty(field.type, field_name, repeated=field.repeated)
            elif isinstance(field, messages.BytesField):
                prop = model.BlobProperty(field_name, repeated=field.repeated, indexed=True)
            else:
                prop = model.GenericProperty(field_name, repeated=field.repeated)
        props[field_name] = prop
    return model.MetaModel(('_%s__Model' % message_type.__name__), (model.Model,), props)

Construct a Model subclass corresponding to a Message subclass.

Args:
message_type: A Message subclass.
indexed_fields: A list of dotted and undotted field names.
**props: Additional properties with which to seed the class.

Returns:
A Model subclass whose properties correspond to those fields of
message_type whose field name is listed in indexed_fields, plus
the properties specified by the **props arguments.  For dotted
field names, a StructuredProperty is generated using a Model
subclass created by a recursive call.

Raises:
Whatever _analyze_indexed_fields() raises.
ValueError if a field name conflicts with a name in **props.
ValueError if a field name is not valid field of message_type.
ValueError if an undotted field name designates a MessageField.


def _update_annotations(discretized_pulse: Callable) -> Callable:

    undecorated_annotations = list(discretized_pulse.__annotations__.items())
    decorated_annotations = undecorated_annotations[1:]
    decorated_annotations.insert(0, ('duration', int))
    discretized_pulse.__annotations__ = dict(decorated_annotations)
    return discretized_pulse

Update annotations of discretized continuous pulse function with duration.

Args:
discretized_pulse: Discretized decorated continuous pulse.


def setNetworkKey(self, key):

        masterKey = ''
        print '%s call setNetworkKey' % self.port

        try:
            if not isinstance(key, str):
                masterKey = self.__convertLongToString(key)

                if len(masterKey) < 32:
                    masterKey = masterKey.zfill(32)

                cmd = WPANCTL_CMD + 'setprop Network:Key %s' % masterKey
                datasetCmd = WPANCTL_CMD + 'setprop Dataset:MasterKey %s' % masterKey
            else:
                masterKey = key
                cmd = WPANCTL_CMD + 'setprop Network:Key %s' % masterKey
                datasetCmd = WPANCTL_CMD + 'setprop Dataset:MasterKey %s' % masterKey

            self.networkKey = masterKey
            self.hasActiveDatasetToCommit = True
            return self.__sendCommand(cmd)[0] != 'Fail' and self.__sendCommand(datasetCmd)[0] != 'Fail'
        except Exception, e:
            ModuleHelper.WriteIntoDebugLogger('setNetworkkey() Error: ' + str(e))

set Thread Network master key

Args:
key: Thread Network master key used in secure the MLE/802.15.4 packet

Returns:
True: successful to set the Thread Network master key
False: fail to set the Thread Network master key


def markdown_to_text(body):
    md = markdown.markdown(body, extensions=['markdown.extensions.extra'])
    soup = BeautifulSoup(md, 'html.parser')
    return soup.get_text()

Converts markdown to text.

Args:
body: markdown (or plaintext, or maybe HTML) input

Returns:
Plaintext with all tags and frills removed


def intraday(ticker, dt, session='', **kwargs) -> pd.DataFrame:
    from xbbg.core import intervals
    cur_data = bdib(ticker=ticker, dt=dt, typ=kwargs.get('typ', 'TRADE'))
    if cur_data.empty:
        return pd.DataFrame()
    fmt = '%H:%M:%S'
    ss = intervals.SessNA
    ref = kwargs.get('ref', None)
    exch = (pd.Series() if (ref is None) else const.exch_info(ticker=ref))
    if session:
        ss = intervals.get_interval(ticker=kwargs.get('ref', ticker), session=session)
    start_time = kwargs.get('start_time', None)
    end_time = kwargs.get('end_time', None)
    if (ss != intervals.SessNA):
        start_time = pd.Timestamp(ss.start_time).strftime(fmt)
        end_time = pd.Timestamp(ss.end_time).strftime(fmt)
    if (start_time and end_time):
        kw = dict(start_time=start_time, end_time=end_time)
        if (not exch.empty):
            cur_tz = cur_data.index.tz
            res = cur_data.tz_convert(exch.tz).between_time(**kw)
            if kwargs.get('keep_tz', False):
                res = res.tz_convert(cur_tz)
            return pd.DataFrame(res)
        return pd.DataFrame(cur_data.between_time(**kw))
    return cur_data

Bloomberg intraday bar data within market session

Args:
ticker: ticker
dt: date
session: examples include
day_open_30, am_normal_30_30, day_close_30, allday_exact_0930_1000
**kwargs:
ref: reference ticker or exchange for timezone
keep_tz: if keep tz if reference ticker / exchange is given
start_time: start time
end_time: end time
typ: [TRADE, BID, ASK, BID_BEST, ASK_BEST, BEST_BID, BEST_ASK]

Returns:
pd.DataFrame


def pop(self, identifier, default=None):
    if (identifier in self.children):
        item = self[identifier]
        self.__delitem__(identifier)
        return item
    else:
        return default

Pop a node of the AttrTree using its path string.

Args:
identifier: Path string of the node to return
default: Value to return if no node is found

Returns:
The node that was removed from the AttrTree


def get_index(self, prefix=''):
    if prefix:
        prefixed = ('%s_index' % prefix)
    else:
        prefixed = 'index'
    if ((prefixed in self.__cli) and self.__cli[prefixed]):
        index = self.__cli.get(prefixed)
        from_conf = False
    else:
        index = self.__config.get(prefixed)
        from_conf = True
    return self.__abspath(index, from_conf)

Retrieve the absolute path to an index, according to
`prefix`.

Args:
prefix: str, the desired prefix or `None`.

Returns:
str: An absolute path, or `None`


def _get_no_split_modules(self, device_map: str):
    _no_split_modules = set()
    modules_to_check = [self]
    while len(modules_to_check) > 0:
        module = modules_to_check.pop(-1)
        if module.__class__.__name__ not in _no_split_modules:
            if isinstance(module, PreTrainedModel):
                if module._no_split_modules is None:
                    raise ValueError(f"{module.__class__.__name__} does not support `device_map='{device_map}'`. To implement support, the model class needs to implement the `_no_split_modules` attribute.")
                else:
                    _no_split_modules = _no_split_modules | set(module._no_split_modules)
            modules_to_check += list(module.children())
    return list(_no_split_modules)

Get the modules of the model that should not be spit when using device_map. We iterate through the modules to
get the underlying `_no_split_modules`.

Args:
device_map (`str`):
The device map value. Options are ["auto", "balanced", "balanced_low_0", "sequential"]

Returns:
`List[str]`: List of modules that should not be split


def submodules(self):
    return tuple(self._flatten(predicate=_is_module))

Sequence of all sub-modules.

Submodules are modules which are properties of this module, or found as
properties of modules which are properties of this module (and so on).

>>> a = tf.Module()
>>> b = tf.Module()
>>> c = tf.Module()
>>> a.b = b
>>> b.c = c
>>> list(a.submodules) == [b, c]
True
>>> list(b.submodules) == [c]
True
>>> list(c.submodules) == []
True

Returns:
A sequence of all submodules.


async def update_state(self, name, state):

        await self.send_command(OPERATIONS.CMD_UPDATE_STATE,
                                {'name': name, 'new_status': state},
                                MESSAGES.UpdateStateResponse, timeout=5.0)

Update the state for a service.

Args:
name (string): The name of the service
state (int): The new state of the service


def mnist_common_generator(tmp_dir,
                           training,
                           how_many,
                           data_filename,
                           label_filename,
                           start_from=0):

  data_path = os.path.join(tmp_dir, data_filename)
  labels_path = os.path.join(tmp_dir, label_filename)
  images = _extract_mnist_images(data_path, 60000 if training else 10000)
  labels = _extract_mnist_labels(labels_path, 60000 if training else 10000)

  data = list(zip(images, labels))
  random.shuffle(data)
  images, labels = list(zip(*data))
  return image_utils.image_generator(images[start_from:start_from + how_many],
                                     labels[start_from:start_from + how_many])

Image generator for MNIST.

Args:
tmp_dir: path to temporary storage directory.
training: a Boolean; if true, we use the train set, otherwise the test set.
how_many: how many images and labels to generate.
data_filename: file that contains features data.
label_filename: file that contains labels.
start_from: from which image to start.

Returns:
An instance of image_generator that produces MNIST images.


def __init__(self, latent_size, hidden_size):

    super(EncoderDynamicFactorized, self).__init__()
    self.latent_size = latent_size
    self.hidden_size = hidden_size
    self.dense = tf.keras.layers.Dense(hidden_size, activation=tf.nn.leaky_relu)
    self.output_layer = tf.keras.layers.Dense(2*latent_size)

Constructs a "factorized" encoder for `z_t`.

Args:
latent_size: An integer corresponding to the
dimensionality of the distribution.
hidden_size: Dimensionality of the affine function parameters.


def _create_hash_str(self, input_arg, output_arg, node_def):
    hasher = hashlib.sha1()

    def update_num(n):
        hasher.update(compat.as_bytes('%x' % n))

    def update_str(s):
        update_num(len(s))
        hasher.update(compat.as_bytes(s))

    def update_strs(slist):
        update_num(len(slist))
        for s in slist:
            update_str(s)
    for adef in input_arg:
        update_str(adef.SerializeToString())
    for adef in output_arg:
        update_str(adef.SerializeToString())
    for n in sorted(node_def, key=lambda n: n.name):
        update_str(n.name)
        update_str(n.op)
        update_strs(n.input)
        update_num(len(n.attr))
        for k in sorted(n.attr):
            update_str(k)
            update_str(n.attr[k].SerializeToString())
    return hasher.hexdigest()[:8]

Creates an 8-character string unique to this input.

Args:
input_arg: the input_arg field of an OpDef
(e.g. self._definition.signature.input_arg)
output_arg: the output_arg field of an OpDef
(e.g. self._definition.signature.output_arg)
node_def: the node_def field of a FunctionDef
(e.g. self._definition.node_def)

Returns:
The unique string for this input


def __init__(self, semantic_config: Optional[Dict]=None, coarse_acoustics_config: Optional[Dict]=None, fine_acoustics_config: Optional[Dict]=None, sample_rate=24000, codebook_size=1024, **kwargs):
    if semantic_config is None:
        semantic_config = {}
        logger.info('semantic_config is None. initializing the semantic model with default values.')
    if coarse_acoustics_config is None:
        coarse_acoustics_config = {}
        logger.info('coarse_acoustics_config is None. initializing the coarse model with default values.')
    if fine_acoustics_config is None:
        fine_acoustics_config = {}
        logger.info('fine_acoustics_config is None. initializing the fine model with default values.')
    self.semantic_config = BarkSemanticGenerationConfig(**semantic_config)
    self.coarse_acoustics_config = BarkCoarseGenerationConfig(**coarse_acoustics_config)
    self.fine_acoustics_config = BarkFineGenerationConfig(**fine_acoustics_config)
    self.sample_rate = sample_rate
    self.codebook_size = codebook_size

Class that holds a generation configuration for [`BarkModel`].

The [`BarkModel`] does not have a `generate` method, but uses this class to generate speeches with a nested
[`BarkGenerationConfig`] which uses [`BarkSemanticGenerationConfig`], [`BarkCoarseGenerationConfig`],
[`BarkFineGenerationConfig`].

This configuration inherit from [`GenerationConfig`] and can be used to control the model generation. Read the
documentation from [`GenerationConfig`] for more information.

Args:
semantic_config (`Dict`, *optional*):
Semantic generation configuration.
coarse_acoustics_config (`Dict`, *optional*):
Coarse generation configuration.
fine_acoustics_config (`Dict`, *optional*):
Fine generation configuration.
sample_rate (`int`, *optional*, defaults to 24_000):
Sample rate.
codebook_size (`int`, *optional*, defaults to 1024):
Vector length for each codebook.


def speed_metrics(split, start_time, num_samples=None, num_steps=None, num_tokens=None):
    runtime = time.time() - start_time
    result = {f'{split}_runtime': round(runtime, 4)}
    if runtime == 0:
        return result
    if num_samples is not None:
        samples_per_second = num_samples / runtime
        result[f'{split}_samples_per_second'] = round(samples_per_second, 3)
    if num_steps is not None:
        steps_per_second = num_steps / runtime
        result[f'{split}_steps_per_second'] = round(steps_per_second, 3)
    if num_tokens is not None:
        tokens_per_second = num_tokens / runtime
        result[f'{split}_tokens_per_second'] = round(tokens_per_second, 3)
    return result

Measure and return speed performance metrics.

This function requires a time snapshot `start_time` before the operation to be measured starts and this function
should be run immediately after the operation to be measured has completed.

Args:
- split: name to prefix metric (like train, eval, test...)
- start_time: operation start time
- num_samples: number of samples processed
- num_steps: number of steps processed
- num_tokens: number of tokens processed


def setModelData(self, editor, model, index):

        model.setData(index, editor.itemText(editor.currentIndex()))

Updates the model after changing data in the editor.

Args:
editor (QtGui.QComboBox): The current editor for the item. Should be
a `QtGui.QComboBox` as defined in `createEditor`.
model (ColumnDtypeModel): The model which holds the displayed data.
index (QtCore.QModelIndex): The index of the current item of the model.


def ValidateServiceGaps(self, problems, validation_start_date, validation_end_date, service_gap_interval):
    if (service_gap_interval is None):
        return
    departures = self.GenerateDateTripsDeparturesList(validation_start_date, validation_end_date)
    first_day_without_service = validation_start_date
    last_day_without_service = validation_start_date
    consecutive_days_without_service = 0
    for (day_date, day_trips, _) in departures:
        if (day_trips == 0):
            if (consecutive_days_without_service == 0):
                first_day_without_service = day_date
            consecutive_days_without_service += 1
            last_day_without_service = day_date
        else:
            if (consecutive_days_without_service >= service_gap_interval):
                problems.TooManyDaysWithoutService(first_day_without_service, last_day_without_service, consecutive_days_without_service)
            consecutive_days_without_service = 0
    if (consecutive_days_without_service >= service_gap_interval):
        problems.TooManyDaysWithoutService(first_day_without_service, last_day_without_service, consecutive_days_without_service)

Validate consecutive dates without service in the feed.
Issue a warning if it finds service gaps of at least
"service_gap_interval" consecutive days in the date range
[validation_start_date, last_service_date)

Args:
problems: The problem reporter object
validation_start_date: A date object representing the date from which the
validation should take place
validation_end_date: A date object representing the first day the feed is
active
service_gap_interval: An integer indicating how many consecutive days the
service gaps need to have for a warning to be issued

Returns:
None


def add_edge_bias(x, filter_size):

  x_shape = common_layers.shape_list(x)
  if filter_size[0] == 1 and filter_size[1] == 1:
    return x
  a = (filter_size[0] - 1)
  b = (filter_size[1] - 1)
  padding = [[0, 0], [a, a], [b, b], [0, 0]]
  x_bias = tf.zeros(x_shape[:-1] + [1])

  x = tf.pad(x, padding)
  x_pad = tf.pad(x_bias, padding, constant_values=1)
  return tf.concat([x, x_pad], axis=3)

Pad x and concatenates an edge bias across the depth of x.

The edge bias can be thought of as a binary feature which is unity when
the filter is being convolved over an edge and zero otherwise.

Args:
x: Input tensor, shape (NHWC)
filter_size: filter_size to determine padding.
Returns:
x_pad: Input tensor, shape (NHW(c+1))


def generate_states(state_count, process_matrix, process_covariance, initial_state=None):
    process_matrix = np.atleast_2d(process_matrix)
    process_covariance = np.atleast_2d(process_covariance)
    state_dim = process_matrix.shape[0]
    if (process_matrix.shape != (state_dim, state_dim)):
        raise ValueError('Process matrix has inconsistent shape: {}'.format(process_matrix.shape))
    if (process_covariance.shape != (state_dim, state_dim)):
        raise ValueError('Process covariance has inconsistent shape: {}'.format(process_covariance.shape))
    if (initial_state is None):
        initial_state = np.zeros(process_matrix.shape[0])
    states = [initial_state]
    while (len(states) < state_count):
        states.append((process_matrix.dot(states[(- 1)]) + np.random.multivariate_normal(mean=np.zeros(state_dim), cov=process_covariance)))
    return np.vstack(states)

Generate states by simulating a linear system with constant process matrix
and process noise covariance.

Args:
state_count (int): Number of states to generate.
process_matrix (array): Square array
process_covariance (array): Square array specifying process noise
covariance.
initial_state (array or None): If omitted, use zero-filled vector as
initial state.


def curie_search(self, curie:str) -> dict:

        ilx_row = self.curie2row.get(curie)
        if not ilx_row:
            return None
        else:
            return ilx_row

Returns the row in InterLex associated with the curie

Note:
Pressumed to not have duplicate curies in InterLex
Args:
curie: The "prefix:fragment_id" of the existing_id pertaining to the ontology
Returns:
None or dict


def generate_code(max_length, max_nest, ops):

  stack = []
  def fetch_one():

    if stack:
      return stack.pop()
    else:

      value = random.randint(10 ** (max_length - 1), 10 ** max_length - 1)
      code = str(value)
      return value, code

  def fetch(num_operands):
    values, codes = zip(*[fetch_one() for _ in six.moves.range(num_operands)])
    return values, codes

  for _ in six.moves.range(max_nest):
    op = random.choice(ops)
    values, codes = fetch(op.num_operands)
    new_value = op.eval(values)
    new_code = op.get_code(codes)
    stack.append((new_value, "(" + new_code + ")"))
  final_value, final_code = stack.pop()
  final_code = final_code[1:-1]
  final_code.strip("()")
  if not op.is_memory:
    final_value = int(final_value) % 10 ** (max_length+1)
  return str(final_value), final_code

Generates code samples.

Args:
max_length: int.  max literal length.
max_nest: int. max nesting level.
ops: CodeOp. set of allowable operations.

Returns:
1. (str) output value.
2. (str) Code operation.


def read_committed_file(gitref, filename):
    repo = Repo()
    commitobj = repo.commit(gitref)
    blob = commitobj.tree[(_delta_dir() + filename)]
    return blob.data_stream.read()

Retrieve the content of a file in an old commit and returns it.

Ketword Arguments:
:gitref: (str) -- full reference of the git commit
:filename: (str) -- name (full path) of the file

Returns:
str -- content of the file