def get_sample_dataset(dataset_properties):
    kwargs = dataset_properties.copy()
    data_type = kwargs.pop('type')
    if (data_type == 'multiclass'):
        try:
            (X, y) = datasets.make_classification(random_state=8, **kwargs)
            splits = model_selection.StratifiedKFold(n_splits=2, random_state=8).split(X, y)
        except Exception as e:
            raise exceptions.UserError(repr(e))
    elif (data_type == 'iris'):
        (X, y) = datasets.load_iris(return_X_y=True)
        splits = model_selection.StratifiedKFold(n_splits=2, random_state=8).split(X, y)
    elif (data_type == 'mnist'):
        (X, y) = datasets.load_digits(return_X_y=True)
        splits = model_selection.StratifiedKFold(n_splits=2, random_state=8).split(X, y)
    elif (data_type == 'breast_cancer'):
        (X, y) = datasets.load_breast_cancer(return_X_y=True)
        splits = model_selection.StratifiedKFold(n_splits=2, random_state=8).split(X, y)
    elif (data_type == 'boston'):
        (X, y) = datasets.load_boston(return_X_y=True)
        splits = model_selection.KFold(n_splits=2, random_state=8).split(X)
    elif (data_type == 'diabetes'):
        (X, y) = datasets.load_diabetes(return_X_y=True)
        splits = model_selection.KFold(n_splits=2, random_state=8).split(X)
    else:
        raise exceptions.UserError('Unknown dataset type {}'.format(dataset_properties['type']))
    return (X, y, splits)

Returns sample dataset

Args:
dataset_properties (dict): Dictionary corresponding to the properties of the dataset
used to verify the estimator and metric generators.

Returns:
X (array-like): Features array

y (array-like): Labels array

splits (iterator): This is an iterator that returns train test splits for
cross-validation purposes on ``X`` and ``y``.


def _load_stop_words(self, language=None):

        self._logger.debug('Loading stop words')

        loaded = False

        if language:
            file_path = 'data/stop-' + language
            loaded = self._parse_stop_words_file(os.path.join(PATH, file_path))
        else:
            for file in os.listdir(os.path.join(PATH, 'data')):
                loaded = self._parse_stop_words_file(os.path.join(PATH, 'data', file)) or loaded

        return loaded

Load stop words into __stop_words set.

Stop words will be loaded according to the language code
received during instantiation.

Args:
language: Language code.

Returns:
A boolean indicating whether a file was loaded.


def ParseCookieRow(self, parser_mediator, query, row, **unused_kwargs):

    query_hash = hash(query)

    cookie_data = self._GetRowValue(query_hash, row, 'value')
    cookie_name = self._GetRowValue(query_hash, row, 'name')

    hostname = self._GetRowValue(query_hash, row, 'host')
    if hostname.startswith('.'):
      hostname = hostname[1:]

    is_secure = bool(self._GetRowValue(query_hash, row, 'isSecure'))
    if is_secure:
      url_scheme = 'https'
    else:
      url_scheme = 'http'

    path = self._GetRowValue(query_hash, row, 'path')
    url = '{0:s}:

    event_data = FirefoxCookieEventData()
    event_data.cookie_name = cookie_name
    event_data.data = cookie_data
    event_data.host = hostname
    event_data.httponly = bool(self._GetRowValue(query_hash, row, 'isHttpOnly'))
    event_data.offset = self._GetRowValue(query_hash, row, 'id')
    event_data.path = path
    event_data.query = query
    event_data.secure = is_secure
    event_data.url = url

    timestamp = self._GetRowValue(query_hash, row, 'creationTime')
    if timestamp:
      date_time = dfdatetime_posix_time.PosixTimeInMicroseconds(
          timestamp=timestamp)
      event = time_events.DateTimeValuesEvent(
          date_time, definitions.TIME_DESCRIPTION_CREATION)
      parser_mediator.ProduceEventWithEventData(event, event_data)

    timestamp = self._GetRowValue(query_hash, row, 'lastAccessed')
    if timestamp:
      date_time = dfdatetime_posix_time.PosixTimeInMicroseconds(
          timestamp=timestamp)
      event = time_events.DateTimeValuesEvent(
          date_time, definitions.TIME_DESCRIPTION_LAST_ACCESS)
      parser_mediator.ProduceEventWithEventData(event, event_data)

    timestamp = self._GetRowValue(query_hash, row, 'expiry')
    if timestamp:

      date_time = dfdatetime_posix_time.PosixTime(
          timestamp=timestamp)
      event = time_events.DateTimeValuesEvent(
          date_time, definitions.TIME_DESCRIPTION_EXPIRATION)
      parser_mediator.ProduceEventWithEventData(event, event_data)

    for cookie_plugin in self._cookie_plugins:
      try:
        cookie_plugin.UpdateChainAndProcess(
            parser_mediator, cookie_name=cookie_name, cookie_data=cookie_data,
            url=url)
      except errors.WrongPlugin:
        pass

Parses a cookie row.

Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
query (str): query that created the row.
row (sqlite3.Row): row.


def change_subscription(self, topics):
    if self._user_assignment:
        raise IllegalStateError(self._SUBSCRIPTION_EXCEPTION_MESSAGE)
    if isinstance(topics, six.string_types):
        topics = [topics]
    if (self.subscription == set(topics)):
        log.warning('subscription unchanged by change_subscription(%s)', topics)
        return
    for t in topics:
        self._ensure_valid_topic_name(t)
    log.info('Updating subscribed topics to: %s', topics)
    self.subscription = set(topics)
    self._group_subscription.update(topics)
    for tp in set(self.assignment.keys()):
        if (tp.topic not in self.subscription):
            del self.assignment[tp]

Change the topic subscription.

Arguments:
topics (list of str): topics for subscription

Raises:
IllegalStateErrror: if assign_from_user has been used already
TypeError: if a topic is None or a non-str
ValueError: if a topic is an empty string or
- a topic name is '.' or '..' or
- a topic name does not consist of ASCII-characters/'-'/'_'/'.'


def _add_name_scope_wrapper(func, api_signature):
    if 'name' not in api_signature.parameters:
        return func
    func_signature = tf_inspect.signature(func)
    func_argspec = tf_inspect.getargspec(func)
    if 'name' in func_signature.parameters or func_argspec.keywords is not None:
        return func
    name_index = list(api_signature.parameters).index('name')

    def wrapped_func(*args, **kwargs):
        if name_index < len(args):
            name = args[name_index]
            args = args[:name_index] + args[name_index + 1:]
        else:
            name = kwargs.pop('name', None)
        if name is None:
            return func(*args, **kwargs)
        else:
            with ops.name_scope(name):
                return func(*args, **kwargs)
    wrapped_func = tf_decorator.make_decorator(func, wrapped_func)
    wrapped_func.__signature__ = func_signature.replace(parameters=list(func_signature.parameters.values()) + [api_signature.parameters['name']])
    del wrapped_func._tf_decorator
    return wrapped_func

Wraps `func` to expect a "name" arg, and use it to call `ops.name_scope`.

If `func` already expects a "name" arg, or if `api_signature` does not
expect a "name" arg, then returns `func` as-is.

Args:
func: The function to wrap.  Signature must match `api_signature` (except
the "name" parameter may be missing.
api_signature: The signature of the original API (used to find the index for
the "name" parameter).

Returns:
The wrapped function (or the original function if no wrapping is needed).


def computeAccuracy(model, size, top):

  accuracy = []

  filename = os.path.join(os.path.dirname(__file__), "msnbc990928.zip")
  with zipfile.ZipFile(filename) as archive:
    with archive.open("msnbc990928.seq") as datafile:

      for _ in xrange(7):
        next(datafile)

      for _ in xrange(LEARNING_RECORDS):
        next(datafile)

      for _ in xrange(size):
        pages = readUserSession(datafile)
        model.resetSequenceStates()
        for i in xrange(len(pages) - 1):
          result = model.run({"page": pages[i]})
          inferences = result.inferences["multiStepPredictions"][1]

          predicted = sorted(inferences.items(), key=itemgetter(1), reverse=True)[:top]

          accuracy.append(1 if pages[i + 1] in zip(*predicted)[0] else 0)

  return np.mean(accuracy)

Compute prediction accuracy by checking if the next page in the sequence is
within the top N predictions calculated by the model
Args:
model: HTM model
size: Sample size
top: top N predictions to use

Returns: Probability the next page in the sequence is within the top N
predicted pages


def set_day_time(self, hour):

        self._should_write_to_command_buffer = True
        command_to_send = DayTimeCommand(hour % 24)
        self._commands.add_command(command_to_send)

Queue up a change day time command. It will be applied when `tick` or `step` is called next.
By the next tick, the lighting and the skysphere will be updated with the new hour. If there is no skysphere
or directional light in the world, the command will not function properly but will not cause a crash.

Args:
hour (int): The hour in military time, between 0 and 23 inclusive.


def create_token(self, *, holder_name, card_number, credit_card_cvv, expiration_date, token_type='credit_card', identity_document=None, billing_address=None, additional_details=None):
    headers = self.client._get_public_headers()
    payload = {'token_type': token_type, 'credit_card_cvv': credit_card_cvv, 'card_number': card_number, 'expiration_date': expiration_date, 'holder_name': holder_name, 'identity_document': identity_document, 'billing_address': billing_address, 'additional_details': additional_details}
    endpoint = '/tokens'
    return self.client._post((self.client.URL_BASE + endpoint), json=payload, headers=headers)

When creating a Token, remember to use the public-key header instead of the private-key header,
and do not include the app-id header.

Args:
holder_name: Name of the credit card holder.
card_number: Credit card number.
credit_card_cvv: The CVV number on the card (3 or 4 digits) to be encrypted.
expiration_date: Credit card expiration date. Possible formats: mm-yyyy, mm-yy, mm.yyyy,
mm.yy, mm/yy, mm/yyyy, mm yyyy, or mm yy.
token_type: The type of token
billing_address: Address.
identity_document: National identity document of the card holder.
additional_details: Optional additional data stored with your token in key/value pairs.

Returns:


def gpio_get(self, pins=None):

        if pins is None:
            pins = range(4)

        size = len(pins)
        indices = (ctypes.c_uint8 * size)(*pins)
        statuses = (ctypes.c_uint8 * size)()
        result = self._dll.JLINK_EMU_GPIO_GetState(ctypes.byref(indices),
                                                   ctypes.byref(statuses),
                                                   size)
        if result < 0:
            raise errors.JLinkException(result)

        return list(statuses)

Returns a list of states for the given pins.

Defaults to the first four pins if an argument is not given.

Args:
self (JLink): the ``JLink`` instance
pins (list): indices of the GPIO pins whose states are requested

Returns:
A list of states.

Raises:
JLinkException: on error.


def json_set_fields(recipe, variables):
    if isinstance(recipe, dict):
        for key, value in list(recipe.items()):
            if isinstance(value, dict) and 'field' in value:
                variable_value = variables.get(value['field']['name'], value['field'].get('default'))
                field_value = get_field_value(value, variable_value)
                if field_value is None and value.get('default') is None:
                    del recipe[key]
                else:
                    recipe[key] = field_value
            else:
                json_set_fields(value, variables)
    elif isinstance(recipe, list) or isinstance(recipe, tuple):
        for index, value in enumerate(recipe):
            if isinstance(value, dict) and 'field' in value:
                variable_value = variables.get(value['field']['name'], value['field'].get('default'))
                recipe[index] = get_field_value(value, variable_value)
            else:
                json_set_fields(value, variables)
    return recipe

Recusrsively replaces fields in script JSON with values provided.

Field has format: { "field":{ "name":"???", "kind":"???", "default":???,
"description":"???" }}

If field value is empty and field default is null, the value is removed
from JSON as a parameter,
allowing the python task to pick a default value. Allows optional
parameters to exist.

Args:
recipe: (dict) A dictionary representation of the JSON script.
variables: (dict) A lookup table of all values to be replaced, key is name
of field.

Returns:
Nothig. Struct is modified in place.


def has_no_checked_field(self, locator, **kwargs):
    kwargs['checked'] = True
    return self.has_no_selector('field', locator, **kwargs)

Checks if the page or current node has no radio button or checkbox with the given label,
value, or id that is currently checked.

Args:
locator (str): The label, name, or id of a checked field.
**kwargs: Arbitrary keyword arguments for :class:`SelectorQuery`.

Returns:
bool: Whether it doesn't exist.


def extrapolation_step():

    def step_fn(time, next_time, coord_grid, value_grid, boundary_conditions, second_order_coeff_fn, first_order_coeff_fn, zeroth_order_coeff_fn, inner_second_order_coeff_fn, inner_first_order_coeff_fn, num_steps_performed, dtype=None, name=None):

        del num_steps_performed
        name = name or 'extrapolation_step'
        return parabolic_equation_step(time, next_time, coord_grid, value_grid, boundary_conditions, second_order_coeff_fn, first_order_coeff_fn, zeroth_order_coeff_fn, inner_second_order_coeff_fn, inner_first_order_coeff_fn, time_marching_scheme=extrapolation_scheme, dtype=dtype, name=name)
    return step_fn

Creates a stepper function with Extrapolation time marching scheme.

Extrapolation scheme combines two half-steps and the full time step to obtain
desirable properties. See more details below in `extrapolation_scheme`.

It is slower than Crank-Nicolson scheme, but deals better with value grids
that have discontinuities. Consider also `oscillation_damped_crank_nicolson`,
an efficient combination of Crank-Nicolson and Extrapolation schemes.

Returns:
Callable to be used in finite-difference PDE solvers (see fd_solvers.py).


def to_string(self, other_separation_char=None):

        separation_char = self._separation_char
        if other_separation_char is not None:
            separation_char = other_separation_char
        return separation_char.join(self._locations_list)

String representation of :class:`LocationDescriptor` object.

Args:
other_separation_char: If needed, another separator character can be used.

Returns:


def update_user(self, user_id,
                    roles=None, netmask=None,
                    secret=None, pubkey=None):

        arguments = {'roles': roles,
                     'netmask': netmask,
                     'secret': secret,
                     'pubkey': pubkey}
        return self.do_req('PUT',
                           self.merchant_api_base_url + '/user/' +
                           user_id + '/', arguments)

Update user. Returns the raw response object.

Arguments:
user_id:
User id of user to update
roles:
Role
netmask:
Limit user connections by netmask, for example 192.168.1.0/24
secret:
Secret used when authenticating with mCASH
pubkey:
RSA key used for authenticating by signing


class _LazyAutoMapping(OrderedDict[type[PretrainedConfig], _LazyAutoMappingValue]):

    def __init__(self, config_mapping, model_mapping) -> None:
        self._config_mapping = config_mapping
        self._reverse_config_mapping = {v: k for k, v in config_mapping.items()}
        self._model_mapping = model_mapping
        self._model_mapping._model_mapping = self
        self._extra_content = {}
        self._modules = {}

    def __len__(self) -> int:
        common_keys = set(self._config_mapping.keys()).intersection(self._model_mapping.keys())
        return len(common_keys) + len(self._extra_content)

    def __getitem__(self, key: type[PretrainedConfig]) -> _LazyAutoMappingValue:
        if key in self._extra_content:
            return self._extra_content[key]
        model_type = self._reverse_config_mapping[key.__name__]
        if model_type in self._model_mapping:
            model_name = self._model_mapping[model_type]
            return self._load_attr_from_module(model_type, model_name)
        model_types = [k for k, v in self._config_mapping.items() if v == key.__name__]
        for mtype in model_types:
            if mtype in self._model_mapping:
                model_name = self._model_mapping[mtype]
                return self._load_attr_from_module(mtype, model_name)
        raise KeyError(key)

    def _load_attr_from_module(self, model_type, attr):
        module_name = model_type_to_module_name(model_type)
        if module_name not in self._modules:
            self._modules[module_name] = importlib.import_module(f'.{module_name}', 'transformers.models')
        return getattribute_from_module(self._modules[module_name], attr)

    def keys(self) -> list[type[PretrainedConfig]]:
        mapping_keys = [self._load_attr_from_module(key, name) for key, name in self._config_mapping.items() if key in self._model_mapping.keys()]
        return mapping_keys + list(self._extra_content.keys())

    def get(self, key: type[PretrainedConfig], default: _T) -> Union[_LazyAutoMappingValue, _T]:
        try:
            return self.__getitem__(key)
        except KeyError:
            return default

    def __bool__(self) -> bool:
        return bool(self.keys())

    def values(self) -> list[_LazyAutoMappingValue]:
        mapping_values = [self._load_attr_from_module(key, name) for key, name in self._model_mapping.items() if key in self._config_mapping.keys()]
        return mapping_values + list(self._extra_content.values())

    def items(self) -> list[tuple[type[PretrainedConfig], _LazyAutoMappingValue]]:
        mapping_items = [(self._load_attr_from_module(key, self._config_mapping[key]), self._load_attr_from_module(key, self._model_mapping[key])) for key in self._model_mapping.keys() if key in self._config_mapping.keys()]
        return mapping_items + list(self._extra_content.items())

    def __iter__(self) -> Iterator[type[PretrainedConfig]]:
        return iter(self.keys())

    def __contains__(self, item: type) -> bool:
        if item in self._extra_content:
            return True
        if not hasattr(item, '__name__') or item.__name__ not in self._reverse_config_mapping:
            return False
        model_type = self._reverse_config_mapping[item.__name__]
        return model_type in self._model_mapping

    def register(self, key: type[PretrainedConfig], value: _LazyAutoMappingValue, exist_ok=False) -> None:

        if hasattr(key, '__name__') and key.__name__ in self._reverse_config_mapping:
            model_type = self._reverse_config_mapping[key.__name__]
            if model_type in self._model_mapping.keys() and (not exist_ok):
                raise ValueError(f"'{key}' is already used by a Transformers model.")
        self._extra_content[key] = value

" A mapping config to object (model or tokenizer for instance) that will load keys and values when it is accessed.

Args:
- config_mapping: The map model type to config class
- model_mapping: The map model type to model (or tokenizer) class


def enable_plugin(self, name, timeout=0):

        url = self._url('/plugins/{0}/enable', name)
        params = {'timeout': timeout}
        res = self._post(url, params=params)
        self._raise_for_status(res)
        return True

Enable an installed plugin.

Args:
name (string): The name of the plugin. The ``:latest`` tag is
optional, and is the default if omitted.
timeout (int): Operation timeout (in seconds). Default: 0

Returns:
``True`` if successful


def read_from_hdx(identifier, configuration=None):
    showcase = Showcase(configuration=configuration)
    result = showcase._load_from_hdx('showcase', identifier)
    if result:
        return showcase
    return None

Reads the showcase given by identifier from HDX and returns Showcase object

Args:
identifier (str): Identifier of showcase
configuration (Optional[Configuration]): HDX configuration. Defaults to global configuration.

Returns:
Optional[Showcase]: Showcase object if successful read, None if not


def __init__(self, name, distribution_fn, required_gpus=None, required_physical_gpus=0, required_tpu=False, use_cloud_tpu=False, has_chief=False, num_workers=1, num_ps=0, share_gpu=True, pool_runner_fn=None, no_xla=False):
    object.__init__(self)
    self._name = name
    self._distribution_fn = distribution_fn
    self.required_gpus = required_gpus
    self.required_physical_gpus = required_physical_gpus
    self.required_tpu = required_tpu
    self.use_cloud_tpu = use_cloud_tpu
    self.has_chief = has_chief
    self.num_workers = num_workers
    self.num_ps = num_ps
    self.share_gpu = share_gpu
    self._pool_runner_fn = pool_runner_fn
    self.no_xla = no_xla

Initialize NamedDistribution.

Args:
name: Name that will be a part of the name of the test case.
distribution_fn: A callable that creates a `tf.distribute.Strategy`.
required_gpus: The number of GPUs that the strategy requires. Only one of
`required_gpus` and `required_physical_gpus` should be set.
required_physical_gpus: Number of physical GPUs required. Only one of
`required_gpus` and `required_physical_gpus` should be set.
required_tpu: Whether the strategy requires TPU.
use_cloud_tpu: Whether the strategy requires cloud TPU.
has_chief: Whether the strategy requires a chief worker.
num_workers: The number of workers that the strategy requires.
num_ps: The number of parameter servers.
share_gpu: Whether to share GPUs among workers.
pool_runner_fn: An optional callable that returns a MultiProcessPoolRunner
to run the test.
no_xla: Whether to skip in XLA tests.


def read(self, istream, kmip_version=enums.KMIPVersion.KMIP_1_0):
    super(ExtensionInformation, self).read(istream, kmip_version=kmip_version)
    tstream = BytearrayStream(istream.read(self.length))
    self.extension_name.read(tstream, kmip_version=kmip_version)
    if self.is_tag_next(Tags.EXTENSION_TAG, tstream):
        self.extension_tag = ExtensionTag()
        self.extension_tag.read(tstream, kmip_version=kmip_version)
    if self.is_tag_next(Tags.EXTENSION_TYPE, tstream):
        self.extension_type = ExtensionType()
        self.extension_type.read(tstream, kmip_version=kmip_version)
    self.is_oversized(tstream)
    self.validate()

Read the data encoding the ExtensionInformation object and decode it
into its constituent parts.

Args:
istream (Stream): A data stream containing encoded object data,
supporting a read method; usually a BytearrayStream object.
kmip_version (KMIPVersion): An enumeration defining the KMIP
version with which the object will be decoded. Optional,
defaults to KMIP 1.0.


def _ReformatMessageString(self, message_string):

    def _PlaceHolderSpecifierReplacer(match_object):
        'Replaces message string place holders into Python format() style.'
        expanded_groups = []
        for group in match_object.groups():
            try:
                place_holder_number = (int(group, 10) - 1)
                expanded_group = '{{{0:d}:s}}'.format(place_holder_number)
            except ValueError:
                expanded_group = group
            expanded_groups.append(expanded_group)
        return ''.join(expanded_groups)
    if (not message_string):
        return None
    message_string = self._WHITE_SPACE_SPECIFIER_RE.sub('', message_string)
    message_string = self._TEXT_SPECIFIER_RE.sub('\\\\\\1', message_string)
    message_string = self._CURLY_BRACKETS.sub('\\1\\1', message_string)
    return self._PLACE_HOLDER_SPECIFIER_RE.sub(_PlaceHolderSpecifierReplacer, message_string)

Reformats the message string.

Args:
message_string (str): message string.

Returns:
str: message string in Python format() (PEP 3101) style.


def evaluate_ising(linear, quad, state):
    if (_numpy and isinstance(state, np.ndarray)):
        return evaluate_ising(linear, quad, state.tolist())
    energy = 0.0
    for (index, value) in uniform_iterator(linear):
        energy += (state[index] * value)
    for ((index_a, index_b), value) in six.iteritems(quad):
        energy += ((value * state[index_a]) * state[index_b])
    return energy

Calculate the energy of a state given the Hamiltonian.

Args:
linear: Linear Hamiltonian terms.
quad: Quadratic Hamiltonian terms.
state: Vector of spins describing the system state.

Returns:
Energy of the state evaluated by the given energy function.


def setColumn(self, header, values):
    if any((isinstance(value, basestring) for value in values)):
        values = list(map(str, values))
        self._impl.setColumnStr(header, values, len(values))
    elif all((isinstance(value, Real) for value in values)):
        values = list(map(float, values))
        self._impl.setColumnDbl(header, values, len(values))
    else:
        print(values)
        raise NotImplementedError

Set the values of a column.

Args:
header: The header of the column to be set.

values: The values to set.


def layer(self, queryset, stylename=None):

        cls = RasterLayer if hasattr(queryset, 'image') else VectorLayer
        layer = cls(queryset, style=stylename)
        try:
            style = self.map.find_style(layer.stylename)
        except KeyError:
            self.map.append_style(layer.stylename, layer.style())
        layer.styles.append(layer.stylename)
        self.map.layers.append(layer._layer)
        return layer

Returns a map Layer.

Arguments:
queryset -- QuerySet for Layer
Keyword args:
stylename -- str name of style to apply


def set_from_tree(self, address_value_dict):
    for (address, value) in address_value_dict.items():
        if (address in self._state):
            self._state[address].set_result(result=value, from_tree=True)

Set the result for each future at the given addresses with the value
stored in the merkle database.

Args:
address_value_dict (dict of str: bytes): The unique
full addresses that the bytes values should be set with.


def groups_invite(self, *, channel: str, user: str, **kwargs) -> SlackResponse:

        self._validate_xoxp_token()
        kwargs.update({"channel": channel, "user": user})
        return self.api_call("groups.invite", json=kwargs)

Invites a user to a private channel.

Args:
channel (str): The group id. e.g. 'G1234567890'
user (str): The user id. e.g. 'U1234567890'


def PluginTagToContent(self, plugin_name):

    if plugin_name not in self._plugin_to_tag_to_content:
      raise KeyError('Plugin %r could not be found.' % plugin_name)
    return self._plugin_to_tag_to_content[plugin_name]

Returns a dict mapping tags to content specific to that plugin.

Args:
plugin_name: The name of the plugin for which to fetch plugin-specific
content.

Raises:
KeyError: if the plugin name is not found.

Returns:
A dict mapping tags to plugin-specific content (which are always strings).
Those strings are often serialized protos.


def Draw(self, stoplist=None, triplist=None, height=520):

    output = str()
    if not triplist:
      triplist = []
    if not stoplist:
      stoplist = []

    if not self._cache or triplist or stoplist:
      self._gheight = height
      self._tlist=triplist
      self._slist=stoplist
      self._decorators = []
      self._stations = self._BuildStations(stoplist)
      self._cache = "%s %s %s %s" % (self._DrawBox(),
                                      self._DrawHours(),
                                      self._DrawStations(),
                                      self._DrawTrips(triplist))

    output = "%s %s %s %s" % (self._DrawHeader(),
                              self._cache,
                              self._DrawDecorators(),
                              self._DrawFooter())
    return output

Main interface for drawing the marey graph.

If called without arguments, the data generated in the previous call
will be used. New decorators can be added between calls.

Args:
# Class Stop is defined in transitfeed.py
stoplist: [Stop, Stop, ...]
# Class Trip is defined in transitfeed.py
triplist: [Trip, Trip, ...]

Returns:
# A string that contain a svg/xml web-page with a marey graph.
" <svg  width="1440" height="520" version="1.1" ... "


def add_comment(node, text, location='above'):
    anno.setanno(node, 'comment', dict(location=location, text=text), safe=False)
    return node

Add a comment to the given node.

If the `SourceWithCommentGenerator` class is used these comments will be
output as part of the source code.

Note that a node can only contain one comment. Subsequent calls to
`add_comment` will ovverride the existing comments.

Args:
node: The AST node whose containing statement will be commented.
text: A comment string.
location: Where the comment should appear. Valid values are 'above',
'below' and 'right'

Returns:
The node with the comment stored as an annotation.


def _padded_split(tensor, pieces):
    shape = tensor.shape
    if 1 != len(shape):
        raise ValueError('input tensor must be 1D')
    tensor_len = shape.dims[0].value
    with ops.colocate_with(tensor):
        if tensor_len % pieces != 0:
            chunk_size = 1 + tensor_len
            if pieces > tensor_len:
                pad_len = pieces - tensor_len
                extended_whole = array_ops.concat([tensor, array_ops.zeros([pad_len], dtype=tensor.dtype)], 0)
                parts = array_ops.split(extended_whole, pieces)
                return (parts, pad_len)
            elif (pieces - 1) * chunk_size >= tensor_len:
                pad_len = pieces * chunk_size % tensor_len
                extended_whole = array_ops.concat([tensor, array_ops.zeros([pad_len], dtype=tensor.dtype)], 0)
                parts = array_ops.split(extended_whole, pieces)
                return (parts, pad_len)
            else:
                last_chunk_size = tensor_len - (pieces - 1) * chunk_size
                pad_len = chunk_size - last_chunk_size
                piece_lens = [chunk_size for _ in range(pieces - 1)] + [last_chunk_size]
                parts = array_ops.split(tensor, piece_lens)
                parts[-1] = array_ops.concat([parts[-1], array_ops.zeros([pad_len], dtype=tensor.dtype)], 0)
                return (parts, pad_len)
        else:
            return (array_ops.split(tensor, pieces), 0)

Like split for 1D tensors but pads-out case where len % pieces != 0.

Args:
tensor: `tf.Tensor` that must be 1D.
pieces: a positive integer specifying the number of pieces into which
tensor should be split.

Returns:
list of `tf.Tensor` of length pieces, which hold the values of
thin input tensor, in order. The final tensor may
be zero-padded on the end to make its size equal to those of all
of the other tensors.

Raises:
ValueError: The input tensor is not 1D.


def update_nanopubstore_start_dt(url: str, start_dt: str):
    hostname = urllib.parse.urlsplit(url)[1]
    start_dates_doc = state_mgmt.get(start_dates_doc_key)
    if (not start_dates_doc):
        start_dates_doc = {'_key': start_dates_doc_key, 'start_dates': [{'nanopubstore': hostname, 'start_dt': start_dt}]}
        state_mgmt.insert(start_dates_doc)
    else:
        for (idx, start_date) in enumerate(start_dates_doc['start_dates']):
            if (start_date['nanopubstore'] == hostname):
                start_dates_doc['start_dates'][idx]['start_dt'] = start_dt
                break
        else:
            start_dates_doc['start_dates'].append({'nanopubstore': hostname, 'start_dt': start_dt})
        state_mgmt.replace(start_dates_doc)

Add nanopubstore start_dt to belapi.state_mgmt collection

Args:
url: url of nanopubstore
start_dt: datetime of last query against nanopubstore for new ID's


def clean(self, value, *_):

        if not value or not isinstance(value, LocalizedValue):
            return None

        is_all_null = True
        for lang_code, _ in settings.LANGUAGES:
            if value.get(lang_code) is not None:
                is_all_null = False
                break

        if is_all_null and self.null:
            return None

        return value

Cleans the specified value into something we
can store in the database.

For example, when all the language fields are
left empty, and the field is allowed to be null,
we will store None instead of empty keys.

Arguments:
value:
The value to clean.

Returns:
The cleaned value, ready for database storage.


def _findOptionValueAdvAudit(option):

    if 'lgpo.adv_audit_data' not in __context__:
        system_root = os.environ.get('SystemRoot', 'C:\\Windows')
        f_audit = os.path.join(system_root, 'security', 'audit', 'audit.csv')
        f_audit_gpo = os.path.join(system_root, 'System32', 'GroupPolicy',
                                   'Machine', 'Microsoft', 'Windows NT',
                                   'Audit', 'audit.csv')

        if not __salt__['file.file_exists'](f_audit):
            if __salt__['file.file_exists'](f_audit_gpo):

                __salt__['file.copy'](f_audit_gpo, f_audit)
            else:
                field_names = _get_audit_defaults('fieldnames')

                __salt__['file.makedirs'](f_audit)
                __salt__['file.write'](f_audit, ','.join(field_names))

        audit_settings = {}
        with salt.utils.files.fopen(f_audit, mode='r') as csv_file:
            reader = csv.DictReader(csv_file)

            for row in reader:
                audit_settings.update(
                    {row['Subcategory']: row['Setting Value']})

        __context__['lgpo.adv_audit_data'] = audit_settings

    return __context__['lgpo.adv_audit_data'].get(option, None)

Get the Advanced Auditing policy as configured in
``C:\\Windows\\Security\\Audit\\audit.csv``

Args:
option (str): The name of the setting as it appears in audit.csv

Returns:
bool: ``True`` if successful, otherwise ``False``


def flatten(self, d=None):

        if d is None:
            d = {}
        if self.name is not None:
            d[self.name] = self
        for child in self.children:
            child.flatten(d=d)
        return d

Flatten tree structure to a one level dictionary.

Args:
d (dict, optional): output dictionary to update

Returns:
dict: Node.name -> Node. The returned dictionary includes the
current Node and all its children.


def _revoke(self, http):

        self._do_revoke(http, self.refresh_token or self.access_token)

Revokes this credential and deletes the stored copy (if it exists).

Args:
http: an object to be used to make HTTP requests.


def __init__(self, *, content: content_api.ProcessorContentTypes | None=None, content_factory: PreambleFactory | None=None):
    if content is not None and content_factory is not None:
        raise ValueError('Only one of `content` and `content_factory` must be provided.')
    self._content = None if content is None else content_api.ProcessorContent(content)
    self._content_factory = content_factory

Constructs a Preamble processor.

Args:
content: content to prepend.
content_factory: function for returning a content given no input. This is
helpful for when contents are not fully known on __init__, e.g. if they
depend on the user or time of the request.

Raises:
ValueError if both `content` and `content_factory` are provided.


def get(self, request, customer_uuid):
    context = self._build_context(request, customer_uuid)
    manage_learners_form = ManageLearnersForm(user=request.user, enterprise_customer=context[self.ContextParameters.ENTERPRISE_CUSTOMER])
    context.update({self.ContextParameters.MANAGE_LEARNERS_FORM: manage_learners_form})
    return render(request, self.template, context)

Handle GET request - render linked learners list and "Link learner" form.

Arguments:
request (django.http.request.HttpRequest): Request instance
customer_uuid (str): Enterprise Customer UUID

Returns:
django.http.response.HttpResponse: HttpResponse


def _safe_get(self, revision, key):

        if self.has_revision(revision):
            return self.raw_answers[revision].get(key)
        else:
            return None

Get an answer data (vote or rationale) by revision

Args:
revision (int): the revision number for student answer, could be
0 (original) or 1 (revised)
key (str); key for retrieve answer data, could be VOTE_KEY or
RATIONALE_KEY

Returns:
the answer data or None if revision doesn't exists


def register_items(self, items):
    for item in items:
        item.set_parent(self)
    self.items.extend(items)

Bulk ``register_item``.

Args:
items (iterable[Tree]):
Sequence of nodes to be registered as children.


def broadcast_recv_v2(shape, dtype, group_size, group_key, instance_key, communication_hint='auto', timeout=0):
    return gen_collective_ops.collective_bcast_recv_v2(T=dtype, group_size=group_size, group_key=group_key, instance_key=instance_key, shape=shape, communication_hint=communication_hint.lower(), timeout_seconds=timeout)

Receives a broadcasts tensor, across devices.

Args:
shape: an int tensor.  Shape of the tensor to be received.
dtype: Type of the tensor to be received.
group_size: an int32 tensor.  One plus the number of receiving tensors, i.e.
the total number of devices participating.  Each tensor must reside on a
different device.
group_key: an int32 tensor identifying the group of devices.
instance_key: an int32 tensor identifying the participating group of Ops.
communication_hint: preferred collective communication.  The implementation
may fall back to another mechanism.  Options include `auto`, `ring`, and
`nccl`.
timeout: If set to a non zero, set a completion timeout to detect staleness.
If the timer goes off, a DeadlineExceededError is raised.
The timeout value in seconds. This feature is experimental.

Returns:
An Op implementing the broadcast receive.


def _GetAccountsData(self, metadata_dict):

    instance_data, project_data = self._GetInstanceAndProjectAttributes(
        metadata_dict)
    valid_keys = [instance_data.get('sshKeys'), instance_data.get('ssh-keys')]
    block_project = instance_data.get('block-project-ssh-keys', '').lower()
    if block_project != 'true' and not instance_data.get('sshKeys'):
      valid_keys.append(project_data.get('ssh-keys'))
      valid_keys.append(project_data.get('sshKeys'))
    accounts_data = '\n'.join([key for key in valid_keys if key])
    return self._ParseAccountsData(accounts_data)

Get the user accounts specified in metadata server contents.

Args:
metadata_dict: json, the deserialized contents of the metadata server.

Returns:
dict, a mapping of the form: {'username': ['sshkey1, 'sshkey2', ...]}.


def _recompute_attrs_type_from_mro(self, all_attrs: dict[str, Attribute], type_params: 'dict[str | int, _base.BaseValue]') -> None:
    for typ_name, typ_obj in type_params.items():
        for attr in all_attrs.values():
            if typ_name == attr.typ.cls.name:
                attr.typ = typ_obj

Traverse the MRO and apply Generic type params to class attributes.

This IS REQUIRED for dataclass instances that inherits from a Generic.

Args:
all_attrs: All __init__ attributes of a class.
type_params: List of ParameterizedClass instances that will override
TypeVar attributes in all_attrs.


def check_exists(self):
    response = self.repo.api.http_request('HEAD', self.uri)
    self.status_code = response.status_code
    if (self.status_code == 200):
        self.exists = True
    elif (self.status_code == 410):
        self.exists = False
    elif (self.status_code == 404):
        self.exists = False
    return self.exists

Check if resource exists, update self.exists, returns

Returns:
None: sets self.exists


def render_unregistered(error=None):

    return template(
        read_index_template(),
        registered=False,
        error=error,
        seeder_data=None,
        url_id=None,
    )

Render template file for the unregistered user.

Args:
error (str, default None): Optional error message.

Returns:
str: Template filled with data.


def _hat_integral(self, x):
    x = tf.cast(x, self.power.dtype)
    t = (self.power - 1.0)
    return tf.exp((((- t) * tf.math.log1p(x)) - tf.math.log(t)))

Integral of the `hat` function, used for sampling.

We choose a `hat` function, h(x) = x^(-power), which is a continuous
(unnormalized) density touching each positive integer at the (unnormalized)
pmf. This function implements `hat` integral: H(x) = int_x^inf h(t) dt;
which is needed for sampling purposes.

Arguments:
x: A Tensor of points x at which to evaluate H(x).

Returns:
A Tensor containing evaluation H(x) at x.


def get(self, key):

        data = self._store.get(key)
        if not data:
            return None
        value, expire = data
        if expire and time.time() > expire:
            del self._store[key]
            return None
        return value

Get an item from the cache
Args:
key: item key
Returns:
the value of the item or None if the item isn't in the cache


def ragged_shape(input: ragged_tensor.Ragged, name: Optional[str]=None, out_type=dtypes.int32) -> dynamic_ragged_shape.DynamicRaggedShape:
    with ops.name_scope(name, 'RaggedShape', [input]):
        return dynamic_ragged_shape.DynamicRaggedShape.from_tensor(input, out_type)

Returns the shape of a RaggedTensor.

Args:
input: A `RaggedTensor`
name: A name for the operation (optional).
out_type: dtype used to encode the shape.

Returns:
A `tf.experimental.DynamicRaggedShape`


def rename_variables(expression: Expression, renaming: Dict[str, str]) -> Expression:

    if isinstance(expression, Operation):
        if hasattr(expression, 'variable_name'):
            variable_name = renaming.get(expression.variable_name, expression.variable_name)
            return create_operation_expression(
                expression, [rename_variables(o, renaming) for o in op_iter(expression)], variable_name=variable_name
            )
        operands = [rename_variables(o, renaming) for o in op_iter(expression)]
        return create_operation_expression(expression, operands)
    elif isinstance(expression, Expression):
        expression = expression.__copy__()
        expression.variable_name = renaming.get(expression.variable_name, expression.variable_name)
    return expression

Rename the variables in the expression according to the given dictionary.

Args:
expression:
The expression in which the variables are renamed.
renaming:
The renaming dictionary. Maps old variable names to new ones.
Variable names not occuring in the dictionary are left unchanged.

Returns:
The expression with renamed variables.


def config_from_url(u, **kwargs):
    path = u.path.lstrip('/').split('/')
    if ((len(path) > 2) or (not path)):
        raise AssertionError('zmq url format: zmq:
    typ = path[0].upper()
    try:
        topic = path[1]
    except IndexError as _:
        topic = ''
    param = dict(urllib.parse.parse_qsl(u.query))
    transport = param.get('transport', 'tcp')
    _id = ('%s-%s-%s-%s' % (typ, topic, transport, u.netloc))
    if (kwargs.get('prefix') is not None):
        _id = ('%s-%s' % (kwargs.get('prefix'), _id))
    return {'id': _id, 'typ_str': typ, 'typ': getattr(zmq, typ), 'topic': topic, 'transport': transport, 'url': ('%s:

Returns dict containing zmq configuration arguments
parsed from xbahn url

Arguments:

- u (urlparse.urlparse result)

Returns:

dict:
- id (str): connection index key
- typ_str (str): string representation of zmq socket type
- typ (int): zmq socket type (PUB, SUB, REQ, REP, PUSH, PULL)
- topic (str): subscription topic
- url (str): url to use with zmq's bind function


async def on_message(message):

    server = message.server
    author = message.author
    channel = message.channel
    content = message.content

    data = datatools.get_data()

    if not data["discord"]["servers"][server.id][_data.modulename]["activated"]:
        return

    if server is not None and author != channel.server.me:

        if channel.server.me in message.mentions:

            logger.info("Bot was mentioned, summoning Mitsuku")
            await client.send_typing(channel)

            if channel.id not in data["discord"]["servers"][server.id][_data.modulename]["channels"]:
                new_serverdata = data
                new_serverdata["discord"]["servers"][server.id][_data.modulename]["channels"][channel.id] = \
                    api_mitsuku.get_botcust2()
                datatools.write_data(new_serverdata)

            botcust2 = data["discord"]["servers"][server.id][_data.modulename]["channels"][channel.id]

            content = content.replace("<@{}>".format(str(channel.server.me.id)), ' ')
            content = content.replace("<@!{}>".format(str(channel.server.me.id)), ' ')

            if botcust2:
                response = api_mitsuku.query(botcust2, content)
                if response:
                    await client.send_message(channel, response)
                else:
                    await client.send_message(channel, "```Couldn't get readable response from Mitsuku.```")
            else:
                await client.send_message(channel, "```Couldn't initialise with Mitsuku.```")

The on_message event handler for this module

Args:
message (discord.Message): Input message


def output_forecasts_csv(self, forecasts, mode, csv_path, run_date_format="%Y%m%d-%H%M"):

        merged_forecasts = pd.merge(forecasts["condition"],
                                    forecasts["dist"],
                                    on=["Step_ID","Track_ID","Ensemble_Member","Forecast_Hour"])
        all_members = self.data[mode]["combo"]["Ensemble_Member"]
        members = np.unique(all_members)
        all_run_dates = pd.DatetimeIndex(self.data[mode]["combo"]["Run_Date"])
        run_dates = pd.DatetimeIndex(np.unique(all_run_dates))
        print(run_dates)
        for member in members:
            for run_date in run_dates:
                mem_run_index = (all_run_dates == run_date) & (all_members == member)
                member_forecast = merged_forecasts.loc[mem_run_index]
                member_forecast.to_csv(join(csv_path, "hail_forecasts_{0}_{1}_{2}.csv".format(self.ensemble_name,
                                                                                member,
                                                                                run_date.strftime
																							  (run_date_format))))
        return

Output hail forecast values to csv files by run date and ensemble member.

Args:
forecasts:
mode:
csv_path:
Returns:


def load_config(self, settings=None):

        self._load_defaults()
        if settings:
            self.update(settings)
        else:
            config_paths = _get_config_files()
            for p in config_paths:
                conf = _process_config_file([p])
                self.update(conf)
        self._loaded = True
        self._validate()

Load the configuration either from the config file, or from the given settings.

Args:
settings (dict): If given, the settings are pulled from this dictionary. Otherwise, the
config file is used.


def pbs_for_set_no_merge(document_path, document_data):

    extractor = DocumentExtractor(document_data)

    if extractor.deleted_fields:
        raise ValueError(
            "Cannot apply DELETE_FIELD in a set request without "
            "specifying 'merge=True' or 'merge=[field_paths]'."
        )

    write_pbs = [extractor.get_update_pb(document_path)]

    if extractor.has_transforms:
        transform_pb = extractor.get_transform_pb(document_path)
        write_pbs.append(transform_pb)

    return write_pbs

Make ``Write`` protobufs for ``set()`` methods.

Args:
document_path (str): A fully-qualified document path.
document_data (dict): Property names and values to use for
replacing a document.

Returns:
List[google.cloud.firestore_v1beta1.types.Write]: One
or two ``Write`` protobuf instances for ``set()``.


async def event_wait(event: asyncio.Event, timeout=None):
    if (timeout is None):
        (await event.wait())
        return True
    try:
        (await asyncio.wait_for(event.wait(), timeout))
    except asyncio.TimeoutError:
        return False
    return True

Wait on an an asyncio event with an optional timeout

Returns:
true if the event got set, None if timed out


def forward(self, hidden_states: torch.Tensor, attention_mask: torch.Tensor, causal_attention_mask: torch.Tensor, output_attentions: Optional[bool]=False) -> Tuple[torch.FloatTensor]:
    residual = hidden_states
    hidden_states = self.layer_norm1(hidden_states)
    hidden_states, attn_weights = self.self_attn(hidden_states=hidden_states, attention_mask=attention_mask, causal_attention_mask=causal_attention_mask, output_attentions=output_attentions)
    hidden_states = residual + hidden_states
    residual = hidden_states
    hidden_states = self.layer_norm2(hidden_states)
    hidden_states = self.mlp(hidden_states)
    hidden_states = residual + hidden_states
    outputs = (hidden_states,)
    if output_attentions:
        outputs += (attn_weights,)
    return outputs

Args:
hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
attention_mask (`torch.FloatTensor`): attention mask of size
`(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
`(config.encoder_attention_heads,)`.
output_attentions (`bool`, *optional*):
Whether or not to return the attentions tensors of all attention layers. See `attentions` under
returned tensors for more detail.


def _check(cls, name, val, can_be_zero=False, val_type=float):
    valid_types = [val_type]
    if (val_type is float):
        valid_types.append(int)
    if (type(val) not in valid_types):
        raise TypeError(('Expect type %s for parameter %s' % (val_type.__name__, name)))
    if (val < 0):
        raise ValueError(('Value for parameter %s has to be greater than 0' % name))
    if ((not can_be_zero) and (val == 0)):
        raise ValueError(('Value for parameter %s can not be 0' % name))
    return val

Check init arguments.

Args:
name: name of the argument. For logging purpose.
val: value. Value has to be non negative number.
can_be_zero: whether value can be zero.
val_type: Python type of the value.

Returns:
The value.

Raises:
ValueError: when invalid value is passed in.
TypeError: when invalid value type is passed in.


def DetermineType(value):
    object_type = type(value)
    if (not hasattr(object_type, '__name__')):
        return None
    type_string = getattr(object_type, '__module__', '')
    if type_string:
        type_string += '.'
    type_string += object_type.__name__
    return type_string

Determines the type of val, returning a "full path" string.

For example:
DetermineType(5) -> __builtin__.int
DetermineType(Foo()) -> com.google.bar.Foo

Args:
value: Any value, the value is irrelevant as only the type metadata
is checked

Returns:
Type path string.  None if type cannot be determined.


def mape(y, p):

    filt = np.abs(y) > EPS
    return np.mean(np.abs(1 - p[filt] / y[filt]))

Mean Absolute Percentage Error (MAPE).

Args:
y (numpy.array): target
p (numpy.array): prediction

Returns:
e (numpy.float64): MAPE


def _evolve(self, state, qargs=None):

        if qargs is not None:
            return SuperOp(self)._evolve(state, qargs)

        state = self._format_state(state)
        if state.shape[0] != self._input_dim:
            raise QiskitError(
                "QuantumChannel input dimension is not equal to state dimension."
            )
        if state.ndim == 1 and self._data[1] is None and len(
                self._data[0]) == 1:

            return np.dot(self._data[0][0], state)

        state = self._format_state(state, density_matrix=True)
        kraus_l, kraus_r = self._data
        if kraus_r is None:
            kraus_r = kraus_l
        return np.einsum('AiB,BC,AjC->ij', kraus_l, state,
                         np.conjugate(kraus_r))

Evolve a quantum state by the QuantumChannel.

Args:
state (QuantumState): The input statevector or density matrix.
qargs (list): a list of QuantumState subsystem positions to apply
the operator on.

Returns:
QuantumState: the output quantum state.

Raises:
QiskitError: if the operator dimension does not match the
specified QuantumState subsystem dimensions.


def get_smeared_densities(self, sigma):

        from scipy.ndimage.filters import gaussian_filter1d
        smeared_dens = {}
        diff = [self.energies[i + 1] - self.energies[i]
                for i in range(len(self.energies) - 1)]
        avgdiff = sum(diff) / len(diff)
        for spin, dens in self.densities.items():
            smeared_dens[spin] = gaussian_filter1d(dens, sigma / avgdiff)
        return smeared_dens

Returns the Dict representation of the densities, {Spin: densities},
but with a Gaussian smearing of std dev sigma applied about the fermi
level.

Args:
sigma: Std dev of Gaussian smearing function.

Returns:
Dict of Gaussian-smeared densities.


def get_mask(self, layers=None, output='vector', in_global_mask=True):
    if in_global_mask:
        output = 'vector'
    if (layers is None):
        layers = self.layers.keys()
    elif (not isinstance(layers, list)):
        layers = [layers]
    layers = map((lambda x: (x if isinstance(x, string_types) else self.stack[x])), layers)
    layers = [self.layers[l] for l in layers if (l in self.layers)]
    layers.append(self.full)
    layers = np.vstack(layers).T.astype(bool)
    mask = layers.all(axis=1)
    mask = self.get_image(mask, output)
    return (mask[self.global_mask] if in_global_mask else mask)

Set the current mask by taking the conjunction of all specified
layers.

Args:
layers: Which layers to include. See documentation for add() for
format.
include_global_mask: Whether or not to automatically include the
global mask (i.e., self.volume) in the conjunction.


def nice_join(seq, sep=', ', conjuction='or'):
    seq = [str(x) for x in seq]
    if ((len(seq) <= 1) or (conjuction is None)):
        return sep.join(seq)
    else:
        return ('%s %s %s' % (sep.join(seq[:(- 1)]), conjuction, seq[(- 1)]))

Join together sequences of strings into English-friendly phrases using
the conjunction ``or`` when appropriate.

Args:
seq (seq[str]) : a sequence of strings to nicely join
sep (str, optional) : a sequence delimiter to use (default: ", ")
conjunction (str or None, optional) : a conjuction to use for the last
two items, or None to reproduce basic join behaviour (default: "or")

Returns:
a joined string

Examples:
>>> nice_join(["a", "b", "c"])
'a, b or c'


Performs the preparation steps before starting the remote server.

For example, subclass can check or modify the device settings at this
stage.

NOTE: Any error at this stage will abort the initialization without cleanup.
So do not acquire resources in this function, or this function should
release the acquired resources if an error occurs.

Raises:
errors.ServerStartPreCheckError: when prechecks for starting the server
failed.


def AtMaximumDepth(self, search_depth):

    if self._location_segments is not None:
      if search_depth >= self._number_of_location_segments:
        return True

    return False

Determines if the find specification is at maximum depth.

Args:
search_depth (int): number of location path segments to compare.

Returns:
bool: True if at maximum depth, False if not.


def create(self, path, mime_type='application/octet-stream', compression_type=CompressionTypes.AUTO):
    return self._path_open(path, 'wb', mime_type, compression_type)

Returns a write channel for the given file path.

Args:
path: string path of the file object to be written to the system
mime_type: MIME type to specify the type of content in the file object
compression_type: Type of compression to be used for this object

Returns: file handle with a close function for the user to use


def broadcast_to(x, shape):
    if any_symbolic_tensors((x,)):
        return BroadcastTo(shape=shape).symbolic_call(x)
    return backend.numpy.broadcast_to(x, shape)

Broadcast a tensor to a new shape.

Args:
x: The tensor to broadcast.
shape: The shape of the desired tensor. A single integer `i` is
interpreted as `(i,)`.

Returns:
A tensor with the desired shape.

Examples:
>>> x = keras.ops.array([1, 2, 3])
>>> keras.ops.broadcast_to(x, (3, 3))
array([[1, 2, 3],
[1, 2, 3],
[1, 2, 3]])


def add_review(self, reviewer, product, review, date=None):

        if not isinstance(reviewer, self._reviewer_cls):
            raise TypeError(
                "Type of given reviewer isn't acceptable:", reviewer,
                ", expected:", self._reviewer_cls)
        elif not isinstance(product, self._product_cls):
            raise TypeError(
                "Type of given product isn't acceptable:", product,
                ", expected:", self._product_cls)
        r = self._review_cls(review, date=date)
        self.graph.add_edge(reviewer, product, review=r)
        return r

Add a new review from a given reviewer to a given product.

Args:
reviewer: an instance of Reviewer.
product: an instance of Product.
review: a float value.
date: date the review issued.

Returns:
the added new review object.

Raises:
TypeError: when given reviewer and product aren't instance of
specified reviewer and product class when this graph is constructed.


def remote_file(self, branch='master', filename=''):

        LOG.info('Retrieving "%s" from "%s".', filename, self.git_short)

        file_contents = ''

        try:
            file_blob = self.project.files.get(file_path=filename, ref=branch)
        except gitlab.exceptions.GitlabGetError:
            file_blob = None

        LOG.debug('GitLab file response:\n%s', file_blob)

        if not file_blob:
            msg = 'Project "{0}" is missing file "{1}" in "{2}" branch.'.format(self.git_short, filename, branch)
            LOG.warning(msg)
            raise FileNotFoundError(msg)
        else:
            file_contents = b64decode(file_blob.content).decode()

        LOG.debug('Remote file contents:\n%s', file_contents)
        return file_contents

Read the remote file on Git Server.

Args:
branch (str): Git Branch to find file.
filename (str): Name of file to retrieve relative to root of
repository.

Returns:
str: Contents of remote file.

Raises:
FileNotFoundError: Requested file missing.


class IncSlidingMeanTracker(IncMeanTracker):

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

Sliding window mean tracker using incremental calculation.

Args:
window_size: The size of the sliding window.


def get_added_vocab(self) -> dict[str, int]:
    return self._added_tokens_encoder

Returns the added tokens in the vocabulary as a dictionary of token to index. Results might be different from
the fast call because for now we always add the tokens even if they are already in the vocabulary. This is
something we should change.

Returns:
`Dict[str, int]`: The added tokens.


def to_query(self, fields=None):

    from . import _query
    if fields is None:
      fields = '*'
    elif isinstance(fields, list):
      fields = ','.join(fields)
    return _query.Query('SELECT %s FROM %s' % (fields, self._repr_sql_()), context=self._context)

Return a Query for this Table.

Args:
fields: the fields to return. If None, all fields will be returned. This can be a string
which will be injected into the Query after SELECT, or a list of field names.

Returns:
A Query object that will return the specified fields from the records in the Table.


def _add_material(self, x_bot_left, y_bot_left, x_top_right, y_top_right, n_material, angle=0):
    x_mask = np.logical_and((x_bot_left <= self.x), (self.x <= x_top_right))
    y_mask = np.logical_and((y_bot_left <= self.y), (self.y <= y_top_right))
    xy_mask = np.kron(y_mask, x_mask).reshape((y_mask.size, x_mask.size))
    self.n[xy_mask] = n_material
    if angle:
        self._add_triangular_sides(xy_mask, angle, y_top_right, y_bot_left, x_top_right, x_bot_left, n_material)
    return self.n

A low-level function that allows writing a rectangle refractive
index profile to a `Structure`.

Args:
x_bot_left (float): The bottom-left x-coordinate of the
rectangle.
y_bot_left (float): The bottom-left y-coordinate of the
rectangle.
x_top_right (float): The top-right x-coordinate of the
rectangle.
y_top_right (float): The top-right y-coordinate of the
rectangle.
n_material (float): The refractive index of the points
encompassed by the defined rectangle.
angle (float): The angle in degrees of the sidewalls
of the defined rectangle.  Default is 0.  This
is useful for creating a ridge with angled
sidewalls.


def _ParseFileEntry(self, knowledge_base, file_entry):
    file_object = file_entry.GetFileObject()
    try:
        self._ParseFileData(knowledge_base, file_object)
    finally:
        file_object.close()

Parses a file entry for a preprocessing attribute.

Args:
knowledge_base (KnowledgeBase): to fill with preprocessing information.
file_entry (dfvfs.FileEntry): file entry that contains the artifact
value data.

Raises:
PreProcessFail: if the preprocessing fails.


def plot(self, figsize=None, rotation=45):

    fig, ax = plt.subplots(figsize=figsize)

    plt.imshow(self._cm, interpolation='nearest', cmap=plt.cm.Blues, aspect='auto')
    plt.title('Confusion matrix')
    plt.colorbar()
    tick_marks = np.arange(len(self._labels))
    plt.xticks(tick_marks, self._labels, rotation=rotation)
    plt.yticks(tick_marks, self._labels)
    if isinstance(self._cm, list):

      thresh = max(max(self._cm)) / 2.
      for i, j in itertools.product(range(len(self._labels)), range(len(self._labels))):
        plt.text(j, i, self._cm[i][j], horizontalalignment="center",
                 color="white" if self._cm[i][j] > thresh else "black")
    else:

      thresh = self._cm.max() / 2.
      for i, j in itertools.product(range(len(self._labels)), range(len(self._labels))):
        plt.text(j, i, self._cm[i, j], horizontalalignment="center",
                 color="white" if self._cm[i, j] > thresh else "black")
    plt.tight_layout()
    plt.ylabel('True label')
    plt.xlabel('Predicted label')

Plot the confusion matrix.

Args:
figsize: tuple (x, y) of ints. Sets the size of the figure
rotation: the rotation angle of the labels on the x-axis.


def save(self, path, compressed=True, exist_ok=False):

        path = os.path.expandvars(os.path.expanduser(path))
        if os.path.isfile(path) and not exist_ok:
            raise OSError(17, os.strerror(17), path)

        if os.path.isdir(path):
            path = os.path.join(path, "out.gdg")

        if compressed:
            bytes_written = cgaddag.gdg_save_compressed(self.gdg, path.encode("ascii"))
        else:
            bytes_written = cgaddag.gdg_save(self.gdg, path.encode("ascii"))

        if bytes_written == -1:
            errno = ctypes.c_int.in_dll(ctypes.pythonapi, "errno").value
            raise OSError(errno, os.strerror(errno), path)

        return bytes_written

Save the GADDAG to file.

Args:
path: path to save the GADDAG to.
compressed: compress the saved GADDAG using gzip.
exist_ok: overwrite existing file at `path`.


def prefix2ns(self, prefix: YangIdentifier, mid: ModuleId) -> YangIdentifier:
    try:
        mdata = self.modules[mid]
    except KeyError:
        raise ModuleNotRegistered(*mid) from None
    try:
        return mdata.prefix_map[prefix][0]
    except KeyError:
        raise UnknownPrefix(prefix, mid) from None

Return the namespace corresponding to a prefix.

Args:
prefix: Prefix associated with a module and its namespace.
mid: Identifier of the module in which the prefix is declared.

Raises:
ModuleNotRegistered: If `mid` is not registered in the data model.
UnknownPrefix: If `prefix` is not declared.


def read32(self, offset):

        if not isinstance(offset, (int, long)):
            raise TypeError("Invalid offset type, should be integer.")

        offset = self._adjust_offset(offset)
        self._validate_offset(offset, 4)
        return struct.unpack("=L", self.mapping[offset:offset + 4])[0]

Read 32-bits from the specified `offset` in bytes, relative to the
base physical address of the MMIO region.

Args:
offset (int, long): offset from base physical address, in bytes.

Returns:
int: 32-bit value read.

Raises:
TypeError: if `offset` type is invalid.
ValueError: if `offset` is out of bounds.


def upload_to_metta(train_features_path, train_labels_path, test_features_path, test_labels_path, train_quarter, test_quarter, num_dimensions):

    train_config = metta_config(train_quarter, num_dimensions)
    test_config = metta_config(test_quarter, num_dimensions)

    X_train = pd.read_csv(train_features_path, sep=',')
    X_train.columns = ['doc2vec_'+str(i) for i in range(X_train.shape[1])]

    Y_train = pd.read_csv(train_labels_path)
    Y_train.columns = ['onet_soc_code']
    train = pd.concat([X_train, Y_train], axis=1)

    X_test = pd.read_csv(test_features_path, sep=',')
    X_test.columns = ['doc2vec_'+str(i) for i in range(X_test.shape[1])]

    Y_test = pd.read_csv(test_labels_path)
    Y_test.columns = ['onet_soc_code']
    test = pd.concat([X_test, Y_test], axis=1)

    metta.archive_train_test(
        train_config,
        X_train,
        test_config,
        X_test,
        directory='wdi'
    )

Store train and test matrices using metta

Args:
train_features_path (str) Path to matrix with train features
train_labels_path (str) Path to matrix with train labels
test_features_path (str) Path to matrix with test features
test_labels_path (str) Path to matrix with test labels
train_quarter (str) Quarter of train matrix
test_quarter (str) Quarter of test matrix
num_dimensions (int) Number of features


def CheckSchema(self, database):

    schema_match = False
    if self.SCHEMAS:
      for schema in self.SCHEMAS:
        if database and database.schema == schema:
          schema_match = True

    return schema_match

Checks the schema of a database with that defined in the plugin.

Args:
database (SQLiteDatabase): database.

Returns:
bool: True if the schema of the database matches that defined by
the plugin, or False if the schemas do not match or no schema
is defined by the plugin.


def _ConvertValueBinaryDataToFloatingPointValue(self, value):

    if not value:
      return None

    value_length = len(value)
    if value_length not in (4, 8):
      raise errors.ParseError('Unsupported value data size: {0:d}'.format(
          value_length))

    if value_length == 4:
      floating_point_map = self._GetDataTypeMap('float32le')
    elif value_length == 8:
      floating_point_map = self._GetDataTypeMap('float64le')

    try:
      return self._ReadStructureFromByteStream(value, 0, floating_point_map)
    except (ValueError, errors.ParseError) as exception:
      raise errors.ParseError(
          'Unable to parse floating-point value with error: {0!s}'.format(
              exception))

Converts a binary data value into a floating-point value.

Args:
value (bytes): binary data value containing an ASCII string or None.

Returns:
float: floating-point representation of binary data value or None if
value is not set.

Raises:
ParseError: if the floating-point value data size is not supported or
if the value cannot be parsed.


def do_put(endpoint, body, access_token):
    headers = {'content-type': 'application/json', 'Authorization': ('Bearer ' + access_token)}
    headers['User-Agent'] = get_user_agent()
    return requests.put(endpoint, data=body, headers=headers)

Do an HTTP PUT request and return JSON.

Args:
endpoint (str): Azure Resource Manager management endpoint.
body (str): JSON body of information to put.
access_token (str): A valid Azure authentication token.

Returns:
HTTP response. JSON body.


def from_json_value(v):
    if isinstance(v, extra_types.JsonValue):
        if v.string_value is not None:
            return v.string_value
        elif v.boolean_value is not None:
            return v.boolean_value
        elif v.integer_value is not None:
            return v.integer_value
        elif v.double_value is not None:
            return v.double_value
        elif v.array_value is not None:
            return from_json_value(v.array_value)
        elif v.object_value is not None:
            return from_json_value(v.object_value)
        elif v.is_null:
            return None
    elif isinstance(v, extra_types.JsonArray):
        return [from_json_value(e) for e in v.entries]
    elif isinstance(v, extra_types.JsonObject):
        return {p.key: from_json_value(p.value) for p in v.properties}
    raise TypeError('Cannot convert %s from a JSON value.' % repr(v))

For internal use only; no backwards-compatibility guarantees.

Converts ``extra_types.JsonValue`` objects into Python objects.

Args:
v: ``JsonValue`` object to be converted.

Returns:
A Python object structured as values, lists, and dictionaries corresponding
to ``JsonValue``, ``JsonArray`` and ``JsonObject`` types.

Raises:
TypeError: if the ``JsonValue`` object contains a type that is
not supported.

The types supported are ``str``, ``bool``, ``list``, ``dict``, and ``None``.
The Dataflow API returns JsonValue(s) in many places and it is quite
convenient to be able to convert these hierarchical objects to much simpler
Python objects.


def print_level(log_function, fmt, level, *args):
    if _SILENT:
        return
    msg = (fmt % args)
    spaces = ('    ' * level)
    log_function(('%s%s' % (spaces, msg)))

Print a formatted message to stdout prepended by spaces. Useful for
printing hierarchical information, like bullet lists.

Note:
If the application is running in "Silent Mode"
(i.e., ``_SILENT == True``), this function will return
immediately and no message will be printed.

Args:
log_function: The function that will be called to output the formatted
message.
fmt (str): A Python formatted string.
level (int): Used to determing how many spaces to print. The formula
is ``'    ' * level ``.
*args: Variable length list of arguments. Values are plugged into the
format string.

Examples:
>>> print_level("%s %d", 0, "TEST", 0)
TEST 0
>>> print_level("%s %d", 1, "TEST", 1)
TEST 1
>>> print_level("%s %d", 2, "TEST", 2)
TEST 2


def clear_agent(self, short_name, client_id):

        if short_name not in self.services:
            raise ArgumentError("Unknown service name", short_name=short_name)

        if short_name not in self.agents:
            raise ArgumentError("No agent registered for service", short_name=short_name)

        if client_id != self.agents[short_name]:
            raise ArgumentError("Client was not registered for service", short_name=short_name,
                                client_id=client_id, current_client=self.agents[short_name])

        del self.agents[short_name]

Remove a client id from being the command handler for a service.

Args:
short_name (str): The name of the service to set an agent
for.
client_id (str): A globally unique id for the client that
should no longer receive commands for this service.


def get_staged_signatures(vcs):

    staged_path = _get_staged_history_path(vcs)
    known_signatures = []
    if os.path.exists(staged_path):
        with open(staged_path, 'r') as f:
            known_signatures = f.read().split()
    return known_signatures

Get the list of staged signatures

Args:
vcs (easyci.vcs.base.Vcs)

Returns:
list(basestring) - list of signatures


def combine_assignments(self, assignments):
    group_by_fn = collections.defaultdict(list)
    for a in assignments:
        if (not isinstance(a, Assign)):
            raise ValueError('ops should be instances of mtf.Assign')
        group_by_fn[a.assign_fn].append(a)
    assignments_set = set(assignments)
    self._operations = [op for op in self._operations if (op not in assignments_set)]
    ret = []
    for (fn, ops) in six.iteritems(group_by_fn):
        variables = []
        values = []
        for a in ops:
            variables.extend(a.variables)
            values.extend(a.inputs)
        ret.append(Assign(variables, values, fn))
    return ret

Rewrite the current graph to combine "Assign" operations.

Combine similar Assign operations into grouped Assign operations.
This is useful when using the rewrite_stack_variables() optimization,
since variables can only be stacked if they are present in the same set
of Assign operations.

This function takes a list of Assign operations and returns a possibly
shorter list of Assign operations.  The input Assignment operations
are removed from the graph and become invalid.

Args:
assignments: a list of Assign objects
Returns:
a list of Assign objects


def register_layouts(layouts, app, url="/api/props/", brand="Pyxley"):

    def props(name):
        if name not in layouts:

            name = list(layouts.keys())[0]
        return jsonify({"layouts": layouts[name]["layout"]})

    def apps():
        paths = []
        for i, k in enumerate(layouts.keys()):
            if i == 0:
                paths.append({
                    "path": "/",
                    "label": layouts[k].get("title", k)
                })

            paths.append({
                "path": "/"+k,
                "label": layouts[k].get("title", k)
            })

        return jsonify({"brand": brand, "navlinks": paths})

    app.add_url_rule(url+"<string:name>/", view_func=props)
    app.add_url_rule(url, view_func=apps)

register UILayout with the flask app

create a function that will send props for each UILayout

Args:
layouts (dict): dict of UILayout objects by name
app (object): flask app
url (string): address of props; default is /api/props/


def when_matches_async(self, path, good_value, bad_values=None):
    when = When(good_value, bad_values)
    future = self.subscribe(path, when)
    when.set_future_context(future, weakref.proxy(self))
    return future

Wait for an attribute to become a given value

Args:
path (list): The path to wait to
good_value: If it is a callable then expect it to return
True if we are satisfied and raise on error. If it is not
callable then compare each value against this one and return
if it matches.
bad_values (list): values to raise an error on

Returns:
Future: a single Future that will resolve when the path matches
good_value or bad_values


def parse_message(message):
    error_message = []
    func_tags = []
    node_tags = []
    pos = 0
    for match in re.finditer(_INTERPOLATION_PATTERN, message):
        parsed_tag = _ParseTag(match.group('type'), match.group('name'))
        if parsed_tag.type == 'function_node':
            error_message.append(match.group('sep'))
            func_tags.append(parsed_tag)
        else:
            error_message.append(match.group())
            node_tags.append(parsed_tag)
        pos = match.end()
    error_message.append(message[pos:])
    return (''.join(error_message), func_tags, node_tags)

Extract function tags and node tags from a message.

Tags are named tuples representing the string {{type name}}. For example,
in "123{{node Foo}}456{{function_node Bar}}789", there are two tags: a node
tag and a function tag.

Args:
message: An error message, possibly from an OpError.

Returns:
A tuple containing the original message with function nodes stripped,
function tags, and node tags.

For example, if message is "123{{node Foo}}456{{function_node Bar}}789"
then this function returns ("123{{node Foo}}456789",
[_ParseTag("function_node", "Bar")], [_ParseTag("node", "Foo")]).


def batch_insert(self, records, typecast=False):

        return self._batch_request(self.insert, records)

Calls :any:`insert` repetitively, following set API Rate Limit (5/sec)
To change the rate limit use ``airtable.API_LIMIT = 0.2``
(5 per second)

>>> records = [{'Name': 'John'}, {'Name': 'Marc'}]
>>> airtable.batch_insert(records)

Args:
records(``list``): Records to insert
typecast(``boolean``): Automatic data conversion from string values.

Returns:
records (``list``): list of added records


def _pull_out_perm_lhs(lhs, rest, out_port, in_port):
    (out_inv, lhs_red) = lhs._factor_lhs(out_port)
    return (lhs_red << Feedback.create(SeriesProduct.create(*rest), out_port=out_inv, in_port=in_port))

Pull out a permutation from the Feedback of a SeriesProduct with itself.

Args:
lhs (CPermutation): The permutation circuit
rest (tuple): The other SeriesProduct operands
out_port (int): The feedback output port index
in_port (int): The feedback input port index

Returns:
Circuit: The simplified circuit


def isprocess(pid, error=False):
    try:
        os.kill(pid, 0)
        return True
    except OSError:
        return False

Check that a process is running.

Arguments:

pid (int): Process ID to check.

Returns:

True if the process is running, else false.


def _examples_from_path_handler(self, request):
    examples_count = int(request.args.get('max_examples'))
    examples_path = request.args.get('examples_path')
    sampling_odds = float(request.args.get('sampling_odds'))
    self.example_class = (tf.train.SequenceExample if (request.args.get('sequence_examples') == 'true') else tf.train.Example)
    try:
        platform_utils.throw_if_file_access_not_allowed(examples_path, self._logdir, self._has_auth_group)
        example_strings = platform_utils.example_protos_from_path(examples_path, examples_count, parse_examples=False, sampling_odds=sampling_odds, example_class=self.example_class)
        self.examples = [self.example_class.FromString(ex) for ex in example_strings]
        self.generate_sprite(example_strings)
        json_examples = [json_format.MessageToJson(example) for example in self.examples]
        self.updated_example_indices = set(range(len(json_examples)))
        return http_util.Respond(request, {'examples': json_examples, 'sprite': (True if self.sprite else False)}, 'application/json')
    except common_utils.InvalidUserInputError as e:
        return http_util.Respond(request, {'error': e.message}, 'application/json', code=400)

Returns JSON of the specified examples.

Args:
request: A request that should contain 'examples_path' and 'max_examples'.

Returns:
JSON of up to max_examlpes of the examples in the path.


def unsubscribe(self, topic):
    del self.queues[topic]
    try:
        self.client.unsubscribe(topic)
    except operationError as exc:
        raise InternalError('Could not unsubscribe from topic', topic=topic, message=exc.message)

Unsubscribe from messages on a given topic

Args:
topic (string): The MQTT topic to unsubscribe from


def get_table_metadata(engine, table):

    metadata = MetaData()
    metadata.reflect(bind=engine, only=[table])
    table_metadata = Table(table, metadata, autoload=True)
    return table_metadata

Extract all useful infos from the given table

Args:
engine: SQLAlchemy connection engine
table: table name

Returns:
Dictionary of infos


def _duplicate_example(self, request):

    index = int(request.args.get('index'))
    if index >= len(self.examples):
      return http_util.Respond(request, {'error': 'invalid index provided'},
                               'application/json', code=400)
    new_example = self.example_class()
    new_example.CopyFrom(self.examples[index])
    self.examples.append(new_example)
    self.updated_example_indices.add(len(self.examples) - 1)
    self.generate_sprite([ex.SerializeToString() for ex in self.examples])
    return http_util.Respond(request, {}, 'application/json')

Duplicates the specified example.

Args:
request: A request that should contain 'index'.

Returns:
An empty response.


def similar_text(self, *args, **kwargs):
    return SimilarRequest(self, *args, mode='text', **kwargs).send()

Search for documents that are similar to directly supplied text or to the textual content of an existing document.

Args:
text -- Text to found something similar to.
len -- Number of keywords to extract from the source.
quota -- Minimum number of keywords matching in the destination.

Keyword args:
offset -- Number of results to skip before returning the following ones.
docs -- Number of documents to retrieve. Default is 10.
query -- An optional query that all found documents have to match against. See Search().
See Request.__init__()

Returns:
A ListResponse object.


def connect(self, funds: typing.TokenAmount, initial_channel_target: int=3, joinable_funds_target: float=0.4):
    token = self.raiden.chain.token(self.token_address)
    token_balance = token.balance_of(self.raiden.address)
    if (token_balance < funds):
        raise InvalidAmount(f'Insufficient balance for token {pex(self.token_address)}')
    if (funds <= 0):
        raise InvalidAmount('The funds to use in the connection need to be a positive integer')
    if ((joinable_funds_target < 0) or (joinable_funds_target > 1)):
        raise InvalidAmount(f'joinable_funds_target should be between 0 and 1. Given: {joinable_funds_target}')
    with self.lock:
        self.funds = funds
        self.initial_channel_target = initial_channel_target
        self.joinable_funds_target = joinable_funds_target
        log_open_channels(self.raiden, self.registry_address, self.token_address, funds)
        qty_network_channels = views.count_token_network_channels(views.state_from_raiden(self.raiden), self.registry_address, self.token_address)
        if (not qty_network_channels):
            log.info('Bootstrapping token network.', node=pex(self.raiden.address), network_id=pex(self.registry_address), token_id=pex(self.token_address))
            self.api.channel_open(self.registry_address, self.token_address, self.BOOTSTRAP_ADDR)
        else:
            self._open_channels()

Connect to the network.

Subsequent calls to `connect` are allowed, but will only affect the spendable
funds and the connection strategy parameters for the future. `connect` will not
close any channels.

Note: the ConnectionManager does not discriminate manually opened channels from
automatically opened ones. If the user manually opened channels, those deposit
amounts will affect the funding per channel and the number of new channels opened.

Args:
funds: Target amount of tokens spendable to join the network.
initial_channel_target: Target number of channels to open.
joinable_funds_target: Amount of funds not initially assigned.


def get_string(self, distance=6, velocity=8, charge=3):
    file_template = 'Generated by pymatgen.io.lammps.data.LammpsData\n\n{stats}\n\n{box}\n\n{body}\n'
    box = self.box.get_string(distance)
    body_dict = OrderedDict()
    body_dict['Masses'] = self.masses
    types = OrderedDict()
    types['atom'] = len(self.masses)
    if self.force_field:
        all_ff_kws = (SECTION_KEYWORDS['ff'] + SECTION_KEYWORDS['class2'])
        ff_kws = [k for k in all_ff_kws if (k in self.force_field)]
        for kw in ff_kws:
            body_dict[kw] = self.force_field[kw]
            if (kw in SECTION_KEYWORDS['ff'][2:]):
                types[kw.lower()[:(- 7)]] = len(self.force_field[kw])
    body_dict['Atoms'] = self.atoms
    counts = OrderedDict()
    counts['atoms'] = len(self.atoms)
    if (self.velocities is not None):
        body_dict['Velocities'] = self.velocities
    if self.topology:
        for kw in SECTION_KEYWORDS['topology']:
            if (kw in self.topology):
                body_dict[kw] = self.topology[kw]
                counts[kw.lower()] = len(self.topology[kw])
    all_stats = (list(counts.values()) + list(types.values()))
    stats_template = ('{:>%d}  {}' % len(str(max(all_stats))))
    count_lines = [stats_template.format(v, k) for (k, v) in counts.items()]
    type_lines = [stats_template.format(v, (k + ' types')) for (k, v) in types.items()]
    stats = '\n'.join(((count_lines + ['']) + type_lines))
    map_coords = (lambda q: ('{:.%df}' % distance).format(q))
    map_velos = (lambda q: ('{:.%df}' % velocity).format(q))
    map_charges = (lambda q: ('{:.%df}' % charge).format(q))
    formatters = {'x': map_coords, 'y': map_coords, 'z': map_coords, 'vx': map_velos, 'vy': map_velos, 'vz': map_velos, 'q': map_charges}
    section_template = '{kw}\n\n{df}\n'
    parts = []
    for (k, v) in body_dict.items():
        index = (True if (k != 'PairIJ Coeffs') else False)
        df_string = v.to_string(header=False, formatters=formatters, index_names=False, index=index)
        parts.append(section_template.format(kw=k, df=df_string))
    body = '\n'.join(parts)
    return file_template.format(stats=stats, box=box, body=body)

Returns the string representation of LammpsData, essentially
the string to be written to a file.

Args:
distance (int): No. of significant figures to output for
box settings (bounds and tilt) and atomic coordinates.
Default to 6.
velocity (int): No. of significant figures to output for
velocities. Default to 8.
charge (int): No. of significant figures to output for
charges. Default to 3.

Returns:
String representation


def ack_deadline(self):
    target = min([(self._last_histogram_size * 2), (self._last_histogram_size + 100)])
    if (len(self.ack_histogram) > target):
        self._ack_deadline = self.ack_histogram.percentile(percent=99)
    return self._ack_deadline

Return the current ack deadline based on historical time-to-ack.

This method is "sticky". It will only perform the computations to
check on the right ack deadline if the histogram has gained a
significant amount of new information.

Returns:
int: The ack deadline.


def PrivateKeyFromNEP2(nep2_key, passphrase):
    if ((not nep2_key) or (len(nep2_key) != 58)):
        raise ValueError('Please provide a nep2_key with a length of 58 bytes (LEN: {0:d})'.format(len(nep2_key)))
    ADDRESS_HASH_SIZE = 4
    ADDRESS_HASH_OFFSET = (len(NEP_FLAG) + len(NEP_HEADER))
    try:
        decoded_key = base58.b58decode_check(nep2_key)
    except Exception as e:
        raise ValueError('Invalid nep2_key')
    address_hash = decoded_key[ADDRESS_HASH_OFFSET:(ADDRESS_HASH_OFFSET + ADDRESS_HASH_SIZE)]
    encrypted = decoded_key[(- 32):]
    pwd_normalized = bytes(unicodedata.normalize('NFC', passphrase), 'utf-8')
    derived = scrypt.hash(pwd_normalized, address_hash, N=SCRYPT_ITERATIONS, r=SCRYPT_BLOCKSIZE, p=SCRYPT_PARALLEL_FACTOR, buflen=SCRYPT_KEY_LEN_BYTES)
    derived1 = derived[:32]
    derived2 = derived[32:]
    cipher = AES.new(derived2, AES.MODE_ECB)
    decrypted = cipher.decrypt(encrypted)
    private_key = xor_bytes(decrypted, derived1)
    kp_new = KeyPair(priv_key=private_key)
    kp_new_address = kp_new.GetAddress()
    kp_new_address_hash_tmp = hashlib.sha256(kp_new_address.encode('utf-8')).digest()
    kp_new_address_hash_tmp2 = hashlib.sha256(kp_new_address_hash_tmp).digest()
    kp_new_address_hash = kp_new_address_hash_tmp2[:4]
    if (kp_new_address_hash != address_hash):
        raise ValueError('Wrong passphrase')
    return private_key

Gets the private key from a NEP-2 encrypted private key

Args:
nep2_key (str): The nep-2 encrypted private key
passphrase (str): The password to encrypt the private key with, as unicode string

Returns:
bytes: The private key


def __init__(self, min_shard_bytes=256 << 10, max_shards=1, bytes_per_string=16):
    if min_shard_bytes < 1:
        raise ValueError(f'Argument `min_shard_bytes` must be positive. Received: {min_shard_bytes}')
    if max_shards < 1:
        raise ValueError(f'Argument `max_shards` must be positive. Received: {max_shards}')
    if bytes_per_string < 1:
        raise ValueError(f'Argument `bytes_per_string` must be positive. Received: {bytes_per_string}')
    self._min_shard_bytes = min_shard_bytes
    self._max_shards = max_shards
    self._bytes_per_string = bytes_per_string

Creates a new `MinSizePartitioner`.

Args:
min_shard_bytes: Minimum bytes of each shard. Defaults to 256K.
max_shards: Upper bound on the number of shards. Defaults to 1.
bytes_per_string: If the partition value is of type string, this provides
an estimate of how large each string is.


def AddDir(self, dirpath):
    if (dirpath not in self._dirs):
        self._dirs.add(dirpath)
        return True
    return False

Adds a directory path as a source.

Args:
dirpath: a string representing a path to the directory.

Returns:
True if the directory is not an already existing source.


def tf_step(self, time, variables, **kwargs):

        fn_loss = kwargs["fn_loss"]
        if variables is None:
            variables = tf.trainable_variables
        return tf.gradients(fn_loss, variables)

Creates the TensorFlow operations for performing an optimization step on the given variables, including
actually changing the values of the variables.

Args:
time: Time tensor. Not used for this optimizer.
variables: List of variables to optimize.
**kwargs:
fn_loss : loss function tensor to differentiate.

Returns:
List of delta tensors corresponding to the updates for each optimized variable.


def _get_files_set(path, start_tag, end_tag):
    with open(path, 'r') as f:
        contents = f.read()
        start = contents.find(start_tag) + len(start_tag) + 1
        end = contents.find(end_tag)
        contents = contents[start:end]
        file_paths = [file_path.strip().strip('"') for file_path in contents.split(',')]
        return set((file_path for file_path in file_paths if file_path))

Get set of file paths from the given file.

Args:
path: Path to file. File at `path` is expected to contain a list of paths
where entire list starts with `start_tag` and ends with `end_tag`. List
must be comma-separated and each path entry must be surrounded by double
quotes.
start_tag: String that indicates start of path list.
end_tag: String that indicates end of path list.

Returns:
List of string paths.


def path_size(p: tcod.path.AStar) -> int:
    return int(lib.TCOD_path_size(p._path_c))

Return the current length of the computed path.

Args:
p (AStar): An AStar instance.
Returns:
int: Length of the path.


def GetLineWidth(line):
    if isinstance(line, unicode):
        width = 0
        for uc in unicodedata.normalize('NFC', line):
            if (unicodedata.east_asian_width(uc) in ('W', 'F')):
                width += 2
            elif (not unicodedata.combining(uc)):
                width += 1
        return width
    else:
        return len(line)

Determines the width of the line in column positions.

Args:
line: A string, which may be a Unicode string.

Returns:
The width of the line in column positions, accounting for Unicode
combining characters and wide characters.


def transpose(self, name=None):
    if (name is None):
        name = (self.module_name + '_transpose')
    return AddBias(output_shape=(lambda : self._input_shape), bias_dims=self._bias_dims, initializers=self._initializers, regularizers=self._regularizers, name=name)

Returns transposed `AddBias` module.

Args:
name: Optional string assigning name of transpose module. The default name
is constructed by appending "_transpose" to `self.module_name`.

Returns:
Transposed `AddBias` module.


def _make_callable(self, feed_arrays, feed_symbols, symbol_vals, session):
    callable_opts = config_pb2.CallableOptions()
    for x in feed_arrays:
        callable_opts.feed.append(x.name)
    if self.feed_dict:
        for key in sorted(self.feed_dict.keys()):
            callable_opts.feed.append(key.name)
    for x, y in zip(feed_symbols, symbol_vals):
        connection = callable_opts.tensor_connection.add()
        if x.dtype != y.dtype:
            y = math_ops.cast(y, dtype=x.dtype)
        from_tensor = _as_graph_element(y)
        if from_tensor is None:
            from_tensor = y
        connection.from_tensor = from_tensor.name
        connection.to_tensor = x.name
    for x in self.outputs + self.fetches:
        callable_opts.fetch.append(x.name)
    callable_opts.target.append(self.updates_op.name)
    if self.run_options:
        callable_opts.run_options.CopyFrom(self.run_options)
    callable_fn = session._make_callable_from_options(callable_opts)
    self._callable_fn = callable_fn
    self._feed_arrays = feed_arrays
    self._feed_symbols = feed_symbols
    self._symbol_vals = symbol_vals
    self._fetches = list(self.fetches)
    self._session = session

Generates a callable that runs the graph.

Args:
feed_arrays: List of input tensors to be fed Numpy arrays at runtime.
feed_symbols: List of input tensors to be fed symbolic tensors at runtime.
symbol_vals: List of symbolic tensors to be fed to `feed_symbols`.
session: Session to use to generate the callable.

Returns:
Function that runs the graph according to the above options.


def apply(self, elements, *args, **kwargs):
    return self.extract_output(self.add_inputs(self.create_accumulator(*args, **kwargs), elements, *args, **kwargs), *args, **kwargs)

Returns result of applying this CombineFn to the input values.

Args:
elements: the set of values to combine.
*args: Additional arguments and side inputs.
**kwargs: Additional arguments and side inputs.


def check_valid(money):

    if not isinstance(money, sc_messages.Money):
        raise ValueError(u'Inputs should be of type %s' % (sc_messages.Money,))
    currency = money.currencyCode
    if not currency or len(currency) != 3:
        raise ValueError(_MSG_3_LETTERS_LONG)
    units = money.units
    nanos = money.nanos
    if ((units > 0) and (nanos < 0)) or ((units < 0) and (nanos > 0)):
        raise ValueError(_MSG_UNITS_NANOS_MISMATCH)
    if abs(nanos) > MAX_NANOS:
        raise ValueError(_MSG_NANOS_OOB)

Determine if an instance of `Money` is valid.

Args:
money (:class:`endpoints_management.gen.servicecontrol_v1_messages.Money`): the
instance to test

Raises:
ValueError: if the money instance is invalid


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

Stop the environment.

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

Raises:
GitlabAuthenticationError: If authentication is not correct
GitlabStopError: If the operation failed


def bernoulli(key, mean=np.float32(0.5), shape=None):
    mean = tf_np.asarray(mean)
    if shape is None:
        shape = mean.shape
    return uniform(key, shape) < mean

Sample Bernoulli random values with given shape and mean.

Args:
key: the RNG key.
mean: optional, an array_like broadcastable to `shape` for the mean of the
random variables (default 0.5).
shape: optional, a tuple of nonnegative integers representing the shape
(default to `mean`'s shape).

Returns:
A random array with the specified shape and boolean dtype.


def stringify(self, use_bytes=False):

        def _str_value(value):
            if isinstance(value, (list, tuple)):
                value = (self.EOL + '\t').join(map(_str_value, value))
            elif callable(value):
                value = _str_value(value())
            return value

        s = self.EOL.join(("{key}: {value}".format(key=key,
                                                   value=_str_value(value))
                           for key, value in self._header_data.values()
                           if value is not None))
        return s + (self.EOL * 2)

Returns representation of headers as a valid HTTP header string. This
is called by __str__.

Args:
use_bytes (bool): Returns a bytes object instead of a str.


def decrypt_report(self, device_id, root, data, **kwargs):
    report_key = self._verify_derive_key(device_id, root, **kwargs)
    try:
        from Crypto.Cipher import AES
        import Crypto.Util.Counter
    except ImportError:
        raise NotFoundError
    ctr = Crypto.Util.Counter.new(128)
    encryptor = AES.new(bytes(report_key[:16]), AES.MODE_CTR, counter=ctr)
    decrypted = encryptor.decrypt(bytes(data))
    return {'data': decrypted}

Decrypt a buffer of report data on behalf of a device.

Args:
device_id (int): The id of the device that we should encrypt for
root (int): The root key type that should be used to generate the report
data (bytearray): The data that we should decrypt
**kwargs: There are additional specific keyword args that are required
depending on the root key used.  Typically, you must specify
- report_id (int): The report id
- sent_timestamp (int): The sent timestamp of the report

These two bits of information are used to construct the per report
signing and encryption key from the specific root key type.

Returns:
dict: The decrypted data and any associated metadata about the data.
The data itself must always be a bytearray stored under the 'data'
key, however additional keys may be present depending on the encryption method
used.

Raises:
NotFoundError: If the auth provider is not able to decrypt the data.


def list_stack(list_, opts):
    assert isinstance(opts, ListStackOpts)
    if isinstance(list_, tensor_array_ops.TensorArray):
        return _tf_tensorarray_stack(list_)
    elif tensor_util.is_tf_type(list_):
        if list_.dtype == dtypes.variant:
            return _tf_tensor_list_stack(list_, opts)
        else:
            return list_
    else:
        return _py_list_stack(list_, opts)

The list stack function.

This does not have a direct correspondent in Python. The closest idiom to
this is tf.append or np.stack. It's different from those in the sense that it
accepts a Tensor list, rather than a list of tensors. It can also accept
TensorArray. When the target is anything else, the dispatcher will rely on
ctx.original_call for fallback.

Args:
list_: An entity that supports append semantics.
opts: A ListStackOpts object.

Returns:
The output of the stack operation, typically a Tensor.


def get_v1_names(symbol: Any) -> Sequence[str]:
    names_v1 = []
    tensorflow_api_attr_v1 = API_ATTRS_V1[TENSORFLOW_API_NAME].names
    keras_api_attr_v1 = API_ATTRS_V1[KERAS_API_NAME].names
    if not hasattr(symbol, '__dict__'):
        return names_v1
    if tensorflow_api_attr_v1 in symbol.__dict__:
        names_v1.extend(getattr(symbol, tensorflow_api_attr_v1))
    if keras_api_attr_v1 in symbol.__dict__:
        names_v1.extend(getattr(symbol, keras_api_attr_v1))
    return names_v1

Get a list of TF 1.* names for this symbol.

Args:
symbol: symbol to get API names for.

Returns:
List of all API names for this symbol.


def getVarianceComps(self, univariance=False):

        RV=sp.zeros((self.P,self.n_randEffs))
        for term_i in range(self.n_randEffs):
            RV[:,term_i] = self.getTraitCovar(term_i).diagonal()
        if univariance:
            RV /= RV.sum(1)[:,sp.newaxis]
        return RV

Return the estimated variance components

Args:
univariance:   Boolean indicator, if True variance components are normalized to sum up to 1 for each trait
Returns:
variance components of all random effects on all phenotypes [P, n_randEffs matrix]


def set_datetime_format(self, format):
    if (not (format in ['UNIX', 'RFC3339'])):
        return
    self.datetime_format = format
    self.set_header('Accept-Datetime-Format', self.datetime_format)

Set the Accept-Datetime-Format header to an acceptable
value

Args:
format: UNIX or RFC3339