def filter(self, filter_fn=None, desc=None, **kwargs):
    if ((filter_fn is not None) and kwargs):
        raise TypeError('Must supply either a filter_fn or attribute filter parameters to filter(), but not both.')
    if ((filter_fn is None) and (not kwargs)):
        raise TypeError('Must supply one of filter_fn or one or more attribute filter parameters to filter().')
    if (desc is None):
        if (filter_fn is not None):
            desc = getattr(filter_fn, '__name__', '')
        elif kwargs:
            desc = u', '.join([u'{}={!r}'.format(key, value) for (key, value) in kwargs.items()])
    desc = u'filter({})'.format(desc)
    if kwargs:

        def filter_fn(elem):
            return all(((getattr(elem, filter_key) == filter_value) for (filter_key, filter_value) in kwargs.items()))
    return self.transform((lambda xs: (x for x in xs if filter_fn(x))), desc=desc)

Return a copy of this query, with some values removed.

Example usages:

.. code:: python

# Returns a query that matches even numbers
q.filter(filter_fn=lambda x: x % 2)

# Returns a query that matches elements with el.description == "foo"
q.filter(description="foo")

Keyword Args:
filter_fn (callable): If specified, a function that accepts one argument (the element)
and returns a boolean indicating whether to include that element in the results.

kwargs: Specify attribute values that an element must have to be included in the results.

desc (str): A description of the filter, for use in log messages.
Defaults to the name of the filter function or attribute.

Raises:
TypeError: neither or both of `filter_fn` and `kwargs` are provided.


def format_ascii(sensor_graph):
    cmdfile = CommandFile('Sensor Graph', '1.0')
    cmdfile.add('set_online', False)
    cmdfile.add('clear')
    cmdfile.add('reset')
    for node in sensor_graph.dump_nodes():
        cmdfile.add('add_node', node)
    for streamer in sensor_graph.streamers:
        other = 255
        if (streamer.with_other is not None):
            other = streamer.with_other
        args = [streamer.selector, streamer.dest, streamer.automatic, streamer.format, streamer.report_type, other]
        cmdfile.add('add_streamer', *args)
    for (stream, value) in sorted(sensor_graph.constant_database.items(), key=(lambda x: x[0].encode())):
        cmdfile.add('push_reading', stream, value)
    cmdfile.add('persist')
    cmdfile.add('set_online', True)
    return cmdfile.dump()

Format this sensor graph as a loadable ascii file format.

This includes commands to reset and clear previously stored
sensor graphs.

NB. This format does not include any required configuration
variables that were specified in this sensor graph, so you
should also output tha information separately in, e.g.
the config format.

Args:
sensor_graph (SensorGraph): the sensor graph that we want to format

Returns:
str: The ascii output lines concatenated as a single string


def _VerifyValues(self, tensor_in_sizes, filter_in_sizes, stride, padding, data_type, use_gpu, grouped_conv=False, data_format='NHWC', dilations=None, tolerance=None):
    input_size = 1
    filter_size = 1
    for s in tensor_in_sizes:
        input_size *= s
    for s in filter_in_sizes:
        filter_size *= s
    x1 = [f * 1.0 / input_size for f in range(1, input_size + 1)]
    x1 = np.array(x1).reshape(tensor_in_sizes)
    x2 = [f * 1.0 / filter_size for f in range(1, filter_size + 1)]
    x2 = np.array(x2).reshape(filter_in_sizes)
    strides = [1, stride, stride, 1]
    if isinstance(padding, list):
        padding = [(0, 0)] + padding + [(0, 0)]
    np_result = _DepthwiseConv2dNumpy(x1, x2, strides, padding, 'NHWC', dilations)
    ops.reset_default_graph()
    graph = ops.get_default_graph()
    with self.session(graph=graph, use_gpu=use_gpu) as sess:
        tolerance = tolerance or {dtypes.float16: 0.04, dtypes.float32: 1e-05, dtypes.float64: 1e-12, dtypes.bfloat16: 0.01}[data_type]
        t1 = constant_op.constant(x1, shape=tensor_in_sizes, dtype=data_type)
        t2 = constant_op.constant(x2, shape=filter_in_sizes, dtype=data_type)
        if data_format == 'NCHW':
            t1 = array_ops.transpose(t1, [0, 3, 1, 2])
            strides = [1, 1, stride, stride]
            if isinstance(padding, list):
                padding = [padding[0], padding[3], padding[1], padding[2]]
        if dilations is None:
            with sess.graph._kernel_label_map({'DepthwiseConv2dNative': 'cudnn_grouped_convolution'} if grouped_conv else {}):
                conv_native = nn_ops.depthwise_conv2d_native(t1, t2, strides=strides, data_format=data_format, padding=padding)
            if data_format == 'NCHW':
                conv_native = array_ops.transpose(conv_native, [0, 2, 3, 1])
            try:
                native_result = self.evaluate(conv_native)
            except errors.InvalidArgumentError as e:
                if "No OpKernel was registered to support Op 'DepthwiseConv2dNative'" in e.message:
                    tf_logging.warn('Skipping grouped convolution test')
                    return
                raise e
        conv_interface = nn_impl.depthwise_conv2d(t1, t2, strides=strides, padding=padding, data_format=data_format, dilations=dilations)
        if data_format == 'NCHW':
            conv_interface = array_ops.transpose(conv_interface, [0, 2, 3, 1])
        interface_result = self.evaluate(conv_interface)
    if dilations is None:
        self.assertAllClose(native_result, np_result, atol=tolerance, rtol=tolerance)
    self.assertAllClose(interface_result, np_result, atol=tolerance, rtol=tolerance)

Verifies the output values of the convolution function.

Args:
tensor_in_sizes: Input tensor dimensions in [batch, input_rows,
input_cols, input_depth].
filter_in_sizes: Filter tensor dimensions in [filter_rows, filter_cols,
input_depth, depth_multiplier].
stride: Stride.
padding: Padding type.
data_type: The data type to use.
use_gpu: Whether to use GPU.
grouped_conv: Whether to use cuDNN 7's grouped convolution.
data_format: The data_format of the input. "NHWC" or "NCHW".
dilations: A list of 2 elements, representing the dilations.
tolerance: The absolute and relative tolarance when verifying the output.


def install_event_handlers(self, categories=None, handlers=None):

        if categories is not None and handlers is not None:
            raise ValueError("categories and handlers are mutually exclusive!")

        from .events import get_event_handler_classes
        if categories:
            raise NotImplementedError()
            handlers = [cls() for cls in get_event_handler_classes(categories=categories)]
        else:
            handlers = handlers or [cls() for cls in get_event_handler_classes()]

        self._event_handlers = handlers

Install the `EventHandlers for this `Node`. If no argument is provided
the default list of handlers is installed.

Args:
categories: List of categories to install e.g. base + can_change_physics
handlers: explicit list of :class:`EventHandler` instances.
This is the most flexible way to install handlers.

.. note::

categories and handlers are mutually exclusive.


def remove_bond(self, idx1, idx2):
    for obbond in ob.OBMolBondIter(self._obmol):
        if (((obbond.GetBeginAtomIdx() == idx1) and (obbond.GetEndAtomIdx() == idx2)) or ((obbond.GetBeginAtomIdx() == idx2) and (obbond.GetEndAtomIdx() == idx1))):
            self._obmol.DeleteBond(obbond)

Remove a bond from an openbabel molecule

Args:
idx1: The atom index of one of the atoms participating the in bond
idx2: The atom index of the other atom participating in the bond


def convert_videos_to_summaries(input_videos, output_videos, target_videos,
                                tag, decode_hparams,
                                display_ground_truth=False):

  fps = decode_hparams.frames_per_second
  border_percent = decode_hparams.border_percent
  max_outputs = decode_hparams.max_display_outputs
  target_steps = target_videos.shape[1]
  all_summaries = []
  input_videos = create_border(
      input_videos, color="blue", border_percent=border_percent)
  target_videos = create_border(
      target_videos, color="red", border_percent=border_percent)
  output_videos = create_border(
      output_videos, color="red", border_percent=border_percent)

  all_input = np.concatenate((input_videos, target_videos), axis=1)
  all_output = np.concatenate((input_videos, output_videos), axis=1)
  output_summ_vals, _ = common_video.py_gif_summary(
      "%s/output" % tag, all_output, max_outputs=max_outputs, fps=fps,
      return_summary_value=True)
  all_summaries.extend(output_summ_vals)

  if display_ground_truth:
    input_summ_vals, _ = common_video.py_gif_summary(
        "%s/input" % tag, all_input, max_outputs=max_outputs, fps=fps,
        return_summary_value=True)
    all_summaries.extend(input_summ_vals)

  iterable = zip(output_videos[:max_outputs, :target_steps],
                 target_videos[:max_outputs])
  for ind, (input_video, output_video) in enumerate(iterable):
    t, h, w, c = input_video.shape

    input_frames = np.reshape(input_video, (t*h, w, c))
    output_frames = np.reshape(output_video, (t*h, w, c))

    all_frames = np.concatenate((input_frames, output_frames), axis=1)
    tag = "input/output/%s_sample_%d" % (tag, ind)
    frame_by_frame_summ = image_utils.image_to_tf_summary_value(
        all_frames, tag=tag)
    all_summaries.append(frame_by_frame_summ)
  return all_summaries

Converts input, output and target videos into video summaries.

Args:
input_videos: 5-D NumPy array, (NTHWC) conditioning frames.
output_videos: 5-D NumPy array, (NTHWC) model predictions.
target_videos: 5-D NumPy array, (NTHWC) target frames.
tag: tf summary tag.
decode_hparams: HParams.
display_ground_truth: Whether or not to display ground truth videos.
Returns:
summaries: a list of tf frame-by-frame and video summaries.


def generate_json_schema(cls, schema, context=DEFAULT_DICT):
    schema = cls._get_schema(schema)
    return cls(context=context).dump(schema).data

Generate a JSON Schema from a Marshmallow schema.

Args:
schema (marshmallow.Schema|str): The Marshmallow schema, or the
Python path to one, to create the JSON schema for.

Keyword Args:
file_pointer (file, optional): The path or pointer to the file
to write this schema to. If not provided, the schema will be
dumped to ``sys.stdout``.

Returns:
dict: The JSON schema in dictionary form.


def _clean_url(url):
    if (url == 'default'):
        url = DEFAULT_SERVER_HTTP_URL
    if url.startswith('ws'):
        raise ValueError('url should be the http or https URL for the server, not the websocket URL')
    return url.rstrip('/')

Produce a canonical Bokeh server URL.

Args:
url (str)
A URL to clean, or "defatul". If "default" then the
``BOKEH_SERVER_HTTP_URL`` will be returned.

Returns:
str


def encode(self, tf_graph_predictions):

    row = []
    for col in self._header:
      row.append(str(tf_graph_predictions[col]))

    return ','.join(row)

Encodes the graph json prediction into csv.

Args:
tf_graph_predictions: python dict.

Returns:
csv string.


def lookup_value(self, api_name, key):

        if api_name in self._cache:
            return self._cache[api_name].get(key, None)
        return None

Add the value of an API call to the cache.

Args:
api_name: a string name of the API. Keys and values are segmented by api_name.
key: a string key for the specific call.


def make_triple(sub, pred, obj):

    return "{s} {p} {o} .".format(s=sub, p=pred, o=obj)

Takes a subject predicate and object and joins them with a space
in between

Args:
sub -- Subject
pred -- Predicate
obj  -- Object
Returns
str


def build_inputs_with_special_tokens(self, token_ids_0: List[int], token_ids_1: Optional[List[int]]=None) -> List[int]:
    if token_ids_1 is None:
        return [self.cls_token_id] + token_ids_0 + [self.sep_token_id]
    cls = [self.cls_token_id]
    sep = [self.sep_token_id]
    return cls + token_ids_0 + sep + token_ids_1 + sep

Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
adding special tokens. A ConvBERT sequence has the following format:

- single sequence: `[CLS] X [SEP]`
- pair of sequences: `[CLS] A [SEP] B [SEP]`

Args:
token_ids_0 (`List[int]`):
List of IDs to which the special tokens will be added.
token_ids_1 (`List[int]`, *optional*):
Optional second list of IDs for sequence pairs.

Returns:
`List[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens.


def to_sql(self, view: views.View, limit: Optional[int]=None) -> str:
    encoder = _spark_interpreter.SparkSqlInterpreter(value_set_codes_table='VALUESET_VIEW')
    dataset = f'{self._fhir_dataset}'
    sql_generator = runner_utils.RunnerSqlGenerator(view, encoder, dataset, self._snake_case_resource_tables)
    sql_statement = sql_generator.build_sql_statement()
    valuesets_clause = sql_generator.build_valueset_expression(self._value_set_codes_table)
    if limit is not None and limit < 1:
        raise ValueError('Query limits must be positive integers.')
    limit_clause = '' if limit is None else f' LIMIT {limit}'
    return f'{valuesets_clause}{sql_statement}{limit_clause}'

Returns the SQL used to run the given view in Spark.

Args:
view: the view used to generate the SQL.
limit: optional limit to attach to the generated SQL.

Returns:
The SQL used to run the given view.


def copy_workspace(self, uri, new_name):
    payload = {'isPublic': True, 'newName': new_name}
    return self._api.request('post', (((('/api/documents/' + uri['did']) + '/workspaces/') + uri['wvm']) + '/copy'), body=payload)

Copy the current workspace.

Args:
- uri (dict): the uri of the workspace being copied. Needs to have a did and wid key.
- new_name (str): the new name of the copied workspace.

Returns:
- requests.Response: Onshape response data


def compile_keywords(keywords):
    mdt = []
    cz_keywords = []
    en_keywords = []
    for keyword in keywords:
        keyword = keyword_to_info(keyword.encode('utf-8'))
        if (not keyword):
            continue
        cz_keywords.append({'uid': keyword['uid'], 'zahlavi': keyword['zahlavi'], 'zdroj': 'czenas'})
        if keyword.get('mdt'):
            mdt.append({'mdt': keyword['mdt'], 'mrf': keyword['mrf']})
        angl_ekvivalent = keyword.get('angl_ekvivalent')
        if angl_ekvivalent:
            en_keywords.append({'zahlavi': angl_ekvivalent, 'zdroj': (keyword.get('zdroj_angl_ekvivalentu') or 'eczenas')})
    return (mdt, cz_keywords, en_keywords)

Translate `keywords` to full keyword records as they are used in Aleph.

Returns tuple with three lists, each of which is later used in different
part of the MRC/MARC record.

Args:
keywords (list): List of keyword strings.

Returns:
tuple: (mdt_list, cz_keyword_list, en_keyword_list)


def GetVShadowStoreByPathSpec(self, path_spec):
    store_index = vshadow.VShadowPathSpecGetStoreIndex(path_spec)
    if (store_index is None):
        return None
    return self._vshadow_volume.get_store(store_index)

Retrieves a VSS store for a path specification.

Args:
path_spec (PathSpec): path specification.

Returns:
pyvshadow.store: a VSS store or None if not available.


def add_string_parameters(self, string):
    if isinstance(string, list):
        for x in string:
            self.add_string_parameters(x)
        return
    self._parameters.append((('{ "value": "' + string) + '" }'))

Add given string parameters to the internal list.

Args:
string (list of str or str): A string or list of strings to add to the parameters.


def file_digest(source):
    hash_sha256 = hashlib.sha256()
    should_close = False
    if isinstance(source, six.string_types):
        should_close = True
        source = open(source, 'rb')
    for chunk in iter((lambda : source.read(_BUFFER_SIZE)), b''):
        hash_sha256.update(chunk)
    if should_close:
        source.close()
    return hash_sha256.hexdigest()

Calculates SHA256 digest of a file.

Args:
source: either a file-like object or a path to file


def _new_open_bin(self, remaining_rect):

        factories_to_delete = set()
        new_bin = None

        for key, binfac in self._empty_bins.items():

            a_rectangle_fits = False
            for _, rect in remaining_rect.items():
                if binfac.fits_inside(rect[0], rect[1]):
                    a_rectangle_fits = True
                    break

            if not a_rectangle_fits:
                factories_to_delete.add(key)
                continue

            new_bin = binfac.new_bin()
            if new_bin is None:
                continue
            self._open_bins.append(new_bin)

            if binfac.is_empty():
                factories_to_delete.add(key)

            break

        for f in factories_to_delete:
            del self._empty_bins[f]

        return new_bin

Extract the next bin where at least one of the rectangles in
rem

Arguments:
remaining_rect (dict): rectangles not placed yet

Returns:
PackingAlgorithm: Initialized empty packing bin.
None: No bin big enough for the rectangle was found


def find_element(driver, elem_path, by=CSS, timeout=TIMEOUT, poll_frequency=0.5):
    wait = WebDriverWait(driver, timeout, poll_frequency)
    return wait.until(EC.presence_of_element_located((by, elem_path)))

Find and return an element once located

find_element locates an element on the page, waiting
for up to timeout seconds. The element, when located,
is returned. If not located, a TimeoutException is raised.

Args:
driver (selenium webdriver or element): A driver or element
elem_path (str): String used to located the element
by (selenium By): Selenium By reference
timeout (int): Selenium Wait timeout, in seconds
poll_frequency (float): Selenium Wait polling frequency, in seconds

Returns:
element: Selenium element

Raises:
TimeoutException: Raised when target element isn't located


def create_issues_report(self, timeout=(- 1)):
    uri = '{}/issues/'.format(self.data['uri'])
    return self._helper.create_report(uri, timeout)

Creates an unexpected zoning report for a SAN.

Args:
timeout:
Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation in
OneView, just stops waiting for its completion.

Returns:
list: A list of FCIssueResponse dict.


def save_features(self, train_features, test_features, feature_names, feature_list_id):

        self.save_feature_names(feature_names, feature_list_id)
        self.save_feature_list(train_features, 'train', feature_list_id)
        self.save_feature_list(test_features, 'test', feature_list_id)

Save features for the training and test sets to disk, along with their metadata.

Args:
train_features: A NumPy array of features for the training set.
test_features: A NumPy array of features for the test set.
feature_names: A list containing the names of the feature columns.
feature_list_id: The name for this feature list.


def channel_interpolate(layer1, n_channel1, layer2, n_channel2):

    def inner(T):
        batch_n = T(layer1).get_shape().as_list()[0]
        arr1 = T(layer1)[(..., n_channel1)]
        arr2 = T(layer2)[(..., n_channel2)]
        weights = (np.arange(batch_n) / float((batch_n - 1)))
        S = 0
        for n in range(batch_n):
            S += ((1 - weights[n]) * tf.reduce_mean(arr1[n]))
            S += (weights[n] * tf.reduce_mean(arr2[n]))
        return S
    return inner

Interpolate between layer1, n_channel1 and layer2, n_channel2.

Optimize for a convex combination of layer1, n_channel1 and
layer2, n_channel2, transitioning across the batch.

Args:
layer1: layer to optimize 100% at batch=0.
n_channel1: neuron index to optimize 100% at batch=0.
layer2: layer to optimize 100% at batch=N.
n_channel2: neuron index to optimize 100% at batch=N.

Returns:
Objective


def add_cohp_dict(self, cohp_dict, key_sort_func=None):
    if key_sort_func:
        keys = sorted(cohp_dict.keys(), key=key_sort_func)
    else:
        keys = cohp_dict.keys()
    for label in keys:
        self.add_cohp(label, cohp_dict[label])

Adds a dictionary of COHPs with an optional sorting function
for the keys.

Args:
cohp_dict: dict of the form {label: Cohp}

key_sort_func: function used to sort the cohp_dict keys.


def returns(desc=None, printer=None, data=True):

    if data is False:
        raise ArgumentError("Specifying non data return type in returns is no longer supported")

    def _returns(func):
        annotated(func)
        func.custom_returnvalue(printer, desc)
        return func

    return _returns

Specify how the return value of this function should be handled.

Args:
desc (str): A deprecated description of the return value
printer (callable): A callable function that can format this return value
data (bool): A deprecated parameter for specifying that this function
returns data.


def recursive_copy(source, destination):

    if os.path.isdir(source):
        copy_tree(source, destination)

A wrapper around distutils.dir_util.copy_tree but won't throw any exception when the source
directory does not exist.

Args:
source (str): source path
destination (str): destination path


def update_ports(self, ports, id_or_uri, timeout=-1):

        resources = merge_default_values(ports, {'type': 'port'})

        uri = self._client.build_uri(id_or_uri) + "/update-ports"
        return self._client.update(resources, uri, timeout)

Updates the interconnect ports.

Args:
id_or_uri: Can be either the interconnect id or the interconnect uri.
ports (list): Ports to update.
timeout: Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation
in OneView; it just stops waiting for its completion.

Returns:
dict: The interconnect.


def google_maps_geoloc_link(data):
    if isinstance(data, str):
        lat_lon = ip_geoloc(data)
        if (lat_lon is None):
            return ''
        (lat, lon) = lat_lon
    else:
        (lat, lon) = data
    loc = ('%s,%s' % (lat, lon))
    return ('https:

Get a link to google maps pointing on this IP's geolocation.

Args:
data (str/tuple): IP address or (latitude, longitude).

Returns:
str: a link to google maps pointing on this IP's geolocation.


def put_content(self, url, content):

        cache_path = self._url_to_path(url)

        try:
            dir = os.path.dirname(cache_path)
            os.makedirs(dir)
        except OSError as e:
            if e.errno != errno.EEXIST:
                raise Error('Failed to create cache directories for ' % cache_path)

        try:
            with open(cache_path, 'wb') as f:
                f.write(content)
        except IOError:
            raise Error('Failed to cache content as %s for %s' % (cache_path, url))

Stores the content of a resource into the disk cache.

Args:
url: The url of the resource
content: The content of the resource

Raises:
CacheError: If the content cannot be put in cache


def renew(self, requested_timeout=None):
    if self._has_been_unsubscribed:
        raise SoCoException('Cannot renew subscription once unsubscribed')
    if (not self.is_subscribed):
        raise SoCoException('Cannot renew subscription before subscribing')
    if (self.time_left == 0):
        raise SoCoException('Cannot renew subscription after expiry')
    headers = {'SID': self.sid}
    if (requested_timeout is None):
        requested_timeout = self.requested_timeout
    if (requested_timeout is not None):
        headers['TIMEOUT'] = 'Second-{}'.format(requested_timeout)
    response = requests.request('SUBSCRIBE', (self.service.base_url + self.service.event_subscription_url), headers=headers)
    response.raise_for_status()
    timeout = response.headers['timeout']
    if (timeout.lower() == 'infinite'):
        self.timeout = None
    else:
        self.timeout = int(timeout.lstrip('Second-'))
    self._timestamp = time.time()
    self.is_subscribed = True
    log.info('Renewed subscription to %s, sid: %s', (self.service.base_url + self.service.event_subscription_url), self.sid)

Renew the event subscription.

You should not try to renew a subscription which has been
unsubscribed, or once it has expired.

Args:
requested_timeout (int, optional): The period for which a renewal
request should be made. If None (the default), use the timeout
requested on subscription.


def depth(script, iterations=3, viewpoint=(0, 0, 0), selected=False):
    filter_xml = ''.join(['  <filter name="Depth Smooth">\n', '    <Param name="stepSmoothNum" ', 'value="{:d}" '.format(iterations), 'description="Smoothing steps" ', 'type="RichInt" ', '/>\n', '    <Param name="viewPoint" ', 'x="{}" '.format(viewpoint[0]), 'y="{}" '.format(viewpoint[1]), 'z="{}" '.format(viewpoint[2]), 'description="Smoothing steps" ', 'type="RichPoint3f" ', '/>\n', '    <Param name="Selected" ', 'value="{}" '.format(str(selected).lower()), 'description="Affect only selected faces" ', 'type="RichBool" ', '/>\n', '  </filter>\n'])
    util.write_filter(script, filter_xml)
    return None

A laplacian smooth that is constrained to move vertices only along the
view direction.

Args:
script: the FilterScript object or script filename to write
the filter to.
iterations (int): The number of times that the whole algorithm (normal
smoothing + vertex fitting) is iterated.
viewpoint (vector tuple or list): The position of the view point that
is used to get the constraint direction.
selected (bool): If selected the filter is performed only on the
selected faces

Layer stack:
No impacts

MeshLab versions:
2016.12
1.3.4BETA


def format_search_results(self, search_results):
    formatted_lines = []
    for search_result in search_results:
        lines = self._format_search_result(search_result)
        formatted_lines.extend(lines)
    return formatted_lines

Format search results.

Args:
search_results (list of `ResourceSearchResult`): Search to format.

Returns:
List of 2-tuple: Text and color to print in.


def set_message(self, title, msg, typ, url=None):

        return self.user.send_notification(title=title,
                                           message=msg,
                                           typ=typ,
                                           url=url)

Sets user notification message.

Args:
title: Msg. title
msg:  Msg. text
typ: Msg. type
url: Additional URL (if exists)

Returns:
Message ID.


def _AssertValidators(self, validators):
    for validator in sorted(validators, key=(lambda validator: validator.insertion_index)):
        try:
            validator.verify(self)
        except exceptions.ValidationError as e:
            message = validator.print_flags_with_values(self)
            raise exceptions.IllegalFlagValueError(('%s: %s' % (message, str(e))))

Assert if all validators in the list are satisfied.

Asserts validators in the order they were created.
Args:
validators: Iterable(validators.Validator), validators to be
verified
Raises:
AttributeError: if validators work with a non-existing flag.
IllegalFlagValueError: if validation fails for at least one validator


def validate_to_schema(nanopub, schema) -> Tuple[(bool, List[Tuple[(str, str)]])]:
    v = jsonschema.Draft4Validator(schema)
    messages = []
    errors = sorted(v.iter_errors(nanopub), key=(lambda e: e.path))
    for error in errors:
        for suberror in sorted(error.context, key=(lambda e: e.schema_path)):
            print(list(suberror.schema_path), suberror.message, sep=', ')
            messages.append(('ERROR', suberror.message))
    is_valid = True
    if errors:
        is_valid = False
    return (is_valid, messages)

Validate nanopub against jsonschema for nanopub

Args:
nanopub (Mapping[str, Any]): nanopub dict
schema (Mapping[str, Any]): nanopub schema

Returns:
Tuple[bool, List[str]]:
bool: Is valid?  Yes = True, No = False
List[Tuple[str, str]]: Validation issues, empty if valid, tuple is ('Error|Warning', msg)
e.g. [('ERROR', "'subject' is a required property")]


def all_sum(tensors):
    return _apply_all_reduce('sum', tensors)

Returns a list of tensors with the all-reduce sum across `tensors`.

The computation is done with an all-reduce operation, so if only some of the
returned tensors are evaluated then the computation will hang.

Args:
tensors: The input tensors across which to sum; must be assigned
to GPU devices.

Returns:
List of tensors, each with the sum of the input tensors, where tensor i has
the same device as `tensors[i]`.


Called at the beginning of prediction.

Subclasses should override for any actions to run.

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


def optimize_for_inference(input_graph_def: graph_pb2.GraphDef, input_node_names: Sequence[str], output_node_names: Sequence[str], placeholder_type_enum: int, toco_compatible: bool=False, placeholder_to_const_names=None) -> graph_pb2.GraphDef:
    ensure_graph_is_valid(input_graph_def)
    optimized_graph_def = input_graph_def
    optimized_graph_def = convert_placeholder_to_const(optimized_graph_def, placeholder_to_const_names)
    optimized_graph_def = strip_unused_lib.strip_unused(optimized_graph_def, input_node_names, output_node_names, placeholder_type_enum)
    optimized_graph_def = graph_util.remove_training_nodes(optimized_graph_def, output_node_names)
    optimized_graph_def = fuse_decomposed_batch_norm(optimized_graph_def)
    optimized_graph_def = fold_batch_norms(optimized_graph_def)
    if not toco_compatible:
        optimized_graph_def = fuse_resize_and_conv(optimized_graph_def, output_node_names)
    ensure_graph_is_valid(optimized_graph_def)
    return optimized_graph_def

Applies a series of inference optimizations on the input graph.

Args:
input_graph_def: A GraphDef containing a training model.
input_node_names: A list of names of the nodes that are fed inputs during
inference.
output_node_names: A list of names of the nodes that produce the final
results.
placeholder_type_enum: The AttrValue enum for the placeholder data type, or
a list that specifies one value per input node name.
toco_compatible: Boolean, if True, only runs optimizations that result in
TOCO compatible graph operations (default=False).
placeholder_to_const_names: A list of names of the PlaceholderWithDefault
nodes to be converted to Constant.

Returns:
An optimized version of the input graph.


def _normalize_mlengine_job_id(job_id):
    match = re.search('\\d|\\{{2}', job_id)
    if (match and (match.start() == 0)):
        job = 'z_{}'.format(job_id)
    else:
        job = job_id
    tracker = 0
    cleansed_job_id = ''
    for m in re.finditer('\\{{2}.+?\\}{2}', job):
        cleansed_job_id += re.sub('[^0-9a-zA-Z]+', '_', job[tracker:m.start()])
        cleansed_job_id += job[m.start():m.end()]
        tracker = m.end()
    cleansed_job_id += re.sub('[^0-9a-zA-Z]+', '_', job[tracker:])
    return cleansed_job_id

Replaces invalid MLEngine job_id characters with '_'.

This also adds a leading 'z' in case job_id starts with an invalid
character.

Args:
job_id: A job_id str that may have invalid characters.

Returns:
A valid job_id representation.


def get_array_from_hist2D(hist: Hist, set_zero_to_NaN: bool=True, return_bin_edges: bool=False) -> Tuple[(np.ndarray, np.ndarray, np.ndarray)]:
    shape = (hist.GetYaxis().GetNbins(), hist.GetXaxis().GetNbins())
    hist_array = np.array([hist.GetBinContent(x) for x in range(1, hist.GetNcells()) if ((not hist.IsBinUnderflow(x)) and (not hist.IsBinOverflow(x)))])
    hist_array = hist_array.reshape(shape)
    hist_array = hist_array.T
    if set_zero_to_NaN:
        hist_array[(hist_array == 0)] = np.nan
    if return_bin_edges:
        x_bin_edges = get_bin_edges_from_axis(hist.GetXaxis())
        y_bin_edges = get_bin_edges_from_axis(hist.GetYaxis())
        epsilon = 1e-09
        x_range = np.arange(np.amin(x_bin_edges), (np.amax(x_bin_edges) + epsilon), hist.GetXaxis().GetBinWidth(1))
        y_range = np.arange(np.amin(y_bin_edges), (np.amax(y_bin_edges) + epsilon), hist.GetYaxis().GetBinWidth(1))
    else:
        x_range = np.array([hist.GetXaxis().GetBinCenter(i) for i in range(1, (hist.GetXaxis().GetNbins() + 1))])
        y_range = np.array([hist.GetYaxis().GetBinCenter(i) for i in range(1, (hist.GetYaxis().GetNbins() + 1))])
    (X, Y) = np.meshgrid(x_range, y_range)
    return (X, Y, hist_array)

Extract x, y, and bin values from a 2D ROOT histogram.

Converts the histogram into a numpy array, and suitably processes it for a surface plot
by removing 0s (which can cause problems when taking logs), and returning a set of (x, y) mesh
values utilziing either the bin edges or bin centers.

Note:
This is a different format than the 1D version!

Args:
hist (ROOT.TH2): Histogram to be converted.
set_zero_to_NaN: If true, set 0 in the array to NaN. Useful with matplotlib so that it will
ignore the values when plotting. See comments in this function for more details. Default: True.
return_bin_edges: Return x and y using bin edges instead of bin centers.
Returns:
Contains (x values, y values, numpy array of hist data) where (x, y) are values on a
grid (from np.meshgrid) using the selected bin values.


def __init__(self, metagraph, ignore_colocation=True, ignore_user_placement=False):
    self._metagraph = metagraph
    self._item_graph = meta_graph_pb2.MetaGraphDef()
    self._item_graph.CopyFrom(metagraph)
    self._ignore_colocation = ignore_colocation
    self._ignore_user_placement = ignore_user_placement
    self._tf_item = None
    self._BuildTFItem()

Creates an Item.

Args:
metagraph: a TensorFlow metagraph.
ignore_colocation: if set, the tool will ignore all the colocation
constraints generated by TensorFlow.
ignore_user_placement: if set, all the placement annotations annotated in
the metagraph will be ignored.
Raises:
ValueError: the metagraph is incomplete or invalid.


def register(self, token, regexp):

        self._tokens.append((token, re.compile(regexp)))

Register a token.

Args:
token (Token): the token class to register
regexp (str): the regexp for that token


def __init__(self, value=None, length=0):

        super().__init__(value)
        self.length = length
        self._fmt = '!{}{}'.format(self.length, 's')

Create a Char with the optional parameters below.

Args:
value: The character to be build.
length (int): Character size.


def parse_vhdl_file(fname):

  with open(fname, 'rt') as fh:
    text = fh.read()
  return parse_vhdl(text)

Parse a named VHDL file

Args:
fname(str): Name of file to parse
Returns:
Parsed objects.


def heightmap_rain_erosion(hm: np.ndarray, nbDrops: int, erosionCoef: float, sedimentationCoef: float, rnd: Optional[tcod.random.Random]=None) -> None:
    lib.TCOD_heightmap_rain_erosion(_heightmap_cdata(hm), nbDrops, erosionCoef, sedimentationCoef, (rnd.random_c if rnd else ffi.NULL))

Simulate the effect of rain drops on the terrain, resulting in erosion.

``nbDrops`` should be at least hm.size.

Args:
hm (numpy.ndarray): A numpy.ndarray formatted for heightmap functions.
nbDrops (int): Number of rain drops to simulate.
erosionCoef (float): Amount of ground eroded on the drop's path.
sedimentationCoef (float): Amount of ground deposited when the drops
stops to flow.
rnd (Optional[Random]): A tcod.Random instance, or None.


def read_html_file(data_dir, fileroot, encoding=None):
    fname = os.path.join(data_dir, RAW_HTML_DIRNAME, (fileroot + RAW_HTML_EXT))
    encodings = ((encoding,) if encoding else ('utf-8', 'iso-8859-1'))
    for encoding in encodings:
        try:
            with io.open(fname, mode='rt', encoding=encoding) as f:
                raw_html = f.read()
            break
        except (UnicodeDecodeError, UnicodeError):
            raw_html = None
    return ftfy.fix_encoding(raw_html).strip()

Read the HTML file corresponding to identifier ``fileroot``
in the raw HTML directory below the root ``data_dir``.

Args:
data_dir (str)
fileroot (str)
encoding (str)

Returns:
str


def begin_scan(self, callback=None, interval=DEF_SCAN_INTERVAL, window=DEF_SCAN_WINDOW):
    logger.debug('configuring scan parameters')
    self.api.ble_cmd_gap_set_scan_parameters(interval, window, 1)
    self._set_state(self._STATE_CONFIGURE_SCAN)
    self.api.ble_cmd_gap_discover(1)
    self._wait_for_state(self._STATE_CONFIGURE_SCAN)
    logger.debug('starting async scan for devices')
    self.scan_targets = None
    self.scan_callback = callback
    self._set_state(self._STATE_SCANNING)
    return True

Begins a BLE scan and returns immediately.

Using this method you can begin a BLE scan and leave the dongle in scanning
mode in the background. It will remain in scanning mode until you call the
:meth:`end_scan` method or the :meth:`reset` method.

Args:
callback (callbable): a callback that will be called for each new device
discovered by the scanning process. Will be passed a single argument,
a :class:`ScanResult` object. May be None if not needed.
interval (int): BLE scan interval, in units of 625us
window (int): BLE scan window, in units of 625us

Returns:
True on success, False otherwise.


def split(input_file, file_1, file_2, no_in_first_file):

    with open(input_file) as f:
        feat_collection = geojson.load(f)

    features = feat_collection['features']
    feat_collection_1 = geojson.FeatureCollection(features[0:no_in_first_file])
    feat_collection_2 = geojson.FeatureCollection(features[no_in_first_file:])

    with open(file_1, 'w') as f:
        geojson.dump(feat_collection_1, f)

    with open(file_2, 'w') as f:
        geojson.dump(feat_collection_2, f)

Split a geojson in two separate files.

Args:
input_file (str): Input filename.
file_1 (str): Output file name 1.
file_2 (str): Output file name 2.
no_features (int): Number of features in input_file to go to file_1.
output_file (str): Output file name.


def find_backend(line: str) -> Optional[str]:
    if _re_test_backend.search(line) is None:
        return None
    backends = [b[0] for b in _re_backend.findall(line)]
    backends.sort()
    return '_and_'.join(backends)

Find one (or multiple) backend in a code line of the init.

Args:
line (`str`): A code line of the main init.

Returns:
Optional[`str`]: If one (or several) backend is found, returns it. In the case of multiple backends (the line
contains `if is_xxx_available() and `is_yyy_available()`) returns all backends joined on `_and_` (so
`xxx_and_yyy` for instance).


def dump(config):

    return yaml.safe_dump(
        config.to_primitive(),
        default_flow_style=False,
        encoding='utf-8',
        allow_unicode=True)

Dumps a stacker Config object as yaml.

Args:
config (:class:`Config`): the stacker Config object.
stream (stream): an optional stream object to write to.

Returns:
str: the yaml formatted stacker Config.


def read_nmr_efg_tensor(self):
    header_pattern = 'Electric field gradients \\(V/A\\^2\\)\\n-*\\n ion\\s+V_xx\\s+V_yy\\s+V_zz\\s+V_xy\\s+V_xz\\s+V_yz\\n-*\\n'
    row_pattern = '\\d+\\s+([-\\d\\.]+)\\s+([-\\d\\.]+)\\s+([-\\d\\.]+)\\s+([-\\d\\.]+)\\s+([-\\d\\.]+)\\s+([-\\d\\.]+)'
    footer_pattern = '-*\\n'
    data = self.read_table_pattern(header_pattern, row_pattern, footer_pattern, postprocess=float)
    tensors = [make_symmetric_matrix_from_upper_tri(d) for d in data]
    self.data['unsym_efg_tensor'] = tensors
    return tensors

Parses the NMR Electric Field Gradient Raw Tensors

Returns:
A list of Electric Field Gradient Tensors in the order of Atoms from OUTCAR


def copy(self, **override_parameters_kwargs):
    parameters = dict(self.parameters, **override_parameters_kwargs)
    return type(self)(**parameters)

Creates a deep copy of the distribution.

Note: the copy distribution may continue to depend on the original
initialization arguments.

Args:
**override_parameters_kwargs: String/value dictionary of initialization
arguments to override with new values.

Returns:
distribution: A new instance of `type(self)` initialized from the union
of self.parameters and override_parameters_kwargs, i.e.,
`dict(self.parameters, **override_parameters_kwargs)`.


def with_stack(cls, stack, severity, message, **kwargs):
    stack = _dedup_opcodes(stack) if stack else None
    opcode = stack[-1].current_opcode if stack else None
    if opcode is None:
        return cls(severity, message, **kwargs)
    else:
        return cls(severity, message, filename=opcode.code.filename, line=opcode.line, endline=opcode.endline, col=opcode.col, endcol=opcode.endcol, methodname=opcode.code.name, opcode_name=opcode.__class__.__name__, traceback=_make_traceback_str(stack), **kwargs)

Return an error using a stack for position information.

Args:
stack: A list of state.Frame or state.SimpleFrame objects.
severity: The error level (error or warning), an integer.
message: The error message string.
**kwargs: Additional keyword args to pass onto the class ctor.

Returns:
An Error object.


Element-wise exponential.

Args:
x: Tensor or variable.

Returns:
A tensor.


def _GetDateTime(self, filetime):

    if filetime == 0:
      return dfdatetime_semantic_time.SemanticTime('Not set')

    return dfdatetime_filetime.Filetime(timestamp=filetime)

Retrieves the date and time from a FILETIME timestamp.

Args:
filetime (int): FILETIME timestamp.

Returns:
dfdatetime.DateTimeValues: date and time.


def __init__(self, config_file=None, config_header=None):

    self.config_file = config_file or CONFIG
    self.config_header = config_header
    self.config = parser.Parser()
    self.config.read(self.config_file)

Constructor.

Args:
config_file: string, the location of the config file.
config_header: string, the message to write at the top of the config.


def GetEstimatedYear(self):
    if self._preferred_year:
        return self._preferred_year
    if self._knowledge_base.year:
        return self._knowledge_base.year
    year = self._GetEarliestYearFromFileEntry()
    if (not year):
        year = self._GetLatestYearFromFileEntry()
    if (not year):
        year = timelib.GetCurrentYear()
    return year

Retrieves an estimate of the year.

This function determines the year in the following manner:
* see if the user provided a preferred year;
* see if knowledge base defines a year e.g. derived from preprocessing;
* determine the year based on the file entry metadata;
* default to the current year;

Returns:
int: estimated year.


def divide_to_patches(image: np.array, patch_size: int, input_data_format) -> List[np.array]:
    patches = []
    height, width = get_image_size(image, channel_dim=input_data_format)
    for i in range(0, height, patch_size):
        for j in range(0, width, patch_size):
            if input_data_format == ChannelDimension.LAST:
                patch = image[i:i + patch_size, j:j + patch_size]
            else:
                patch = image[:, i:i + patch_size, j:j + patch_size]
            patches.append(patch)
    return patches

Divides an image into patches of a specified size.

Args:
image (`np.array`):
The input image.
patch_size (`int`):
The size of each patch.
input_data_format (`ChannelDimension` or `str`):
The channel dimension format of the input image.

Returns:
list: A list of np.array representing the patches.


def _GetActualMessage(self):
    if six.PY2:
        return self._actual.message
    return self._actual.args[0] if self._actual.args else ''

Returns the "message" portion of an exception.

Many Python 2 exceptions have a "message" attribute, so return that directly
in Python 2. However, this attribute is never present in Python 3, so return
the first argument passed to the exception instance as the message.

Returns:
String


def load_b26_file(file_name):

    assert os.path.exists(file_name)

    with open(file_name, 'r') as infile:
        data = yaml.safe_load(infile)
    return data

loads a .b26 file into a dictionary

Args:
file_name:

Returns: dictionary with keys instrument, scripts, probes


def append_from_list(self, content, fill_title=False):

        row_index = 0
        for row in content:
            tr = TableRow()
            column_index = 0
            for item in row:
                if row_index == 0 and fill_title:
                    ti = TableTitle(item)
                else:
                    ti = TableItem(item)
                tr.append(ti, str(column_index))
                column_index = column_index + 1
            self.append(tr, str(row_index))
            row_index = row_index + 1

Appends rows created from the data contained in the provided
list of tuples of strings. The first tuple of the list can be
set as table title.

Args:
content (list): list of tuples of strings. Each tuple is a row.
fill_title (bool): if true, the first tuple in the list will
be set as title.


def struct_member_error(err, sid, name, offset, size):
    (exception, msg) = STRUCT_ERROR_MAP[err]
    struct_name = idc.GetStrucName(sid)
    return exception('AddStructMember(struct="{}", member="{}", offset={}, size={}) failed: {}'.format(struct_name, name, offset, size, msg))

Create and format a struct member exception.

Args:
err: The error value returned from struct member creation
sid: The struct id
name: The member name
offset: Memeber offset
size: Member size

Returns:
A ``SarkErrorAddStructMemeberFailed`` derivative exception, with an
informative message.


def validate_language_key(obj, key):

    backend = bigchaindb.config['database']['backend']

    if backend == 'localmongodb':
        data = obj.get(key, {})
        if isinstance(data, dict):
            validate_all_values_for_key_in_obj(data, 'language', validate_language)
        elif isinstance(data, list):
            validate_all_values_for_key_in_list(data, 'language', validate_language)

Validate all nested "language" key in `obj`.

Args:
obj (dict): dictionary whose "language" key is to be validated.

Returns:
None: validation successful

Raises:
ValidationError: will raise exception in case language is not valid.


def split_input(cls, mapper_spec, _reader=blobstore.BlobReader):
    params = _get_params(mapper_spec)
    blob_key = params[cls.BLOB_KEY_PARAM]
    zip_input = zipfile.ZipFile(_reader(blob_key))
    zfiles = zip_input.infolist()
    total_size = sum((x.file_size for x in zfiles))
    num_shards = min(mapper_spec.shard_count, cls._MAX_SHARD_COUNT)
    size_per_shard = (total_size
    shard_start_indexes = [0]
    current_shard_size = 0
    for (i, fileinfo) in enumerate(zfiles):
        current_shard_size += fileinfo.file_size
        if (current_shard_size >= size_per_shard):
            shard_start_indexes.append((i + 1))
            current_shard_size = 0
    if (shard_start_indexes[(- 1)] != len(zfiles)):
        shard_start_indexes.append(len(zfiles))
    return [cls(blob_key, start_index, end_index, _reader) for (start_index, end_index) in zip(shard_start_indexes, shard_start_indexes[1:])]

Returns a list of input shard states for the input spec.

Args:
mapper_spec: The MapperSpec for this InputReader. Must contain
'blob_key' parameter with one blob key.
_reader: a callable that returns a file-like object for reading blobs.
Used for dependency injection.

Returns:
A list of InputReaders spanning files within the zip.


def to_cache_timer(datetime_func):

    if datetime_func is None:
        datetime_func = datetime.utcnow

    def _timer():

        return (datetime_func() - datetime(1970, 1, 1)).total_seconds()

    return _timer

Converts a datetime_func to a timestamp_func.

Args:
datetime_func (callable[[datatime]]): a func that returns the current
time

Returns:
time_func (callable[[timestamp]): a func that returns the timestamp
from the epoch


def c_overturned(step):

    rbot, rtop = misc.get_rbounds(step)
    cinit, rad = init_c_overturn(step)
    radf = (rtop**3 + rbot**3 - rad**3)**(1 / 3)
    return cinit, radf

Theoretical overturned concentration.

This compute the resulting composition profile if fractional
crystallization of a SMO is assumed and then a purely radial
overturn happens.

Args:
step (:class:`~stagpy.stagyydata._Step`): a step of a StagyyData
instance.
Returns:
tuple of :class:`numpy.array`: the composition and the radial position
at which it is evaluated.


def _add_result(self, dict_entry, entry, dt, start_time):
    time_entry = {}
    time_entry['dt'] = dt
    time_entry['start_time'] = start_time
    dict_entry[entry] = time_entry

Adds a result to the dictionary.

Args:
dict_entry: main dict to add entry
entry: slot for this entry (likely an integer)
dt: the timing for the entry
start_time: when the entry started unix time float


def _VerifyHandValues(self, tensor_in_sizes, filter_in_sizes, stride, padding, expected):
    total_size_1 = 1
    total_size_2 = 1
    for s in tensor_in_sizes:
        total_size_1 *= s
    for s in filter_in_sizes:
        total_size_2 *= s
    x1 = np.array([f * 1.0 for f in range(1, total_size_1 + 1)], dtype=np.float32).reshape(tensor_in_sizes)
    x2 = np.array([f * 1.0 for f in range(1, total_size_2 + 1)], dtype=np.float32).reshape(filter_in_sizes)
    with self.session() as sess:
        t1 = array_ops.placeholder(shape=tensor_in_sizes, dtype=np.float32)
        t2 = array_ops.placeholder(shape=filter_in_sizes, dtype=np.float32)
        with self.test_scope():
            conv = nn_ops.depthwise_conv2d_native(t1, t2, strides=[1, stride, stride, 1], padding=padding)
        value = sess.run(conv, {t1: x1, t2: x2})
    print('value = ', value)
    self.assertArrayNear(expected, np.ravel(value), 0.0001)
    self.assertShapeEqual(value, conv)

Verifies the output values of the depthwise convolution function.

Args:
tensor_in_sizes: Input tensor dimensions in
[batch, input_rows, input_cols, input_depth].
filter_in_sizes: Filter tensor dimensions in
[filter_rows, filter_cols, input_depth, depth_multiplier].
stride: Stride.
padding: Padding type.
expected: An array containing the expected operation outputs.


def get_all_instances(include_fastboot=False):
    if include_fastboot:
        serial_list = (list_adb_devices() + list_fastboot_devices())
        return get_instances(serial_list)
    return get_instances(list_adb_devices())

Create AndroidDevice instances for all attached android devices.

Args:
include_fastboot: Whether to include devices in bootloader mode or not.

Returns:
A list of AndroidDevice objects each representing an android device
attached to the computer.


def replace_in_list(stringlist: Iterable[str],
                    replacedict: Dict[str, str]) -> List[str]:

    newlist = []
    for fromstring in stringlist:
        newlist.append(multiple_replace(fromstring, replacedict))
    return newlist

Returns a list produced by applying :func:`multiple_replace` to every
string in ``stringlist``.

Args:
stringlist: list of source strings
replacedict: dictionary mapping "original" to "replacement" strings

Returns:
list of final strings


def _assert_rank_condition(x, rank, static_condition, dynamic_condition, data, summarize):
    assert_type(rank, dtypes.int32)
    rank_static = tensor_util.constant_value(rank)
    if rank_static is not None:
        if rank_static.ndim != 0:
            raise ValueError('Rank must be a scalar.')
        x_rank_static = x.get_shape().ndims
        if x_rank_static is not None:
            if not static_condition(x_rank_static, rank_static):
                raise ValueError('Static rank condition failed', x_rank_static, rank_static)
            return control_flow_ops.no_op(name='static_checks_determined_all_ok')
    condition = dynamic_condition(array_ops.rank(x), rank)
    if rank_static is None:
        this_data = ['Rank must be a scalar. Received rank: ', rank]
        rank_check = assert_rank(rank, 0, data=this_data)
        condition = control_flow_ops.with_dependencies([rank_check], condition)
    return control_flow_assert.Assert(condition, data, summarize=summarize)

Assert `x` has a rank that satisfies a given condition.

Args:
x:  Numeric `Tensor`.
rank:  Scalar `Tensor`.
static_condition:   A python function that takes `[actual_rank, given_rank]`
and returns `True` if the condition is satisfied, `False` otherwise.
dynamic_condition:  An `op` that takes [actual_rank, given_rank] and return
`True` if the condition is satisfied, `False` otherwise.
data:  The tensors to print out if the condition is false.  Defaults to
error message and first few entries of `x`.
summarize: Print this many entries of each tensor.

Returns:
Op raising `InvalidArgumentError` if `x` fails dynamic_condition.

Raises:
ValueError:  If static checks determine `x` fails static_condition.


def __init__(self, client, conv_states, user_list, sync_timestamp):
        self._client = client
        self._conv_dict = {}
        self._sync_timestamp = sync_timestamp
        self._user_list = user_list

        for conv_state in conv_states:
            self._add_conversation(conv_state.conversation, conv_state.event,
                                   conv_state.event_continuation_token)

        self._client.on_state_update.add_observer(self._on_state_update)
        self._client.on_connect.add_observer(self._sync)
        self._client.on_reconnect.add_observer(self._sync)

        self.on_event = event.Event('ConversationList.on_event')

        self.on_typing = event.Event('ConversationList.on_typing')

        self.on_watermark_notification = event.Event(
            'ConversationList.on_watermark_notification'
        )

:class:`.Event` fired when an event occurs in any conversation.

Args:
conv_event: :class:`ConversationEvent` that occurred.


def confirm(question):

    if FORCE_YES:
        return True

    while True:
        answer = input(question + ' <Yes|No>').lower()

        if answer == 'yes' or answer == 'y':
            confirmed = True
            break
        if answer == 'no' or answer == 'n':
            confirmed = False
            break

    return confirmed

Ask the user if he really want something to happen.

Args:
question(str): What can happen

Returns:
(boolean): Confirmed or not


def get_domain_workgroup():
    with salt.utils.winapi.Com():
        conn = wmi.WMI()
        for computer in conn.Win32_ComputerSystem():
            if computer.PartOfDomain:
                return {'Domain': computer.Domain}
            else:
                return {'Workgroup': computer.Workgroup}

Get the domain or workgroup the computer belongs to.

.. versionadded:: 2015.5.7
.. versionadded:: 2015.8.2

Returns:
str: The name of the domain or workgroup

CLI Example:

.. code-block:: bash

salt 'minion-id' system.get_domain_workgroup


def bilinearly_sampled_image(texture, uv):

    h, w = tf.unstack(tf.shape(texture)[:2])
    u, v = tf.split(uv, 2, axis=-1)
    v = 1.0 - v
    u, v = u * tf.to_float(w) - 0.5, v * tf.to_float(h) - 0.5
    u0, u1 = tf.floor(u), tf.ceil(u)
    v0, v1 = tf.floor(v), tf.ceil(v)
    uf, vf = u - u0, v - v0
    u0, u1, v0, v1 = map(tf.to_int32, [u0, u1, v0, v1])

    def sample(u, v):
        vu = tf.concat([v % h, u % w], axis=-1)
        return tf.gather_nd(texture, vu)

    s00, s01 = sample(u0, v0), sample(u0, v1)
    s10, s11 = sample(u1, v0), sample(u1, v1)
    s0 = s00 * (1.0 - vf) + s01 * vf
    s1 = s10 * (1.0 - vf) + s11 * vf
    s = s0 * (1.0 - uf) + s1 * uf
    return s

Build bilinear texture sampling graph.

Coordinate transformation rules match OpenGL GL_REPEAT wrapping and GL_LINEAR
interpolation modes.

Args:
texture: [tex_h, tex_w, channel_n] tensor.
uv: [frame_h, frame_h, 2] tensor with per-pixel UV coordinates in range [0..1]

Returns:
[frame_h, frame_h, channel_n] tensor with per-pixel sampled values.


def RunScripts(self, script_dict):
    metadata_types = ['%s-script-url', '%s-script']
    metadata_keys = [(key % self.script_type) for key in metadata_types]
    metadata_keys = [key for key in metadata_keys if script_dict.get(key)]
    if (not metadata_keys):
        self.logger.info('No %s scripts found in metadata.', self.script_type)
    for metadata_key in metadata_keys:
        metadata_script = script_dict.get(metadata_key)
        self._MakeExecutable(metadata_script)
        self._RunScript(metadata_key, metadata_script)

Run the metadata scripts; execute a URL script first if one is provided.

Args:
script_dict: a dictionary mapping metadata keys to script files.


def author_id_normalize_and_schema(uid, schema=None):

    def _get_uid_normalized_in_schema(_uid, _schema):
        (regex, template) = _RE_AUTHORS_UID[_schema]
        match = regex.match(_uid)
        if match:
            return template.format(match.group('uid'))
    if (idutils.is_orcid(uid) and (schema in (None, 'ORCID'))):
        return (idutils.normalize_orcid(uid), 'ORCID')
    if (schema and (schema not in _RE_AUTHORS_UID)):
        raise UnknownUIDSchema(uid)
    if schema:
        normalized_uid = _get_uid_normalized_in_schema(uid, schema)
        if normalized_uid:
            return (normalized_uid, schema)
        else:
            raise SchemaUIDConflict(schema, uid)
    (match_schema, normalized_uid) = (None, None)
    for candidate_schema in _RE_AUTHORS_UID:
        candidate_uid = _get_uid_normalized_in_schema(uid, candidate_schema)
        if candidate_uid:
            if match_schema:
                raise UnknownUIDSchema(uid)
            match_schema = candidate_schema
            normalized_uid = candidate_uid
    if match_schema:
        return (normalized_uid, match_schema)
    raise UnknownUIDSchema(uid)

Detect and normalize an author UID schema.

Args:
uid (string): a UID string
schema (string): try to resolve to schema

Returns:
Tuple[string, string]: a tuple (uid, schema) where:
- uid: the UID normalized to comply with the id.json schema
- schema: a schema of the UID or *None* if not recognised

Raise:
UnknownUIDSchema: if UID is too little to definitively guess the schema
SchemaUIDConflict: if specified schema is not matching the given UID


def load_configuration(yaml: yaml.ruamel.yaml.YAML, filename: str) -> DictLike:
    with open(filename, 'r') as f:
        config = yaml.load(f)
    return config

Load an analysis configuration from a file.

Args:
yaml: YAML object to use in loading the configuration.
filename: Filename of the YAML configuration file.
Returns:
dict-like object containing the loaded configuration


def is_within_strict_int_range(lower_bound: int, upper_bound: int) -> RuleChecker[Numeric]:

    def _checker(value: Numeric) -> RuleOutput:
        if lower_bound < value < upper_bound:
            return None
        else:
            return 'Value is not within the strict range.'
    return _checker

Checks if the provided numeric value IS strictly bounded by integers
i.e. (lower_bound, upper_bound) with both bounds exclusive.

Args:
* lower_bound: lowest integer value (exclusive)
* upper_bound: highest integer value (exclusive)

Returns:
* None: if lower_bound < value < upper_bound
* Error message, otherwise


def get_client_kwargs(self, path):

        container, obj = self.split_locator(path)
        kwargs = dict(container=container)
        if obj:
            kwargs['obj'] = obj
        return kwargs

Get base keyword arguments for client for a
specific path.

Args:
path (str): Absolute path or URL.

Returns:
dict: client args


def _ip_unnumbered_type(self, **kwargs):

        method_name = 'interface_%s_ip_ip_config_unnumbered_ip_donor_'\
            'interface_type' % kwargs['int_type']
        ip_unnumbered_type = getattr(self._interface, method_name)
        config = ip_unnumbered_type(**kwargs)
        if kwargs['delete']:
            tag = 'ip-donor-interface-type'
            config.find('.
        return config

Return the `ip unnumbered` donor type XML.

You should not use this method.
You probably want `Interface.ip_unnumbered`.

Args:
int_type (str): Type of interface. (gigabitethernet,
tengigabitethernet etc).
delete (bool): Remove the configuration if ``True``.
ip_donor_interface_type (str): The donor interface type (loopback)

Returns:
XML to be passed to the switch.

Raises:
None


def is_native_ion_gate(gate: ops.Gate) -> bool:
    return isinstance(gate, (ops.XXPowGate, ops.MeasurementGate, ops.XPowGate, ops.YPowGate, ops.ZPowGate))

Check if a gate is a native ion gate.

Args:
gate: Input gate.

Returns:
True if the gate is native to the ion, false otherwise.


def log_estimator_evaluation_result(self, eval_results):
    if (not isinstance(eval_results, dict)):
        tf.logging.warning('eval_results should be directory for logging. Got %s', type(eval_results))
        return
    global_step = eval_results[tf.GraphKeys.GLOBAL_STEP]
    for key in sorted(eval_results):
        if (key != tf.GraphKeys.GLOBAL_STEP):
            self.log_metric(key, eval_results[key], global_step=global_step)

Log the evaluation result for a estimator.

The evaluate result is a directory that contains metrics defined in
model_fn. It also contains a entry for global_step which contains the value
of the global step when evaluation was performed.

Args:
eval_results: dict, the result of evaluate() from a estimator.


def dawsn(x, name=None):
    with ops.name_scope(name, 'dawsn', [x]):
        return gen_special_math_ops.dawsn(x)

Computes Dawson's integral of `x` element-wise.

Dawson's integral is defined as `exp(-x**2)` times the integral of
`exp(t**2)` from `0` to `x`, with the domain of definition all real numbers.

Dawson's function is odd.
>>> tf.math.special.dawsn([-1., -0.5, 0.5, 1.]).numpy()
array([-0.5380795, -0.4244364, 0.4244364,  0.5380795], dtype=float32)

This implementation is based off of the Cephes math library.

Args:
x: A `Tensor` or `SparseTensor`. Must be one of the following types:
`float32`, `float64`.
name: A name for the operation (optional).

Returns:
A `Tensor` or `SparseTensor`, respectively. Has the same type as `x`.

@compatibility(scipy)
Equivalent to scipy.special.dawsn
@end_compatibility


def tag_file(filename, artist, title, year=None, genre=None, artwork_url=None, album=None, track_number=None, url=None):

    try:
        audio = EasyMP3(filename)
        audio.tags = None
        audio["artist"] = artist
        audio["title"] = title
        if year:
            audio["date"] = str(year)
        if album:
            audio["album"] = album
        if track_number:
            audio["tracknumber"] = track_number
        if genre:
            audio["genre"] = genre
        if url:
            audio["website"] = url
        audio.save()

        if artwork_url:

            artwork_url = artwork_url.replace('https', 'http')

            mime = 'image/jpeg'
            if '.jpg' in artwork_url:
                mime = 'image/jpeg'
            if '.png' in artwork_url:
                mime = 'image/png'

            if '-large' in artwork_url:
                new_artwork_url = artwork_url.replace('-large', '-t500x500')
                try:
                    image_data = requests.get(new_artwork_url).content
                except Exception as e:

                    image_data = requests.get(artwork_url).content
            else:
                image_data = requests.get(artwork_url).content

            audio = MP3(filename, ID3=OldID3)
            audio.tags.add(
                APIC(
                    encoding=3,
                    mime=mime,
                    type=3,
                    desc='Cover',
                    data=image_data
                )
            )
            audio.save()

        if url:
            audio = MP3(filename, ID3=OldID3)
            audio.tags.add( WXXX( encoding=3, url=url ) )
            audio.save()

        return True

    except Exception as e:
        puts(colored.red("Problem tagging file: ") + colored.white("Is this file a WAV?"))
        return False

Attempt to put ID3 tags on a file.

Args:
artist (str):
title (str):
year (int):
genre (str):
artwork_url (str):
album (str):
track_number (str):
filename (str):
url (str):


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

        linebreak = kwargs.pop("linebreak", "\n")

        if len(args) > 0:
            self.args = args
        self._update(**kwargs)

        fkwargs = {}
        modtmpl = []

        for line in self:
            cline = copy(line)

            for match in self._regex.findall(line):
                search = "[{}]".format("|".join(match))
                name, indent, delim, qual, _ = match
                if indent != "":
                    indent = " "*int(indent)
                delim = delim.replace("\\|", "|")

                data = getattr(self, name, None)

                if data is None:
                    cline = cline.replace(search, "")
                    continue
                elif delim.isdigit():
                    fkwargs[name] = getattr(self, "_fmt_"+name)()
                else:
                    fkwargs[name] = linebreak.join([indent+k+delim+qual+v+qual for k, v in data.items()])
                cline = cline.replace(search, "{"+name+"}")
            modtmpl.append(cline)
        modtmpl = "\n".join(modtmpl)
        print(modtmpl)
        dct = self.get_kwargs()
        dct.update(fkwargs)
        return self._constructor(textobj=modtmpl.format(*self.args, **dct))

Generate a file from the current template and given arguments.

Warning:
Make certain to check the formatted editor for correctness!

Args:
args: Positional arguments to update the template
kwargs: Keyword arguments to update the template

Returns:
editor: An editor containing the formatted template.


def _AlignUncompressedDataOffset(self, uncompressed_data_offset):

    if self._zip_ext_file:
      self._zip_ext_file.close()
      self._zip_ext_file = None

    try:

      self._zip_ext_file = self._zip_file.open(self._zip_info, 'r')
    except zipfile.BadZipfile as exception:
      raise IOError(
          'Unable to open ZIP file with error: {0!s}'.format(exception))

    self._uncompressed_data = b''
    self._uncompressed_data_size = 0
    self._uncompressed_data_offset = 0

    while uncompressed_data_offset > 0:
      self._ReadCompressedData(self._UNCOMPRESSED_DATA_BUFFER_SIZE)

      if uncompressed_data_offset < self._uncompressed_data_size:
        self._uncompressed_data_offset = uncompressed_data_offset
        break

      uncompressed_data_offset -= self._uncompressed_data_size

Aligns the compressed file with the uncompressed data offset.

Args:
uncompressed_data_offset (int): uncompressed data offset.

Raises:
IOError: if the ZIP file could not be opened.
OSError: if the ZIP file could not be opened.


def _ParseLogline(self, parser_mediator, structure):

    month, day_of_month, year, hours, minutes, seconds, milliseconds = (
        structure.date_time)

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

    try:
      date_time = dfdatetime_time_elements.TimeElementsInMilliseconds(
          time_elements_tuple=time_elements_tuple)
    except ValueError:
      parser_mediator.ProduceExtractionWarning(
          'invalid date time value: {0!s}'.format(structure.date_time))
      return

    event_data = SkyDriveOldLogEventData()
    event_data.log_level = structure.log_level
    event_data.offset = self.offset
    event_data.source_code = structure.source_code
    event_data.text = structure.text

    event = time_events.DateTimeValuesEvent(
        date_time, definitions.TIME_DESCRIPTION_ADDED)
    parser_mediator.ProduceEventWithEventData(event, event_data)

    self._last_date_time = date_time
    self._last_event_data = event_data

Parse a logline and store appropriate attributes.

Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
structure (pyparsing.ParseResults): structure of tokens derived from
a line of a text file.


def _decode_linear_biases(linear_string, nodelist):
    linear_bytes = base64.b64decode(linear_string)
    return dict(zip(nodelist, struct.unpack(('<' + ('d' * (len(linear_bytes)

Inverse of _serialize_linear_biases.

Args:
linear_string (str): base 64 encoded string of little endian
8 byte floats, one for each of the nodes in nodelist.
nodelist (list): list of the form [node1, node2, ...].

Returns:
dict: linear biases in a dict.

Examples:
>>> _decode_linear_biases('AAAAAAAA8L8AAAAAAADwPwAAAAAAAAAA', [1, 2, 3])
{1: -1.0, 2: 1.0, 3: 0.0}
>>> _decode_linear_biases('AAAAAAAA8L8AAAAAAADwPwAAAAAAAAAA', [3, 2, 1])
{1: 0.0, 2: 1.0, 3: -1.0}


def connect(self, address) -> bytes:
    stdout = self._exec_adb_cmd('connect', address, shell=False, timeout=None, stderr=None)
    if PATTERN_ADB_CONNECT_SUCCESS.match(stdout.decode('utf-8')) is None:
        raise AdbError(cmd=f'connect {address}', stdout=stdout, stderr='', ret_code=0)
    return stdout

Executes the `adb connect` command with proper status checking.

Args:
address: string, the address of the Android instance to connect to.

Returns:
The stdout content.

Raises:
AdbError: if the connection failed.


def getGridByCard(self, gssha_card_name):
    with tmp_chdir(self.project_directory):
        if (gssha_card_name not in (self.INPUT_MAPS + self.WMS_DATASETS)):
            raise ValueError('Card {0} not found in valid grid cards ...'.format(gssha_card_name))
        gssha_grid_card = self.getCard(gssha_card_name)
        if (gssha_grid_card is None):
            raise ValueError('{0} card not found ...'.format(gssha_card_name))
        gssha_pro_card = self.getCard('
        if (gssha_pro_card is None):
            raise ValueError('
        return GDALGrid(gssha_grid_card.value.strip('"').strip("'"), gssha_pro_card.value.strip('"').strip("'"))

Returns GDALGrid object of GSSHA grid

Paramters:
gssha_card_name(str): Name of GSSHA project card for grid.

Returns:
GDALGrid


def parse_from_xml(root):

    if root.tag != 'ubcpi':
        raise UpdateFromXmlError(_('Every peer instruction tool must contain an "ubcpi" element.'))

    display_name_el = root.find('display_name')
    if display_name_el is None:
        raise UpdateFromXmlError(_('Every peer instruction tool must contain a "display_name" element.'))
    else:
        display_name = _safe_get_text(display_name_el)

    rationale_size_min = int(root.attrib['rationale_size_min']) if 'rationale_size_min' in root.attrib else None
    rationale_size_max = int(root.attrib['rationale_size_max']) if 'rationale_size_max' in root.attrib else None

    question_el = root.find('question')
    if question_el is None:
        raise UpdateFromXmlError(_('Every peer instruction must tool contain a "question" element.'))
    else:
        question = parse_question_xml(question_el)

    options_el = root.find('options')
    if options_el is None:
        raise UpdateFromXmlError(_('Every peer instruction must tool contain a "options" element.'))
    else:
        options, correct_answer, correct_rationale = parse_options_xml(options_el)

    seeds_el = root.find('seeds')
    if seeds_el is None:
        raise UpdateFromXmlError(_('Every peer instruction must tool contain a "seeds" element.'))
    else:
        seeds = parse_seeds_xml(seeds_el)

    algo = unicode(root.attrib['algorithm']) if 'algorithm' in root.attrib else None
    num_responses = unicode(root.attrib['num_responses']) if 'num_responses' in root.attrib else None

    return {
        'display_name': display_name,
        'question_text': question,
        'options': options,
        'rationale_size': {'min': rationale_size_min, 'max': rationale_size_max},
        'correct_answer': correct_answer,
        'correct_rationale': correct_rationale,
        'seeds': seeds,
        'algo': {"name": algo, 'num_responses': num_responses}
    }

Update the UBCPI XBlock's content from an XML definition.

We need to be strict about the XML we accept, to avoid setting
the XBlock to an invalid state (which will then be persisted).

Args:
root (lxml.etree.Element): The XML definition of the XBlock's content.

Returns:
A dictionary of all of the XBlock's content.

Raises:
UpdateFromXmlError: The XML definition is invalid


def learn(self, features, labels):

        labels = np.ravel(labels)
        self.__learn_labels(labels)
        if len(labels) == 0:
            return

        labels = self.labels.transform(labels)
        if self.feature_length > 0 and hasattr(self.clf, 'partial_fit'):

            self.clf = self.clf.partial_fit(features, labels)
        else:
            self.clf = self.clf.fit(features, labels)
            self.feature_length = len(features[0])

Fits the classifier

If it's state is empty, the classifier is fitted, if not
the classifier is partially fitted.
See sklearn's SGDClassifier fit and partial_fit methods.

Args:
features (:obj:`list` of :obj:`list` of :obj:`float`)
labels (:obj:`list` of :obj:`str`): Labels for each set of features.
New features are learnt.


def get_type_key(self, seen: set['BaseValue'] | None=None):
    return self.get_default_type_key()

Build a key from the information used to perform type matching.

Get a hashable object containing this value's type information. Type keys
are only compared amongst themselves, so we don't care what the internals
look like, only that values with different types *always* have different
type keys and values with the same type preferably have the same type key.

Args:
seen: The set of values seen before while computing the type key.

Returns:
A hashable object built from this value's type information.


def get_stored_metadata(self, temp_ver):

        with open(self._prefixed('%s.metadata' % temp_ver.name)) as f:
            return json.load(f)

Retrieves the metadata for the given template version from the store

Args:
temp_ver (TemplateVersion): template version to retrieve the
metadata for

Returns:
dict: the metadata of the given template version


def loss(logits, labels):
    labels = tf.cast(labels, tf.int64)
    cross_entropy = tf.nn.sparse_softmax_cross_entropy_with_logits(labels=labels, logits=logits, name='cross_entropy_per_example')
    cross_entropy_mean = tf.reduce_mean(cross_entropy, name='cross_entropy')
    tf.add_to_collection('losses', cross_entropy_mean)
    return tf.add_n(tf.get_collection('losses'), name='total_loss')

Add L2Loss to all the trainable variables.

Add summary for "Loss" and "Loss/avg".
Args:
logits: Logits from inference().
labels: Labels from distorted_inputs or inputs(). 1-D tensor
of shape [batch_size]

Returns:
Loss tensor of type float.


def DeregisterDefinition(self, artifact_definition):

    artifact_definition_name = artifact_definition.name.lower()
    if artifact_definition_name not in self._artifact_definitions:
      raise KeyError(
          'Artifact definition not set for name: {0:s}.'.format(
              artifact_definition.name))

    del self._artifact_definitions[artifact_definition_name]

Deregisters an artifact definition.

Artifact definitions are identified based on their lower case name.

Args:
artifact_definition (ArtifactDefinition): an artifact definition.

Raises:
KeyError: if an artifact definition is not set for the corresponding name.


def cost(self, logits, target):
    logits = tf.reshape(logits, [(self._num_steps * self._batch_size), (- 1)])
    target = tf.reshape(target, [(self._num_steps * self._batch_size), (- 1)])
    xent = tf.nn.softmax_cross_entropy_with_logits(logits=logits, labels=target)
    loss = tf.reduce_sum(xent)
    return (loss / self._batch_size)

Returns cost.

Args:
logits: model output.
target: target.

Returns:
Cross-entropy loss for a sequence of logits. The loss will be averaged
across time steps if time_average_cost was enabled at construction time.


def trace(self, predicate):

        self._handler = predicate
        if self.threading_support is None or self.threading_support:
            self._threading_previous = getattr(threading, '_trace_hook', None)
            threading.settrace(self)
        self._previous = sys.gettrace()
        sys.settrace(self)
        return self

Starts tracing with the given callable.

Args:
predicate (callable that accepts a single :obj:`hunter.Event` argument):
Return:
self


def get_dataclass(self, json_dataclass: type[T]) -> T:
    if not mime_types.is_dataclass(self.mimetype):
        raise ValueError('Part is not a dataclass.')
    try:
        return json_dataclass.from_json(self.text)
    except AttributeError as e:
        raise ValueError(f'{json_dataclass.__name__} is not a valid json dataclass') from e

Returns representation of the Part as a given dataclass.

Args:
json_dataclass: A dataclass that can be converted to/from JSON.

Returns:
The dataclass representation of the Part.


def ProcessFile(filename, vlevel, extra_check_functions=None):
    _SetVerboseLevel(vlevel)
    _BackupFilters()
    if (not ProcessConfigOverrides(filename)):
        _RestoreFilters()
        return
    lf_lines = []
    crlf_lines = []
    try:
        if (filename == '-'):
            lines = codecs.StreamReaderWriter(sys.stdin, codecs.getreader('utf8'), codecs.getwriter('utf8'), 'replace').read().split('\n')
        else:
            lines = codecs.open(filename, 'r', 'utf8', 'replace').read().split('\n')
        for linenum in range((len(lines) - 1)):
            if lines[linenum].endswith('\r'):
                lines[linenum] = lines[linenum].rstrip('\r')
                crlf_lines.append((linenum + 1))
            else:
                lf_lines.append((linenum + 1))
    except IOError:
        _cpplint_state.PrintError(("Skipping input '%s': Can't open for reading\n" % filename))
        _RestoreFilters()
        return
    file_extension = filename[(filename.rfind('.') + 1):]
    if ((filename != '-') and (file_extension not in GetAllExtensions())):
        bazel_gen_files = set(['external/local_config_cc/libtool', 'external/local_config_cc/make_hashed_objlist.py', 'external/local_config_cc/wrapped_ar', 'external/local_config_cc/wrapped_clang', 'external/local_config_cc/xcrunwrapper.sh'])
        if (not (filename in bazel_gen_files)):
            _cpplint_state.PrintError(('Ignoring %s; not a valid file name (%s)\n' % (filename, ', '.join(GetAllExtensions()))))
    else:
        ProcessFileData(filename, file_extension, lines, Error, extra_check_functions)
        if (lf_lines and crlf_lines):
            for linenum in crlf_lines:
                Error(filename, linenum, 'whitespace/newline', 1, 'Unexpected \\r (^M) found; better to use only \\n')
    _RestoreFilters()

Does google-lint on a single file.

Args:
filename: The name of the file to parse.

vlevel: The level of errors to report.  Every error of confidence
>= verbose_level will be reported.  0 is a good default.

extra_check_functions: An array of additional check functions that will be
run on each source line. Each function takes 4
arguments: filename, clean_lines, line, error


def visit_indexer(self, indexer: _evaluation.IndexerNode) -> _sql_data_types.Select:
    collection_result = self.visit(indexer.collection)
    index_result = self.visit(indexer.index)
    indexed_collection = f'SELECT ROW_NUMBER() OVER() AS row_,\n{collection_result.sql_alias}\nFROM {collection_result.to_subquery()}'
    sql_alias = f'indexed_{collection_result.sql_alias}'
    return _sql_data_types.Select(select_part=_sql_data_types.Identifier(collection_result.sql_alias, collection_result.sql_data_type, _sql_alias=sql_alias), from_part=f'({indexed_collection}) AS inner_tbl', where_part=f'(inner_tbl.row_ - 1) = {index_result.as_operand()}')

Translates a FHIRPath indexer expression to Standard SQL.

Args:
indexer: The `_Indexer` Expression node.

Returns:
A compiled Standard SQL expression.


def solve(ast, builtins_pytd, protocols_pytd):
    builtins_pytd = transforms.RemoveMutableParameters(builtins_pytd)
    builtins_pytd = visitors.LookupClasses(builtins_pytd)
    protocols_pytd = visitors.LookupClasses(protocols_pytd)
    ast = visitors.LookupClasses(ast, builtins_pytd)
    return (TypeSolver(ast, builtins_pytd, protocols_pytd).solve(), extract_local(ast))

Solve the unknowns in a pytd AST using the standard Python builtins.

Args:
ast: A pytd.TypeDeclUnit, containing classes named ~unknownXX.
builtins_pytd: A pytd for builtins.
protocols_pytd: A pytd for protocols.

Returns:
A tuple of (1) a dictionary (str->str) mapping unknown class names to known
class names and (2) a pytd.TypeDeclUnit of the complete classes in ast.


def generate_sentence(self, chain):

    def weighted_choice(choices):
        total_weight = sum((weight for (val, weight) in choices))
        rand = random.uniform(0, total_weight)
        upto = 0
        for (val, weight) in choices:
            if ((upto + weight) >= rand):
                return val
            upto += weight
    sentence = list(random.choice(chain.startwords))
    while (not (sentence[(- 1)][(- 1)] in ['.', '?', '!'])):
        sentence.append(weighted_choice(chain.content[tuple(sentence[(- 2):])].items()))
    return ' '.join(sentence)

!DEMO!
Demo function that shows how to generate a simple sentence starting with
uppercase letter without lenght limit.

Args:
chain: MarkovChain that will be used to generate sentence


def process_event(self, event_name: str, data: dict):

        if (isinstance(self.opt.get("learning_rate", None), float) and
                isinstance(self.opt.get("learning_rate_decay", None), float)):
            pass
        else:
            if event_name == 'after_train_log':
                if (self.get_learning_rate_variable() is not None) and ('learning_rate' not in data):
                    data['learning_rate'] = float(K.get_value(self.get_learning_rate_variable()))

                if (self.get_momentum_variable() is not None) and ('momentum' not in data):
                    data['momentum'] = float(K.get_value(self.get_momentum_variable()))

            else:
                super().process_event(event_name, data)

Process event after epoch
Args:
event_name: whether event is send after epoch or batch.
Set of values: ``"after_epoch", "after_batch"``
data: event data (dictionary)

Returns:
None


def from_filenames(poscar_filenames, transformations=None, extend_collection=False):
    tstructs = []
    for filename in poscar_filenames:
        with open(filename, 'r') as f:
            tstructs.append(TransformedStructure.from_poscar_string(f.read(), []))
    return StandardTransmuter(tstructs, transformations, extend_collection=extend_collection)

Convenient constructor to generates a POSCAR transmuter from a list of
POSCAR filenames.

Args:
poscar_filenames: List of POSCAR filenames
transformations: New transformations to be applied to all
structures.
extend_collection:
Same meaning as in __init__.


def export(self, top=True):

        out = []
        if top:
            out.append(self._internal_name)
        out.append(self._to_str(self.number_of_records_per_hour))
        out.append(self._to_str(self.data_period_name_or_description))
        out.append(self._to_str(self.data_period_start_day_of_week))
        out.append(self._to_str(self.data_period_start_day))
        out.append(self._to_str(self.data_period_end_day))
        return ",".join(out)

Exports object to its string representation.

Args:
top (bool):  if True appends `internal_name` before values.
All non list objects should be exported with value top=True,
all list objects, that are embedded in as fields inlist objects
should be exported with `top`=False

Returns:
str: The objects string representation


def _consume_line(line_info, state):
    _update_section_state(line_info, state)
    if state.section.title is None:
        if state.summary.permitted:
            if line_info.remaining:
                state.summary.lines.append(line_info.remaining)
            elif state.summary.lines:
                state.summary.permitted = False
        else:
            state.description.lines.append(line_info.remaining_raw)
    else:
        state.summary.permitted = False
    if state.section.new and state.section.format == Formats.RST:
        directive = _get_directive(line_info)
        directive_tokens = directive.split()
        if state.section.title == Sections.ARGS:
            name = directive_tokens[-1]
            arg = _get_or_create_arg_by_name(state, name, is_kwarg=directive_tokens[0] == 'key')
            if len(directive_tokens) == 3:
                arg.type.lines.append(directive_tokens[1])
            state.current_arg = arg
        elif state.section.title == Sections.TYPE:
            name = directive_tokens[-1]
            arg = _get_or_create_arg_by_name(state, name)
            state.current_arg = arg
    if state.section.format == Formats.NUMPY and _line_is_hyphens(line_info.remaining):
        return
    if state.section.title == Sections.ARGS:
        if state.section.format == Formats.GOOGLE:
            _consume_google_args_line(line_info, state)
        elif state.section.format == Formats.RST:
            state.current_arg.description.lines.append(line_info.remaining.strip())
        elif state.section.format == Formats.NUMPY:
            line_stripped = line_info.remaining.strip()
            if _is_arg_name(line_stripped):
                arg = _get_or_create_arg_by_name(state, line_stripped)
                state.current_arg = arg
            elif _line_is_numpy_parameter_type(line_info):
                possible_args, type_data = line_stripped.split(':', 1)
                arg_names = _as_arg_names(possible_args)
                if arg_names:
                    for arg_name in arg_names:
                        arg = _get_or_create_arg_by_name(state, arg_name)
                        arg.type.lines.append(type_data)
                        state.current_arg = arg
                elif state.current_arg:
                    state.current_arg.description.lines.append(line_info.remaining.strip())
                else:
                    pass
            elif state.current_arg:
                state.current_arg.description.lines.append(line_info.remaining.strip())
            else:
                pass
    elif state.section.title == Sections.RETURNS:
        state.returns.lines.append(line_info.remaining.strip())
    elif state.section.title == Sections.YIELDS:
        state.yields.lines.append(line_info.remaining.strip())
    elif state.section.title == Sections.RAISES:
        state.raises.lines.append(line_info.remaining.strip())
    elif state.section.title == Sections.TYPE:
        if state.section.format == Formats.RST:
            assert state.current_arg is not None
            state.current_arg.type.lines.append(line_info.remaining.strip())
        else:
            pass

Consumes one line of text, updating the state accordingly.

When _consume_line is called, part of the line may already have been processed
for header information.

Args:
line_info: Information about the current and next line of the docstring.
state: The state of the docstring parser.


def output_waiting(self):
    buf = array.array('I', [0])
    try:
        fcntl.ioctl(self._fd, termios.TIOCOUTQ, buf, True)
    except OSError as e:
        raise SerialError(e.errno, ('Querying output waiting: ' + e.strerror))
    return buf[0]

Query the number of bytes waiting to be written to the serial port.

Returns:
int: number of bytes waiting to be written.

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


async def get_headline(self, name):

        resp = await self.send_command(OPERATIONS.CMD_QUERY_HEADLINE, {'name': name},
                                       MESSAGES.QueryHeadlineResponse, timeout=5.0)

        if resp is not None:
            resp = states.ServiceMessage.FromDictionary(resp)

        return resp

Get stored messages for a service.

Args:
name (string): The name of the service to get messages from.

Returns:
ServiceMessage: the headline or None if no headline has been set


def update_metadata(self, resource, keys_vals):

        self.metadata_service.set_auth(self._token_metadata)
        self.metadata_service.update(resource, keys_vals)

Updates key-value pairs with the given resource.

Will attempt to update all key-value pairs even if some fail.
Keys must already exist.

Args:
resource (intern.resource.boss.BossResource)
keys_vals (dictionary): Collection of key-value pairs to update on
the given resource.

Raises:
HTTPErrorList on failure.


def __init__(self, storage_writer, knowledge_base, data_location=None):

    super(AnalysisMediator, self).__init__()
    self._abort = False
    self._data_location = data_location
    self._event_filter_expression = None
    self._knowledge_base = knowledge_base
    self._mount_path = None
    self._storage_writer = storage_writer
    self._text_prepend = None

    self.last_activity_timestamp = 0.0
    self.number_of_produced_analysis_reports = 0
    self.number_of_produced_event_tags = 0

Initializes an analysis plugin mediator.

Args:
storage_writer (StorageWriter): storage writer.
knowledge_base (KnowledgeBase): contains information from the source
data needed for analysis.
data_location (Optional[str]): location of data files used during
analysis.


def make_tensor_model_fn(model_fn: str) -> TensorInferenceFn:

    def attr_fn(batch: Sequence[torch.Tensor], model: torch.nn.Module, device: str, inference_args: Optional[dict[str, Any]]=None, model_id: Optional[str]=None) -> Iterable[PredictionResult]:
        with torch.no_grad():
            batched_tensors = torch.stack(batch)
            batched_tensors = _convert_to_device(batched_tensors, device)
            pred_fn = getattr(model, model_fn)
            predictions = pred_fn(batched_tensors, **inference_args)
            return utils._convert_to_result(batch, predictions, model_id)
    return attr_fn

Produces a TensorInferenceFn that uses a method of the model other that
the forward() method.

Args:
model_fn: A string name of the method to be used. This is accessed through
getattr(model, model_fn)


def install_exception_handler(handler):

  if not isinstance(handler, ExceptionHandler):
    raise TypeError('handler of type %s does not inherit from ExceptionHandler'
                    % type(handler))
  EXCEPTION_HANDLERS.append(handler)

Installs an exception handler.

Args:
handler: ExceptionHandler, the exception handler to install.

Raises:
TypeError: Raised when the handler was not of the correct type.

All installed exception handlers will be called if main() exits via
an abnormal exception, i.e. not one of SystemExit, KeyboardInterrupt,
FlagsError or UsageError.


def _get_context_id(self, context):
    if context in self._context_to_id:
        return self._context_to_id[context]
    graph_is_new = False
    with self._context_lock:
        if context not in self._context_to_id:
            graph_is_new = True
            context_id = _get_id()
            self._context_to_id[context] = context_id
    if graph_is_new:
        self.get_writer().WriteDebuggedGraph(debug_event_pb2.DebuggedGraph(graph_id=context_id, graph_name=getattr(context, 'name', None), outer_context_id=self._get_outer_context_id(context)))
    return self._context_to_id[context]

Get a unique ID for an op-construction context (e.g., a graph).

If the graph has been encountered before, reuse the same unique ID.
When encountering a new context (graph), this methods writes a DebugEvent
proto with the debugged_graph field to the proper DebugEvent file.

Args:
context: A context to get the unique ID for. Must be hashable. E.g., a
Graph object.

Returns:
A unique ID for the context.


def _process_using_meta_feature_generator(self, X, meta_feature_generator):

        all_learner_meta_features = []
        for idx, base_learner in enumerate(self.base_learners):
            single_learner_meta_features = getattr(base_learner,
                                                   self.meta_feature_generators[idx])(X)

            if len(single_learner_meta_features.shape) == 1:
                single_learner_meta_features = single_learner_meta_features.reshape(-1, 1)
            all_learner_meta_features.append(single_learner_meta_features)

        all_learner_meta_features = np.concatenate(all_learner_meta_features, axis=1)

        out = getattr(self.secondary_learner, meta_feature_generator)(all_learner_meta_features)

        return out

Process using secondary learner meta-feature generator

Since secondary learner meta-feature generator can be anything e.g. predict, predict_proba,
this internal method gives the ability to use any string. Just make sure secondary learner
has the method.

Args:
X (array-like): Features array

meta_feature_generator (str, unicode): Method for use by secondary learner


def retry_target(target, predicate, sleep_generator, deadline, on_error=None):
    if (deadline is not None):
        deadline_datetime = (datetime_helpers.utcnow() + datetime.timedelta(seconds=deadline))
    else:
        deadline_datetime = None
    last_exc = None
    for sleep in sleep_generator:
        try:
            return target()
        except Exception as exc:
            if (not predicate(exc)):
                raise
            last_exc = exc
            if (on_error is not None):
                on_error(exc)
        now = datetime_helpers.utcnow()
        if ((deadline_datetime is not None) and (deadline_datetime < now)):
            six.raise_from(exceptions.RetryError('Deadline of {:.1f}s exceeded while calling {}'.format(deadline, target), last_exc), last_exc)
        _LOGGER.debug('Retrying due to {}, sleeping {:.1f}s ...'.format(last_exc, sleep))
        time.sleep(sleep)
    raise ValueError('Sleep generator stopped yielding sleep values.')

Call a function and retry if it fails.

This is the lowest-level retry helper. Generally, you'll use the
higher-level retry helper :class:`Retry`.

Args:
target(Callable): The function to call and retry. This must be a
nullary function - apply arguments with `functools.partial`.
predicate (Callable[Exception]): A callable used to determine if an
exception raised by the target should be considered retryable.
It should return True to retry or False otherwise.
sleep_generator (Iterable[float]): An infinite iterator that determines
how long to sleep between retries.
deadline (float): How long to keep retrying the target.
on_error (Callable): A function to call while processing a retryable
exception.  Any error raised by this function will *not* be
caught.

Returns:
Any: the return value of the target function.

Raises:
google.api_core.RetryError: If the deadline is exceeded while retrying.
ValueError: If the sleep generator stops yielding values.
Exception: If the target raises a method that isn't retryable.


def __init__(self, cluster_resolver=None, communication_options=None, *, mesh=None):
    self._validate_init_args(mesh, cluster_resolver)
    if not mesh:
        if not cluster_resolver:
            cluster_resolver = tfconfig_cluster_resolver.TFConfigClusterResolver()
        dtensor_env_var = _parse_dtensor_env_var_from_cluster_resolver(cluster_resolver)
        _config_dtensor_env_var(dtensor_env_var)
        mesh = _build_distributed_mesh(dtensor_util.DEFAULT_BATCH_MESH_DIM_NAME)
    extended = dtensor_strategy_extended.DTensorStrategyExtended(container_strategy=self, mesh=mesh)
    super().__init__(extended)
    self._mesh = mesh
    self._cluster_resolver = cluster_resolver

Creates the strategy.

Args:
cluster_resolver: optional
`tf.distribute.cluster_resolver.ClusterResolver`. In case neither `mesh`
nor `cluster_resolver` are provided,
`tf.distribute.cluster_resolver.TFConfigClusterResolver` is used.
communication_options: currently ignore.
mesh: optional Dtensor global mesh for the computation. Note that either
`mesh` or the `cluster_resolver` should be provided. and not both.


def _ragged_getitem(rt_input, key_list):
    if not key_list:
        return rt_input
    row_key = key_list[0]
    inner_keys = key_list[1:]
    if row_key is Ellipsis:
        expanded_key_list = _expand_ellipsis(key_list, rt_input.shape.ndims)
        return _ragged_getitem(rt_input, expanded_key_list)
    if row_key is array_ops.newaxis:
        inner_rt = _ragged_getitem(rt_input, inner_keys)
        nsplits = tensor_shape.dimension_at_index(inner_rt.row_splits.shape, 0)
        if nsplits.value is not None:
            nsplits = nsplits.value
        else:
            nsplits = array_ops.shape(inner_rt.row_splits, out_type=inner_rt.row_splits.dtype)[0]
        return ragged_tensor.RaggedTensor.from_uniform_row_length(inner_rt, nsplits - 1, nrows=1, validate=False)
    if isinstance(row_key, slice):
        sliced_rt_input = _slice_ragged_row_dimension(rt_input, row_key)
        if rt_input.uniform_row_length is not None:
            sliced_rt_input = ragged_tensor.RaggedTensor.from_uniform_row_length(sliced_rt_input.values, rt_input.uniform_row_length, nrows=sliced_rt_input.nrows())
        return _ragged_getitem_inner_dimensions(sliced_rt_input, inner_keys)
    else:
        starts = rt_input.row_splits[:-1]
        limits = rt_input.row_splits[1:]
        if context.executing_eagerly():
            try:
                if int(row_key) >= len(starts):
                    raise IndexError('Row key {} out of bounds'.format(row_key))
            except (TypeError, ValueError):
                pass
        row = rt_input.values[starts[row_key]:limits[row_key]]
        return row.__getitem__(inner_keys)

Helper for indexing and slicing ragged tensors with __getitem__().

Extracts the specified piece of the `rt_input`.  See
`RaggedTensor.__getitem__` for examples and restrictions.

Args:
rt_input: The `RaggedTensor` from which a piece should be returned.
key_list: The list of keys specifying which piece to return. Each key
corresponds with a separate dimension.

Returns:
The indicated piece of rt_input.

Raises:
ValueError: If `key_list` is not supported.
TypeError: If any keys in `key_list` have an unsupported type.


def parsed_forensic_reports_to_csv(reports):

    fields = ["feedback_type", "user_agent", "version", "original_envelope_id",
              "original_mail_from", "original_rcpt_to", "arrival_date",
              "arrival_date_utc", "subject", "message_id",
              "authentication_results", "dkim_domain", "source_ip_address",
              "source_country", "source_reverse_dns", "source_base_domain",
              "delivery_result", "auth_failure", "reported_domain",
              "authentication_mechanisms", "sample_headers_only"]

    if type(reports) == OrderedDict:
        reports = [reports]
    csv_file = StringIO()
    csv_writer = DictWriter(csv_file, fieldnames=fields)
    csv_writer.writeheader()
    for report in reports:
        row = report.copy()
        row["source_ip_address"] = report["source"]["ip_address"]
        row["source_reverse_dns"] = report["source"]["reverse_dns"]
        row["source_base_domain"] = report["source"]["base_domain"]
        row["source_country"] = report["source"]["country"]
        del row["source"]
        row["subject"] = report["parsed_sample"]["subject"]
        row["auth_failure"] = ",".join(report["auth_failure"])
        authentication_mechanisms = report["authentication_mechanisms"]
        row["authentication_mechanisms"] = ",".join(
            authentication_mechanisms)
        del row["sample"]
        del row["parsed_sample"]
        csv_writer.writerow(row)

    return csv_file.getvalue()

Converts one or more parsed forensic reports to flat CSV format, including
headers

Args:
reports: A parsed forensic report or list of parsed forensic reports

Returns:
str: Parsed forensic report data in flat CSV format, including headers