def remove_interaction(self, u, v):
    try:
        del self.quadratic[(u, v)]
    except KeyError:
        return
    try:
        del self._counterpart
        if ((self.vartype is not Vartype.BINARY) and hasattr(self, '_binary')):
            del self._binary
        elif ((self.vartype is not Vartype.SPIN) and hasattr(self, '_spin')):
            del self._spin
    except AttributeError:
        pass

Remove interaction of variables u, v from a binary quadratic model.

Args:
u (variable):
One of the pair of variables in the binary quadratic model that
has an interaction.

v (variable):
One of the pair of variables in the binary quadratic model that
has an interaction.

Notes:
Any interaction not in the binary quadratic model is ignored.

Examples:
This example creates an Ising model with three variables that has interactions
between two, and then removes an interaction.

>>> import dimod
...
>>> bqm = dimod.BinaryQuadraticModel({}, {('a', 'b'): -1.0, ('b', 'c'): 1.0}, 0.0, dimod.SPIN)
>>> bqm.remove_interaction('b', 'c')
>>> ('b', 'c') in bqm.quadratic
False
>>> bqm.remove_interaction('a', 'c')  # not an interaction, so ignored
>>> len(bqm.quadratic)
1


def show_warning_messages(self, title=_(u'Incorrect Operation'), box_type='warning'):
    msg = self.current.task_data['msg']
    self.current.output['msgbox'] = {'type': box_type, 'title': title, 'msg': msg}
    del self.current.task_data['msg']

It shows incorrect operations or successful operation messages.

Args:
title (string): title of message box
box_type (string): type of message box (warning, info)


def _resize_output_size_scale_below_upper_bound(height: int, width: int, max_len: Optional[Dict[str, int]]=None) -> Tuple[int, int]:
    max_len = max(height, width) if max_len is None else max_len
    aspect_ratio = width / height
    if width >= height and width > max_len:
        width = max_len
        height = int(width / aspect_ratio)
    elif height > width and height > max_len:
        height = max_len
        width = int(height * aspect_ratio)
    height = max(height, 1)
    width = max(width, 1)
    return (height, width)

Get the output size of the image after resizing given a dictionary specifying the max and min sizes.
Args:
height (`int`):
Height of the input image.
width (`int`):
Width of the input image.
max_len (`Dict[str, int]`, *optional*, defaults to the maximum size of the image):
Defines the maximum dimensions of the image.
Returns:
The output size of the image after resizing.


def coerce(self, value):

        if isinstance(value, int) or isinstance(value, compat.long):

            return value

        return int(value)

Convert text values into integer values.

Args:
value (str or int): The value to coerce.

Raises:
TypeError: If the value is not an int or string.
ValueError: If the value is not int or an acceptable value.

Returns:
int: The integer value represented.


def _parse_url_and_validate(cls, url):
    parsed_url = urlparse(url)
    if (parsed_url.scheme and parsed_url.netloc):
        final_url = parsed_url.geturl()
    else:
        raise BadURLException
    return final_url

Recieves a URL string and validates it using urlparse.

Args:
url: A URL string
Returns:
parsed_url: A validated URL
Raises:
BadURLException


def set_mode(self, value=None, default=False, disable=False):
    if ((not default) and (not disable)):
        if (value not in ['mstp', 'none']):
            raise ValueError("Specified value must be one of 'mstp', 'none'")
    cmds = self.command_builder('spanning-tree mode', value=value, default=default, disable=disable)
    return self.configure(cmds)

Configures the global spanning-tree mode

Note:
This configuration parameter is not defaultable

Args:
value (string): The value to configure the global spanning-tree
mode of operation.  Valid values include 'mstp', 'none'
default (bool): Set the global spanning-tree mode to default.
disable (bool): Negate the global spanning-tree mode.

Returns:
True if the configuration operation succeeds otherwise False

Raises:
ValueError if the value is not in the accepted range


def validate_client_properties(props):
    for key in ('version', 'information', 'product'):
        if (key not in props):
            props[key] = DEFAULTS['client_properties'][key]
        if (props[key] != DEFAULTS['client_properties'][key]):
            raise exceptions.ConfigurationException('"{}" is a reserved keyword in client_properties'.format(key))

Validate the client properties setting.

This will add the "version", "information", and "product" keys if they are
missing. All other keys are application-specific.

Raises:
exceptions.ConfigurationException: If any of the basic keys are overridden.


def predict(self, train_x):

        k_trans = np.exp(-np.power(edit_distance_matrix(train_x, self._x), 2))
        y_mean = k_trans.dot(self._alpha_vector)

        l_inv = solve_triangular(self._l_matrix.T, np.eye(self._l_matrix.shape[0]))
        k_inv = l_inv.dot(l_inv.T)

        y_var = np.ones(len(train_x), dtype=np.float)
        y_var -= np.einsum("ij,ij->i", np.dot(k_trans, k_inv), k_trans)

        y_var_negative = y_var < 0
        if np.any(y_var_negative):
            y_var[y_var_negative] = 0.0
        return y_mean, np.sqrt(y_var)

Predict the result.
Args:
train_x: A list of NetworkDescriptor.
Returns:
y_mean: The predicted mean.
y_std: The predicted standard deviation.


def generate_xid(identifier=None):

        if identifier is None:
            identifier = str(uuid.uuid4())
        elif isinstance(identifier, list):
            identifier = '-'.join([str(i) for i in identifier])
            identifier = hashlib.sha256(identifier.encode('utf-8')).hexdigest()
        return hashlib.sha256(identifier.encode('utf-8')).hexdigest()

Generate xid from provided identifiers.

.. Important::  If no identifier is provided a unique xid will be returned, but it will
not be reproducible. If a list of identifiers are provided they must be
in the same order to generate a reproducible xid.

Args:
identifier (list|str):  Optional *string* value(s) to be used to make a unique and
reproducible xid.


def get_single_value(value):
    if (not all_elements_equal(value)):
        raise ValueError('Not all values are equal to each other.')
    if is_scalar(value):
        return value
    return value.item(0)

Get a single value out of the given value.

This is meant to be used after a call to :func:`all_elements_equal` that returned True. With this
function we return a single number from the input value.

Args:
value (ndarray or number): a numpy array or a single number.

Returns:
number: a single number from the input

Raises:
ValueError: if not all elements are equal


def mark_as_return(self, tensor):
    if isinstance(tensor, indexed_slices.IndexedSlices):
        values = array_ops.identity(tensor.values)
        indices = array_ops.identity(tensor.indices)
        self._returned_tensors.add(indices)
        self._returned_tensors.add(values)
        return indexed_slices.IndexedSlices(values, indices, dense_shape=tensor.dense_shape)
    elif isinstance(tensor, sparse_tensor.SparseTensor):
        values = array_ops.identity(tensor.values)
        indices = array_ops.identity(tensor.indices)
        self._returned_tensors.add(indices)
        self._returned_tensors.add(values)
        return sparse_tensor.SparseTensor(indices, values, dense_shape=tensor.dense_shape)
    elif isinstance(tensor, tensor_array_ops.TensorArray):
        flow = array_ops.identity(tensor.flow)
        self._returned_tensors.add(flow)
        return tensor_array_ops.build_ta_with_new_flow(tensor, flow)
    tensor = array_ops.identity(tensor)
    self._returned_tensors.add(tensor)
    return tensor

Acts like identity but marks the `Tensor` as a return value.

This will possibly return a copy of the `Tensor`. Usage:

```
with AutomaticControlDependencies() as a:
...
t = a.mark_as_return(t)
_ = ...(t...)  # i.e. it's safe to use t here
```

Args:
tensor: the `Tensor` to be marked

Returns:
a copy of the `Tensor`.


def deps_from_pyp_format(requires, runtime=True):

    parsed = []
    logger.debug("Dependencies from setup.py: {0} runtime: {1}.".format(
        requires, runtime))

    for req in requires:
        try:
            parsed.append(Requirement.parse(req))
        except ValueError:
            logger.warn("Unparsable dependency {0}.".format(req),
                        exc_info=True)

    in_rpm_format = []
    for dep in parsed:
        in_rpm_format.extend(dependency_to_rpm(dep, runtime))
    logger.debug("Dependencies from setup.py in rpm format: {0}.".format(
        in_rpm_format))

    return in_rpm_format

Parses dependencies extracted from setup.py.
Args:
requires: list of dependencies as written in setup.py of the package.
runtime: are the dependencies runtime (True) or build time (False)?
Returns:
List of semi-SPECFILE dependencies (see dependency_to_rpm for format).


def __init__(self, value=''):

        super(ExtensionName, self).__init__(value, Tags.EXTENSION_NAME)

Construct an ExtensionName object.

Args:
value (str): The string data representing the extension name.
Optional, defaults to the empty string.


def stack_template_key_name(blueprint):

    name = blueprint.name
    return "stack_templates/%s/%s-%s.json" % (blueprint.context.get_fqn(name),
                                              name,
                                              blueprint.version)

Given a blueprint, produce an appropriate key name.

Args:
blueprint (:class:`stacker.blueprints.base.Blueprint`): The blueprint
object to create the key from.

Returns:
string: Key name resulting from blueprint.


def apply_op(input_layer, operation, *op_args, **op_kwargs):
    return input_layer.with_tensor(operation(input_layer.tensor, *op_args, **op_kwargs))

Applies the given operation to this before without adding any summaries.

Args:
input_layer: The input layer for this op.
operation: An operation that takes a tensor and the supplied args.
*op_args: Extra arguments for operation.
**op_kwargs: Keyword arguments for the operation.
Returns:
A new layer with operation applied.


def skip_while(self, predicate):

        if self.closed():
            raise ValueError("Attempt to call take_while() on a "
                            "closed Queryable.")

        if not is_callable(predicate):
            raise TypeError("skip_while() parameter predicate={0} is "
                            "not callable".format(repr(predicate)))

        return self._create(itertools.dropwhile(predicate, self))

Omit elements from the start for which a predicate is True.

Note: This method uses deferred execution.

Args:
predicate: A single argument predicate function.

Returns:
A Queryable over the sequence of elements beginning with the first
element for which the predicate returns False.

Raises:
ValueError: If the Queryable is closed().
TypeError: If predicate is not callable.


def getitem_column_array(self, key):
    numeric_indices = list(self.columns.get_indexer_for(key))

    def getitem(df, internal_indices=[]):
        return df.iloc[(:, internal_indices)]
    result = self.data.apply_func_to_select_indices(0, getitem, numeric_indices, keep_remaining=False)
    new_columns = self.columns[numeric_indices]
    new_dtypes = self.dtypes[numeric_indices]
    return self.__constructor__(result, self.index, new_columns, new_dtypes)

Get column data for target labels.

Args:
key: Target labels by which to retrieve data.

Returns:
A new QueryCompiler.


def reset_states(self, states=None):
    if not self.stateful:
        raise AttributeError('Layer must be stateful.')
    spec_shape = None
    if self.input_spec is not None:
        spec_shape = nest.flatten(self.input_spec[0])[0].shape
    if spec_shape is None:
        batch_size = None
    else:
        batch_size = spec_shape[1] if self.time_major else spec_shape[0]
    if not batch_size:
        raise ValueError('If a RNN is stateful, it needs to know its batch size. Specify the batch size of your input tensors: \n- If using a Sequential model, specify the batch size by passing a `batch_input_shape` argument to your first layer.\n- If using the functional API, specify the batch size by passing a `batch_shape` argument to your Input layer.')
    if nest.flatten(self.states)[0] is None:
        if getattr(self.cell, 'get_initial_state', None):
            flat_init_state_values = nest.flatten(self.cell.get_initial_state(inputs=None, batch_size=batch_size, dtype=self.dtype or backend.floatx()))
        else:
            flat_init_state_values = nest.flatten(_generate_zero_filled_state(batch_size, self.cell.state_size, self.dtype or backend.floatx()))
        flat_states_variables = nest.map_structure(backend.variable, flat_init_state_values)
        self.states = nest.pack_sequence_as(self.cell.state_size, flat_states_variables)
        if not nest.is_nested(self.states):
            self.states = [self.states]
    elif states is None:
        for state, size in zip(nest.flatten(self.states), nest.flatten(self.cell.state_size)):
            backend.set_value(state, np.zeros([batch_size] + tensor_shape.TensorShape(size).as_list()))
    else:
        flat_states = nest.flatten(self.states)
        flat_input_states = nest.flatten(states)
        if len(flat_input_states) != len(flat_states):
            raise ValueError('Layer ' + self.name + ' expects ' + str(len(flat_states)) + ' states, but it received ' + str(len(flat_input_states)) + ' state values. Input received: ' + str(states))
        set_value_tuples = []
        for i, (value, state) in enumerate(zip(flat_input_states, flat_states)):
            if value.shape != state.shape:
                raise ValueError('State ' + str(i) + ' is incompatible with layer ' + self.name + ': expected shape=' + str((batch_size, state)) + ', found shape=' + str(value.shape))
            set_value_tuples.append((state, value))
        backend.batch_set_value(set_value_tuples)

Reset the recorded states for the stateful RNN layer.

Can only be used when RNN layer is constructed with `stateful` = `True`.
Args:
states: Numpy arrays that contains the value for the initial state, which
will be feed to cell at the first time step. When the value is None,
zero filled numpy array will be created based on the cell state size.

Raises:
AttributeError: When the RNN layer is not stateful.
ValueError: When the batch size of the RNN layer is unknown.
ValueError: When the input numpy array is not compatible with the RNN
layer state, either size wise or dtype wise.


def AddBatchJob(client):

  batch_job_service = client.GetService('BatchJobService', version='v201809')

  batch_job_operations = [{
      'operand': {},
      'operator': 'ADD'
  }]
  return batch_job_service.mutate(batch_job_operations)['value'][0]

Add a new BatchJob to upload operations to.

Args:
client: an instantiated AdWordsClient used to retrieve the BatchJob.

Returns:
The new BatchJob created by the request.


class VectorDatabaseWriteTransform(beam.PTransform):

    def __init__(self, database_config: VectorDatabaseWriteConfig):

        if not isinstance(database_config, VectorDatabaseWriteConfig):
            raise TypeError(f'database_config must be VectorDatabaseWriteConfig, got {type(database_config)}')
        self.database_config = database_config

    def expand(self, pcoll: beam.PCollection[Chunk]) -> beam.PTransform[Chunk, Any]:

        write_transform = self.database_config.create_write_transform()
        return pcoll | write_transform

A PTransform for writing embedded chunks to vector databases.

This transform uses a VectorDatabaseWriteConfig to write chunks with
embeddings to vector database. It handles validating the config and applying
the database-specific write transform.

Example usage:
>>> config = BigQueryVectorConfig(
...     table='project.dataset.embeddings',
...     embedding_column='embedding'
... )
>>>
>>> with beam.Pipeline() as p:
...     chunks = p | beam.Create([...])  # PCollection[Chunk]
...     chunks | VectorDatabaseWriteTransform(config)

Args:
database_config: Configuration for the target vector database.
Must be a subclass of VectorDatabaseWriteConfig that implements
create_write_transform().

Raises:
TypeError: If database_config is not a VectorDatabaseWriteConfig instance.


def _GetRecordValue(self, record, value_entry):
    column_type = record.get_column_type(value_entry)
    long_value = None
    if record.is_long_value(value_entry):
        long_value = record.get_value_data_as_long_value(value_entry)
    if record.is_multi_value(value_entry):
        raise ValueError('Multi value support not implemented yet.')
    if (column_type == pyesedb.column_types.NULL):
        return None
    if (column_type == pyesedb.column_types.BOOLEAN):
        raise ValueError('Boolean value support not implemented yet.')
    if (column_type in self.INTEGER_COLUMN_TYPES):
        if long_value:
            raise ValueError('Long integer value not supported.')
        return record.get_value_data_as_integer(value_entry)
    if (column_type in self.FLOATING_POINT_COLUMN_TYPES):
        if long_value:
            raise ValueError('Long floating point value not supported.')
        return record.get_value_data_as_floating_point(value_entry)
    if (column_type in self.STRING_COLUMN_TYPES):
        if long_value:
            return long_value.get_data_as_string()
        return record.get_value_data_as_string(value_entry)
    if (column_type == pyesedb.column_types.GUID):
        raise ValueError('GUID value support not implemented yet.')
    if long_value:
        return long_value.get_data()
    return record.get_value_data(value_entry)

Retrieves a specific value from the record.

Args:
record (pyesedb.record): ESE record.
value_entry (int): value entry.

Returns:
object: value.

Raises:
ValueError: if the value is not supported.


def wrapped_body(loop_counter, maximum_iterations_arg, *args):
    _copy_handle_data(nest.flatten(loop_vars[2:], expand_composites=True), nest.flatten(args, expand_composites=True))
    for t in cond_graph.external_captures:
        ops.get_default_graph().capture(t)
    outputs = body(*_pack_sequence_as(loop_vars_signature, flat_orig_loop_vars, args))
    if not nest.is_nested(outputs):
        outputs = [outputs]
    try:
        nest.assert_same_structure(outputs, orig_loop_vars, check_types=False, expand_composites=True)
    except ValueError:
        vars1 = variable_utils.convert_variables_to_tensors(outputs)
        vars2 = variable_utils.convert_variables_to_tensors(orig_loop_vars)
        nest.assert_same_structure(vars1, vars2, check_types=False, expand_composites=True)
    outputs = _tensor_array_to_flow(outputs)
    return [loop_counter + 1, maximum_iterations_arg] + list(outputs)

Loop body augmented with counter update.

Args:
loop_counter: Loop counter which needs to be incremented in the body.
maximum_iterations_arg: Maximum iterations of the loop.
*args: List of args

Returns:
A list of tensors the same length as args.


def get_features(self, did, wid, eid):

        return self._api.request('get', '/api/partstudios/d/' + did + '/w/' + wid + '/e/' + eid + '/features')

Gets the feature list for specified document / workspace / part studio.

Args:
- did (str): Document ID
- wid (str): Workspace ID
- eid (str): Element ID

Returns:
- requests.Response: Onshape response data


def evaluate_moment(distribution, k_data, parameters=None, cache=None):
    logger = logging.getLogger(__name__)
    assert (len(k_data) == len(distribution)), ('distribution %s is not of length %d' % (distribution, len(k_data)))
    assert (len(k_data.shape) == 1)
    if numpy.all((k_data == 0)):
        return 1.0

    def cache_key(distribution):
        return (tuple(k_data), distribution)
    if (cache is None):
        cache = {}
    elif (cache_key(distribution) in cache):
        return cache[cache_key(distribution)]
    from .. import baseclass
    try:
        parameters = load_parameters(distribution, '_mom', parameters, cache, cache_key)
        out = distribution._mom(k_data, **parameters)
    except baseclass.StochasticallyDependentError:
        logger.warning('Distribution %s has stochastic dependencies; Approximating moments with quadrature.', distribution)
        from .. import approximation
        out = approximation.approximate_moment(distribution, k_data)
    if isinstance(out, numpy.ndarray):
        out = out.item()
    cache[cache_key(distribution)] = out
    return out

Evaluate raw statistical moments.

Args:
distribution (Dist):
Distribution to evaluate.
x_data (numpy.ndarray):
Locations for where evaluate moment of.
parameters (:py:data:typing.Any):
Collection of parameters to override the default ones in the
distribution.
cache (:py:data:typing.Any):
A collection of previous calculations in case the same distribution
turns up on more than one occasion.

Returns:
The raw statistical moment of ``distribution`` at location ``x_data``
using parameters ``parameters``.


def increment(self, counter_name, delta=1):

    self._shard_state.counters_map.increment(counter_name, delta)

Increment counter value.

Args:
counter_name: name of the counter as string.
delta: increment delta as int.


def StopTiming(self, profile_name):
    measurements = self._profile_measurements.get(profile_name)
    if measurements:
        measurements.SampleStop()
        sample = '{0:f}\t{1:s}\t{2:f}\n'.format(measurements.start_sample_time, profile_name, measurements.total_cpu_time)
        self._WritesString(sample)

Stops timing CPU time.

Args:
profile_name (str): name of the profile to sample.


def is_running(process):
    if (os.name == 'nt'):
        process_list = get_cmd_out(['tasklist', '/v'])
        return (process in process_list)
    else:
        process_list = get_cmd_out("ps axw | awk '{print $5}'")
        for i in process_list.split('\n'):
            if ((not (i == 'COMMAND')) or i.startswith('[')):
                if (i == process):
                    return True
                elif (os.path.basename(i) == process):
                    return True
    return False

Check if process is running.

Check if the given process name is running or not.

Note:
On a Linux system, kernel threads (like	``kthreadd`` etc.)
are excluded.

Args:
process (str): The name of the process.

Returns:
bool: Is the process running?


def _test_parsed_sequence_example(self, col_name, col_fn, col_arg, shape, values):
    example = _make_sequence_example()
    columns = [fc.categorical_column_with_identity('int_ctx', num_buckets=100), fc.numeric_column('float_ctx'), col_fn(col_name, col_arg)]
    context, seq_features = parsing_ops.parse_single_sequence_example(example.SerializeToString(), context_features=fc.make_parse_example_spec_v2(columns[:2]), sequence_features=fc.make_parse_example_spec_v2(columns[2:]))
    with self.cached_session() as sess:
        ctx_result, seq_result = sess.run([context, seq_features])
        self.assertEqual(list(seq_result[col_name].dense_shape), shape)
        self.assertEqual(list(seq_result[col_name].values[[0, 2, 6]]), values)
        self.assertEqual(list(ctx_result['int_ctx'].dense_shape), [1])
        self.assertEqual(ctx_result['int_ctx'].values[0], 5)
        self.assertEqual(list(ctx_result['float_ctx'].shape), [1])
        self.assertAlmostEqual(ctx_result['float_ctx'][0], 123.6, places=1)

Helper function to check that each FeatureColumn parses correctly.

Args:
col_name: string, name to give to the feature column. Should match
the name that the column will parse out of the features dict.
col_fn: function used to create the feature column. For example,
sequence_numeric_column.
col_arg: second arg that the target feature column is expecting.
shape: the expected dense_shape of the feature after parsing into
a SparseTensor.
values: the expected values at index [0, 2, 6] of the feature
after parsing into a SparseTensor.


def __init__(self, host="localhost", port=6025):

        Environment.__init__(self)
        self.port = int(port) or 6025
        self.host = host or "localhost"
        self.socket = None

        self.buffer_size = 8192

        self.last_observation = None

A remote Environment that one can connect to through tcp.
Implements a simple msgpack protocol to get the step/reset/etc.. commands to the
remote server and simply waits (blocks) for a response.

Args:
host (str): The hostname to connect to.
port (int): The port to connect to.


def shape(self):
    return self._shape()

`TensorShape` of this `LinearOperator`.

If this operator acts like the batch matrix `A` with
`A.shape = [B1,...,Bb, M, N]`, then this returns
`TensorShape([B1,...,Bb, M, N])`, equivalent to `A.shape`.

Returns:
`TensorShape`, statically determined, may be undefined.


def write_to_fil(self, filename_out, *args, **kwargs):
    t0 = time.time()
    self.__update_header()
    if self.container.isheavy():
        self.__write_to_fil_heavy(filename_out)
    else:
        self.__write_to_fil_light(filename_out)
    t1 = time.time()
    logger.info(('Conversion time: %2.2fsec' % (t1 - t0)))

Write data to .fil file.
It check the file size then decides how to write the file.

Args:
filename_out (str): Name of output file


def __call__(self, unused_op):
    task = self._next_task
    self._next_task = (self._next_task + 1) % self._num_tasks
    return task

Choose a ps task index for the given `Operation`.

Args:
unused_op: An `Operation` to be placed on ps.

Returns:
The next ps task index to use for the `Operation`. Returns the next
index, in the range `[offset, offset + num_tasks)`.


def data_groups(self, groups, entity_count):

        data = []

        for xid in groups.keys():

            assoc_group_data = self.data_group_association(xid)
            data += assoc_group_data
            entity_count += len(assoc_group_data)

            if entity_count >= self._batch_max_chunk:
                break
        return data, entity_count

Process Group data.

Args:
groups (list): The list of groups to process.

Returns:
list: A list of groups including associations


def ban_user(self, room_id, user_id, reason=""):

        body = {
            "user_id": user_id,
            "reason": reason
        }
        return self._send("POST", "/rooms/" + room_id + "/ban", body)

Perform POST /rooms/$room_id/ban

Args:
room_id (str): The room ID
user_id (str): The user ID of the banee(sic)
reason (str): The reason for this ban


def point_sets(script, neighbors=10, smooth_iteration=0, flip=False, viewpoint_pos=(0.0, 0.0, 0.0)):
    filter_xml = ''.join(['  <filter name="Compute normals for point sets">\n', '    <Param name="K" ', 'value="{:d}" '.format(neighbors), 'description="Neighbour num" ', 'type="RichInt" ', '/>\n', '    <Param name="smoothIter" ', 'value="{:d}" '.format(smooth_iteration), 'description="Smooth Iteration" ', 'type="RichInt" ', '/>\n', '    <Param name="flipFlag" ', 'value="{}" '.format(str(flip).lower()), 'description="Flip normals w.r.t. viewpoint" ', 'type="RichBool" ', '/>\n', '    <Param name="viewPos" ', 'x="{}" y="{}" z="{}" '.format(viewpoint_pos[0], viewpoint_pos[1], viewpoint_pos[2]), 'description="Viewpoint Pos." ', 'type="RichPoint3f" ', '/>\n', '  </filter>\n'])
    util.write_filter(script, filter_xml)
    return None

Compute the normals of the vertices of a mesh without exploiting the
triangle connectivity, useful for dataset with no faces.

Args:
script: the FilterScript object or script filename to write
the filter to.
neighbors (int): The number of neighbors used to estimate normals.
smooth_iteration (int): The number of smoothing iteration done on the
p used to estimate and propagate normals.
flip (bool): Flip normals w.r.t. viewpoint. If the 'viewpoint' (i.e.
scanner position) is known, it can be used to disambiguate normals
orientation, so that all the normals will be oriented in the same
direction.
viewpoint_pos (single xyz point, tuple or list): Set the x, y, z
coordinates of the viewpoint position.

Layer stack:
No impacts

MeshLab versions:
2016.12
1.3.4BETA


def update_state(self, y_true, y_pred, sample_weight=None):
    y_true = math_ops.cast(y_true, self._dtype)
    y_pred = math_ops.cast(y_pred, self._dtype)
    [y_pred, y_true], sample_weight = metrics_utils.ragged_assert_compatible_and_get_flat_values([y_pred, y_true], sample_weight)
    y_pred, y_true = losses_utils.squeeze_or_expand_dimensions(y_pred, y_true)
    y_pred, self.normalizer = losses_utils.remove_squeezable_dimensions(y_pred, self.normalizer)
    y_pred.shape.assert_is_compatible_with(y_true.shape)
    relative_errors = math_ops.div_no_nan(math_ops.abs(y_true - y_pred), self.normalizer)
    return super(MeanRelativeError, self).update_state(relative_errors, sample_weight=sample_weight)

Accumulates metric statistics.

Args:
y_true: The ground truth values.
y_pred: The predicted values.
sample_weight: Optional weighting of each example. Defaults to 1. Can be a
`Tensor` whose rank is either 0, or the same rank as `y_true`, and must
be broadcastable to `y_true`.

Returns:
Update op.


def _init_tag(self, tag):

        self._element = tag

        self._parseIsTag()
        self._parseIsComment()

        if not self._istag or self._iscomment:
            self._tagname = self._element
        else:
            self._parseTagName()

        if self._iscomment or not self._istag:
            return

        self._parseIsEndTag()
        self._parseIsNonPairTag()

        if self._istag and (not self._isendtag) or "=" in self._element:
            self._parseParams()

True constructor, which really initializes the :class:`HTMLElement`.

This is the function where all the preprocessing happens.

Args:
tag (str): HTML tag as string.


def generators_from_logdir(logdir):
    subdirs = io_wrapper.GetLogdirSubdirectories(logdir)
    generators = [itertools.chain(*[generator_from_event_file(os.path.join(subdir, f)) for f in tf.io.gfile.listdir(subdir) if io_wrapper.IsTensorFlowEventsFile(os.path.join(subdir, f))]) for subdir in subdirs]
    return generators

Returns a list of event generators for subdirectories with event files.

The number of generators returned should equal the number of directories
within logdir that contain event files. If only logdir contains event files,
returns a list of length one.

Args:
logdir: A log directory that contains event files.

Returns:
List of event generators for each subdirectory with event files.


def destroy_sns_event(app_name, env, region):
    session = boto3.Session(profile_name=env, region_name=region)
    sns_client = session.client('sns')
    lambda_subscriptions = get_sns_subscriptions(app_name=app_name, env=env, region=region)
    for subscription_arn in lambda_subscriptions:
        sns_client.unsubscribe(SubscriptionArn=subscription_arn)
    LOG.debug('Lambda SNS event deleted')
    return True

Destroy all Lambda SNS subscriptions.

Args:
app_name (str): name of the lambda function
env (str): Environment/Account for lambda function
region (str): AWS region of the lambda function

Returns:
boolean: True if subscription destroyed successfully


def append(self, moment_or_operation_tree: Union[(ops.Moment, ops.OP_TREE)], strategy: InsertStrategy=InsertStrategy.EARLIEST):
    self.insert(len(self._moments), moment_or_operation_tree, strategy)

Appends operations onto the end of the circuit.

Moments within the operation tree are appended intact.

Args:
moment_or_operation_tree: The moment or operation tree to append.
strategy: How to pick/create the moment to put operations into.


def subscribe_registration_ids_to_topic(self, registration_ids, topic_name):

        url = 'https:
        payload = {
            'to': '/topics/' + topic_name,
            'registration_tokens': registration_ids,
        }
        response = self.requests_session.post(url, json=payload)
        if response.status_code == 200:
            return True
        elif response.status_code == 400:
            error = response.json()
            raise InvalidDataError(error['error'])
        else:
            raise FCMError()

Subscribes a list of registration ids to a topic

Args:
registration_ids (list): ids to be subscribed
topic_name (str): name of topic

Returns:
True: if operation succeeded

Raises:
InvalidDataError: data sent to server was incorrectly formatted
FCMError: an error occured on the server


def get_user_display_name(self, userid):
    user_info = self.slack_client.api_call('users.info', user=userid)
    if user_info.get('ok'):
        user = user_info.get('user')
        if user.get('profile'):
            return user.get('profile').get('display_name')
        else:
            return user.get('name')
    else:
        return userid

Given a Slack userid, grabs user display_name from api.

Args:
userid (string): the user id of the user being queried
Returns:
dict: a dictionary of the api response


def __rmul__(self, left: torch.Tensor) -> Rigid:
    return self.__mul__(left)

Reverse pointwise multiplication of the transformation with a tensor.

Args:
left:
The left multiplicand
Returns:
The product


def __init__(self, column_metadata):

        self.column_metadata = column_metadata
        self.col_name = column_metadata['name']

        self.check_data_type()

Initialize preprocessor.

Args:
column_metadata(dict): Meta information of the column.
transformer_type(str): Type of data the transformer is able to transform.


def list(self, pattern='*'):

    if self._descriptors is None:
      self._descriptors = self._client.list_metric_descriptors(
          filter_string=self._filter_string, type_prefix=self._type_prefix)
    return [metric for metric in self._descriptors
            if fnmatch.fnmatch(metric.type, pattern)]

Returns a list of metric descriptors that match the filters.

Args:
pattern: An optional pattern to further filter the descriptors. This can
include Unix shell-style wildcards. E.g. ``"compute*"``,
``"*cpu/load_??m"``.

Returns:
A list of MetricDescriptor objects that match the filters.


def tf_loss(self, states, internals, reward, update, reference=None):
    prediction = self.predict(states=states, internals=internals, update=update)
    return tf.nn.l2_loss(t=(prediction - reward))

Creates the TensorFlow operations for calculating the L2 loss between predicted
state values and actual rewards.

Args:
states: Dict of state tensors.
internals: List of prior internal state tensors.
reward: Reward tensor.
update: Boolean tensor indicating whether this call happens during an update.
reference: Optional reference tensor(s), in case of a comparative loss.

Returns:
Loss tensor


def from_vision_qformer_text_configs(cls, vision_config: InstructBlipVideoVisionConfig, qformer_config: InstructBlipVideoQFormerConfig, text_config: PretrainedConfig, **kwargs):
    return cls(vision_config=vision_config.to_dict(), qformer_config=qformer_config.to_dict(), text_config=text_config.to_dict(), **kwargs)

Instantiate a [`InstructBlipVideoConfig`] (or a derived class) from a InstructBlipVideo vision model, Q-Former and
language model configurations.

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


class RemoteMonitor(Callback):

    def __init__(self, root='http:
        super().__init__()
        self.root = root
        self.path = path
        self.field = field
        self.headers = headers
        self.send_as_json = send_as_json

    def on_epoch_end(self, epoch, logs=None):
        if requests is None:
            raise ImportError('RemoteMonitor requires the `requests` library.')
        logs = logs or {}
        send = {}
        send['epoch'] = epoch
        for k, v in logs.items():
            if isinstance(v, (np.ndarray, np.generic)):
                send[k] = v.item()
            else:
                send[k] = v
        try:
            if self.send_as_json:
                requests.post(self.root + self.path, json=send, headers=self.headers)
            else:
                requests.post(self.root + self.path, {self.field: json.dumps(send)}, headers=self.headers)
        except requests.exceptions.RequestException:
            warnings.warn(f'Could not reach RemoteMonitor root server at {self.root}', stacklevel=2)

Callback used to stream events to a server.

Requires the `requests` library.
Events are sent to `root + '/publish/epoch/end/'` by default. Calls are
HTTP POST, with a `data` argument which is a
JSON-encoded dictionary of event data.
If `send_as_json=True`, the content type of the request will be
`"application/json"`.
Otherwise the serialized JSON will be sent within a form.

Args:
root: String; root url of the target server.
path: String; path relative to `root` to which the events will be sent.
field: String; JSON field under which the data will be stored.
The field is used only if the payload is sent within a form
(i.e. when `send_as_json=False`).
headers: Dictionary; optional custom HTTP headers.
send_as_json: Boolean; whether the request should be
sent as `"application/json"`.


def delete_channel(self, channel_name, project_name, dataset_name):
    return self.resources.delete_channel(channel_name, project_name, dataset_name)

Deletes a channel given its name, name of its project
, and name of its dataset.

Arguments:
channel_name (str): Channel name
project_name (str): Project name
dataset_name (str): Dataset name

Returns:
bool: True if channel deleted, False if not


def temporal_segmentation(segments, min_time):

    final_segments = []
    for segment in segments:
        final_segments.append([])
        for point in segment:
            if point.dt > min_time:
                final_segments.append([])
            final_segments[-1].append(point)

    return final_segments

Segments based on time distant points

Args:
segments (:obj:`list` of :obj:`list` of :obj:`Point`): segment points
min_time (int): minimum required time for segmentation


def VShadowPathSpecGetStoreIndex(path_spec):
    store_index = getattr(path_spec, 'store_index', None)
    if (store_index is None):
        location = getattr(path_spec, 'location', None)
        if ((location is None) or (not location.startswith('/vss'))):
            return None
        store_index = None
        try:
            store_index = (int(location[4:], 10) - 1)
        except (TypeError, ValueError):
            pass
        if ((store_index is None) or (store_index < 0)):
            return None
    return store_index

Retrieves the store index from the path specification.

Args:
path_spec (PathSpec): path specification.

Returns:
int: store index or None if not available.


def display_help(cmd: str) -> None:
    cmd_parts = cmd.split(' ')
    if len(cmd_parts) == 2:
        if cmd_parts[1] in command_info:
            print(f'{cmd_parts[1]}  =>  {command_info[cmd_parts[1]]}')
        else:
            list_key_values(command_info)
    elif len(cmd_parts) == 1:
        list_key_values(command_info)
    else:
        print('Incorrect usage. Run .help or .help [cmd] for usage info.')

Display help information for commands.

Args:
cmd (str): The command string.


def create(self, name, action, seqno):
    return self.configure(('route-map %s %s %s' % (name, action, seqno)))

Creates a new routemap on the node

Note:
This method will attempt to create the routemap regardless
if the routemap exists or not.  If the routemap already exists
then this method will still return True.

Args:
name (string): The full name of the routemap.
action (string): The action to take for this routemap clause.
seqno (integer): The sequence number for the routemap clause.

Returns:
True if the routemap could be created otherwise False (see Note)


def migratable_vc_domains(self):
    if (not self.__migratable_vc_domains):
        self.__migratable_vc_domains = MigratableVcDomains(self.__connection)
    return self.__migratable_vc_domains

Gets the VC Migration Manager API client.

Returns:
MigratableVcDomains:


def get_child(self, name: YangIdentifier,
                  ns: YangIdentifier = None) -> Optional[SchemaNode]:

        ns = ns if ns else self.ns
        todo = []
        for child in self.children:
            if child.name is None:
                todo.append(child)
            elif child.name == name and child.ns == ns:
                return child
        for c in todo:
            grandchild = c.get_child(name, ns)
            if grandchild is not None:
                return grandchild

Return receiver's schema child.

Args:
name: Child's name.
ns: Child's namespace (= `self.ns` if absent).


def generate_markdown_doc(app_name, spec):

    sections = [
        HEADER.format(app_name=app_name),
        SOURCES_HEADER.format(app_name=app_name)
    ]

    sorted_labels = sorted(list(spec.sources))
    for label in sorted_labels:
        sections.append(
            _generate_source_section(label, spec.sources[label], app_name)
        )

    sections.append(CONFIG_HEADER.format(app_name=app_name))
    table_rows, item_sections = _generate_item_sections(
        _sorted_dict_values(spec.items),
        app_name
    )

    headers = {
        'name': 'Name',
        'type': 'Type',
        'default': 'Default',
        'description': 'Description'
    }

    sections.append(
        build_markdown_table(
            headers,
            table_rows,
            ['name', 'type', 'default', 'description'],
        )
    )
    for item_section in item_sections:
        sections.append(item_section)

    return '\n'.join([section for section in sections])

Generate Markdown Documentation for the given spec/app name.

Args:
app_name (str): The name of the application.
spec (YapconfSpec): A yapconf specification with sources loaded.

Returns (str):
A valid, markdown string representation of the documentation for
the given specification.


def adjust_column_width(worksheet):

    dims = {}
    padding = 1
    for row in worksheet.rows:
        for cell in row:
            if not cell.value:
                continue
            dims[cell.column] = max(
                dims.get(cell.column, 0),
                len(str(cell.value))
            )
    for col, value in list(dims.items()):
        worksheet.column_dimensions[col].width = value + padding

Adjust column width in worksheet.

Args:
worksheet: worksheet to be adjusted


def extract_tree_without(self, labels, suppress_unifurcations=True):

        return self.extract_tree(labels, True, suppress_unifurcations)

Extract a copy of this ``Tree`` without the leaves labeled by the strings in ``labels``

Args:
``labels`` (``set``): Set of leaf labels to exclude

``suppress_unifurcations`` (``bool``): ``True`` to suppress unifurcations, otherwise ``False``

Returns:
``Tree``: Copy of this ``Tree``, exluding the leaves labeled by the strings in ``labels``


def _benchmarkFetchPrebuilt(self, name, target, size, iters):
    times = []
    with ops.Graph().as_default():
        v = variables.Variable(random_ops.random_normal([size]))
        with session.Session(target) as sess:
            sess.run(v.initializer)
            runner = sess.make_callable(v)
            runner()
            for _ in range(iters):
                start_time = time.time()
                runner()
                end_time = time.time()
                times.append(end_time - start_time)
    print('%s %d %f' % (name, size, np.median(times)))
    self.report_benchmark(iters=1, wall_time=np.median(times), name=name)

Runs a microbenchmark to measure the cost of fetching a tensor.

Reports the median cost of fetching a tensor of `size` * `sizeof(float)`
bytes.

Args:
name: A human-readable name for logging the output.
target: The session target to use for the benchmark.
size: The number of floating-point numbers to be fetched.
iters: The number of iterations to perform.


def AddCampaign(self, client_customer_id, campaign_name, ad_channel_type, budget):
    self.client.SetClientCustomerId(client_customer_id)
    campaign_service = self.client.GetService('CampaignService')
    budget_id = self.AddBudget(client_customer_id, budget)
    operations = [{'operator': 'ADD', 'operand': {'name': campaign_name, 'status': 'PAUSED', 'biddingStrategyConfiguration': {'biddingStrategyType': 'MANUAL_CPC', 'biddingScheme': {'xsi_type': 'ManualCpcBiddingScheme', 'enhancedCpcEnabled': 'false'}}, 'budget': {'budgetId': budget_id}, 'advertisingChannelType': ad_channel_type}}]
    campaign_service.mutate(operations)

Add a Campaign to the client account.

Args:
client_customer_id: str Client Customer Id to use when creating Campaign.
campaign_name: str Name of the campaign to be added.
ad_channel_type: str Primary serving target the campaign's ads.
budget: str a budget amount (in micros) to use.


def _fix_next_url(next_url):
    next_url = str(next_url)
    parsed_url = urllib.parse.urlparse(next_url)
    if ((not parsed_url.scheme) or (not parsed_url.netloc) or (not parsed_url.path)):
        raise ValueError("'next_url' must be a valid API endpoint URL, minimally containing a scheme, netloc and path.")
    if parsed_url.query:
        query_list = parsed_url.query.split('&')
        if ('max=null' in query_list):
            query_list.remove('max=null')
            warnings.warn('`max=null` still present in next-URL returned from Webex Teams', RuntimeWarning)
        new_query = '&'.join(query_list)
        parsed_url = list(parsed_url)
        parsed_url[4] = new_query
    return urllib.parse.urlunparse(parsed_url)

Remove max=null parameter from URL.

Patch for Webex Teams Defect: 'next' URL returned in the Link headers of
the responses contain an errant 'max=null' parameter, which  causes the
next request (to this URL) to fail if the URL is requested as-is.

This patch parses the next_url to remove the max=null parameter.

Args:
next_url(basestring): The 'next' URL to be parsed and cleaned.

Returns:
basestring: The clean URL to be used for the 'next' request.

Raises:
AssertionError: If the parameter types are incorrect.
ValueError: If 'next_url' does not contain a valid API endpoint URL
(scheme, netloc and path).


def newPacker(mode=PackingMode.Offline, bin_algo=PackingBin.BBF, pack_algo=MaxRectsBssf, sort_algo=SORT_AREA, rotation=True):
    packer_class = None
    if (mode == PackingMode.Online):
        sort_algo = None
        if (bin_algo == PackingBin.BNF):
            packer_class = PackerOnlineBNF
        elif (bin_algo == PackingBin.BFF):
            packer_class = PackerOnlineBFF
        elif (bin_algo == PackingBin.BBF):
            packer_class = PackerOnlineBBF
        else:
            raise AttributeError('Unsupported bin selection heuristic')
    elif (mode == PackingMode.Offline):
        if (bin_algo == PackingBin.BNF):
            packer_class = PackerBNF
        elif (bin_algo == PackingBin.BFF):
            packer_class = PackerBFF
        elif (bin_algo == PackingBin.BBF):
            packer_class = PackerBBF
        elif (bin_algo == PackingBin.Global):
            packer_class = PackerGlobal
            sort_algo = None
        else:
            raise AttributeError('Unsupported bin selection heuristic')
    else:
        raise AttributeError('Unknown packing mode.')
    if sort_algo:
        return packer_class(pack_algo=pack_algo, sort_algo=sort_algo, rotation=rotation)
    else:
        return packer_class(pack_algo=pack_algo, rotation=rotation)

Packer factory helper function

Arguments:
mode (PackingMode): Packing mode
Online: Rectangles are packed as soon are they are added
Offline: Rectangles aren't packed untils pack() is called
bin_algo (PackingBin): Bin selection heuristic
pack_algo (PackingAlgorithm): Algorithm used
rotation (boolean): Enable or disable rectangle rotation.

Returns:
Packer: Initialized packer instance.


def _all_saveable_objects(scope=None):
    return ops.get_collection(ops.GraphKeys.GLOBAL_VARIABLES, scope) + ops.get_collection(ops.GraphKeys.SAVEABLE_OBJECTS, scope)

Returns all variables and `SaveableObject`s that must be checkpointed.

Args:
scope: (Optional.) A string. If supplied, the resulting list is filtered to
include only items whose `name` attribute matches `scope` using
`re.match`. Items without a `name` attribute are never returned if a scope
is supplied. The choice of `re.match` means that a `scope` without special
tokens filters by prefix.

Returns:
A list of `Variable` and `SaveableObject` to be checkpointed


def save(self, path):

        for relative_path_and_filename, content in self.files.items():
            full_path_and_filename = os.path.join(path, relative_path_and_filename)
            full_path = os.path.dirname(full_path_and_filename)

            if not os.path.isdir(full_path):
                os.makedirs(full_path)

            with open(full_path_and_filename, 'wb') as handle:
                handle.write(b64decode(content))

Saving stored files at a given path (relative paths are added).

Args:
path (str): root path where to save the files.


def _AddsAnalysisProcessStatusTableRow(self, process_status, table_view):

    used_memory = self._FormatSizeInUnitsOf1024(process_status.used_memory)

    events = ''
    if (process_status.number_of_consumed_events is not None and
        process_status.number_of_consumed_events_delta is not None):
      events = '{0:d} ({1:d})'.format(
          process_status.number_of_consumed_events,
          process_status.number_of_consumed_events_delta)

    event_tags = ''
    if (process_status.number_of_produced_event_tags is not None and
        process_status.number_of_produced_event_tags_delta is not None):
      event_tags = '{0:d} ({1:d})'.format(
          process_status.number_of_produced_event_tags,
          process_status.number_of_produced_event_tags_delta)

    reports = ''
    if (process_status.number_of_produced_reports is not None and
        process_status.number_of_produced_reports_delta is not None):
      reports = '{0:d} ({1:d})'.format(
          process_status.number_of_produced_reports,
          process_status.number_of_produced_reports_delta)

    table_view.AddRow([
        process_status.identifier, process_status.pid, process_status.status,
        used_memory, events, event_tags, reports])

Adds an analysis process status table row.

Args:
process_status (ProcessStatus): processing status.
table_view (CLITabularTableView): table view.


def get_dict_with_chain(self, chain, only_keys=None, chain_keys=None, exclude_attributes=None, df_format=False):
    if (not only_keys):
        keys = list(self.__dict__.keys())
    else:
        keys = ssbio.utils.force_list(only_keys)
    if exclude_attributes:
        exclude_attributes = ssbio.utils.force_list(exclude_attributes)
        for x in exclude_attributes:
            if (x in keys):
                keys.remove(x)
    else:
        exclude_attributes = []
    exclude_attributes.extend(['mapped_chains', 'chains'])
    final_dict = {k: v for (k, v) in Object.get_dict(self, only_attributes=keys, exclude_attributes=exclude_attributes, df_format=df_format).items()}
    chain_prop = self.chains.get_by_id(chain)
    if (not chain_keys):
        chain_keys = [x for x in chain_prop.get_dict().keys() if (x not in final_dict)]
    chain_dict = chain_prop.get_dict(only_attributes=chain_keys, df_format=df_format)
    final_dict.update(chain_dict)
    return final_dict

get_dict method which incorporates attributes found in a specific chain. Does not overwrite any attributes
in the original StructProp.

Args:
chain:
only_keys:
chain_keys:
exclude_attributes:
df_format:

Returns:
dict: attributes of StructProp + the chain specified


def set_join_rule(self, room_id, join_rule):
    content = {'join_rule': join_rule}
    return self.send_state_event(room_id, 'm.room.join_rules', content)

Set the rule for users wishing to join the room.

Args:
room_id(str): The room to set the rules for.
join_rule(str): The chosen rule. One of: ["public", "knock",
"invite", "private"]


def __init__(self, resolver_context):

    super(TSKFileSystem, self).__init__(resolver_context)
    self._file_object = None
    self._tsk_file_system = None
    self._tsk_fs_type = None

Initializes a file system.

Args:
resolver_context (Context): resolver context.


def __init__(self,
               upper=False,
               validate_args=False,
               name="fill_triangular"):

    self._upper = upper
    super(FillTriangular, self).__init__(
        forward_min_event_ndims=1,
        inverse_min_event_ndims=2,
        validate_args=validate_args,
        name=name)

Instantiates the `FillTriangular` bijector.

Args:
upper: Python `bool` representing whether output matrix should be upper
triangular (`True`) or lower triangular (`False`, default).
validate_args: Python `bool` indicating whether arguments should be
checked for correctness.
name: Python `str` name given to ops managed by this object.


def leave_module(self, node):
    for triple_quote in self._tokenized_triple_quotes.values():
        self._check_triple_quotes(triple_quote)
    self._tokenized_triple_quotes = {}

Leave module and check remaining triple quotes.

Args:
node: the module node we are leaving.


def _get_batch_data(self, batch_size, num_objects, num_features):
    all_inputs = []
    all_labels = []
    for _ in six.moves.range(batch_size):
        (inputs, labels) = self._get_single_set(num_objects, num_features)
        all_inputs += [inputs]
        all_labels += [labels]
    input_data = np.concatenate(all_inputs, axis=0)
    label_data = np.concatenate(all_labels, axis=0)
    return (input_data, label_data)

Assembles a batch of input tensors and output labels.

Args:
batch_size: int. number of sequence batches.
num_objects: int. number of objects in the sequence.
num_features: int. feature size of each object.

Returns:
1. np.ndarray (`batch_size`, `num_objects`,
(`num_features` + 3 * `num_objects`)).
2. np.ndarray (`batch_size`). Output object reference label.


def repl(optimize=True, persist=True):
    print('Extra commands for the REPL:')
    print('.code    - print code')
    print('.raw     - print raw code')
    print('.quit    - exit immediately')
    print('.reset   - reset machine (IP and stacks)')
    print('.restart - create a clean, new machine')
    print('.clear   - same as .restart')
    print('.stack   - print data stack')
    print('')
    machine = Machine([])

    def match(s, *args):
        return any(map((lambda arg: (s.strip() == arg)), args))
    while True:
        try:
            source = raw_input('> ').strip()
            if ((source[0] == '.') and (len(source) > 1)):
                if match(source, '.quit'):
                    return
                elif match(source, '.code'):
                    print_code(machine)
                elif match(source, '.raw'):
                    print(machine.code)
                elif match(source, '.reset'):
                    machine.reset()
                elif match(source, '.restart', '.clear'):
                    machine = Machine([])
                elif match(source, '.stack'):
                    print(machine.stack)
                else:
                    raise ParseError(('Unknown command: %s' % source))
                continue
            code = compile(parse(source), silent=False, optimize=optimize)
            if (not persist):
                machine.reset()
            machine.code += code
            machine.run()
        except EOFError:
            return
        except KeyboardInterrupt:
            return
        except ParseError as e:
            print(('Parse error: %s' % e))
        except MachineError as e:
            print(('Machine error: %s' % e))
        except CompileError as e:
            print(('Compile error: %s' % e))

Starts a simple REPL for this machine.

Args:
optimize: Controls whether to run inputted code through the
optimizer.

persist: If True, the machine is not deleted after each line.


def normalize_email(self, email_address):
    normalized_email = email_address.lower()
    email_parts = normalized_email.split('@')
    if len(email_parts) < 2:
        return email_address
    is_gmail = re.match('^(gmail|googlemail)\\.com$', email_parts[1])
    if len(email_parts) > 1 and is_gmail:
        email_parts[0] = email_parts[0].replace('.', '')
        normalized_email = '@'.join(email_parts)
    return normalized_email

Returns the result of normalizing and hashing an email address.

For this use case, Google Ads requires removal of any '.' characters
preceding "gmail.com" or "googlemail.com"

Args:
email_address: An email address to normalize.

Returns:
A normalized (lowercase, removed whitespace).


def generate_new_docstring_for_signature(lines, sig_start_line, sig_end_line, docstring_line, arg_indent='    ', custom_args_dict={}):
    missing_docstring_args = []
    fill_docstring_args = []
    signature_content = lines[sig_start_line:sig_end_line]
    signature_content = [line.split('
    signature_content = ''.join(signature_content)
    signature_content = ''.join(signature_content.split(')')[:-1])
    args_in_signature = re.findall('[,(]\\s*(\\w+)\\s*(?=:|=|,|\\))', signature_content)
    if 'self' in args_in_signature:
        args_in_signature.remove('self')
    args_docstring_dict = {}
    remaining_docstring = ''
    docstring_end = sig_end_line - 1
    if docstring_line is not None:
        docstring_end = docstring_line
        if not lines[docstring_line].count('' not in lines[docstring_end]:
                docstring_end += 1
        docstring_content = lines[docstring_line:docstring_end + 1]
        parsed_docstring, remaining_docstring = parse_docstring('\n'.join(docstring_content))
        args_docstring_dict.update(parsed_docstring)
    for arg in args_in_signature:
        if arg not in args_docstring_dict and arg not in source_args_doc([ModelArgs, ImageProcessorArgs]) and (arg not in custom_args_dict):
            missing_docstring_args.append(arg)
            args_docstring_dict[arg] = {'type': '<fill_type>', 'optional': False, 'shape': None, 'description': f'\n{arg_indent}    <fill_docstring>', 'default': None, 'additional_info': None}
    new_docstring = ''
    if len(args_docstring_dict) > 0 or remaining_docstring:
        new_docstring += 'r'):
                custom_arg_description = '\n'.join(custom_arg_description.split('\n')[:-1])
            new_docstring += f'{arg} ({args_docstring_dict[arg]['type']}{additional_info}):{custom_arg_description}\n'
        close_docstring = True
        if remaining_docstring:
            if remaining_docstring.endswith(''
        new_docstring = set_min_indent(new_docstring, 8)
    return (new_docstring, sig_end_line, docstring_end, missing_docstring_args, fill_docstring_args)

Generalized docstring generator for a function or class signature.
Args:
lines: List of lines from the file.
sig_start_line: Line index where the signature starts.
sig_end_line: Line index where the signature ends.
docstring_line: Line index where the docstring starts (or None if not present).
arg_indent: Indentation for missing argument doc entries.
Returns:
new_docstring, sig_end_line, docstring_end (last docstring line index)


def _get_step_for_v2():
    step = _summary_ops_v2.get_step()
    if step is not None:
        return step
    return _training_util.get_global_step()

Get step for v2 summary invocation in v1.

In order to invoke v2 op in `tf.compat.v1.summary`, global step needs to be
set for the v2 summary writer.

Returns:
The step set by `tf.summary.experimental.set_step` or
`tf.compat.v1.train.create_global_step`, or None is no step has been
set.


def take_shas_of_all_files(G, settings):
    global ERROR_FN
    sprint = settings['sprint']
    error = settings['error']
    ERROR_FN = error
    sha_dict = {}
    all_files = []
    for target in G.nodes(data=True):
        sprint("About to take shas of files in target '{}'".format(target[0]), level='verbose')
        if ('dependencies' in target[1]):
            sprint('It has dependencies', level='verbose')
            deplist = []
            for dep in target[1]['dependencies']:
                glist = glob.glob(dep)
                if glist:
                    for oneglob in glist:
                        deplist.append(oneglob)
                else:
                    deplist.append(dep)
            target[1]['dependencies'] = list(deplist)
            for dep in target[1]['dependencies']:
                sprint('  - {}'.format(dep), level='verbose')
                all_files.append(dep)
        if ('output' in target[1]):
            sprint('It has outputs', level='verbose')
            for out in acts.get_all_outputs(target[1]):
                sprint('  - {}'.format(out), level='verbose')
                all_files.append(out)
    if len(all_files):
        sha_dict['files'] = {}
        extant_files = []
        for item in all_files:
            if ((item not in extant_files) and os.path.isfile(item)):
                extant_files.append(item)
        pool = Pool()
        results = pool.map(get_sha, extant_files)
        pool.close()
        pool.join()
        for (fn, sha) in zip(extant_files, results):
            sha_dict['files'][fn] = {'sha': sha}
        return sha_dict
    sprint('No dependencies', level='verbose')

Takes sha1 hash of all dependencies and outputs of all targets

Args:
The graph we are going to build
The settings dictionary

Returns:
A dictionary where the keys are the filenames and the
value is the sha1 hash


def __init__(self, downloader, error_handler):

        self.downloader = downloader
        self.error_handler = error_handler

        self._work_queue = Queue.PriorityQueue()

        self._workers = []
        self._maximize_workers()

Constructor.

Args:
downloader:
Downloads images.
error_handler:
Handles errors that occur when trying to download resources.


def _get_val_str(obj, path_list=None, reverse=False):

    val_list = _get_val_list(obj, path_list or [], reverse)
    return "<not found>" if obj is None else " / ".join(map(str, val_list))

Extract values from nested objects by attribute names and concatenate their
string representations.

Args:
obj: object
Any type of object

path_list: list
Attribute names

reverse: bool
Reverse the list of values before concatenation.

Returns:
str: Concatenated extracted values.


def __fetch_route53_zone_tags(self, zone_id):

        route53 = self.session.client('route53')

        try:
            return {
                tag['Key']: tag['Value'] for tag in
                route53.list_tags_for_resource(
                    ResourceType='hostedzone',
                    ResourceId=zone_id.split('/')[-1]
                )['ResourceTagSet']['Tags']
            }
        finally:
            del route53

Return a dict with the tags for the zone

Args:
zone_id (`str`): ID of the hosted zone

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


def pivot_bin(self, pivot_columns, value_column, bins=None, **vargs):
    pivot_columns = _as_labels(pivot_columns)
    selected = self.select((pivot_columns + [value_column]))
    grouped = selected.groups(pivot_columns, collect=(lambda x: x))
    if (bins is not None):
        vargs['bins'] = bins
    (_, rbins) = np.histogram(self[value_column], **vargs)
    vargs['bins'] = rbins
    binned = type(self)().with_column('bin', rbins)
    for group in grouped.rows:
        col_label = '-'.join(map(str, group[0:(- 1)]))
        col_vals = group[(- 1)]
        (counts, _) = np.histogram(col_vals, **vargs)
        binned[col_label] = np.append(counts, 0)
    return binned

Form a table with columns formed by the unique tuples in pivot_columns
containing counts per bin of the values associated with each tuple in the value_column.

By default, bins are chosen to contain all values in the value_column. The
following named arguments from numpy.histogram can be applied to
specialize bin widths:

Args:
``bins`` (int or sequence of scalars): If bins is an int,
it defines the number of equal-width bins in the given range
(10, by default). If bins is a sequence, it defines the bin
edges, including the rightmost edge, allowing for non-uniform
bin widths.

``range`` ((float, float)): The lower and upper range of
the bins. If not provided, range contains all values in the
table. Values outside the range are ignored.

``normed`` (bool): If False, the result will contain the number of
samples in each bin. If True, the result is normalized such that
the integral over the range is 1.


def convert_snapshot(self, shift, instruction):
    command_dict = {'name': 'snapshot', 't0': (shift + instruction.start_time), 'label': instruction.name, 'type': instruction.type}
    return self._qobj_model(**command_dict)

Return converted `Snapshot`.

Args:
shift(int): Offset time.
instruction (Snapshot): snapshot instruction.
Returns:
dict: Dictionary of required parameters.


def MessageToJson(message, including_default_value_fields=False, preserving_proto_field_name=False):
    printer = _Printer(including_default_value_fields, preserving_proto_field_name)
    return printer.ToJsonString(message)

Converts protobuf message to JSON format.

Args:
message: The protocol buffers message instance to serialize.
including_default_value_fields: If True, singular primitive fields,
repeated fields, and map fields will always be serialized.  If
False, only serialize non-empty fields.  Singular message fields
and oneof fields are not affected by this option.
preserving_proto_field_name: If True, use the original proto field
names as defined in the .proto file. If False, convert the field
names to lowerCamelCase.

Returns:
A string containing the JSON formatted protocol buffer message.


def get_string(self, direct=True, vasp4_compatible=False, significant_figures=6):
    latt = self.structure.lattice
    if (np.linalg.det(latt.matrix) < 0):
        latt = Lattice((- latt.matrix))
    format_str = '{{:.{0}f}}'.format(significant_figures)
    lines = [self.comment, '1.0']
    for v in latt.matrix:
        lines.append(' '.join([format_str.format(c) for c in v]))
    if (self.true_names and (not vasp4_compatible)):
        lines.append(' '.join(self.site_symbols))
    lines.append(' '.join([str(x) for x in self.natoms]))
    if self.selective_dynamics:
        lines.append('Selective dynamics')
    lines.append(('direct' if direct else 'cartesian'))
    selective_dynamics = self.selective_dynamics
    for (i, site) in enumerate(self.structure):
        coords = (site.frac_coords if direct else site.coords)
        line = ' '.join([format_str.format(c) for c in coords])
        if (selective_dynamics is not None):
            sd = [('T' if j else 'F') for j in selective_dynamics[i]]
            line += (' %s %s %s' % (sd[0], sd[1], sd[2]))
        line += (' ' + site.species_string)
        lines.append(line)
    if self.velocities:
        try:
            lines.append('')
            for v in self.velocities:
                lines.append(' '.join([format_str.format(i) for i in v]))
        except:
            warnings.warn('Velocities are missing or corrupted.')
    if self.predictor_corrector:
        lines.append('')
        if self.predictor_corrector_preamble:
            lines.append(self.predictor_corrector_preamble)
            pred = np.array(self.predictor_corrector)
            for col in range(3):
                for z in pred[(:, col)]:
                    lines.append(' '.join([format_str.format(i) for i in z]))
        else:
            warnings.warn('Preamble information missing or corrupt. Writing Poscar with no predictor corrector data.')
    return ('\n'.join(lines) + '\n')

Returns a string to be written as a POSCAR file. By default, site
symbols are written, which means compatibility is for vasp >= 5.

Args:
direct (bool): Whether coordinates are output in direct or
cartesian. Defaults to True.
vasp4_compatible (bool): Set to True to omit site symbols on 6th
line to maintain backward vasp 4.x compatibility. Defaults
to False.
significant_figures (int): No. of significant figures to
output all quantities. Defaults to 6. Note that positions are
output in fixed point, while velocities are output in
scientific format.

Returns:
String representation of POSCAR.


def __set_no_protein(self, hgvs_string):

        no_protein_list = ['0', '0?']
        if hgvs_string in no_protein_list:
            self.is_no_protein = True
            self.is_non_silent = True
        else:
            self.is_no_protein = False

Set a flag for no protein expected. ("p.0" or "p.0?")

Args:
hgvs_string (str): hgvs syntax with "p." removed


def set_snippet_client_verbose_logging(self, verbose):
    self.log.info('Sets verbose logging to %s.', verbose)
    self.verbose_logging = verbose

Switches verbose logging. True for logging full RPC responses.

By default it will write full messages returned from RPCs. Turning off the
verbose logging will result in writing no more than
_MAX_RPC_RESP_LOGGING_LENGTH characters per RPC returned string.

_MAX_RPC_RESP_LOGGING_LENGTH will be set to 1024 by default. The length
contains the full RPC response in JSON format, not just the RPC result
field.

Args:
verbose: bool, if True, turns on verbose logging, otherwise turns off.


def get_extra(cls, name=None):

    if not name:
      return cls._extra_config
    return cls._extra_config.get(name, None)

Gets extra configuration parameters.

These parameters should be loaded through load_extra or load_extra_data.

Args:
name: str, the name of the configuration data to load.

Returns:
A dictionary containing the requested configuration data. None if
data was never loaded under that name.


def from_sites(cls, sites, charge=0, spin_multiplicity=None, validate_proximity=False):
    props = collections.defaultdict(list)
    for site in sites:
        for (k, v) in site.properties.items():
            props[k].append(v)
    return cls([site.species for site in sites], [site.coords for site in sites], charge=charge, spin_multiplicity=spin_multiplicity, validate_proximity=validate_proximity, site_properties=props)

Convenience constructor to make a Molecule from a list of sites.

Args:
sites ([Site]): Sequence of Sites.
charge (int): Charge of molecule. Defaults to 0.
spin_multiplicity (int): Spin multicipity. Defaults to None,
in which it is determined automatically.
validate_proximity (bool): Whether to check that atoms are too
close.


def subdivide(self):
    (left_nodes, right_nodes) = _curve_helpers.subdivide_nodes(self.nodes)
    midpoint = (0.5 * (self.start + self.end))
    left = SubdividedCurve(left_nodes, self.original_nodes, start=self.start, end=midpoint)
    right = SubdividedCurve(right_nodes, self.original_nodes, start=midpoint, end=self.end)
    return (left, right)

Split the curve into a left and right half.

See :meth:`.Curve.subdivide` for more information.

Returns:
Tuple[SubdividedCurve, SubdividedCurve]: The left and right
sub-curves.


def report_latency(self, now, latency_ms, num_mutations):
    self._commit_time_per_entity_ms.add(now, latency_ms / num_mutations)

Report the latency of a Datastore RPC.

Args:
now: double, completion time of the RPC as seconds since the epoch.
latency_ms: double, the observed latency in milliseconds for this RPC.
num_mutations: int, number of mutations contained in the RPC.


def index_by_id(cls, target_id, resources):
    for index in range(len(resources)):
        if (cls.id_by_index(index, resources) == target_id):
            return index
    raise AssertionError

Helper method to fetch the index of a resource by its id or address

Args:
resources (list of objects): The resources to be paginated
target_id (string): The address or header_signature of the resource

Returns:
integer: The index of the target resource

Raises:
AssertionError: Raised if the target is not found


def BuildService(self, cls):

    def _WrapCallMethod(srvc, method_descriptor, rpc_controller, request, callback):
        return self._CallMethod(srvc, method_descriptor, rpc_controller, request, callback)
    self.cls = cls
    cls.CallMethod = _WrapCallMethod
    cls.GetDescriptor = staticmethod((lambda : self.descriptor))
    cls.GetDescriptor.__doc__ = 'Returns the service descriptor.'
    cls.GetRequestClass = self._GetRequestClass
    cls.GetResponseClass = self._GetResponseClass
    for method in self.descriptor.methods:
        setattr(cls, method.name, self._GenerateNonImplementedMethod(method))

Constructs the service class.

Args:
cls: The class that will be constructed.


def get_num_bytes(self, batch: Sequence[pandas.DataFrame]) -> int:
    return sum((df.memory_usage(deep=True).sum() for df in batch))

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


def get_metrics_namespace(self) -> str:
    return 'BeamML_PyTorch'

Returns:
A namespace for metrics collected by the RunInference transform.


def parse_sampleinfo(data: dict) -> dict:

    genome_build = data['human_genome_build']
    genome_build_str = f"{genome_build['source']}{genome_build['version']}"
    if 'svdb' in data['program']:
        svdb_outpath = (f"{data['program']['svdb']['path']}")
    else:
        svdb_outpath = ''
    outdata = {
        'date': data['analysis_date'],
        'family': data['family'],
        'genome_build': genome_build_str,
        'rank_model_version': data['program']['genmod']['rank_model']['version'],
        'is_finished': True if data['analysisrunstatus'] == 'finished' else False,
        'pedigree_path': data['pedigree_minimal'],
        'peddy': {
            'ped': (data['program']['peddy']['peddy']['path'] if
                    'peddy' in data['program'] else None),
            'ped_check': (data['program']['peddy']['ped_check']['path'] if
                          'peddy' in data['program'] else None),
            'sex_check': (data['program']['peddy']['sex_check']['path'] if
                          'peddy' in data['program'] else None),
        },
        'qcmetrics_path': data['program']['qccollect']['path'],
        'samples': [],
        'snv': {
            'bcf': data['most_complete_bcf']['path'],
            'clinical_vcf': data['vcf_binary_file']['clinical']['path'],
            'gbcf': data['gbcf_file']['path'],
            'research_vcf': data['vcf_binary_file']['research']['path'],
        },
        'svdb_outpath': svdb_outpath,
        'sv': {
            'bcf': data.get('sv_bcf_file', {}).get('path'),
            'clinical_vcf': (data['sv_vcf_binary_file']['clinical']['path'] if
                             'sv_vcf_binary_file' in data else None),
            'merged': svdb_outpath,
            'research_vcf': (data['sv_vcf_binary_file']['research']['path'] if
                             'sv_vcf_binary_file' in data else None),
        },
        'version': data['mip_version'],
    }

    for sample_id, sample_data in data['sample'].items():
        sample = {
            'id': sample_id,
            'bam': sample_data['most_complete_bam']['path'],
            'sambamba': list(sample_data['program']['sambamba_depth'].values())[0]['path'],
            'sex': sample_data['sex'],

            'subsample_mt': (list(sample_data['program']['samtools_subsample_mt'].values())[0]['path'] if
                             'samtools_subsample_mt' in sample_data['program'] else None),
            'vcf2cytosure': list(sample_data['program']['vcf2cytosure'].values())[0]['path'],
        }
        chanjo_sexcheck = list(sample_data['program']['chanjo_sexcheck'].values())[0]
        sample['chanjo_sexcheck'] = chanjo_sexcheck['path']
        outdata['samples'].append(sample)

    return outdata

Parse MIP sample info file.

Args:
data (dict): raw YAML input from MIP qc sample info file

Returns:
dict: parsed data


def add_model_to_main_init(old_model_patterns: ModelPatterns, new_model_patterns: ModelPatterns, frameworks: Optional[List[str]]=None, with_processing: bool=True):
    with open(TRANSFORMERS_PATH / '__init__.py', 'r', encoding='utf-8') as f:
        content = f.read()
    lines = content.split('\n')
    idx = 0
    new_lines = []
    framework = None
    while idx < len(lines):
        new_framework = False
        if not is_empty_line(lines[idx]) and find_indent(lines[idx]) == 0:
            framework = None
        elif lines[idx].lstrip().startswith('if not is_torch_available'):
            framework = 'pt'
            new_framework = True
        elif lines[idx].lstrip().startswith('if not is_tf_available'):
            framework = 'tf'
            new_framework = True
        elif lines[idx].lstrip().startswith('if not is_flax_available'):
            framework = 'flax'
            new_framework = True
        if new_framework:
            while lines[idx].strip() != 'else:':
                new_lines.append(lines[idx])
                idx += 1
        if framework is not None and frameworks is not None and (framework not in frameworks):
            new_lines.append(lines[idx])
            idx += 1
        elif re.search(f'models.{old_model_patterns.model_lower_cased}( |")', lines[idx]) is not None:
            block = [lines[idx]]
            indent = find_indent(lines[idx])
            idx += 1
            while find_indent(lines[idx]) > indent:
                block.append(lines[idx])
                idx += 1
            if lines[idx].strip() in [')', ']', '],']:
                block.append(lines[idx])
                idx += 1
            block = '\n'.join(block)
            new_lines.append(block)
            add_block = True
            if not with_processing:
                processing_classes = [old_model_patterns.tokenizer_class, old_model_patterns.image_processor_class, old_model_patterns.image_processor_fast_class, old_model_patterns.feature_extractor_class, old_model_patterns.processor_class]
                processing_classes = [c for c in processing_classes if c is not None]
                for processing_class in processing_classes:
                    block = block.replace(f' "{processing_class}",', '')
                    block = block.replace(f', "{processing_class}"', '')
                    block = block.replace(f' {processing_class},', '')
                    block = block.replace(f', {processing_class}', '')
                    if processing_class in block:
                        add_block = False
            if add_block:
                new_lines.append(replace_model_patterns(block, old_model_patterns, new_model_patterns)[0])
        else:
            new_lines.append(lines[idx])
            idx += 1
    with open(TRANSFORMERS_PATH / '__init__.py', 'w', encoding='utf-8') as f:
        f.write('\n'.join(new_lines))

Add a model to the main init of Transformers.

Args:
old_model_patterns (`ModelPatterns`): The patterns for the old model.
new_model_patterns (`ModelPatterns`): The patterns for the new model.
frameworks (`List[str]`, *optional*):
If specified, only the models implemented in those frameworks will be added.
with_processing (`bool`, *optional*, defaults to `True`):
Whether the tokenizer/feature extractor/processor of the model should also be added to the init or not.


def verify(self, obj):

        out_obj = {}

        if not isinstance(obj, dict):
            raise ValidationError("Invalid dictionary", reason="object is not a dictionary")

        if self._fixed_length is not None and len(obj) != self._fixed_length:
            raise ValidationError("Dictionary did not have the correct length", expected_length=self._fixed_length,
                                  actual_length=self._fixed_length)

        unmatched_keys = set(obj.keys())
        required_keys = set(self._required_keys.keys())

        for key in required_keys:
            if key not in unmatched_keys:
                raise ValidationError("Required key not found in dictionary",
                                      reason="required key %s not found" % key, key=key)

            out_obj[key] = self._required_keys[key].verify(obj[key])
            unmatched_keys.remove(key)

        to_remove = set()
        for key in unmatched_keys:
            if key not in self._optional_keys:
                continue

            out_obj[key] = self._optional_keys[key].verify(obj[key])
            to_remove.add(key)

        unmatched_keys -= to_remove

        if len(unmatched_keys) > 0:
            if len(self._additional_key_rules) == 0:
                raise ValidationError("Extra key found in dictionary that does not allow extra keys",
                                      reason="extra keys found that were not expected", keys=unmatched_keys)

            to_remove = set()
            for key in unmatched_keys:
                for key_match, rule in self._additional_key_rules:
                    if key_match is None or key_match.matches(key):
                        out_obj[key] = rule.verify(obj[key])
                        to_remove.add(key)
                        break

            unmatched_keys -= to_remove

            if len(unmatched_keys) > 0:
                raise ValidationError("Extra key found in dictionary that did not match any extra key rule",
                                      reason="extra keys found that did not match any rule", keys=unmatched_keys)

        return out_obj

Verify that the object conforms to this verifier's schema

Args:
obj (object): A python object to verify

Raises:
ValidationError: If there is a problem verifying the dictionary, a
ValidationError is thrown with at least the reason key set indicating
the reason for the lack of validation.


def get_out_of_order(list_of_numbers):

  result = []

  for i in range(len(list_of_numbers)):
    if i == 0:
      continue
    if list_of_numbers[i] < list_of_numbers[i - 1]:
      result.append((list_of_numbers[i - 1], list_of_numbers[i]))
  return result

Returns elements that break the monotonically non-decreasing trend.

This is used to find instances of global step values that are "out-of-order",
which may trigger TensorBoard event discarding logic.

Args:
list_of_numbers: A list of numbers.

Returns:
A list of tuples in which each tuple are two elements are adjacent, but the
second element is lower than the first.


def poweroff_vmss_vms(access_token, subscription_id, resource_group, vmss_name, instance_ids):
    endpoint = ''.join([get_rm_endpoint(), '/subscriptions/', subscription_id, '/resourceGroups/', resource_group, '/providers/Microsoft.Compute/virtualMachineScaleSets/', vmss_name, '/powerOff?api-version=', COMP_API])
    body = (('{"instanceIds" : ' + instance_ids) + '}')
    return do_post(endpoint, body, access_token)

Poweroff all the VMs in a virtual machine scale set.

Args:
access_token (str): A valid Azure authentication token.
subscription_id (str): Azure subscription id.
resource_group (str): Azure resource group name.
vmss_name (str): Name of the virtual machine scale set.
instance_ids (str): String representation of a JSON list of VM IDs. E.g. '[1,2]'.

Returns:
HTTP response.


def __call__(self, field, **kwargs):

        if not hasattr(field.widget, '__webwidget__'):
            if field.type in self._lookup:
                field.widget = self._lookup[field.type]

        return field(**kwargs)

Return a rendered field.
Checks to see if the field has a custom widget set. If it does not have
a custom widget, the field type is looked up in the lookup dictionary
to get the default renderer for this field type.

If you wish to not perform any lookup, simply call field() without
invoking this method. This method simply overrides a field's widget
value.

Args:
field (wtforms.Field): The Field to render.


def get_entity(self, etype, entity_id):
    r = fapi.get_entity(self.namespace, self.name, etype, entity_id, self.api_url)
    fapi._check_response_code(r, 200)
    dresp = r.json()
    return Entity(etype, entity_id, dresp['attributes'])

Return entity in this workspace.

Args:
etype (str): Entity type
entity_id (str): Entity name/unique id


def read_knmi_dataset(directory):
    filemask = ('%s*.txt' % directory)
    filelist = glob.glob(filemask)
    columns_hourly = ['temp', 'precip', 'glob', 'hum', 'wind', 'ssd']
    ts = pd.DataFrame(columns=columns_hourly)
    first_call = True
    for file_i in filelist:
        print(file_i)
        current = read_single_knmi_file(file_i)
        if first_call:
            ts = current
            first_call = False
        else:
            ts = pd.concat([ts, current])
    return ts

Reads files from a directory and merges the time series

Please note: For each station, a separate directory must be provided!
data availability: www.knmi.nl/nederland-nu/klimatologie/uurgegevens

Args:
directory: directory including the files

Returns:
pandas data frame including time series


def cppn(
    width,
    batch=1,
    num_output_channels=3,
    num_hidden_channels=24,
    num_layers=8,
    activation_func=_composite_activation,
    normalize=False,
):

    r = 3.0 ** 0.5
    coord_range = tf.linspace(-r, r, width)
    y, x = tf.meshgrid(coord_range, coord_range, indexing="ij")
    net = tf.stack([tf.stack([x, y], -1)] * batch, 0)

    with slim.arg_scope(
        [slim.conv2d],
        kernel_size=[1, 1],
        activation_fn=None,
        weights_initializer=tf.initializers.variance_scaling(),
        biases_initializer=tf.initializers.random_normal(0.0, 0.1),
    ):
        for i in range(num_layers):
            x = slim.conv2d(net, num_hidden_channels)
            if normalize:
                x = slim.instance_norm(x)
            net = activation_func(x)
        rgb = slim.conv2d(
            net,
            num_output_channels,
            activation_fn=tf.nn.sigmoid,
            weights_initializer=tf.zeros_initializer(),
        )
    return rgb

Compositional Pattern Producing Network

Args:
width: width of resulting image, equals height
batch: batch dimension of output, note that all params share the same weights!
num_output_channels:
num_hidden_channels:
num_layers:
activation_func:
normalize:

Returns:
The collapsed shape, represented as a list.


def __init__(self, output_mediator):

    super(Shared4n6TimeOutputModule, self).__init__(output_mediator)
    self._append = False
    self._evidence = '-'
    self._fields = self._DEFAULT_FIELDS
    self._set_status = None

Initializes the output module object.

Args:
output_mediator (OutputMediator): mediates interactions between output
modules and other components, such as storage and dfvfs.

Raises:
ValueError: when there are unused keyword arguments.


def get_blobstore(layout):

    if layout.is_s3:
        from wal_e.blobstore import s3
        blobstore = s3
    elif layout.is_wabs:
        from wal_e.blobstore import wabs
        blobstore = wabs
    elif layout.is_swift:
        from wal_e.blobstore import swift
        blobstore = swift
    elif layout.is_gs:
        from wal_e.blobstore import gs
        blobstore = gs
    elif layout.is_file:
        from wal_e.blobstore import file
        blobstore = file
    return blobstore

Return Blobstore instance for a given storage layout
Args:
layout (StorageLayout): Target storage layout.


def from_dict(data, require=None):
    keys_needed = set((require if (require is not None) else []))
    missing = keys_needed.difference(six.iterkeys(data))
    if missing:
        raise ValueError('Service account info was not in the expected format, missing fields {}.'.format(', '.join(missing)))
    signer = crypt.RSASigner.from_service_account_info(data)
    return signer

Validates a dictionary containing Google service account data.

Creates and returns a :class:`google.auth.crypt.Signer` instance from the
private key specified in the data.

Args:
data (Mapping[str, str]): The service account data
require (Sequence[str]): List of keys required to be present in the
info.

Returns:
google.auth.crypt.Signer: A signer created from the private key in the
service account file.

Raises:
ValueError: if the data was in the wrong format, or if one of the
required keys is missing.


def _SetRow(self, new_values, row=0):

        if not row:
            row = self._row_index

        if row > self.size:
            raise TableError("Entry %s beyond table size %s." % (row, self.size))

        self._table[row].values = new_values

Sets the current row to new list.

Args:
new_values: List|dict of new values to insert into row.
row: int, Row to insert values into.

Raises:
TableError: If number of new values is not equal to row size.


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

        self.filename = filename
        self.verbose = kwargs.get('verbose', False)

        self.conn = None
        self.cursor = None

Initialize a ZealDB.

A connection is not opened here. To do that, use open() or use this
ZealDB instance as a context manager.

Args:
filename: A string containing full path to database file.
**verbose: If True, extra information may be printed to stderr
during operations.


def __ge__(self, other):

    if not isinstance(other, DateTimeValues):
      raise ValueError('Other not an instance of DateTimeValues')

    normalized_timestamp = self._GetNormalizedTimestamp()
    other_normalized_timestamp = other._GetNormalizedTimestamp()

    if normalized_timestamp is None:
      return other_normalized_timestamp is None

    if other_normalized_timestamp is None:
      return True

    return normalized_timestamp >= other_normalized_timestamp

Determines if the date time values are greater than or equal to other.

Args:
other (DateTimeValues): date time values to compare against.

Returns:
bool: True if the date time values are greater than or equal to other.

Raises:
ValueError: if other is not an instance of DateTimeValues.


def __same_types(a, b):
    if nest.is_namedtuple(a) and nest.is_namedtuple(b):
        return nest.same_namedtuples(a, b)
    else:
        return type(a) is type(b)

Returns whether a and b have the same type, up to namedtuple equivalence.

Consistent with tf.nest.assert_same_structure(), two namedtuple types
are considered the same iff they agree in their class name (without
qualification by module name) and in their sequence of field names.
This makes namedtuples recreated by nested_structure_coder compatible with
their original Python definition.

Args:
a: a Python object.
b: a Python object.

Returns:
A boolean that is true iff type(a) and type(b) are the same object
or equivalent namedtuple types.


def get_sizes(self, width, height):
    return list(self._api_sizes(iterate=True).list(profileId=self.profile_id, height=height, width=width).execute())

Retrieves a creative sizes from DCM.

Args:
width: width of the creative.
height: height of the creative.
retry_count: how many times the api call should be retried in case of an
api related error that is not a client error.

Returns:
The sizes object from DCM.


def GetMap(self, cache_info):
    return self.GetParser().GetMap(cache_info, self.CreateMap())

Creates a Map from the cache_info data.

Args:
cache_info: file-like object containing the data to parse

Returns:
A child of Map containing the cache data.


def get_model_list(filename: str, start_prompt: str, end_prompt: str) -> str:
    with open(os.path.join(REPO_PATH, filename), 'r', encoding='utf-8', newline='\n') as f:
        lines = f.readlines()
    start_index = 0
    while not lines[start_index].startswith(start_prompt):
        start_index += 1
    start_index += 1
    result = []
    current_line = ''
    end_index = start_index
    while not lines[end_index].startswith(end_prompt):
        if lines[end_index].startswith('1.'):
            if len(current_line) > 1:
                result.append(current_line)
            current_line = lines[end_index]
        elif len(lines[end_index]) > 1:
            current_line = f'{current_line[:-1]} {lines[end_index].lstrip()}'
        end_index += 1
    if len(current_line) > 1:
        result.append(current_line)
    return ''.join(result)

Extracts the model list from a README.

Args:
filename (`str`): The name of the README file to check.
start_prompt (`str`): The string to look for that introduces the model list.
end_prompt (`str`): The string to look for that ends the model list.

Returns:
`str`: The model list.


def download(self, uri, file_path):
    with open(file_path, 'wb') as file:
        return self._connection.download_to_stream(file, uri)

Downloads the contents of the requested URI to a stream.

Args:
uri: URI
file_path: File path destination

Returns:
bool: Indicates if the file was successfully downloaded.


def set_heat_pump_feature(self, device_label, feature):

        response = None
        try:
            response = requests.put(
                urls.set_heatpump_feature(self._giid, device_label, feature),
                headers={
                    'Accept': 'application/json',
                    'Content-Type': 'application/json',
                    'Cookie': 'vid={}'.format(self._vid)})
        except requests.exceptions.RequestException as ex:
            raise RequestError(ex)
        _validate_response(response)
        return json.loads(response.text)

Set heatpump mode
Args:
feature: 'QUIET', 'ECONAVI', or 'POWERFUL'


def _bbox_overlap(boxes_a, boxes_b):
    with ops.name_scope('bbox_overlap'):
        a_y_min, a_x_min, a_y_max, a_x_max = array_ops.split(value=boxes_a, num_or_size_splits=4, axis=2)
        b_y_min, b_x_min, b_y_max, b_x_max = array_ops.split(value=boxes_b, num_or_size_splits=4, axis=2)
        i_xmin = math_ops.maximum(a_x_min, array_ops.transpose(b_x_min, [0, 2, 1]))
        i_xmax = math_ops.minimum(a_x_max, array_ops.transpose(b_x_max, [0, 2, 1]))
        i_ymin = math_ops.maximum(a_y_min, array_ops.transpose(b_y_min, [0, 2, 1]))
        i_ymax = math_ops.minimum(a_y_max, array_ops.transpose(b_y_max, [0, 2, 1]))
        i_area = math_ops.maximum(i_xmax - i_xmin, 0) * math_ops.maximum(i_ymax - i_ymin, 0)
        a_area = (a_y_max - a_y_min) * (a_x_max - a_x_min)
        b_area = (b_y_max - b_y_min) * (b_x_max - b_x_min)
        EPSILON = 1e-08
        u_area = a_area + array_ops.transpose(b_area, [0, 2, 1]) - i_area + EPSILON
        intersection_over_union = i_area / u_area
        return intersection_over_union

Calculates the overlap (iou - intersection over union) between boxes_a and boxes_b.

Args:
boxes_a: a tensor with a shape of [batch_size, N, 4]. N is the number of
boxes per image. The last dimension is the pixel coordinates in
[ymin, xmin, ymax, xmax] form.
boxes_b: a tensor with a shape of [batch_size, M, 4]. M is the number of
boxes. The last dimension is the pixel coordinates in
[ymin, xmin, ymax, xmax] form.
Returns:
intersection_over_union: a tensor with as a shape of [batch_size, N, M],
representing the ratio of intersection area over union area (IoU) between
two boxes


def sorted_by(key: Callable[[raw_types.Qid], Any]) -> 'QubitOrder':

        return QubitOrder(lambda qubits: tuple(sorted(qubits, key=key)))

A basis that orders qubits ascending based on a key function.

Args:
key: A function that takes a qubit and returns a key value. The
basis will be ordered ascending according to these key values.

Returns:
A basis that orders qubits ascending based on a key function.


def ffn_expert_fn(input_size,
                  hidden_sizes,
                  output_size,
                  hidden_activation=tf.nn.relu):

  def my_fn(x):
    layer_sizes = [input_size] + hidden_sizes + [output_size]
    for i in range(1 + len(hidden_sizes)):
      w = tf.get_variable("w_%d" % i, layer_sizes[i:i+2], tf.float32)
      x = tf.matmul(x, w)
      if i < len(hidden_sizes):
        x = hidden_activation(x)
      if layer_sizes[i] != input_size:
        x *= (layer_sizes[i] / float(input_size))**-0.5
    return x
  return my_fn

Returns a function that creates a feed-forward network.

Use this function to create the expert_fn argument to distributed_moe.

Args:
input_size: an integer
hidden_sizes: a list of integers
output_size: an integer
hidden_activation: a unary function.

Returns:
a unary function


def _ssl_context_factory(parameters):

    client_cert = None
    ca_cert = None
    key = config.conf["tls"]["keyfile"]
    cert = config.conf["tls"]["certfile"]
    ca_file = config.conf["tls"]["ca_cert"]
    if ca_file:
        with open(ca_file, "rb") as fd:

            ca_cert = ssl.Certificate.loadPEM(fd.read())
    if key and cert:

        with open(key) as fd:
            client_keypair = fd.read()
        with open(cert) as fd:
            client_keypair += fd.read()
        client_cert = ssl.PrivateCertificate.loadPEM(client_keypair)

    hostname = parameters.host
    if not isinstance(hostname, six.text_type):

        hostname = hostname.decode(locale.getdefaultlocale()[1])
    try:
        context_factory = ssl.optionsForClientTLS(
            hostname,
            trustRoot=ca_cert or ssl.platformTrust(),
            clientCertificate=client_cert,
            extraCertificateOptions={"raiseMinimumTo": ssl.TLSVersion.TLSv1_2},
        )
    except AttributeError:

        context_factory = ssl.CertificateOptions(
            certificate=client_cert.original,
            privateKey=client_cert.privateKey.original,
            caCerts=[ca_cert.original] or ssl.platformTrust(),
            verify=True,
            requireCertificate=True,
            verifyOnce=False,
            enableSessions=False,
        )

    return context_factory

Produce a Twisted SSL context object from a pika connection parameter object.
This is necessary as Twisted manages the connection, not Pika.

Args:
parameters (pika.ConnectionParameters): The connection parameters built
from the fedora_messaging configuration.


def post(self):
    data = request.get_json()
    (options, sql_raw) = (data.get('options'), data.get('sql_raw'))
    if (options == 'format'):
        sql_formmated = sqlparse.format(sql_raw, keyword_case='upper', reindent=True)
        return build_response(dict(data=sql_formmated, code=200))
    elif (options in ('all', 'selected')):
        conn = SQL(config.sql_host, config.sql_port, config.sql_user, config.sql_pwd, config.sql_db)
        result = conn.run(sql_raw)
        return build_response(dict(data=result, code=200))
    else:
        pass
    pass

return executed sql result to client.

post data format:

{"options": ['all', 'last', 'first', 'format'], "sql_raw": "raw sql ..."}

Returns:
sql result.


Flatten current object into (metadata, components).

Returns:
A `tuple` of (metadata, components), where
- metadata is a custom Python object that stands for the static config
of the current object, which is supposed to be fixed and not affected
by data transformation.
- components is a `tuple` that contains the modifiable fields of the
current object.

Implementation Note:
- This method should not invoke any TensorFlow ops.
- This method only needs to flatten the current level. If current object has
an attribute that also need custom flattening, nest functions (such as
`nest.flatten`) will utilize this method to do recursive flattening.
- Components must be a `tuple`, not a `list`


def Parse(self, filename, feed):

    dom = minidom.parse(filename)
    self.ParseDom(dom, feed)

Reads the kml file, parses it and updated the Google transit feed
object with the extracted information.

Args:
filename - kml file name
feed - an instance of Schedule class to be updated


def _transform(transformer_chain: Sequence[Tuple[DataTransformer, Type]], data: S, context: PipelineContext = None) -> T:

    for transformer, target_type in transformer_chain:

        data = transformer.transform(target_type, data, context)
    return data

Transform data to a new type.

Args:
transformer_chain: A sequence of (transformer, type) pairs to convert the data.
data: The data to be transformed.
context: The context of the transformations (mutable).

Returns:
The transformed data.