def get_stacks(self):
    if (not hasattr(self, '_stacks')):
        stacks = []
        definitions = self._get_stack_definitions()
        for stack_def in definitions:
            stack = Stack(definition=stack_def, context=self, mappings=self.mappings, force=(stack_def.name in self.force_stacks), locked=stack_def.locked, enabled=stack_def.enabled, protected=stack_def.protected)
            stacks.append(stack)
        self._stacks = stacks
    return self._stacks

Get the stacks for the current action.

Handles configuring the :class:`stacker.stack.Stack` objects that will
be used in the current action.

Returns:
list: a list of :class:`stacker.stack.Stack` objects


def analyze_one_classification_result(storage_client, file_path, adv_batch, dataset_batches, dataset_meta):
    class_result = read_classification_results(storage_client, file_path)
    if (class_result is None):
        return (0, 0, 0, 0)
    adv_images = adv_batch['images']
    dataset_batch_images = dataset_batches.data[adv_batch['dataset_batch_id']]['images']
    count_correctly_classified = 0
    count_errors = 0
    count_hit_target_class = 0
    num_images = 0
    for (adv_img_id, label) in iteritems(class_result):
        if (adv_img_id not in adv_images):
            continue
        num_images += 1
        clean_image_id = adv_images[adv_img_id]['clean_image_id']
        dataset_image_id = dataset_batch_images[clean_image_id]['dataset_image_id']
        if (label == dataset_meta.get_true_label(dataset_image_id)):
            count_correctly_classified += 1
        else:
            count_errors += 1
        if (label == dataset_meta.get_target_class(dataset_image_id)):
            count_hit_target_class += 1
    return (count_correctly_classified, count_errors, count_hit_target_class, num_images)

Reads and analyzes one classification result.

This method reads file with classification result and counts
how many images were classified correctly and incorrectly,
how many times target class was hit and total number of images.

Args:
storage_client: instance of CompetitionStorageClient
file_path: result file path
adv_batch: AversarialBatches.data[adv_batch_id]
adv_batch_id is stored in each ClassificationBatch entity
dataset_batches: instance of DatasetBatches
dataset_meta: instance of DatasetMetadata

Returns:
Tuple of (count_correctly_classified, count_errors, count_hit_target_class,
num_images)


def unzip_columns(expr, column_types):

    weld_obj = WeldObject(encoder_, decoder_)
    column_appenders = []
    struct_fields = []
    result_fields = []
    for i, column_type in enumerate(column_types):
        column_appenders.append("appender[%s]" % column_type)
        struct_fields.append("merge(b.$%s, e.$%s)" % (i, i))
        result_fields.append("result(unzip_builder.$%s)" % i)
    appender_string = "{%s}" % ", ".join(column_appenders)
    struct_string = "{%s}" % ", ".join(struct_fields)
    result_string = "{%s}" % ", ".join(result_fields)
    expr_var = weld_obj.update(expr)
    if isinstance(expr, WeldObject):
        expr_var = expr.obj_id
        weld_obj.dependencies[expr_var] = expr

    weld_template =

    weld_obj.weld_code = weld_template % {"expr": expr_var,
                                          "appenders": appender_string,
                                          "struct_builder": struct_string,
                                          "result": result_string}
    return weld_obj

Zip together multiple columns.

Args:
columns (WeldObject / Numpy.ndarray): lust of columns

Returns:
A WeldObject representing this computation


def save_plot(code, elem):
    if ('plt' in elem.attributes):
        (figurewidth, figureheight) = elem.attributes['plt'].split(',')
    else:
        try:
            figureheight = elem.attributes['height']
        except KeyError:
            figureheight = '4cm'
        try:
            figurewidth = elem.attributes['width']
        except KeyError:
            figurewidth = '6cm'
    return f

Converts matplotlib plots to tikz code.

If elem has either the plt attribute (format: plt=width,height) or the
attributes width=width and/or height=height, the figurewidth and -height
are set accordingly. If none are given, a height of 4cm and a width of 6cm
is used as default.

Args:
code: The matplotlib code.
elem: The element.

Returns:
The code and some code to invoke matplotlib2tikz.


def _ParseDateTimeValue(self, parser_mediator, date_time_value):

    if date_time_value[14] != 'Z':
      parser_mediator.ProduceExtractionWarning(
          'invalid date and time value: {0!s}'.format(date_time_value))
      return None

    try:
      year = int(date_time_value[0:4], 10)
      month = int(date_time_value[4:6], 10)
      day_of_month = int(date_time_value[6:8], 10)
      hours = int(date_time_value[8:10], 10)
      minutes = int(date_time_value[10:12], 10)
      seconds = int(date_time_value[12:14], 10)
    except (TypeError, ValueError):
      parser_mediator.ProduceExtractionWarning(
          'invalid date and time value: {0!s}'.format(date_time_value))
      return None

    time_elements_tuple = (year, month, day_of_month, hours, minutes, seconds)

    try:
      return dfdatetime_time_elements.TimeElements(
          time_elements_tuple=time_elements_tuple)
    except ValueError:
      parser_mediator.ProduceExtractionWarning(
          'invalid date and time value: {0!s}'.format(date_time_value))
      return None

Parses a date time value.

Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
date_time_value (str): date time value
(CSSM_DB_ATTRIBUTE_FORMAT_TIME_DATE) in the format: "YYYYMMDDhhmmssZ".

Returns:
dfdatetime.TimeElements: date and time extracted from the value or None
if the value does not represent a valid string.


def get(self, ldap_dn):
    self.base_dn = ldap_dn
    self.sub_tree = BASE
    return self.first()

Return an LDAP entry by DN

Args:
ldap_dn (str): LDAP DN


def get_both_blocks_sibling(self):
    if (not self.is_both_blocks()):
        return None
    if (self.block.block_letter and (self.block.block_letter.upper() not in ['A', 'B'])):
        return None
    other_instances = EighthScheduledActivity.objects.filter(activity=self.activity, block__date=self.block.date)
    for inst in other_instances:
        if (inst == self):
            continue
        if (inst.block.block_letter in ['A', 'B']):
            return inst
    return None

If this is a both-blocks activity, get the other EighthScheduledActivity
object that occurs on the other block.

both_blocks means A and B block, NOT all of the blocks on that day.

Returns:
EighthScheduledActivity object if found
None if the activity cannot have a sibling
False if not found


def on_train_end(self, logs=None):
    logs = self._process_logs(logs)
    for callback in self.callbacks:
        callback.on_train_end(logs)

Calls the `on_train_end` methods of its callbacks.

Args:
logs: Dict. Currently no data is passed to this argument for this method
but that may change in the future.


def _distributed_apply(self, distribution, grads_and_vars, global_step=None, name=None):
    name = name if name is not None else self.get_name()
    grads = [g for g, _ in grads_and_vars]
    loss_scale_update_op, should_apply_grads = self._loss_scale.update(grads)

    def apply_fn():
        return self._apply_gradients(distribution, grads_and_vars, global_step, name + '-wrapped')
    maybe_apply_op = smart_cond.smart_cond(should_apply_grads, apply_fn, control_flow_ops.no_op)
    return control_flow_ops.group(maybe_apply_op, loss_scale_update_op, name=name)

A version of `apply_gradients` for cross replica context.

When users are in a cross replica strategy, they must call this rather than
`apply_gradients()`.

Args:
distribution: a `DistributionStrategy` object.
grads_and_vars: List of (gradient, variable) pairs as returned by
`compute_gradients()` and then aggregated across replicas.
global_step: Optional (mirrored) `Variable` to increment by one after the
variables have been updated.
name: Optional name for the returned operation. Default to the name passed
to the `Optimizer` constructor.

Returns:
An `Operation` that applies the specified gradients across all
replicas. If `global_step` was not None, that operation also
increments `global_step`


def _add_transitions(mcs, field_name, workflow, attrs, implems=None):
    new_implems = ImplementationList(field_name, workflow)
    if implems:
        new_implems.load_parent_implems(implems)
    new_implems.transform(attrs)
    return new_implems

Collect and enhance transition definitions to a workflow.

Modifies the 'attrs' dict in-place.

Args:
field_name (str): name of the field transitions should update
workflow (Workflow): workflow we're working on
attrs (dict): dictionary of attributes to be updated.
implems (ImplementationList): Implementation list from parent
classes (optional)

Returns:
ImplementationList: The new implementation list for this field.


def get_without_ethernet(self, id_or_uri):
    uri = (self._client.build_uri(id_or_uri) + '/withoutEthernet')
    return self._client.get(uri)

Gets the logical downlink with the specified ID without ethernet.

Args:
id_or_uri: Can be either the logical downlink id or the logical downlink uri.

Returns:
dict


def recipe_email_cm_to_bigquery(config, auth_read, email, subject, dataset, table, is_incremental_load):
    email(config, {'auth': auth_read, 'read': {'from': 'noreply-cm@google.com', 'to': email, 'subject': subject, 'attachment': '.*'}, 'write': {'bigquery': {'dataset': dataset, 'table': table, 'header': True, 'is_incremental_load': is_incremental_load}}})

Pulls a CM Report from a gMail powered email account into BigQuery.

Args:
auth_read (authentication) - Credentials used for reading data.
email (string) - Email address report was sent to.
subject (string) - Regular expression to match subject. Double escape backslashes.
dataset (string) - Existing dataset in BigQuery.
table (string) - Name of table to be written to.
is_incremental_load (boolean) - Append report data to table based on date column, de-duplicates.


def retrieve(self, question_hidden_states: np.ndarray, n_docs: int) -> Tuple[np.ndarray, np.ndarray, List[dict]]:
    doc_ids, retrieved_doc_embeds = self._main_retrieve(question_hidden_states, n_docs)
    return (retrieved_doc_embeds, doc_ids, self.index.get_doc_dicts(doc_ids))

Retrieves documents for specified `question_hidden_states`.

Args:
question_hidden_states (`np.ndarray` of shape `(batch_size, vector_size)`):
A batch of query vectors to retrieve with.
n_docs (`int`):
The number of docs retrieved per query.

Return:
`Tuple[np.ndarray, np.ndarray, List[dict]]`: A tuple with the following objects:

- **retrieved_doc_embeds** (`np.ndarray` of shape `(batch_size, n_docs, dim)`) -- The retrieval embeddings
of the retrieved docs per query.
- **doc_ids** (`np.ndarray` of shape `(batch_size, n_docs)`) -- The ids of the documents in the index
- **doc_dicts** (`List[dict]`): The `retrieved_doc_embeds` examples per query.


def get_children_of_type(typ, root):

    if type(typ) is not text:
        typ = typ.__name__

    return get_children(lambda x: x.__class__.__name__ == typ, root)

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

Args:
typ(str or python class): The type of the model object we are
looking for.
root (model object): Python model object which is the start of the
search process.


def CopyToDict(self):
    path_spec_dict = {}
    for (attribute_name, attribute_value) in iter(self.__dict__.items()):
        if (attribute_value is None):
            continue
        if (attribute_name == 'parent'):
            attribute_value = attribute_value.CopyToDict()
        path_spec_dict[attribute_name] = attribute_value
    return path_spec_dict

Copies the path specification to a dictionary.

Returns:
dict[str, object]: path specification attributes.


def _guessEncoding(self, path):
    if (os.path.exists(path) and path.lower().endswith('csv')):
        encoding = None
        if (encoding is not None):
            if encoding.startswith('utf'):
                encoding = encoding.replace('-', '')
            encoding = encoding.replace('-', '_')
            viewValue = _encodings.get(encoding)
            self._encodingKey = encoding
            index = self._encodingComboBox.findText(viewValue.upper())
            self._encodingComboBox.setCurrentIndex(index)

Opens a file from the given `path` and checks the file encoding.

The file must exists on the file system and end with the extension
`.csv`. The file is read line by line until the encoding could be
guessed.
On a successfull identification, the widgets of this dialog will be
updated.

Args:
path (string): Path to a csv file on the file system.


def get_plugin_apps(self):
    return {_ACK_ROUTE: self._serve_ack, _COMM_ROUTE: self._serve_comm, _DEBUGGER_GRPC_HOST_PORT_ROUTE: self._serve_debugger_grpc_host_port, _DEBUGGER_GRAPH_ROUTE: self._serve_debugger_graph, _GATED_GRPC_ROUTE: self._serve_gated_grpc, _TENSOR_DATA_ROUTE: self._serve_tensor_data, _SOURCE_CODE_ROUTE: self._serve_source_code}

Obtains a mapping between routes and handlers.

This function also starts a debugger data server on separate thread if the
plugin has not started one yet.

Returns:
A mapping between routes and handlers (functions that respond to
requests).


def move_test_classes_into_scope(wrapped_test_module):
    for name, obj in wrapped_test_module.__dict__.items():
        if _is_test_class(obj):
            module_variables['tpu_test_imported_%s' % name] = obj

Add all test classes defined in wrapped module to our module.

The test runner works by inspecting the main module for TestCase classes, so
by adding a module-level reference to the TestCase we cause it to execute the
wrapped TestCase.

Args:
wrapped_test_module: The user-provided test code to run.


def WMITimeStrToRDFDatetime(self, timestr):

    offset_minutes = timestr[21:]
    year = timestr[:4]
    month = timestr[4:6]
    day = timestr[6:8]
    hours = timestr[8:10]
    minutes = timestr[10:12]
    seconds = timestr[12:14]
    microseconds = timestr[15:21]

    unix_seconds = calendar.timegm(
        tuple(map(int, [year, month, day, hours, minutes, seconds])))
    unix_seconds -= int(offset_minutes) * 60
    return rdfvalue.RDFDatetime(unix_seconds * 1e6 + int(microseconds))

Return RDFDatetime from string like 20140825162259.000000-420.

Args:
timestr: WMI time string

Returns:
rdfvalue.RDFDatetime

We have some timezone manipulation work to do here because the UTC offset is
in minutes rather than +-HHMM


def CreateTask(self, session_identifier):
    task = tasks.Task(session_identifier)
    logger.debug('Created task: {0:s}.'.format(task.identifier))
    with self._lock:
        self._tasks_queued[task.identifier] = task
        self._total_number_of_tasks += 1
        self.SampleTaskStatus(task, 'created')
    return task

Creates a task.

Args:
session_identifier (str): the identifier of the session the task is
part of.

Returns:
Task: task attribute container.


def _get_min_max_value_by_expanding_range(self, start_idx: int) -> tuple[float, float]:
    mse_min = (float('inf'), float('inf'), float('inf'))
    left, right = (start_idx, start_idx)
    move_left = True
    while not (left == 0 and right == self._num_bins - 1):
        if move_left and left > 0 or right == self._num_bins - 1:
            left = max(left - 1, 0)
        else:
            right = min(right + 1, self._num_bins - 1)
        move_left = not move_left
        quant_min, quant_max = (self._hist_mids[left], self._hist_mids[right])
        mse_tuple = self._get_weighted_mean_squared_error(quant_min, quant_max)
        mse_min = min(mse_tuple, mse_min)
    min_value, max_value = (mse_min[1], mse_min[2])
    return (min_value, max_value)

Starting from start_idx, expand left and right alternately to find the min value of mse loss.

Args:
start_idx: Index to start quantization.

Returns:
(min_value, max_value): Min and max calculated.


def log_combinations(n, counts, name='log_combinations'):
    with tf.name_scope(name):
        n = tf.convert_to_tensor(value=n, name='n')
        counts = tf.convert_to_tensor(value=counts, name='counts')
        total_permutations = tf.math.lgamma((n + 1))
        counts_factorial = tf.math.lgamma((counts + 1))
        redundant_permutations = tf.reduce_sum(input_tensor=counts_factorial, axis=[(- 1)])
        return (total_permutations - redundant_permutations)

Multinomial coefficient.

Given `n` and `counts`, where `counts` has last dimension `k`, we compute
the multinomial coefficient as:

```n! / sum_i n_i!```

where `i` runs over all `k` classes.

Args:
n: Floating-point `Tensor` broadcastable with `counts`. This represents `n`
outcomes.
counts: Floating-point `Tensor` broadcastable with `n`. This represents
counts in `k` classes, where `k` is the last dimension of the tensor.
name: A name for this operation (optional).

Returns:
`Tensor` representing the multinomial coefficient between `n` and `counts`.


def derive_field_name(self, field_name):
    cls = type(self)
    return cls(self[0], self[1], self[2], field_name, self[4], self[5])

Derives a new event from this one setting the ``field_name`` attribute.

Args:
field_name (Union[amazon.ion.symbols.SymbolToken, unicode]): The field name to set.
Returns:
IonEvent: The newly generated event.


def where_node_as_ldap(where, compiler, connection):
    (bits, params) = ([], [])
    for item in where.children:
        if isinstance(item, WhereNode):
            (clause, clause_params) = compiler.compile(item)
        else:
            (clause, clause_params) = item.as_sql(compiler, connection)
        bits.append(clause)
        params.extend(clause_params)
    if (not bits):
        return ('', [])
    if (len(bits) == 1):
        clause = bits[0]
    elif (where.connector == AND):
        clause = ('&' + ''.join((('(%s)' % bit) for bit in bits)))
    elif (where.connector == OR):
        clause = ('|' + ''.join((('(%s)' % bit) for bit in bits)))
    else:
        raise LdapDBError(('Unhandled WHERE connector: %s' % where.connector))
    if where.negated:
        clause = ('!(%s)' % clause)
    return (clause, params)

Parse a django.db.models.sql.where.WhereNode.

Returns:
(clause, [params]): the filter clause, with a list of unescaped parameters.


def detect(self, filename, offset, standalone=False):
    r = RawStruct(filename=filename, offset=(offset + SIG_OFFSET), length=SIG_SIZE)
    oem_id = r.data
    if (oem_id == b'NTFS    '):
        return True
    return False

Verifies NTFS filesystem signature.

Returns:
bool: True if filesystem signature at offset 0x03 \
matches 'NTFS    ', False otherwise.


def print_res(data):

    print('===================================')
    main_part = data['data']
    print(main_part['word_name'])
    symbols = main_part['symbols'][0]
    print("美式音标：[" + symbols['ph_am'] + "]")
    print("英式音标：[" + symbols['ph_en'] + "]")
    print('-----------------------------------')
    parts = symbols['parts']
    for part in parts:
        print(part['part'])
        for mean in part['means']:
            print("    ", mean)
    print('===================================')

Print translate result in a better format
Args:
data(str): result


def nb_cluster(data, k, P_init=None, R_init=None, assignments=None, means=None, max_iters=10):
    (genes, cells) = data.shape
    if (P_init is None):
        P_init = np.random.random((genes, k))
    if (R_init is None):
        R_init = np.random.randint(1, data.max(), (genes, k))
        R_init = R_init.astype(float)
    if (assignments is None):
        (_, assignments) = kmeans_pp(data, k, means)
    means = np.zeros((genes, k))
    old_assignments = np.copy(assignments)
    for i in range(max_iters):
        nb_gene_indices = fit_cluster(data, assignments, k, P_init, R_init, means)
        lls = nb_ll(data[(nb_gene_indices, :)], P_init[(nb_gene_indices, :)], R_init[(nb_gene_indices, :)])
        lls += pois_ll.poisson_ll(data[((~ nb_gene_indices), :)], means[((~ nb_gene_indices), :)])
        P_init[((~ nb_gene_indices), :)] = 0
        R_init[((~ nb_gene_indices), :)] = np.inf
        for c in range(cells):
            assignments[c] = np.argmax(lls[(c, :)])
        if np.equal(assignments, old_assignments).all():
            break
        old_assignments = np.copy(assignments)
    return (assignments, P_init, R_init)

Performs negative binomial clustering on the given data. If some genes have mean > variance, then these genes are fitted to a Poisson distribution.

Args:
data (array): genes x cells
k (int): number of clusters
P_init (array): NB success prob param - genes x k. Default: random
R_init (array): NB stopping param - genes x k. Default: random
assignments (array): cells x 1 array of integers 0...k-1. Default: kmeans-pp (poisson)
means (array): initial cluster means (for use with kmeans-pp to create initial assignments). Default: None
max_iters (int): default: 100

Returns:
assignments (array): 1d array of length cells, containing integers 0...k-1
P (array): genes x k - value is 0 for genes with mean > var
R (array): genes x k - value is inf for genes with mean > var


def Encode(string, encoding=None):
    del encoding
    return string

Encode the text string to a byte string.

Args:
string: str, The text string to encode.
encoding: The suggested encoding if known.

Returns:
str, The binary string.


def get_mac_dot_app_dir(directory):
    return os.path.dirname(os.path.dirname(os.path.dirname(directory)))

Returns parent directory of mac .app

Args:

directory (str): Current directory

Returns:

(str): Parent directory of mac .app


def create_schema(host):

    connection = create_blocking_connection(host)
    channel = connection.channel()

    exchange = settings.get_amqp_settings()[host]["exchange"]
    channel.exchange_declare(
        exchange=exchange,
        exchange_type="topic",
        durable=True
    )
    print "Created exchange '%s'." % exchange
    print "Creating queues:"

    queues = settings.get_amqp_settings()[host]["queues"]
    for queue in queues.keys():
        channel.queue_declare(
            queue=queue,
            durable=True,

        )
        print "\tCreated durable queue '%s'." % queue

    print
    print "Routing exchanges using routing key to queues:"

    for queue in queues.keys():
        channel.queue_bind(
            queue=queue,
            exchange=exchange,
            routing_key=queues[queue]
        )

        print "\tRouting exchange %s['%s'] -> '%s'." % (
            exchange,
            queues[queue],
            queue
        )

Create exchanges, queues and route them.

Args:
host (str): One of the possible hosts.


def Start(self, seed_list: List[str]=None, skip_seeds: bool=False) -> None:
    if (not seed_list):
        seed_list = settings.SEED_LIST
    logger.debug('Starting up nodeleader')
    if (not skip_seeds):
        logger.debug('Attempting to connect to seed list...')
        for bootstrap in seed_list:
            if (not is_ip_address(bootstrap)):
                (host, port) = bootstrap.split(':')
                bootstrap = f'{hostname_to_ip(host)}:{port}'
            addr = Address(bootstrap)
            self.KNOWN_ADDRS.append(addr)
            self.SetupConnection(addr)
    logger.debug('Starting up nodeleader: starting peer, mempool, and blockheight check loops')
    self.start_peer_check_loop()
    self.start_memcheck_loop()
    self.start_blockheight_loop()
    if (settings.ACCEPT_INCOMING_PEERS and (not self.incoming_server_running)):

        class OneShotFactory(Factory):

            def __init__(self, leader):
                self.leader = leader

            def buildProtocol(self, addr):
                print(f'building new protocol for addr: {addr}')
                self.leader.AddKnownAddress(Address(f'{addr.host}:{addr.port}'))
                p = NeoNode(incoming_client=True)
                p.factory = self
                return p

        def listen_err(err):
            print(f'Failed start listening server for reason: {err.value}')

        def listen_ok(value):
            self.incoming_server_running = True
        logger.debug(f'Starting up nodeleader: setting up listen server on port: {settings.NODE_PORT}')
        server_endpoint = TCP4ServerEndpoint(self.reactor, settings.NODE_PORT)
        listenport_deferred = server_endpoint.listen(OneShotFactory(leader=self))
        listenport_deferred.addCallback(listen_ok)
        listenport_deferred.addErrback(listen_err)

Start connecting to the seed list.

Args:
seed_list: a list of host:port strings if not supplied use list from `protocol.xxx.json`
skip_seeds: skip connecting to seed list


def mode(self, axis=0, numeric_only=False, dropna=True):

        axis = self._get_axis_number(axis)
        return self.__constructor__(
            query_compiler=self._query_compiler.mode(
                axis=axis, numeric_only=numeric_only, dropna=dropna
            )
        )

Perform mode across the DataFrame.

Args:
axis (int): The axis to take the mode on.
numeric_only (bool): if True, only apply to numeric columns.

Returns:
DataFrame: The mode of the DataFrame.


def get_signature_params(func):
    if is_cython(func):
        attrs = ['__code__', '__annotations__', '__defaults__', '__kwdefaults__']
        if all((hasattr(func, attr) for attr in attrs)):
            original_func = func

            def func():
                return
            for attr in attrs:
                setattr(func, attr, getattr(original_func, attr))
        else:
            raise TypeError('{!r} is not a Python function we can process'.format(func))
    return list(funcsigs.signature(func).parameters.items())

Get signature parameters

Support Cython functions by grabbing relevant attributes from the Cython
function and attaching to a no-op function. This is somewhat brittle, since
funcsigs may change, but given that funcsigs is written to a PEP, we hope
it is relatively stable. Future versions of Python may allow overloading
the inspect 'isfunction' and 'ismethod' functions / create ABC for Python
functions. Until then, it appears that Cython won't do anything about
compatability with the inspect module.

Args:
func: The function whose signature should be checked.

Raises:
TypeError: A type error if the signature is not supported


def _make_source_table(self, source_list, is_tf_py_library):
    path_head = 'Source file path'
    num_nodes_head = '
    num_tensors_head = '
    num_dumps_head = '
    if is_tf_py_library:
        color = cli_shared.COLOR_GRAY
        lines = [RL('TensorFlow Python library file(s):', color)]
    else:
        color = cli_shared.COLOR_WHITE
        lines = [RL('File(s) outside TensorFlow Python library:', color)]
    if not source_list:
        lines.append(RL('[No files.]'))
        lines.append(RL())
        return debugger_cli_common.rich_text_lines_from_rich_line_list(lines)
    path_column_width = max(max((len(item[0]) for item in source_list)), len(path_head)) + 1
    num_nodes_column_width = max(max((len(str(item[2])) for item in source_list)), len(num_nodes_head)) + 1
    num_tensors_column_width = max(max((len(str(item[3])) for item in source_list)), len(num_tensors_head)) + 1
    head = RL(path_head + ' ' * (path_column_width - len(path_head)), color)
    head += RL(num_nodes_head + ' ' * (num_nodes_column_width - len(num_nodes_head)), color)
    head += RL(num_tensors_head + ' ' * (num_tensors_column_width - len(num_tensors_head)), color)
    head += RL(num_dumps_head, color)
    lines.append(head)
    for file_path, _, num_nodes, num_tensors, num_dumps, first_line_num in source_list:
        path_attributes = [color]
        if source_utils.is_extension_uncompiled_python_source(file_path):
            path_attributes.append(debugger_cli_common.MenuItem(None, 'ps %s -b %d' % (file_path, first_line_num)))
        line = RL(file_path, path_attributes)
        line += ' ' * (path_column_width - len(line))
        line += RL(str(num_nodes) + ' ' * (num_nodes_column_width - len(str(num_nodes))), color)
        line += RL(str(num_tensors) + ' ' * (num_tensors_column_width - len(str(num_tensors))), color)
        line += RL(str(num_dumps), color)
        lines.append(line)
    lines.append(RL())
    return debugger_cli_common.rich_text_lines_from_rich_line_list(lines)

Make a table summarizing the source files that create nodes and tensors.

Args:
source_list: List of source files and related information as a list of
tuples (file_path, is_tf_library, num_nodes, num_tensors, num_dumps,
first_line).
is_tf_py_library: (`bool`) whether this table is for files that belong
to the TensorFlow Python library.

Returns:
The table as a `debugger_cli_common.RichTextLines` object.


async def forget_ticket(self, request):

        session = await get_session(request)
        session.pop(self.cookie_name, '')

Called to forget the ticket data a request

Args:
request: aiohttp Request object.


def match_datetime(file_name: str, regex_expression: str) -> datetime.datetime:

    def rearrange_time_list(order_list: t.List, time_list: t.List) -> t.List:
        if order_list == DEFAULT_TIME_ORDER_LIST:
            return time_list
        new_time_list = []
        for i, j in zip(order_list, time_list):
            dst = DEFAULT_TIME_ORDER_LIST.index(i)
            new_time_list.insert(dst, j)
        return new_time_list
    char_to_replace = {'%Y': ['([0-9]{4})', [0, 1978]], '%m': ['([0-9]{2})', [1, 1]], '%d': ['([0-9]{2})', [2, 1]], '%H': ['([0-9]{2})', [3, 0]], '%M': ['([0-9]{2})', [4, 0]], '%S': ['([0-9]{2})', [5, 0]], '*': ['.*']}
    missing_idx_list = []
    temp_expression = regex_expression
    for key, value in char_to_replace.items():
        if key != '*' and regex_expression.find(key) == -1:
            missing_idx_list.append(value[1])
        else:
            temp_expression = temp_expression.replace(key, value[0])
    regex_matches = re.findall(temp_expression, file_name)[0]
    order_list = [f'%{char}' for char in re.findall('%(\\w{1})', regex_expression)]
    time_list = list(map(int, regex_matches))
    time_list = rearrange_time_list(order_list, time_list)
    if missing_idx_list:
        for [idx, val] in missing_idx_list:
            time_list.insert(idx, val)
    return datetime.datetime(*time_list)

Matches the regex string given and extracts the datetime object.

Args:
file_name: File name from which you want to extract datetime.
regex_expression: Regex expression for extracting datetime from the filename.

Returns:
A datetime object after extracting from the filename.


def _init_saver(self, saver=USE_DEFAULT):
    if saver is Supervisor.USE_DEFAULT:
        saver = self._get_first_op_from_collection(ops.GraphKeys.SAVERS)
        if saver is None and variables.global_variables():
            saver = saver_mod.Saver()
            ops.add_to_collection(ops.GraphKeys.SAVERS, saver)
    self._saver = saver

Initializes saver.

Args:
saver: A `Saver` object. If set to USE_DEFAULT, create one that saves all
the variables.


def search_track(self, artist, album=None, track=None, full_album_art_uri=False):
    subcategories = [artist]
    subcategories.append((album or ''))
    result = self.get_album_artists(full_album_art_uri=full_album_art_uri, subcategories=subcategories, search_term=track, complete_result=True)
    result._metadata['search_type'] = 'search_track'
    return result

Search for an artist, an artist's albums, or specific track.

Args:
artist (str): an artist's name.
album (str, optional): an album name. Default `None`.
track (str, optional): a track name. Default `None`.
full_album_art_uri (bool): whether the album art URI should be
absolute (i.e. including the IP address). Default `False`.

Returns:
A `SearchResult` instance.


def to_dms(angle, style='dms'):

    sign = 1 if angle >= 0 else -1
    angle = abs(angle) * 3600
    minutes, seconds = divmod(angle, 60)
    degrees, minutes = divmod(minutes, 60)
    if style == 'dms':
        return tuple(sign * abs(i) for i in (int(degrees), int(minutes),
                                             seconds))
    elif style == 'dm':
        return tuple(sign * abs(i) for i in (int(degrees),
                                             (minutes + seconds / 60)))
    else:
        raise ValueError('Unknown style type %r' % style)

Convert decimal angle to degrees, minutes and possibly seconds.

Args:
angle (float): Angle to convert
style (str): Return fractional or whole minutes values

Returns:
tuple of int: Angle converted to degrees, minutes and possibly seconds

Raises:
ValueError: Unknown value for ``style``


def get_enum_from_name(self, enum_name):

        return next((e for e in self.enums if e.name == enum_name), None)

Return an enum from a name
Args:
enum_name (str): name of the enum
Returns:
Enum


def first(self) -> 'Builder':
    return self._to_builder(_evaluation.FirstFunction(self.node.context, self.node, []))

The FHIRPath first() function.

Returns:
An expression that evaluates to the first element of the parent, or
empty if the parent has no results.


def get_descriptor(self):
    raise NotImplementedError('Base class should not be called directly!')

This function returns a string describing the sniffer. The specific
string (and its format) is up to each derived sniffer type.

Returns:
A string describing the sniffer.


def add_molecule(self, mol, bond=None, base=None, target=None):

        ai = self.available_idx()
        mapping = {n: n + ai - 1 for n, _ in mol.atoms_iter()}
        relabeled = nx.relabel_nodes(mol.graph, mapping)
        self.graph.add_nodes_from(relabeled.nodes(data=True))
        self.graph.add_edges_from(relabeled.edges(data=True))
        if bond:
            self.add_bond(base, mapping[target], bond)

connect atom group (for SMILES parser)

May requires recalculation of 2D coordinate for drawing

Args:
mol: graphmol.Compound()
the original object will be copied.
bond: Bond object to be connected.
the original will not be copied so be careful.
base: index of atom in self to connect
target: index of atom in group to be connected
Raises:
TypeError


def __frontend_limit_rules_descriptor(self, api_info):

    if not api_info.frontend_limits.rules:
      return None

    rules = []
    for rule in api_info.frontend_limits.rules:
      descriptor = {}
      for propname, descname in (('match', 'match'),
                                 ('qps', 'qps'),
                                 ('user_qps', 'userQps'),
                                 ('daily', 'daily'),
                                 ('analytics_id', 'analyticsId')):
        if getattr(rule, propname) is not None:
          descriptor[descname] = getattr(rule, propname)
      if descriptor:
        rules.append(descriptor)

    return rules

Builds a frontend limit rules descriptor from API info.

Args:
api_info: An _ApiInfo object.

Returns:
A list of dictionaries with frontend limit rules information.


def reindex(self, axis, labels, **kwargs):

        def reindex_builer(df, axis, old_labels, new_labels, **kwargs):
            if axis:
                while len(df.columns) < len(old_labels):
                    df[len(df.columns)] = np.nan
                df.columns = old_labels
                new_df = df.reindex(columns=new_labels, **kwargs)

                new_df.columns = pandas.RangeIndex(len(new_df.columns))
                return new_df
            else:
                while len(df.index) < len(old_labels):
                    df.loc[len(df.index)] = np.nan
                df.index = old_labels
                new_df = df.reindex(index=new_labels, **kwargs)

                new_df.reset_index(inplace=True, drop=True)
                return new_df

        old_labels = self.columns if axis else self.index
        new_index = self.index if axis else labels
        new_columns = labels if axis else self.columns
        func = self._prepare_method(
            lambda df: reindex_builer(df, axis, old_labels, labels, **kwargs)
        )

        new_data = self._map_across_full_axis(axis, func)
        return self.__constructor__(new_data, new_index, new_columns)

Fits a new index for this Manger.

Args:
axis: The axis index object to target the reindex on.
labels: New labels to conform 'axis' on to.

Returns:
A new QueryCompiler with updated data and new index.


def exportData(self, datfile):

        def ampl_set(name, values):
            def format_entry(e):
                return repr(e).replace(' ', '')

            return 'set {0} := {1};'.format(
                name, ','.join(format_entry(e) for e in values)
            )

        def ampl_param(name, values):
            def format_entry(k, v):
                k = repr(k).strip('()').replace(' ', '')
                if v == inf:
                    v = "Infinity"
                elif v == -inf:
                    v = "-Infinity"
                else:
                    v = repr(v).strip('()').replace(' ', '')
                return '[{0}]{1}'.format(k, v)

            return 'param {0} := {1};'.format(
                name, ''.join(format_entry(k, v) for k, v in values.items())
            )

        with open(datfile, 'w') as f:
            for name, entity in self.getSets():
                values = entity.getValues().toList()
                print(ampl_set(name, values), file=f)
            for name, entity in self.getParameters():
                if entity.isScalar():
                    print(
                        'param {} := {};'.format(name, entity.value()),
                        file=f
                    )
                else:
                    values = entity.getValues().toDict()
                    print(ampl_param(name, values), file=f)

Create a .dat file with the data that has been loaded.

Args:
datfile: Path to the file (Relative to the current working
directory or absolute).


def random(self, shape, tf_fn, kwargs):

    slice_shape = self.slice_shape(shape)
    op_seed = random.random()
    def my_fn(pnum):

      seed = hash("%s,%s" % (op_seed, self.slice_begin(shape, pnum)))
      return tf_fn(slice_shape, seed=seed, **kwargs)
    return self.slicewise(my_fn, self.laid_out_pnum())

Call a random tf operation (e.g. tf.random.uniform).

Args:
shape: a Shape
tf_fn: a function such as tf.random.uniform
kwargs: kwargs to pass to tf_fn, except for seed

Returns:
a LaidOutTensor


def generate_selected_rules(rule_configs: List[RuleConfig], rules: RulesMap) -> List[RuleChecker]:
    selected_rules: List[RuleChecker] = []
    for rule_config in rule_configs:
        rule_name = rule_config['rule']
        if rule_name not in rules:
            raise ValueError('Invalid rule specified.')
        else:
            args = rule_config.get('args', {})
            rule = rules[rule_name](**args)
            rule.__name__ = rule_name
            rule.__kwdefaults__ = args
            selected_rules.append(rule)
    if len(selected_rules) == 0:
        raise ValueError('No rules specified.')
    return selected_rules

Generates rule checkers from the provided rule configs and
mappable rules.

Args:
* rule_configs: List of RuleConfigs, with potential args
* rules: Typed RulesMap

Returns:
* List of RuleCheckers with args applied

Raises:
* ValueError: if non-existent rule name provided


def _GetMergeTaskStorageFilePath(self, task):

    filename = '{0:s}.plaso'.format(task.identifier)
    return os.path.join(self._merge_task_storage_path, filename)

Retrieves the path of a task storage file in the merge directory.

Args:
task (Task): task.

Returns:
str: path of a task storage file file in the merge directory.


def FromString(cls, indata):
    lines = [x.strip() for x in indata.split('\n') if ((not x.startswith('
    if (len(lines) < 3):
        raise DataError('Invalid CommandFile string that did not contain 3 header lines', lines=lines)
    (fmt_line, version_line, ascii_line) = lines[:3]
    if (not version_line.startswith('Format: ')):
        raise DataError("Invalid format version that did not start with 'Format: '", line=version_line)
    version = version_line[8:]
    if (ascii_line != 'Type: ASCII'):
        raise DataError('Unknown file type line (expected Type: ASCII)', line=ascii_line)
    cmds = [cls.decode(x) for x in lines[3:]]
    return CommandFile(fmt_line, version, cmds)

Load a CommandFile from a string.

The string should be produced from a previous call to
encode.

Args:
indata (str): The encoded input data.

Returns:
CommandFile: The decoded CommandFile object.


def update_user_attributes(self, user, claims):
    required_fields = [field.name for field in user._meta.fields if (field.blank is False)]
    for (field, claim) in settings.CLAIM_MAPPING.items():
        if hasattr(user, field):
            if (claim in claims):
                setattr(user, field, claims[claim])
                logger.debug("Attribute '{}' for user '{}' was set to '{}'.".format(field, user, claims[claim]))
            elif (field in required_fields):
                msg = "Claim not found in access token: '{}'. Check ADFS claims mapping."
                raise ImproperlyConfigured(msg.format(claim))
            else:
                msg = "Claim '{}' for user field '{}' was not found in the access token for user '{}'. Field is not required and will be left empty".format(claim, field, user)
                logger.warning(msg)
        else:
            msg = "User model has no field named '{}'. Check ADFS claims mapping."
            raise ImproperlyConfigured(msg.format(field))

Updates user attributes based on the CLAIM_MAPPING setting.

Args:
user (django.contrib.auth.models.User): User model instance
claims (dict): claims from the access token


def from_dict(d):
    i = Tags()
    for (k, v) in d.items():
        if (k not in ('@module', '@class')):
            i[k] = v
    return i

Creates Tags object from a dictionary.

Args:
d: Dict of feff parameters and values.

Returns:
Tags object


def occurrence(self, indicator=None):

        self._request_entity = 'fileOccurrence'
        self._request_uri = '{}/fileOccurrences'.format(self._request_uri)
        if indicator is not None:
            self._request_uri = '{}/{}/fileOccurrences'.format(self._api_uri, indicator)

Update the URI to retrieve file occurrences for the provided indicator.

Args:
indicator (string): The indicator to retrieve file occurrences.


def __call__(self, shape, dtype=None, **kwargs):
    _validate_kwargs(self.__class__.__name__, kwargs, support_partition=False)
    dtype = _assert_float_dtype(_get_dtype(dtype))
    if len(shape) < 2:
        raise ValueError('The tensor to initialize must be at least two-dimensional')
    num_rows = 1
    for dim in shape[:-1]:
        num_rows *= dim
    num_cols = shape[-1]
    flat_shape = (max(num_cols, num_rows), min(num_cols, num_rows))
    a = self._random_generator.random_normal(flat_shape, dtype=dtype)
    q, r = gen_linalg_ops.qr(a, full_matrices=False)
    d = array_ops.tensor_diag_part(r)
    q *= math_ops.sign(d)
    if num_rows < num_cols:
        q = array_ops.matrix_transpose(q)
    return self.gain * array_ops.reshape(q, shape)

Returns a tensor object initialized to an orthogonal matrix.

Args:
shape: Shape of the tensor.
dtype: Optional dtype of the tensor. Only floating point types are
supported. If not specified, `tf.keras.backend.floatx()` is used,
which default to `float32` unless you configured it otherwise
(via `tf.keras.backend.set_floatx(float_dtype)`)
**kwargs: Additional keyword arguments.


def _on_action(self, sequence, topic, message):

        try:
            slug = None
            parts = topic.split('/')
            slug = parts[-3]
            uuid = self._extract_device_uuid(slug)
        except Exception as exc:
            self._logger.warn("Error parsing slug in action handler (slug=%s, topic=%s)", slug, topic)
            return

        if messages.DisconnectCommand.matches(message):
            self._logger.debug("Received disconnect command for device 0x%X", uuid)
            key = message['key']
            client = message['client']
            self._loop.add_callback(self._disconnect_from_device, uuid, key, client)
        elif messages.OpenInterfaceCommand.matches(message) or messages.CloseInterfaceCommand.matches(message):
            self._logger.debug("Received %s command for device 0x%X", message['operation'], uuid)
            key = message['key']
            client = message['client']
            oper = message['operation']

            if oper == 'open_interface':
                self._loop.add_callback(self._open_interface, client, uuid, message['interface'], key)
            else:
                self._loop.add_callback(self._close_interface, client, uuid, message['interface'], key)
        elif messages.RPCCommand.matches(message):
            rpc_msg = messages.RPCCommand.verify(message)

            client = rpc_msg['client']
            address = rpc_msg['address']
            rpc = rpc_msg['rpc_id']
            payload = rpc_msg['payload']
            key = rpc_msg['key']
            timeout = rpc_msg['timeout']

            self._loop.add_callback(self._send_rpc, client, uuid, address, rpc, payload, timeout, key)
        elif messages.ScriptCommand.matches(message):
            script_msg = messages.ScriptCommand.verify(message)

            key = script_msg['key']
            client = script_msg['client']
            script = script_msg['script']

            self._loop.add_callback(self._send_script, client, uuid, script, key, (script_msg['fragment_index'], script_msg['fragment_count']))
        else:
            self._logger.error("Unsupported message received (topic=%s) (message=%s)", topic, str(message))

Process a command action that we received on behalf of a device.

Args:
sequence (int): The sequence number of the packet received
topic (string): The topic this message was received on
message (dict): The message itself


def __init__(self, element_value: ValueSpecOrAnnotation, default: typing.Optional[typing.List[typing.Any]]=MISSING_VALUE, min_size: typing.Optional[int]=None, max_size: typing.Optional[int]=None, size: typing.Optional[int]=None, transform: typing.Optional[typing.Callable[[typing.Any], typing.List[typing.Any]]]=None, is_noneable: bool=False, frozen: bool=False):
    element_value = ValueSpec.from_annotation(element_value, auto_typing=True)
    if size is not None and (min_size is not None or max_size is not None):
        raise ValueError(f'Either "size" or "min_size"/"max_size" pair can be specified. Encountered: size={size}, min_size={min_size}, max_size={max_size}.')
    if size is not None:
        min_size = size
        max_size = size
    if min_size is None:
        min_size = 0
    if min_size < 0:
        raise ValueError(f'"min_size" of List must be no less than 0. Encountered: {min_size}.')
    if max_size is not None:
        if max_size < min_size:
            raise ValueError(f'"max_size" of List must be no less than "min_size". Encountered: min_size={min_size}, max_size={max_size}')
    self._element = Field(key_specs.ListKey(min_size, max_size), element_value, 'Field of list element')
    super().__init__(list, default, transform, is_noneable=is_noneable, frozen=frozen)

Constructor.

Args:
element_value: A ``ValueSpec`` object or an equivalent annotation as the
spec for the list element.
default: (Optional) default value for this spec.
min_size: (Optional) min size of list. If None, 0 will be used.
max_size: (Optional) max size of list.
size: (Optional) size of List. A shortcut to specify min_size and max_size
at the same time. `size` and `min_size`/`max_size` are mutual exclusive.
transform: (Optional) user-defined function to be called on the input
of `apply`. It could be used as a type converter or a custom
validator which may raise errors.
is_noneable: If True, None is acceptable.
frozen: If True, values other than the default value is not accceptable.


def _sorted_results(self, results_dicts):

    print('results dicts:', results_dicts)
    sorted_dict = sorted(results_dicts, key=lambda k: k['start_time'])
    results = []
    for entry in sorted_dict:
      results.append(entry['dt'])
    return results

Sorts dict of results based on log start_time.

Sorts the results and returns an array with only the values but sorted
by oldest value first.value

Args:
results_dicts: List of result dicts

Returns:
List of only the time but sorted oldest first.


def _create_filter(col_param, extractor):
    include_missing_values = (not col_param.exclude_missing_values)
    if col_param.HasField('filter_regexp'):
        value_filter_fn = _create_regexp_filter(col_param.filter_regexp)
    elif col_param.HasField('filter_interval'):
        value_filter_fn = _create_interval_filter(col_param.filter_interval)
    elif col_param.HasField('filter_discrete'):
        value_filter_fn = _create_discrete_set_filter(col_param.filter_discrete)
    elif include_missing_values:
        return None
    else:
        value_filter_fn = (lambda _: True)

    def filter_fn(session_group):
        value = extractor(session_group)
        if (value is None):
            return include_missing_values
        return value_filter_fn(value)
    return filter_fn

Creates a filter for the given col_param and extractor.

Args:
col_param: A tensorboard.hparams.ColParams object identifying the column
and describing the filter to apply.
extractor: A function that extract the column value identified by
'col_param' from a tensorboard.hparams.SessionGroup protobuffer.
Returns:
A boolean function taking a tensorboard.hparams.SessionGroup protobuffer
returning True if the session group passes the filter described by
'col_param'. If col_param does not specify a filter (i.e. any session
group passes) returns None.


def make_unique_script_attr(attributes):

    filtered_attr = []
    script_list = []
    for attr in attributes:
        if attr.Usage != TransactionAttributeUsage.Script:
            filtered_attr.append(attr)
        else:
            data = attr.Data
            if isinstance(data, UInt160):

                data = attr.Data.ToArray()

            if data not in script_list:
                script_list.append(data)
                filtered_attr.append(attr)

    return filtered_attr

Filter out duplicate `Script` TransactionAttributeUsage types.
Args:
attributes: a list of TransactionAttribute's

Returns:
list:


def generate_poisson_data(centers, n_cells, cluster_probs=None):
    (genes, clusters) = centers.shape
    output = np.zeros((genes, n_cells))
    if (cluster_probs is None):
        cluster_probs = (np.ones(clusters) / clusters)
    labels = []
    for i in range(n_cells):
        c = np.random.choice(range(clusters), p=cluster_probs)
        labels.append(c)
        output[(:, i)] = np.random.poisson(centers[(:, c)])
    return (output, np.array(labels))

Generates poisson-distributed data, given a set of means for each cluster.

Args:
centers (array): genes x clusters matrix
n_cells (int): number of output cells
cluster_probs (array): prior probability for each cluster.
Default: uniform.

Returns:
output - array with shape genes x n_cells
labels - array of cluster labels


def dict_isect(*args):
    if (not args):
        return {}
    else:
        dictclass = (OrderedDict if isinstance(args[0], OrderedDict) else dict)
        common_keys = set.intersection(*map(set, args))
        first_dict = args[0]
        return dictclass(((k, first_dict[k]) for k in common_keys))

Constructs a dictionary that contains keys common between all inputs.
The returned values will only belong to the first dictionary.

Args:
*args : a sequence of dictionaries (or sets of keys)

Returns:
Dict | OrderedDict :
OrderedDict if the first argument is an OrderedDict, otherwise dict

Notes:
This function can be used as an alternative to `dict_subset` where any
key not in the dictionary is ignored. See the following example:

>>> dict_isect({'a': 1, 'b': 2, 'c': 3}, ['a', 'c', 'd'])
{'a': 1, 'c': 3}

Example:
>>> dict_isect({'a': 1, 'b': 1}, {'b': 2, 'c': 2})
{'b': 1}
>>> dict_isect(odict([('a', 1), ('b', 2)]), odict([('c', 3)]))
OrderedDict()
>>> dict_isect()
{}


def safe_call(request: Request, methods: Methods, *, debug: bool) -> Response:

    with handle_exceptions(request, debug) as handler:
        result = call(methods.items[request.method], *request.args, **request.kwargs)
        handler.response = SuccessResponse(result=result, id=request.id)
    return handler.response

Call a Request, catching exceptions to ensure we always return a Response.

Args:
request: The Request object.
methods: The list of methods that can be called.
debug: Include more information in error responses.

Returns:
A Response object.


def GetTermIdentifier(self):
    return self._term

Returns the TERM environment variable for the console.

Returns:
str: A str that describes the console's text capabilities


def reshape(self, shape: tf.TensorShape) -> 'TensorFluent':
    t = tf.reshape(self.tensor, shape)
    scope = self.scope.as_list()
    batch = self.batch
    return TensorFluent(t, scope, batch=batch)

Returns a TensorFluent for the reshape operation with given `shape`.

Args:
shape: The output's shape.

Returns:
A TensorFluent wrapping the reshape operation.


def resolve_aliases(data_type):

    if not is_alias(data_type):
        return data_type

    resolved = resolve_aliases(data_type.data_type)
    data_type.data_type = resolved

    return resolved

Resolve all chained / nested aliases. This will recursively point
nested aliases to their resolved data type (first non-alias in the chain).

Note: This differs from unwrap_alias which simply identifies/returns
the resolved data type.

Args:
data_type (DataType): The target DataType/Alias to resolve.
Return:
DataType: The resolved type.


def run(self, data_loaders, workflow, max_epochs, **kwargs):

        assert isinstance(data_loaders, list)
        assert mmcv.is_list_of(workflow, tuple)
        assert len(data_loaders) == len(workflow)

        self._max_epochs = max_epochs
        work_dir = self.work_dir if self.work_dir is not None else 'NONE'
        self.logger.info('Start running, host: %s, work_dir: %s',
                         get_host_info(), work_dir)
        self.logger.info('workflow: %s, max: %d epochs', workflow, max_epochs)
        self.call_hook('before_run')

        while self.epoch < max_epochs:
            for i, flow in enumerate(workflow):
                mode, epochs = flow
                if isinstance(mode, str):
                    if not hasattr(self, mode):
                        raise ValueError(
                            'runner has no method named "{}" to run an epoch'.
                            format(mode))
                    epoch_runner = getattr(self, mode)
                elif callable(mode):
                    epoch_runner = mode
                else:
                    raise TypeError('mode in workflow must be a str or '
                                    'callable function, not {}'.format(
                                        type(mode)))
                for _ in range(epochs):
                    if mode == 'train' and self.epoch >= max_epochs:
                        return
                    epoch_runner(data_loaders[i], **kwargs)

        time.sleep(1)
        self.call_hook('after_run')

Start running.

Args:
data_loaders (list[:obj:`DataLoader`]): Dataloaders for training
and validation.
workflow (list[tuple]): A list of (phase, epochs) to specify the
running order and epochs. E.g, [('train', 2), ('val', 1)] means
running 2 epochs for training and 1 epoch for validation,
iteratively.
max_epochs (int): Total training epochs.


def get(self, value):

        config = self.get_block('vrf definition %s' % value)
        if not config:
            return None
        response = dict(vrf_name=value)
        response.update(self._parse_rd(config))
        response.update(self._parse_description(config))
        config = self.get_block('no ip routing vrf %s' % value)
        if config:
            response['ipv4_routing'] = False
        else:
            response['ipv4_routing'] = True
        config = self.get_block('no ipv6 unicast-routing vrf %s' % value)
        if config:
            response['ipv6_routing'] = False
        else:
            response['ipv6_routing'] = True

        return response

Returns the VRF configuration as a resource dict.

Args:
value (string): The vrf name to retrieve from the
running configuration.

Returns:
A Python dict object containing the VRF attributes as
key/value pairs.


def with_bloomberg(func):

    @wraps(func)
    def wrapper(*args, **kwargs):

        scope = utils.func_scope(func=func)
        param = inspect.signature(func).parameters
        port = kwargs.pop('port', _PORT_)
        timeout = kwargs.pop('timeout', _TIMEOUT_)
        restart = kwargs.pop('restart', False)
        all_kw = {
            k: args[n] if n < len(args) else v.default
            for n, (k, v) in enumerate(param.items()) if k != 'kwargs'
        }
        all_kw.update(kwargs)
        log_level = kwargs.get('log', logs.LOG_LEVEL)

        for to_list in ['tickers', 'flds']:
            conv = all_kw.get(to_list, None)
            if hasattr(conv, 'tolist'):
                all_kw[to_list] = getattr(conv, 'tolist')()
            if isinstance(conv, str):
                all_kw[to_list] = [conv]

        cached_data = []
        if scope in ['xbbg.blp.bdp', 'xbbg.blp.bds']:
            to_qry = cached.bdp_bds_cache(func=func.__name__, **all_kw)
            cached_data += to_qry.cached_data

            if not (to_qry.tickers and to_qry.flds):
                if not cached_data: return pd.DataFrame()
                res = pd.concat(cached_data, sort=False).reset_index(drop=True)
                if not all_kw.get('raw', False):
                    res = assist.format_output(
                        data=res, source=func.__name__,
                        col_maps=all_kw.get('col_maps', dict())
                    )
                return res

            all_kw['tickers'] = to_qry.tickers
            all_kw['flds'] = to_qry.flds

        if scope in ['xbbg.blp.bdib']:
            data_file = storage.hist_file(
                ticker=all_kw['ticker'], dt=all_kw['dt'], typ=all_kw['typ'],
            )
            if files.exists(data_file):
                logger = logs.get_logger(func, level=log_level)
                if all_kw.get('batch', False): return
                logger.debug(f'reading from {data_file} ...')
                return assist.format_intraday(data=pd.read_parquet(data_file), **all_kw)

        _, new = create_connection(port=port, timeout=timeout, restart=restart)
        res = func(**{
            k: v for k, v in all_kw.items() if k not in ['raw', 'col_maps']
        })
        if new: delete_connection()

        if scope.startswith('xbbg.blp.') and isinstance(res, list):
            final = cached_data + res
            if not final: return pd.DataFrame()
            res = pd.DataFrame(pd.concat(final, sort=False))

        if (scope in ['xbbg.blp.bdp', 'xbbg.blp.bds']) \
                and (not all_kw.get('raw', False)):
            res = assist.format_output(
                data=res.reset_index(drop=True), source=func.__name__,
                col_maps=all_kw.get('col_maps', dict()),
            )

        return res
    return wrapper

Wrapper function for Bloomberg connection

Args:
func: function to wrap


def matchmaker_request(url, token, method, content_type=None, accept=None, data=None):

    headers = Headers()
    headers = { 'X-Auth-Token': token}
    if content_type:
        headers['Content-Type'] = content_type
    if accept:
        headers['Accept'] = accept

    req_data = data or {'timestamp' : datetime.datetime.now().timestamp()}
    json_response = None
    try:
        LOG.info('Sending {} request to MME url {}. Data sent: {}'.format(
            method, url, req_data))
        resp = requests.request(
            method = method,
            url = url,
            headers = headers,
            data = json.dumps(req_data)
        )
        json_response = resp.json()
        LOG.info('MME server response was:{}'.format(json_response))

        if isinstance(json_response, str):
            json_response = {
                'message' : json_response,
            }
        elif isinstance(json_response, list):
            return json_response
        json_response['status_code'] = resp.status_code
    except Exception as err:
        LOG.info('An error occurred while sending HTTP request to server ({})'.format(err))
        json_response = {
            'message' : str(err)
        }
    return json_response

Send a request to MatchMaker and return its response

Args:
url(str): url to send request to
token(str): MME server authorization token
method(str): 'GET', 'POST' or 'DELETE'
content_type(str): MME request Content-Type
accept(str): accepted response
data(dict): eventual data to send in request

Returns:
json_response(dict): server response


def _get_class_repr(cls, type_, bound, keyfunc, keyfunc_name):

        if keyfunc is not cls._default:
            return "{}.{}[{}, {}, {}]".format(
                cls.__module__,
                cls.__name__,
                cls._get_fullname(type_),
                cls._get_bound_repr(bound),
                keyfunc_name,
            )
        return "{}.{}[{}, {}]".format(
            cls.__module__,
            cls.__name__,
            cls._get_fullname(type_),
            cls._get_bound_repr(bound),
        )

Return a class representation using the slice parameters.

Args:
type_: The type the class was sliced with.
bound: The boundaries specified for the values of type_.
keyfunc: The comparison function used to check the value
boundaries.
keyfunc_name: The name of keyfunc.

Returns:
A string representing the class.


def _get_truncated_table_rows(self, query_tokens: List[str], tokenized_table: TokenizedTable, num_rows: int, num_columns: int, max_length: int, truncation_strategy: Union[str, TapasTruncationStrategy]) -> Tuple[int, int]:
    if not isinstance(truncation_strategy, TapasTruncationStrategy):
        truncation_strategy = TapasTruncationStrategy(truncation_strategy)
    if max_length is None:
        max_length = self.model_max_length
    if truncation_strategy == TapasTruncationStrategy.DROP_ROWS_TO_FIT:
        while True:
            num_tokens = self._get_max_num_tokens(query_tokens, tokenized_table, num_rows=num_rows, num_columns=num_columns, max_length=max_length)
            if num_tokens is not None:
                break
            num_rows -= 1
            if num_rows < 1:
                break
    elif truncation_strategy != TapasTruncationStrategy.DO_NOT_TRUNCATE:
        raise ValueError(f'Unknown truncation strategy {truncation_strategy}.')
    return (num_rows, num_tokens or 1)

Truncates a sequence pair in-place following the strategy.

Args:
query_tokens (`List[str]`):
List of strings corresponding to the tokenized query.
tokenized_table (`TokenizedTable`):
Tokenized table
num_rows (`int`):
Total number of table rows
num_columns (`int`):
Total number of table columns
max_length (`int`):
Total maximum length.
truncation_strategy (`str` or [`TapasTruncationStrategy]`):
Truncation strategy to use. Seeing as this method should only be called when truncating, the only
available strategy is the `"drop_rows_to_fit"` strategy.

Returns:
`Tuple(int, int)`: tuple containing the number of rows after truncation, and the number of tokens available
for each table element.


def banner(text, border='=', width=80):
    text_padding = ('{0:^%d}' % width)
    LOG.info((border * width))
    LOG.info(text_padding.format(text))
    LOG.info((border * width))

Center _text_ in a banner _width_ wide with _border_ characters.

Args:
text (str): What to write in the banner
border (str): Border character
width (int): How long the border should be


def create_application_configuration(self, name, properties, description=None):
    if (not hasattr(self, 'applicationConfigurations')):
        raise NotImplementedError()
    cv = ApplicationConfiguration._props(name, properties, description)
    res = self.rest_client.session.post(self.applicationConfigurations, headers={'Accept': 'application/json'}, json=cv)
    _handle_http_errors(res)
    return ApplicationConfiguration(res.json(), self.rest_client)

Create an application configuration.

Args:
name (str, optional): Only return application configurations containing property **name** that matches `name`. `name` can be a
.. versionadded 1.12


def make_conv_bias_activation_tests(activation_op):

    def create_test(options):

        test_parameters = [{'input_shape': [[1, 3, 4, 3]], 'filter_shape': [[2, 3], [3, 3]], 'filter_2_shape': [[2, 1, 1, 3]], 'strides': [[1, 1, 1, 1]], 'dilations': [[1, 1, 1, 1]], 'data_format': ['NCHW'], 'channel_multiplier': [1, 2], 'fully_quantize': [False], 'dynamic_range_quantize': [False]}]

        def get_tensor_shapes(parameters):
            input_shape = parameters['input_shape']
            filter_size = parameters['filter_shape']
            filter_shape = filter_size + [input_shape[3], parameters['channel_multiplier']]
            return [input_shape, filter_shape]

        @tf.function(jit_compile=True)
        def add_conv(input_tensor, filter_input, parameters):
            out = tf.nn.conv2d(input=input_tensor, filters=filter_input, strides=parameters['strides'], dilations=parameters['dilations'], padding='VALID', data_format=parameters['data_format'])
            return out

        def add_bias_add(data_input, filter_shape):
            bias_input = create_tensor_data(np.float32, (filter_shape[-1],))
            out = tf.nn.bias_add(data_input, bias_input, data_format='NHWC')
            return out

        def build_graph(parameters):

            input_shape, filter_shape = get_tensor_shapes(parameters)
            input_tensor = tf.compat.v1.placeholder(dtype=tf.float32, name='input', shape=input_shape)
            filter_input = create_tensor_data(np.float32, filter_shape, min_value=-10, max_value=10)
            input_tensors = [input_tensor]
            if parameters['data_format'] == 'NCHW':
                out = add_conv(input_tensor, filter_input, parameters)
            else:
                out = tf.nn.conv2d(input=input_tensor, filters=filter_input, strides=parameters['strides'], dilations=parameters['dilations'], padding='VALID', data_format=parameters['data_format'])
            out = add_bias_add(out, filter_shape)
            out = activation_op(out)
            filter_input_2 = create_tensor_data(np.float32, parameters['filter_2_shape'], min_value=-10, max_value=10)
            if parameters['data_format'] == 'NCHW':
                out = add_conv(out, filter_input_2, parameters)
            else:
                out = tf.nn.conv2d(input=out, filters=filter_input_2, strides=parameters['strides'], dilations=parameters['dilations'], padding='VALID', data_format=parameters['data_format'])
            out = add_bias_add(out, filter_shape)
            out = activation_op(out)
            return (input_tensors, [out])

        def build_inputs(parameters, sess, inputs, outputs):

            input_shape, _ = get_tensor_shapes(parameters)
            values = [create_tensor_data(np.float32, input_shape, min_value=-1, max_value=1)]
            return (values, sess.run(outputs, feed_dict=dict(zip(inputs, values))))
        make_zip_of_tests(options, test_parameters, build_graph, build_inputs, expected_tf_failures=2)
    return create_test

Make a set of tests to do convolution with activation and bias.

This test will create multiple consecutive convolutions with NCHW layout to
make sure that the tranformations to NHWC works as expected. Note this
doesn't check any performance so manual checking of the generated model is
advised.

Args:
activation_op: The activation op to be used in the test.

Returns:
The function that creates the test.


def __init__(self, dataset_merger, problem_type=transitfeed.TYPE_WARNING,
               **kwargs):

    kwargs['type'] = problem_type
    kwargs['entity_type_name'] = dataset_merger.ENTITY_TYPE_NAME
    transitfeed.ExceptionWithContext.__init__(self, None, None, **kwargs)
    self.dataset_merger = dataset_merger

Initialise the exception object.

Args:
dataset_merger: The DataSetMerger instance that generated this problem.
problem_type: The problem severity. This should be set to one of the
corresponding constants in transitfeed.
kwargs: Keyword arguments to be saved as instance attributes.


def load(self, validate=True):

        self._load()
        try:
            self.config = self._load_config(self.system_config_file)
            user = self._load_config(self.global_config_file)
            config = self._load_config(self.config_file)
            local = self._load_config(self.config_local_file)

            for conf in [user, config, local]:
                self.config = self._merge(self.config, conf)

            if validate:
                self.config = Schema(self.SCHEMA).validate(self.config)

            self.config = configobj.ConfigObj(
                self.config, write_empty_values=True
            )
            self.config.filename = self.config_file
            self._resolve_paths(self.config, self.config_file)
        except Exception as ex:
            raise ConfigError(ex)

Loads config from all the config files.

Args:
validate (bool): optional flag to tell dvc if it should validate
the config or just load it as is. 'True' by default.

Raises:
dvc.config.ConfigError: thrown if config has invalid format.


def _create_w_objective(m, X, Z=None):

    genes, clusters = m.shape
    cells = X.shape[1]
    nonzeros = (X!=0)
    def objective(w):

        w = w.reshape((m.shape[1], X.shape[1]))
        d = m.dot(w)+eps

        temp = X/d
        m_sum = m.T.dot(nonzeros)
        m2 = m.T.dot(temp)
        deriv = m_sum - m2
        return np.sum(nonzeros*(d - X*np.log(d)))/genes, deriv.flatten()/genes
    return objective

Creates an objective function and its derivative for W, given M and X (data)

Args:
m (array): genes x clusters
X (array): genes x cells
Z (array): zero-inflation parameters - genes x 1


def binary_arguments_to_tensors(x1, x2):
    if ((not isinstance(x1, Tensor)) and (not isinstance(x2, Tensor))):
        raise ValueError('at least one of x1 and x2 must be an mtf Tensor')
    elif (isinstance(x1, Tensor) and isinstance(x2, Tensor)):
        return (x1, x2)
    elif isinstance(x1, Tensor):
        return (x1, import_tf_tensor(x1.mesh, tf.convert_to_tensor(x2, dtype=x1.dtype), Shape([])))
    else:
        return (import_tf_tensor(x2.mesh, tf.convert_to_tensor(x1, dtype=x2.dtype), Shape([])), x2)

Convert argument of a binary operation to Tensors.

Args:
x1: a Tensor or something convertible to a tf Scalar
x2: a Tensor or something convertible to a tf Scalar

Returns:
new_x1: a Tensor
new_x2: a Tensor

Raises:
ValueError: on failure


def AddProcessingOptions(self, argument_group):
    argument_helper_names = ['temporary_directory', 'zeromq']
    if self._CanEnforceProcessMemoryLimit():
        argument_helper_names.append('process_resources')
    helpers_manager.ArgumentHelperManager.AddCommandLineArguments(argument_group, names=argument_helper_names)
    argument_group.add_argument('--worker-memory-limit', '--worker_memory_limit', dest='worker_memory_limit', action='store', type=int, metavar='SIZE', help='Maximum amount of memory (data segment and shared memory) a worker process is allowed to consume in bytes, where 0 represents no limit. The default limit is 2147483648 (2 GiB). If a worker process exceeds this limit is is killed by the main (foreman) process.')

Adds processing options to the argument group

Args:
argument_group (argparse._ArgumentGroup): argparse argument group.


def IsErrorSuppressedByNolint(category, linenum):
    return ((linenum in _error_suppressions.get(category, set())) or (linenum in _error_suppressions.get(None, set())))

Returns true if the specified error category is suppressed on this line.

Consults the global error_suppressions map populated by
ParseNolintSuppressions/ResetNolintSuppressions.

Args:
category: str, the category of the error.
linenum: int, the current line number.
Returns:
bool, True iff the error should be suppressed due to a NOLINT comment.


def _group(self, group_data):

        if isinstance(group_data, dict):

            xid = group_data.get('xid')
        else:

            xid = group_data.xid

        if self.groups.get(xid) is not None:

            group_data = self.groups.get(xid)
        elif self.groups_shelf.get(xid) is not None:

            group_data = self.groups_shelf.get(xid)
        else:

            self.groups[xid] = group_data
        return group_data

Return previously stored group or new group.

Args:
group_data (dict|obj): An Group dict or instance of Group object.

Returns:
dict|obj: The new Group dict/object or the previously stored dict/object.


def publish(self, event_type: str, event_data: dict=None):
    import inspect
    import os.path
    _stack = inspect.stack()
    _origin = (((os.path.basename(_stack[3][1]) + '::') + _stack[3][3]) + '::L{}'.format(_stack[3][2]))
    publish(event_type=event_type, event_data=event_data, object_type=self._type, object_id=self._id, object_key=self._key, origin=_origin)

Publish an event associated with the scheduling object.

Note:
Ideally publish should not be used directly but by other methods
which perform actions on the object.

Args:
event_type (str): Type of event.
event_data (dict, optional): Event data.


def SerializeUnsigned(self, writer):

        writer.WriteUInt32(self.Version)
        writer.WriteUInt256(self.PrevHash)
        writer.WriteUInt256(self.MerkleRoot)
        writer.WriteUInt32(self.Timestamp)
        writer.WriteUInt32(self.Index)
        writer.WriteUInt64(self.ConsensusData)
        writer.WriteUInt160(self.NextConsensus)

Serialize unsigned data only.

Args:
writer (neo.IO.BinaryWriter):


def __init__(self, url=None):

        self._url = None
        self.users_url = None
        self.groups_url = None

        self.url = url

Construct a SLUGSConnector.

Args:
url (string): The base URL for the remote SLUGS instance. Optional,
defaults to None. Required for authentication.


def Detect(self, baseline, host_data):

    result = CheckResult()
    for detector in self.detectors:
      finding = detector(baseline, host_data)
      if finding:
        result.ExtendAnomalies([finding])
    if result:
      return result

Run host_data through detectors and return them if a detector triggers.

Args:
baseline: The base set of rdf values used to evaluate whether an issue
exists.
host_data: The rdf values passed back by the filters.

Returns:
A CheckResult message containing anomalies if any detectors identified an
issue, None otherwise.


def read_full(fileobj, size):
    if (size < 0):
        raise ValueError('size must not be negative')
    data = fileobj.read(size)
    if (len(data) != size):
        raise IOError
    return data

Like fileobj.read but raises IOError if not all requested data is
returned.

If you want to distinguish IOError and the EOS case, better handle
the error yourself instead of using this.

Args:
fileobj (fileobj)
size (int): amount of bytes to read
Raises:
IOError: In case read fails or not enough data is read


def get_variant_slice(self, package_name, range_):
    variant_list = self.variant_lists.get(package_name)
    if (variant_list is None):
        variant_list = _PackageVariantList(package_name, self.solver)
        self.variant_lists[package_name] = variant_list
    entries = variant_list.get_intersection(range_)
    if (not entries):
        return None
    slice_ = _PackageVariantSlice(package_name, entries=entries, solver=self.solver)
    return slice_

Get a list of variants from the cache.

Args:
package_name (str): Name of package.
range_ (`VersionRange`): Package version range.

Returns:
`_PackageVariantSlice` object.


def dispatch_command(self, prefix, argv, screen_info=None):
    if not prefix:
        raise ValueError('Prefix is empty')
    resolved_prefix = self._resolve_prefix(prefix)
    if not resolved_prefix:
        raise ValueError('No handler is registered for command prefix "%s"' % prefix)
    handler = self._handlers[resolved_prefix]
    try:
        output = handler(argv, screen_info=screen_info)
    except CommandLineExit as e:
        raise e
    except SystemExit as e:
        lines = ['Syntax error for command: %s' % prefix, 'For help, do "help %s"' % prefix]
        output = RichTextLines(lines)
    except BaseException as e:
        lines = ['Error occurred during handling of command: %s %s:' % (resolved_prefix, ' '.join(argv)), '%s: %s' % (type(e), str(e))]
        lines.append('')
        lines.extend(traceback.format_exc().split('\n'))
        output = RichTextLines(lines)
    if not isinstance(output, RichTextLines) and output is not None:
        raise ValueError('Return value from command handler %s is not None or a RichTextLines instance' % str(handler))
    return output

Handles a command by dispatching it to a registered command handler.

Args:
prefix: Command prefix, as a str, e.g., "print".
argv: Command argument vector, excluding the command prefix, represented
as a list of str, e.g.,
["tensor_1"]
screen_info: A dictionary containing screen info, e.g., {"cols": 100}.

Returns:
An instance of RichTextLines or None. If any exception is caught during
the invocation of the command handler, the RichTextLines will wrap the
error type and message.

Raises:
ValueError: If
1) prefix is empty, or
2) no command handler is registered for the command prefix, or
3) the handler is found for the prefix, but it fails to return a
RichTextLines or raise any exception.
CommandLineExit:
If the command handler raises this type of exception, this method will
simply pass it along.


def convert_to_tensor_or_ragged_tensor(value, dtype=None, preferred_dtype=None, name=None):
    if isinstance(value, RaggedTensor):
        if dtype and (not dtype.is_compatible_with(value.dtype)):
            raise ValueError(f'Tensor conversion requested dtype {dtype.name} for RaggedTensor with dtype {value.dtype.name}: {value}.')
        return value
    elif isinstance(value, ragged_tensor_value.RaggedTensorValue):
        with ops.name_scope(name, 'ConvertToTensorOrRaggedTensor', []):
            flat_values = ops.convert_to_tensor(value=value.flat_values, dtype=dtype, dtype_hint=preferred_dtype, name='flat_values')
            return RaggedTensor.from_nested_row_splits(flat_values, value.nested_row_splits, validate=False)
    else:
        return tensor_conversion.convert_to_tensor_v2_with_dispatch(value=value, dtype=dtype, dtype_hint=preferred_dtype, name=name)

Converts value to a `RaggedTensor` or `Tensor`.

* If `value` is a `RaggedTensor`, then return it as-is.
* If `value` is a `RaggedTensorValue`, return a corresponding constant
`RaggedTensor`.
* Otherwise, use `convert_to_tensor` to convert `value` to a `Tensor`.

Args:
value: A `RaggedTensor`, a `RaggedTensorValue`, or an object whose type has
a registered `Tensor` conversion function.
dtype: Optional element type for the returned tensor.  If missing the type
is inferred from the type of `value`.
preferred_dtype: Optional element type for the returned tensor, used when
dtype is None.  This argument has no effect if `value` is already a
tensor, or when conversion is not possible.
name: Optional name to use if a new `Tensor` is created.

Returns:
A `Tensor` or `RaggedTensor`.


def _slice_params_to_dict(dist, params_event_ndims, slices):

  override_dict = {}
  for param_name, param_event_ndims in six.iteritems(params_event_ndims):

    if param_name not in dist.parameters:
      raise ValueError('Distribution {} is missing advertised '
                       'parameter {}'.format(dist, param_name))
    param = dist.parameters[param_name]
    if param is None:

      continue
    dtype = None
    if hasattr(dist, param_name):
      attr = getattr(dist, param_name)
      dtype = getattr(attr, 'dtype', None)
    if dtype is None:
      dtype = dist.dtype
      warnings.warn('Unable to find property getter for parameter Tensor {} '
                    'on {}, falling back to Distribution.dtype {}'.format(
                        param_name, dist, dtype))
    param = tf.convert_to_tensor(value=param, dtype=dtype)
    override_dict[param_name] = _slice_single_param(param, param_event_ndims,
                                                    slices,
                                                    dist.batch_shape_tensor())
  return override_dict

Computes the override dictionary of sliced parameters.

Args:
dist: The tfd.Distribution being batch-sliced.
params_event_ndims: Per-event parameter ranks, a `str->int` `dict`.
slices: Slices as received by __getitem__.

Returns:
overrides: `str->Tensor` `dict` of batch-sliced parameter overrides.


def _contains_internal_dynamic_call(contract):
    for func in contract.all_functions_called:
        for node in func.nodes:
            for ir in node.irs:
                if isinstance(ir, InternalDynamicCall):
                    return True
    return False

Checks if a contract contains a dynamic call either in a direct definition, or through inheritance.

Returns:
(boolean): True if this contract contains a dynamic call (including through inheritance).


def __init__(self, **sections):

        self._sections = []
        for sct_name, sct_meta in sections.items():
            if _is_valid(sct_name):
                setattr(self, sct_name, Section(**sct_meta.def_))
                self._sections.append(sct_name)
            else:
                raise error.SectionError(sct_name)
        self._parser = None
        self._nosub_valid = False
        self._subcmds = {}
        self._config_files = ()

Initialization of instances.

Args:
sections (:class:`~loam.manager.Section`): section metadata. The
name of each *section* is the name of the keyword argument
passed on to this function. Section names should be valid
identifiers, otherwise a :class:`~loam.error.SectionError` is
raised.


def build_avatar_url(jid):
    digest = md5(str(jid).encode('utf-8')).hexdigest()
    return 'http:

Static method to build a gravatar url with the agent's JID

Args:
jid (aioxmpp.JID): an XMPP identifier

Returns:
str: an URL for the gravatar


def _insert(self, new_item, feed_item):
    filename = feed_item.get(FieldMap.CREATIVE_ASSET_FILE_NAME, None)
    file_buffer = object_get(self.config, self.auth, '%s:%s' % (feed_item.get(FieldMap.CREATIVE_ASSET_BUCKET_NAME, None), filename))
    file_mime = mimetypes.guess_type(filename, strict=False)[0]
    media = MediaIoBaseUpload(BytesIO(file_buffer), mimetype=file_mime, chunksize=CHUNKSIZE, resumable=True)
    result = self._api().insert(profileId=self.profile_id, advertiserId=str(feed_item.get(FieldMap.ADVERTISER_ID, None)), media_body=media, body=new_item).execute()
    return result

Handles the upload of creative assets to DCM and the creation of the associated entity.

This method makes a call to the DCM API to create a new entity.

Args:
new_item: The item to insert into DCM.
feed_item: The feed item representing the creative asset from the
Bulkdozer feed.

Returns:
The newly created item in DCM.


def get_query_parameters(args, cell_body, date_time=datetime.datetime.now()):
    env = google.datalab.utils.commands.notebook_environment()
    config = google.datalab.utils.commands.parse_config(cell_body, env=env, as_dict=False)
    sql = args['query']
    if (sql is None):
        raise Exception('Cannot extract query parameters in non-query cell')
    if config:
        jsonschema.validate(config, BigQuerySchema.QUERY_PARAMS_SCHEMA)
    config = (config or {})
    config_parameters = config.get('parameters', [])
    return bigquery.Query.get_query_parameters(config_parameters, date_time=date_time)

Extract query parameters from cell body if provided
Also validates the cell body schema using jsonschema to catch errors before sending the http
request. This validation isn't complete, however; it does not validate recursive schemas,
but it acts as a good filter against most simple schemas

Args:
args: arguments passed to the magic cell
cell_body: body of the magic cell
date_time: The timestamp at which the date-time related parameters need to be resolved.

Returns:
Validated object containing query parameters


def get_ogr_driver(filepath):

    filename, file_extension = os.path.splitext(filepath)
    EXTENSION = file_extension[1:]

    ogr_driver_count = ogr.GetDriverCount()
    for idx in range(ogr_driver_count):
        driver = ogr.GetDriver(idx)
        driver_extension = driver.GetMetadataItem(str('DMD_EXTENSION')) or ''
        driver_extensions = driver.GetMetadataItem(str('DMD_EXTENSIONS')) or ''

        if EXTENSION == driver_extension or EXTENSION in driver_extensions:
            return driver

    else:
        msg = 'No driver found for the following file extension: {}'.format(
            EXTENSION)
        raise ValueError(msg)

Get the OGR driver from the provided file extension.

Args:
file_extension (str): file extension

Returns:
osgeo.ogr.Driver

Raises:
ValueError: no driver is found


class TimeSeriesFeatureEmbedder(nn.Module):

    def __init__(self, cardinalities: List[int], embedding_dims: List[int]) -> None:
        super().__init__()
        self.num_features = len(cardinalities)
        self.embedders = nn.ModuleList([nn.Embedding(c, d) for c, d in zip(cardinalities, embedding_dims)])

    def forward(self, features: torch.Tensor) -> torch.Tensor:
        if self.num_features > 1:
            cat_feature_slices = torch.chunk(features, self.num_features, dim=-1)
        else:
            cat_feature_slices = [features]
        return torch.cat([embed(cat_feature_slice.squeeze(-1)) for embed, cat_feature_slice in zip(self.embedders, cat_feature_slices)], dim=-1)

Embed a sequence of categorical features.

Args:
cardinalities (`list[int]`):
List of cardinalities of the categorical features.
embedding_dims (`list[int]`):
List of embedding dimensions of the categorical features.


def put(self, key, value):

    path = self.object_path(key)
    self._write_object(path, value)

Stores the object `value` named by `key`.

Args:
key: Key naming `value`
value: the object to store.


def setdefault(pb_or_dict, key, value):
    if (not get(pb_or_dict, key, default=None)):
        set(pb_or_dict, key, value)

Set the key on the object to the value if the current value is falsy.

Because protobuf Messages do not distinguish between unset values and
falsy ones particularly well, this method treats any falsy value
(e.g. 0, empty list) as a target to be overwritten, on both Messages
and dictionaries.

Args:
pb_or_dict (Union[~google.protobuf.message.Message, Mapping]): the
object.
key (str): The key on the object in question.
value (Any): The value to set.

Raises:
TypeError: If pb_or_dict is not a Message or Mapping.


def _expansion_request_url_for_value_set_url(value_set_url: str) -> Tuple[str, str]:
    value_set_domain = urllib.parse.urlparse(value_set_url).netloc
    root_url = TERMINOLOGY_BASE_URL_PER_DOMAIN.get(value_set_domain)
    if root_url is None:
        raise ValueError('Unknown domain %s. Can not find appropriate terminology server.' % value_set_domain)
    return (root_url, urllib.parse.urljoin(root_url, 'ValueSet/$expand'))

Builds a URL for querying a terminology service to expand `value_set_url`.

Args:
value_set_url: The URL being expanded.

Raises:
ValueError: If a terminology service can not be found for `value_set_url`.

Returns:
A tuple of (root_url, expansion_url) where root_url is the root URL of the
terminology service and expansion_url is the URL to use when performing
value set expansion against that terminology service.


def translate_index(index_name):

    uuid = SEARCH_INDEX_UUIDS.get(index_name.strip().lower())
    if not uuid:
        try:
            index_info = globus_sdk.SearchClient().get_index(index_name).data
            if not isinstance(index_info, dict):
                raise ValueError("Multiple UUIDs possible")
            uuid = index_info.get("id", index_name)
        except Exception:
            uuid = index_name
    return uuid

Translate a known Globus Search index into the index UUID.
The UUID is the proper way to access indices, and will eventually be the only way.
This method will return names it cannot disambiguate.

Arguments:
index_name (str): The name of the index.

Returns:
str: The UUID of the index. If the index is not known and is not unambiguous,
this will be the ``index_name`` unchanged instead.


def timestampFormat(self, timestampFormat):
    if (not isinstance(timestampFormat, str)):
        raise TypeError('not of type unicode')
    self._timestampFormat = timestampFormat

Setter to _timestampFormat. Formatting string for conversion of timestamps to QtCore.QDateTime

Raises:
AssertionError: if timestampFormat is not of type unicode.

Args:
timestampFormat (unicode): assign timestampFormat to _timestampFormat.
Formatting string for conversion of timestamps to QtCore.QDateTime. Used in data method.


def send_state_event(self, room_id, event_type, content, state_key="",
                         timestamp=None):

        path = "/rooms/%s/state/%s" % (
            quote(room_id), quote(event_type),
        )
        if state_key:
            path += "/%s" % (quote(state_key))
        params = {}
        if timestamp:
            params["ts"] = timestamp
        return self._send("PUT", path, content, query_params=params)

Perform PUT /rooms/$room_id/state/$event_type

Args:
room_id(str): The room ID to send the state event in.
event_type(str): The state event type to send.
content(dict): The JSON content to send.
state_key(str): Optional. The state key for the event.
timestamp (int): Set origin_server_ts (For application services only)


def subprogram_signature(vo, fullname=None):

  if fullname is None:
    fullname = vo.name

  if isinstance(vo, VhdlFunction):
    plist = ','.join(p.data_type for p in vo.parameters)
    sig = '{}[{} return {}]'.format(fullname, plist, vo.return_type)
  else:
    plist = ','.join(p.data_type for p in vo.parameters)
    sig = '{}[{}]'.format(fullname, plist)

  return sig

Generate a signature string

Args:
vo (VhdlFunction, VhdlProcedure): Subprogram object
Returns:
Signature string.


def pprint(sequence, keys=None):
    if (len(sequence) > 0):
        columns = calculate_columns(sequence)
        row_format = calculate_row_format(columns, keys)
        header = (row_format % dict([(key, key.title()) for key in columns]))
        separator = (row_format % dict([(key, ('-' * columns[key])) for key in columns]))
        print(separator)
        print(header)
        print(separator)
        for row in sequence:
            print((row_format % row))
        print(separator)

Print sequence as ascii table to stdout.

Args:
sequence (list or tuple): a sequence with a dictionary each entry.
keys (list): optional list of keys to order columns as well as to filter for them.


def combine_graph_defs(to_proto, from_proto):
    if (from_proto.version != to_proto.version):
        raise ValueError('Cannot combine GraphDefs of different versions.')
    try:
        _safe_copy_proto_list_values(to_proto.node, from_proto.node, (lambda n: n.name))
    except _ProtoListDuplicateKeyError as exc:
        raise ValueError(('A GraphDef contains non-unique node names: %s' % exc))
    except _SameKeyDiffContentError as exc:
        raise ValueError(('Cannot combine GraphDefs because nodes share a name but contents are different: %s' % exc))
    try:
        _safe_copy_proto_list_values(to_proto.library.function, from_proto.library.function, (lambda n: n.signature.name))
    except _ProtoListDuplicateKeyError as exc:
        raise ValueError(('A GraphDef contains non-unique function names: %s' % exc))
    except _SameKeyDiffContentError as exc:
        raise ValueError(('Cannot combine GraphDefs because functions share a name but are different: %s' % exc))
    try:
        _safe_copy_proto_list_values(to_proto.library.gradient, from_proto.library.gradient, (lambda g: g.gradient_func))
    except _ProtoListDuplicateKeyError as exc:
        raise ValueError(('A GraphDef contains non-unique gradient function names: %s' % exc))
    except _SameKeyDiffContentError as exc:
        raise ValueError(('Cannot combine GraphDefs because gradients share a gradient_func name but map to different functions: %s' % exc))
    return to_proto

Combines two GraphDefs by adding nodes from from_proto into to_proto.

All GraphDefs are expected to be of TensorBoard's.
It assumes node names are unique across GraphDefs if contents differ. The
names can be the same if the NodeDef content are exactly the same.

Args:
to_proto: A destination TensorBoard GraphDef.
from_proto: A TensorBoard GraphDef to copy contents from.

Returns:
to_proto

Raises:
ValueError in case any assumption about GraphDef is violated: A
GraphDef should have unique node, function, and gradient function
names. Also, when merging GraphDefs, they should have not have nodes,
functions, or gradient function mappings that share the name but details
do not match.


def get_sequence_dense_tensor(self, transformation_cache, state_manager):
    sp_tensor = transformation_cache.get(self, state_manager)
    dense_tensor = sparse_ops.sparse_tensor_to_dense(sp_tensor, default_value=self.default_value)
    dense_shape = array_ops.concat([array_ops.shape(dense_tensor)[:1], [-1], self.variable_shape], axis=0)
    dense_tensor = array_ops.reshape(dense_tensor, shape=dense_shape)
    if sp_tensor.shape.ndims == 2:
        num_elements = self.variable_shape.num_elements()
    else:
        num_elements = 1
    seq_length = fc_utils.sequence_length_from_sparse_tensor(sp_tensor, num_elements=num_elements)
    return fc.SequenceDenseColumn.TensorSequenceLengthPair(dense_tensor=dense_tensor, sequence_length=seq_length)

Returns a `TensorSequenceLengthPair`.

Args:
transformation_cache: A `FeatureTransformationCache` object to access
features.
state_manager: A `StateManager` to create / access resources such as
lookup tables.


def is_debug_node(node_name):
    return node_name.startswith('__dbg_')

Determine whether a node name is that of a debug node.

Such nodes are inserted by TensorFlow core upon request in
RunOptions.debug_options.debug_tensor_watch_opts.

Args:
node_name: Name of the node.

Returns:
A bool indicating whether the input argument is the name of a debug node.


def put(self, json=None):
    return self._call('put', url=self.endpoint, json=json)

Send a PUT request and return the JSON decoded result.

Args:
json (dict, optional): Object to encode and send in request.

Returns:
mixed: JSON decoded response data.


def setAvatar(self, image):

        self.conn("PUT", "{0}/users/{1}/profile/avatar".format(SkypeConnection.API_USER, self.userId),
                  auth=SkypeConnection.Auth.SkypeToken, data=image.read())

Update the profile picture for the current user.

Args:
image (file): a file-like object to read the image from


def __init__(self, **kwargs):

        self.address = self.name = address.new(kwargs['name'])

        self.subgraph = None
        self.params = {}
        log.debug('New target: %s', self.address)

        try:
            for param_name, param_type in self.required_params:
                self.params[param_name] = kwargs.pop(param_name)
                assert isinstance(self.params[param_name], param_type)
        except AssertionError as err:
            if isinstance(param_type, tuple) and len(param_type) > 1:
                msg = 'one of: %s' % ', '.join(param_type.__name__)
            else:
                msg = str(param_type.__name__)
            raise error.InvalidRule(
                'While loading %s: Invalid type for %s. '
                'Expected: %s. Actual: %s.' % (
                    self.address, param_name, msg,
                    repr(self.params[param_name])))
        except KeyError as err:
            log.error(err)
            raise error.InvalidRule(
                'While loading %s: Required parameter %s not given.' % repr(
                    self.address, param_name))

        for (param_name, param_type, param_default) in self.optional_params:
            if param_name not in kwargs:
                self.params[param_name] = param_default
            else:
                self.params[param_name] = kwargs.pop(param_name)
                if not isinstance(self.params[param_name], param_type):
                    msg = str(param_type.__name__)
                    if isinstance(param_type, tuple) and len(param_type) > 1:
                        msg = 'one of: %s' % ', '.join(param_type.__name__)
                    raise error.InvalidRule(
                        'While loading %s: Invalid type for %s. '
                        'Expected: %s. Actual: %s.' % (
                            self.address, param_name, msg,
                            repr(self.params[param_name])))

        if kwargs:
            raise error.InvalidRule(
                '[%s]: Unknown argument(s): %s' % (
                    self.address, ', '.join(kwargs.keys())))

        if self.graphcontext is not None:
            self.graphcontext.add_node(self.address, target_obj=self)

        try:
            self.validate_args()
        except AssertionError as err:
            raise error.InvalidRule('Error in %s: %s' % (self.address, err))

Initialize the build rule.

Args:
**kwargs: Assorted parameters; see subclass implementations for
details.


def serialize_array(array, domain=(0, 1), fmt='png', quality=70):

  normalized = _normalize_array(array, domain=domain)
  return _serialize_normalized_array(normalized, fmt=fmt, quality=quality)

Given an arbitrary rank-3 NumPy array,
returns the byte representation of the encoded image.

Args:
array: NumPy array of dtype uint8 and range 0 to 255
domain: expected range of values in array, see `_normalize_array()`
fmt: string describing desired file format, defaults to 'png'
quality: specifies compression quality from 0 to 100 for lossy formats

Returns:
image data as BytesIO buffer


def list_alias():
    alias_table = get_alias_table()
    output = []
    for alias in alias_table.sections():
        if alias_table.has_option(alias, 'command'):
            output.append({'alias': alias, 'command': ' '.join(alias_table.get(alias, 'command').split())})
    return output

List all registered aliases.

Returns:
An array of  dictionary containing the alias and the command that it points to.