def get_records(self, name):
    if (name in self._cache):
        return self._cache[name].values()
    else:
        return []

Return all the records for the given name in the cache.

Args:
name (string): The name which the required models are stored under.

Returns:
list: A list of :class:`cinder_data.model.CinderModel` models.


def _get_storage_model():
    storage_model_settings = getattr(django.conf.settings, 'GOOGLE_OAUTH2_STORAGE_MODEL', None)
    if (storage_model_settings is not None):
        return (storage_model_settings['model'], storage_model_settings['user_property'], storage_model_settings['credentials_property'])
    else:
        return (None, None, None)

This configures whether the credentials will be stored in the session
or the Django ORM based on the settings. By default, the credentials
will be stored in the session, unless `GOOGLE_OAUTH2_STORAGE_MODEL`
is found in the settings. Usually, the ORM storage is used to integrate
credentials into an existing Django user system.

Returns:
A tuple containing three strings, or None. If
``GOOGLE_OAUTH2_STORAGE_MODEL`` is configured, the tuple
will contain the fully qualifed path of the `django.db.model`,
the name of the ``django.contrib.auth.models.User`` field on the
model, and the name of the
:class:`oauth2client.contrib.django_util.models.CredentialsField`
field on the model. If Django ORM storage is not configured,
this function returns None.


def encode_json_body(data):

    if hasattr(data, "read"):
        return data

    response.content_type = "application/json; charset=utf-8"

    return json.dumps(
        data,
        indent=4,
        separators=(',', ': ')
    )

Return prettified JSON `data`, set ``response.content_type`` to
``application/json; charset=utf-8``.

Args:
data (any): Any basic python data structure.

Returns:
str: Data converted to prettified JSON.


def GetEntries(self, parser_mediator, match=None, **unused_kwargs):
    if ('RememberedNetworks' not in match):
        return
    for wifi in match['RememberedNetworks']:
        ssid = wifi.get('SSIDString', 'UNKNOWN_SSID')
        security_type = wifi.get('SecurityType', 'UNKNOWN_SECURITY_TYPE')
        event_data = plist_event.PlistTimeEventData()
        event_data.desc = '[WiFi] Connected to network: <{0:s}> using security {1:s}'.format(ssid, security_type)
        event_data.key = 'item'
        event_data.root = '/RememberedNetworks'
        datetime_value = wifi.get('LastConnected', None)
        if datetime_value:
            event = time_events.PythonDatetimeEvent(datetime_value, definitions.TIME_DESCRIPTION_WRITTEN)
        else:
            date_time = dfdatetime_semantic_time.SemanticTime('Not set')
            event = time_events.DateTimeValuesEvent(date_time, definitions.TIME_DESCRIPTION_NOT_A_TIME)
        parser_mediator.ProduceEventWithEventData(event, event_data)

Extracts relevant Airport entries.

Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
match (Optional[dict[str: object]]): keys extracted from PLIST_KEYS.


def list_offers(access_token, subscription_id, location, publisher):
    endpoint = ''.join([get_rm_endpoint(), '/subscriptions/', subscription_id, '/providers/Microsoft.Compute/', 'locations/', location, '/publishers/', publisher, '/artifacttypes/vmimage/offers?api-version=', COMP_API])
    return do_get(endpoint, access_token)

List available VM image offers from a publisher.

Args:
access_token (str): A valid Azure authentication token.
subscription_id (str): Azure subscription id.
location (str): Azure data center location. E.g. westus.
publisher (str): Publisher name, e.g. Canonical.

Returns:
HTTP response with JSON list of image offers.


def _get_batch_data(self, batch_size, num_objects, num_features):

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

Assembles a batch of input tensors and output labels.

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

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


def write_top_half(f, row_metadata_df, col_metadata_df, metadata_null, filler_null):

    size_of_top_half_df = (1 + col_metadata_df.shape[1],
                           1 + row_metadata_df.shape[1] + col_metadata_df.shape[0])

    top_half_df = pd.DataFrame(np.full(size_of_top_half_df, filler_null, dtype=object))

    top_half_df.iloc[0, :] = np.hstack(("id", row_metadata_df.columns.values, col_metadata_df.index.values))

    top_half_df.iloc[range(1, top_half_df.shape[0]), 0] = col_metadata_df.columns.values

    col_metadata_indices = (range(1, top_half_df.shape[0]),
                            range(1 + row_metadata_df.shape[1], top_half_df.shape[1]))

    top_half_df.at[col_metadata_indices[0], col_metadata_indices[1]] = (
        col_metadata_df.astype(str).replace("nan", value=metadata_null).T.values)

    top_half_df.to_csv(f, header=False, index=False, sep="\t")

Write the top half of the gct file: top-left filler values, row metadata
headers, and top-right column metadata.

Args:
f (file handle): handle for output file
row_metadata_df (pandas df)
col_metadata_df (pandas df)
metadata_null (string): how to represent missing values in the metadata
filler_null (string): what value to fill the top-left filler block with

Returns:
None


def _fn(arg0, arg1, deprecated=True):
    return arg0 + arg1 if deprecated else arg1 + arg0

fn doc.

Args:
arg0: Arg 0.
arg1: Arg 1.
deprecated: Deprecated!

Returns:
Sum of args.


def add_request(self, request):
    queue_item = QueueItem(request, Response(request.url))
    self.add(queue_item)
    return queue_item

Add a request to the queue.

Args:
request (:class:`nyawc.http.Request`): The request to add.

Returns:
:class:`nyawc.QueueItem`: The created queue item.


def __init__(self, options, queue_item):

        self.__options = options
        self.__queue_item = queue_item

        self.__queue_item.response = self.__make_request(
            self.__queue_item.request.url,
            self.__queue_item.request.method,
            self.__queue_item.request.data,
            self.__queue_item.request.auth,
            self.__queue_item.request.cookies,
            self.__queue_item.request.headers,
            self.__queue_item.request.proxies,
            self.__queue_item.request.timeout,
            self.__queue_item.request.verify
        )

        self.__queue_item.response.url = str(self.__queue_item.response.url)

Construct the HTTP handler.

Args:
options (:class:`nyawc.Options`): The settins/options object.
queue_item (:class:`nyawc.QueueItem`): The queue item containing the request.


def _add_result(self, dict_entry, entry, dt, start_time):

    time_entry = {}
    time_entry['dt'] = dt
    time_entry['start_time'] = start_time
    dict_entry[entry] = time_entry

Adds a result to the dictionary.

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


def __init__(self, name, lim_low=85., lim_high=95., **kwargs):

        self.lim_low = lim_low
        self.lim_high = lim_high
        super(DayNightCompositor, self).__init__(name, **kwargs)

Collect custom configuration values.

Args:
lim_low (float): lower limit of Sun zenith angle for the
blending of the given channels
lim_high (float): upper limit of Sun zenith angle for the
blending of the given channels


def __init__(self, parent=None):

        super(DelimiterSelectionWidget, self).__init__(parent)
        self.semicolonRadioButton = None
        self.commaRadioButton = None
        self.tabRadioButton = None
        self.otherRadioButton = None
        self.otherSeparatorLineEdit = None
        self._initUI()

Constructs the object with the given parent.

Args:
parent (QObject, optional): Causes the objected to be owned
by `parent` instead of Qt. Defaults to `None`.


def get_battery_level(self):
    battery_level = self.get_characteristic_handle_from_uuid(UUID_BATTERY_LEVEL)
    if (battery_level is None):
        logger.warn('Failed to find handle for battery level')
        return None
    level = self.dongle._read_attribute(self.conn_handle, battery_level)
    if (level is None):
        return (- 1)
    return ord(level)

Reads the battery level descriptor on the device.

Returns:
int. If successful this will be a positive value representing the current
battery level as a percentage. On error, -1 is returned.


def _get_output_tensors(self, interpreter: _interpreter.Interpreter) -> List[np.ndarray]:
    outputs = []
    for output_detail in interpreter.get_output_details():
        tensor = interpreter.get_tensor(output_detail['index'])
        if output_detail['dtype'] == np.int8:
            quant_params = _get_quant_params(output_detail)
            if quant_params:
                scale, zero_point = quant_params
                tensor = ((tensor.astype(np.float32) - zero_point) * scale).astype(np.float32)
        outputs.append(tensor)
    return outputs

Returns output tensors of given TFLite model Interpreter.

Args:
interpreter: a tf.lite.Interpreter object with allocated tensors.

Returns:
a list of numpy arrays representing output tensor results.


def getattr_sdk(attr, name):
    if inspect.isroutine(attr):
        if hasattr(attr, '_sdkmeta'):
            return attr
    raise AttributeError(name)

Filter SDK attributes

Args:
attr(attribute): Attribute as returned by :func:`getattr`.
name(str): Attribute name.

Returns:
`attr` if passed.


def _UpdateCounters(self, event):

    self._session.parsers_counter['total'] += 1

    parser_name = getattr(event, 'parser', '')
    _, _, parser_name = parser_name.rpartition('/')
    if not parser_name:
      parser_name = 'N/A'
    self._session.parsers_counter[parser_name] += 1

Updates the counters.

Args:
event (EventObject): event.


def __init__(self, initializer=None):

    if initializer is None:
      self.data = []
      return
    if isinstance(initializer, Timeseries):
      self.data = copy.deepcopy(initializer.data)
      return
    raise RuntimeError("Unrecognized initializer.")

Create a timeseries with an optional initializer.

Args:
initializer: An optional Timeseries to clone.

Raises:
RuntimeError: If initializer is not understood.


def put(cls, obj):

        return PyarrowOnRayFramePartition(ray.put(pyarrow.Table.from_pandas(obj)))

Put an object in the Plasma store and wrap it in this object.

Args:
obj: The object to be put.

Returns:
A `RayRemotePartition` object.


def dot(A, B):

    try:
        result = A.__matmul__(B)
        if result is NotImplemented:
            result = B.__rmatmul__(A)
    except AttributeError:
        result = B.__rmatmul__(A)
    return result

Matrix multiplication between A and B

This function is equivalent to ``A @ B``, which is unfortunately
not possible under python 2.x.

Args:
A (sequence):
B (sequence):

Returns:
sequence:


def dframe(self, dimensions=None, multi_index=False):

        import pandas as pd
        if dimensions is None:
            outer_dimensions = self.kdims
            inner_dimensions = None
        else:
            outer_dimensions = [self.get_dimension(d) for d in dimensions
                                if d in self.kdims]
            inner_dimensions = [d for d in dimensions
                                if d not in outer_dimensions]
        inds = [(d, self.get_dimension_index(d)) for d in outer_dimensions]

        dframes = []
        for key, element in self.data.items():
            df = element.dframe(inner_dimensions, multi_index)
            names = [d.name for d in outer_dimensions]
            key_dims = [(d.name, key[i]) for d, i in inds]
            if multi_index:
                length = len(df)
                indexes = [[v]*length for _, v in key_dims]
                if df.index.names != [None]:
                    indexes += [df.index]
                    names += list(df.index.names)
                df = df.set_index(indexes)
                df.index.names = names
            else:
                for dim, val in key_dims:
                    dimn = 1
                    while dim in df:
                        dim = dim+'_%d' % dimn
                        if dim in df:
                            dimn += 1
                    df.insert(0, dim, val)
            dframes.append(df)
        return pd.concat(dframes)

Convert dimension values to DataFrame.

Returns a pandas dataframe of columns along each dimension,
either completely flat or indexed by key dimensions.

Args:
dimensions: Dimensions to return as columns
multi_index: Convert key dimensions to (multi-)index

Returns:
DataFrame of columns corresponding to each dimension


def tcp_ping(
    task: Task, ports: List[int], timeout: int = 2, host: Optional[str] = None
) -> Result:

    if isinstance(ports, int):
        ports = [ports]

    if isinstance(ports, list):
        if not all(isinstance(port, int) for port in ports):
            raise ValueError("Invalid value for 'ports'")

    else:
        raise ValueError("Invalid value for 'ports'")

    host = host or task.host.hostname

    result = {}
    for port in ports:
        s = socket.socket()
        s.settimeout(timeout)
        try:
            status = s.connect_ex((host, port))
            if status == 0:
                connection = True
            else:
                connection = False
        except (socket.gaierror, socket.timeout, socket.error):
            connection = False
        finally:
            s.close()
        result[port] = connection

    return Result(host=task.host, result=result)

Tests connection to a tcp port and tries to establish a three way
handshake. To be used for network discovery or testing.

Arguments:
ports (list of int): tcp ports to ping
timeout (int, optional): defaults to 2
host (string, optional): defaults to ``hostname``

Returns:
Result object with the following attributes set:
* result (``dict``): Contains port numbers as keys with True/False as values


def formula_html(self, reversed_=False):
    if (self.H_count == 1):
        text = 'H'
    elif (self.H_count > 1):
        text = 'H<sub>{}</sub>'.format(self.H_count)
    else:
        text = ''
    seq = [self.symbol, text, self.charge_sign_html()]
    if reversed_:
        seq = reversed(seq)
    return ''.join(seq)

Chemical formula HTML

Args:
reversed (bool): reversed text for leftmost atom groups


def _add_collection_def(meta_graph_def, key, export_scope=None):
    meta_graph.add_collection_def(meta_graph_def, key, export_scope=export_scope)

Adds a collection to MetaGraphDef protocol buffer.

Args:
meta_graph_def: MetaGraphDef protocol buffer.
key: One of the GraphKeys or user-defined string.
export_scope: Optional `string`. Name scope to remove.


def __getattr__(cls, item):

        if item in cls._meta.settings.keys():
            return cls._meta.settings[item]
        raise AttributeError("'%s' class has no attribute '%s'" % (cls.__name__, item))

Return a setting object if it is in the ``_meta.settings`` dictionary.

Args:
item (str):
the name of the setting variable (not the setting's name).

Returns:
``Setting``: the setting object.

Raises:
AttributeError if the setting does not exist.


def load_img(path, grayscale=False, target_size=None):

    img = io.imread(path, grayscale)
    if target_size:
        img = transform.resize(img, target_size, preserve_range=True).astype('uint8')
    return img

Utility function to load an image from disk.

Args:
path: The image file path.
grayscale: True to convert to grayscale image (Default value = False)
target_size: (w, h) to resize. (Default value = None)

Returns:
The loaded numpy image.


def set_mac_addr_adv_interval(self, name, vrid, value=None, disable=False, default=False, run=True):
    if ((not default) and (not disable)):
        if ((not int(value)) or (int(value) < 1) or (int(value) > 3600)):
            raise ValueError("vrrp property 'mac_addr_adv_interval' must be in the range 1-3600")
    cmd = self.command_builder(('vrrp %d mac-address advertisement-interval' % vrid), value=value, default=default, disable=disable)
    if run:
        result = self.configure_interface(name, cmd)
        if (result is False):
            return self.error
        return result
    return cmd

Set the mac_addr_adv_interval property of the vrrp

Args:
name (string): The interface to configure.
vrid (integer): The vrid number for the vrrp to be managed.
value (integer): mac-address advertisement-interval value to
assign to the vrrp.
disable (boolean): Unset mac-address advertisement-interval
if True.
default (boolean): Set mac-address advertisement-interval to
default if True.
run (boolean): Set to True to execute the command, False to
return a string with the formatted command.

Returns:
If run is True, returns True if the command executed successfully,
error if failure.

If run is False, returns the formatted command string which can
be passed to the node


def is_table(engine, sql):
    if engine.dialect.has_table(engine, sql):
        return True
    return False

Check with the given sql arg is query or table

Args:
engine: SQLAlchemy connection engine
sql: SQL query or table name

Returns:
True for table or False if not


def root_cause(binding, node, seen=()):
    if isinstance(binding, (list, tuple)):
        bindings = list(binding)
    else:
        bindings = [binding]
    del binding
    key = frozenset(bindings)
    if key in seen:
        return (next(iter(bindings), None), node)
    for b in bindings:
        if not node.HasCombination([b]):
            for o in b.origins:
                for source_set in o.source_sets:
                    cause, n = root_cause(list(source_set), o.where)
                    if cause is not None:
                        return (cause, n)
            return (b, node)
    return (None, None)

Tries to determine why a binding isn't possible at a node.

This tries to find the innermost source that's still impossible. It only works
if the failure isn't due to a combination of bindings.

Args:
binding: A binding, or a list of bindings.
node: The node at which (one of the) binding(s) is impossible.
seen: Internal. Bindings already looked at.

Returns:
A tuple (binding, node), with "binding" the innermost binding that's
not possible, and "node" the CFG node at which it isn't.


def EnrolFleetspeakClient(self, client_id):

    client_urn = rdf_client.ClientURN(client_id)

    if data_store.RelationalDBEnabled():
      try:
        data_store.REL_DB.ReadClientMetadata(client_id)
        return False
      except db.UnknownClientError:
        pass
    else:
      if aff4.FACTORY.ExistsWithType(
          client_urn, aff4_type=aff4_grr.VFSGRRClient, token=self.token):
        return False

    logging.info("Enrolling a new Fleetspeak client: %r", client_id)

    if data_store.RelationalDBEnabled():
      now = rdfvalue.RDFDatetime.Now()
      data_store.REL_DB.WriteClientMetadata(
          client_id, first_seen=now, fleetspeak_enabled=True, last_ping=now)

    if data_store.AFF4Enabled():

      with aff4.FACTORY.Create(
          client_urn,
          aff4_type=aff4_grr.VFSGRRClient,
          mode="rw",
          token=self.token) as client:

        client.Set(client.Schema.FLEETSPEAK_ENABLED, rdfvalue.RDFBool(True))

        index = client_index.CreateClientIndex(token=self.token)
        index.AddClient(client)
        if data_store.RelationalDBEnabled():
          client_obj = rdf_objects.ClientSnapshot(
              client_id=client_urn.Basename())
          index = client_index.ClientIndex()
          index.AddClient(client_obj)

    events.Events.PublishEvent("ClientEnrollment", client_urn, token=self.token)
    return True

Enrols a Fleetspeak-enabled client for use with GRR.

Args:
client_id: GRR client-id for the client.

Returns:
True if the client is new, and actually got enrolled. This method
is a no-op if the client already exists (in which case False is returned).


def min_sequence_length(self, dataset_split):
    return {problem.DatasetSplit.TRAIN: 8, problem.DatasetSplit.EVAL: 65, problem.DatasetSplit.TEST: 65}[dataset_split]

Determine the minimum sequence length given a dataset_split.

Args:
dataset_split: A problem.DatasetSplit.

Returns:
The minimum length that a sequence can be for this dataset_split.


def rApply(d, f):

  remainingDicts = [(d, ())]
  while len(remainingDicts) > 0:
    current, prevKeys = remainingDicts.pop()
    for k, v in current.iteritems():
      keys = prevKeys + (k,)
      if isinstance(v, dict):
        remainingDicts.insert(0, (v, keys))
      else:
        f(v, keys)

Recursively applies f to the values in dict d.

Args:
d: The dict to recurse over.
f: A function to apply to values in d that takes the value and a list of
keys from the root of the dict to the value.


def run(self, feed_dict=None, session=None) -> None:
    _run_using_default_session(self, feed_dict, self.graph, session)

Runs this operation in a `Session`.

Calling this method will execute all preceding operations that
produce the inputs needed for this operation.

*N.B.* Before invoking `Operation.run()`, its graph must have been
launched in a session, and either a default session must be
available, or `session` must be specified explicitly.

Args:
feed_dict: A dictionary that maps `Tensor` objects to feed values. See
`tf.Session.run` for a description of the valid feed values.
session: (Optional.) The `Session` to be used to run to this operation. If
none, the default session will be used.


def stop(self):
    self.log.debug('Stopping snippet package %s.', self.package)
    self.close_connection()
    self._stop_server()
    self._destroy_event_client()
    self.log.debug('Snippet package %s stopped.', self.package)

Releases all the resources acquired in `initialize`.

This function releases following resources:
* Close the socket connection.
* Stop forwarding the device port to host.
* Stop the standing server subprocess running on the host side.
* Stop the snippet server running on the device side.
* Stop the event client and set `self._event_client` to None.

Raises:
android_device_lib_errors.DeviceError: if the server exited with errors on
the device side.


def __init__(self, code, message=None, command=None):

        super().__init__(message)
        self.code = code
        self.command = command

Initializes a new instance of SMTPCommandFailedError.

Args:
code (int): Error code returned by the SMTP server.
message (str): Exception message, ideally providing help for the
user.
command (str): Command sent to the server that originated the
exception.


def run(components=None, broker=None):
    components = (components or COMPONENTS[GROUPS.single])
    components = _determine_components(components)
    broker = (broker or Broker())
    for component in run_order(components):
        start = time.time()
        try:
            if ((component not in broker) and (component in DELEGATES) and is_enabled(component)):
                log.info(('Trying %s' % get_name(component)))
                result = DELEGATES[component].process(broker)
                broker[component] = result
        except MissingRequirements as mr:
            if log.isEnabledFor(logging.DEBUG):
                name = get_name(component)
                reqs = stringify_requirements(mr.requirements)
                log.debug(('%s missing requirements %s' % (name, reqs)))
            broker.add_exception(component, mr)
        except SkipComponent:
            pass
        except Exception as ex:
            tb = traceback.format_exc()
            log.warn(tb)
            broker.add_exception(component, ex, tb)
        finally:
            broker.exec_times[component] = (time.time() - start)
            broker.fire_observers(component)
    return broker

Executes components in an order that satisfies their dependency
relationships.

Keyword Args:
components: Can be one of a dependency graph, a single component, a
component group, or a component type. If it's anything other than a
dependency graph, the appropriate graph is built for you and before
evaluation.
broker (Broker): Optionally pass a broker to use for evaluation. One is
created by default, but it's often useful to seed a broker with an
initial dependency.
Returns:
Broker: The broker after evaluation.


def create_raw(self, key, value):

        data = None
        if key is not None and value is not None:
            data = self.db.create(key.strip(), value)
        else:
            self.tcex.log.warning(u'The key or value field was None.')
        return data

Create method of CRUD operation for raw data.

Args:
key (string): The variable to write to the DB.
value (any): The data to write to the DB.

Returns:
(string): Result of DB write.


def create(self, algorithm, length, operation_policy_name=None, name=None, cryptographic_usage_mask=None):
    if (not isinstance(algorithm, enums.CryptographicAlgorithm)):
        raise TypeError('algorithm must be a CryptographicAlgorithm enumeration')
    elif ((not isinstance(length, six.integer_types)) or (length <= 0)):
        raise TypeError('length must be a positive integer')
    if (cryptographic_usage_mask is not None):
        if ((not isinstance(cryptographic_usage_mask, list)) or (all((isinstance(item, enums.CryptographicUsageMask) for item in cryptographic_usage_mask)) is False)):
            raise TypeError('cryptographic_usage_mask must be a list of CryptographicUsageMask enumerations')
    common_attributes = self._build_common_attributes(operation_policy_name)
    key_attributes = self._build_key_attributes(algorithm, length, cryptographic_usage_mask)
    key_attributes.extend(common_attributes)
    if name:
        key_attributes.extend(self._build_name_attribute(name))
    template = cobjects.TemplateAttribute(attributes=key_attributes)
    result = self.proxy.create(enums.ObjectType.SYMMETRIC_KEY, template)
    status = result.result_status.value
    if (status == enums.ResultStatus.SUCCESS):
        return result.uuid
    else:
        reason = result.result_reason.value
        message = result.result_message.value
        raise exceptions.KmipOperationFailure(status, reason, message)

Create a symmetric key on a KMIP appliance.

Args:
algorithm (CryptographicAlgorithm): An enumeration defining the
algorithm to use to generate the symmetric key.
length (int): The length in bits for the symmetric key.
operation_policy_name (string): The name of the operation policy
to use for the new symmetric key. Optional, defaults to None
name (string): The name to give the key. Optional, defaults to None
cryptographic_usage_mask (list): list of enumerations of crypto
usage mask passing to the symmetric key. Optional, defaults to
None

Returns:
string: The uid of the newly created symmetric key.

Raises:
ClientConnectionNotOpen: if the client connection is unusable
KmipOperationFailure: if the operation result is a failure
TypeError: if the input arguments are invalid


def search(self, filepath=None, basedir=None, kind=None):
    if (filepath is None):
        filepath = ''
    if (basedir is None):
        basedir = '.'
    if ((not basedir) and (not filepath)):
        msg = 'Either basedir or filepath is required for discovering'
        raise SettingsDiscoveryError(msg)
    if (kind and (kind not in self.engines)):
        msg = 'Given settings format is unknow: {}'
        raise SettingsDiscoveryError(msg.format(kind))
    if (not filepath):
        (filename, engine) = self.guess_filename(basedir, kind)
        filepath = os.path.join(basedir, filename)
    else:
        if os.path.isabs(filepath):
            (basedir, filename) = os.path.split(filepath)
        else:
            filepath = os.path.join(basedir, filepath)
        if (not os.path.exists(filepath)):
            msg = 'Given settings file does not exists: {}'
            raise SettingsDiscoveryError(msg.format(filepath))
        engine = self.get_engine(filepath, kind)
    return (filepath, engine)

Search for a settings file.

Keyword Arguments:
filepath (string): Path to a config file, either absolute or
relative. If absolute set its directory as basedir (omitting
given basedir argument). If relative join it to basedir.
basedir (string): Directory path where to search for.
kind (string): Backend engine kind name (value of attribute
``_kind_name``) to help discovering with empty or relative
filepath. Also if explicit absolute filepath is given, this
will enforce the backend engine (such as yaml kind will be
forced for a ``foo.json`` file).

Returns:
tuple: Absolute filepath and backend engine class.


def _parse_trunk_native_vlan(self, config):
    match = re.search('switchport trunk native vlan (\\d+)', config)
    return dict(trunk_native_vlan=match.group(1))

Scans the specified config and parse the trunk native vlan value

Args:
config (str): The interface configuration block to scan

Returns:
dict: A Python dict object with the value of switchport trunk
native vlan value.  The dict returned is intended to be
merged into the resource dict


def get_video_features(self, pixel_values_videos: torch.FloatTensor, vision_feature_layer: Optional[Union[int, List[int]]]=None):
    vision_feature_layer = vision_feature_layer if vision_feature_layer is not None else self.config.vision_feature_layer
    batch_size_vid, num_frames, channels, height, width = pixel_values_videos.shape
    pixel_values = pixel_values_videos.reshape(batch_size_vid * num_frames, channels, height, width)
    video_outputs = self.video_tower(pixel_values, output_hidden_states=True)
    if isinstance(vision_feature_layer, int):
        video_features = video_outputs.hidden_states[vision_feature_layer]
    else:
        hs_pool = [video_outputs.hidden_states[layer_idx] for layer_idx in vision_feature_layer]
        video_features = torch.cat(hs_pool, dim=-1)
    video_features = self.multi_modal_projector(video_features)
    return (video_features, num_frames)

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

Args:
pixel_values_videos (`torch.FloatTensor]` of shape `(batch_size, num_frames, channels, height, width)`)
The tensors corresponding to the input videos.
vision_feature_layer (`Union[int, List[int]]`, *optional*):
The index of the layer to select the vision feature. If multiple indices are provided,
the vision feature of the corresponding indices will be concatenated to form the
vision features.
Returns:
video_features (`torch.Tensor`): Video feature tensor of shape `(num_videos * num_frames, image_length, embed_dim)`).
frames (`int`): Number of frames the videos have.


def _schema_line(args):

  name = args['table'] if args['table'] else args['view']
  if name is None:
    raise Exception('No table or view specified; cannot show schema')

  schema = _get_schema(name)
  if schema:
    html = _repr_html_table_schema(schema)
    return IPython.core.display.HTML(html)
  else:
    raise Exception('%s is not a schema and does not appear to have a schema member' % name)

Implements the BigQuery schema magic used to display table/view schemas.

Args:
args: the arguments following '%bigquery schema'.
Returns:
The HTML rendering for the schema.


def get_file(self, url, path_or_file=None, headers=None, filename=None):
    path_or_file = (path_or_file or filename)
    if self.debug:
        print(('GET FILE: %s, headers=%s' % (url, headers)))
    self.headers = self._get_default_headers()
    if (headers is not None):
        self.headers.update(headers)
    response = requests.get(url, headers=self.headers, auth=self.auth, verify=self.verify_ssl)
    self.http_status_code = response.status_code
    try:
        self._check_error(response)
        try:
            path_or_file.write(response.content)
        except AttributeError:
            fd = os.open(path_or_file, (os.O_CREAT | os.O_RDWR))
            with os.fdopen(fd, 'w+b') as f:
                f.write(response.content)
    except:
        return False
    return True

Get a file from a url and save it as `filename`

Args:
url (str): URL to send the request to

path_or_file (str or file): A writable File-like object or a path to save the file to.

filename (str): [DEPRECATED] File name to save the file as, this can be either
a full path or a relative path

headers (str, optional): custom headers

Returns:
True if file is downloaded and written successfully, False
otherwise.


def pipelines(self, **kwargs):

        path = '%s/%s/pipelines' % (self.manager.path, self.get_id())
        return self.manager.gitlab.http_get(path, **kwargs)

List the merge request pipelines.

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

Raises:
GitlabAuthenticationError: If authentication is not correct
GitlabListError: If the list could not be retrieved

Returns:
RESTObjectList: List of changes


def mount(self, app=None):
    for endpoint in self._routes:
        endpoint.register_app(app)
    return self

Mounts all registered routes to a bottle.py application instance.

Args:
app (instance): A `bottle.Bottle()` application instance.

Returns:
The Router instance (for chaining purposes).


def get_mysql_vars(mysql: str, host: str, port: int, user: str) -> Dict[(str, str)]:
    cmdargs = [mysql, '-h', host, '-P', str(port), '-e', 'SHOW VARIABLES; SHOW STATUS', '-u', user, '-p']
    log.info('Connecting to MySQL with user: {}', user)
    log.debug(cmdargs)
    process = subprocess.Popen(cmdargs, stdout=subprocess.PIPE)
    (out, err) = process.communicate()
    lines = out.decode('utf8').splitlines()
    mysqlvars = {}
    for line in lines:
        (var, val) = line.split('\t')
        mysqlvars[var] = val
    return mysqlvars

Asks MySQL for its variables and status.

Args:
mysql: ``mysql`` executable filename
host: host name
port: TCP/IP port number
user: username

Returns:
dictionary of MySQL variables/values


def proc_ovrds(**kwargs):

    return [
        (k, v) for k, v in kwargs.items()
        if k not in list(ELEM_KEYS.keys()) + list(ELEM_KEYS.values()) + PRSV_COLS
    ]

Bloomberg overrides

Args:
**kwargs: overrides

Returns:
list of tuples

Examples:
>>> proc_ovrds(DVD_Start_Dt='20180101')
[('DVD_Start_Dt', '20180101')]
>>> proc_ovrds(DVD_Start_Dt='20180101', cache=True, has_date=True)
[('DVD_Start_Dt', '20180101')]


def unshare(self, group_id, **kwargs):

        path = '/projects/%s/share/%s' % (self.get_id(), group_id)
        self.manager.gitlab.http_delete(path, **kwargs)

Delete a shared project link within a group.

Args:
group_id (int): ID of the group.
**kwargs: Extra options to send to the server (e.g. sudo)

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


def ones_like(array, dtype=None, keepmeta=True):
    if keepmeta:
        return xr.ones_like(array, dtype)
    else:
        return dc.ones(array.shape, dtype)

Create an array of ones with the same shape and type as the input array.

Args:
array (xarray.DataArray): The shape and data-type of it define
these same attributes of the output array.
dtype (data-type, optional): If spacified, this function overrides
the data-type of the output array.
keepmeta (bool, optional): Whether *coords, attrs, and name of the input
array are kept in the output one. Default is True.

Returns:
array (decode.array): Decode array filled with ones.


def initGP(self,fast=False):

        if fast:
            assert self.n_terms==2, 'CVarianceDecomposition: for fast inference number of terms must be == 2'
            assert self.P>1,        'CVarianceDecomposition: for fast inference number of traits must be > 1'
            self.vd.initGPkronSum()
        else:
            self.vd.initGP()
        self.gp=self.vd.getGP()
        self.init=True
        self.fast=fast

Initialize GP objetct

Args:
fast:   if fast==True initialize gpkronSum gp


def call_requests(
    requests: Union[Request, Iterable[Request]], methods: Methods, debug: bool
) -> Response:

    if isinstance(requests, collections.Iterable):
        return BatchResponse(safe_call(r, methods, debug=debug) for r in requests)
    return safe_call(requests, methods, debug=debug)

Takes a request or list of Requests and calls them.

Args:
requests: Request object, or a collection of them.
methods: The list of methods that can be called.
debug: Include more information in error responses.


def _bit_list_to_bytes(bit_list):
    num_bits = len(bit_list)
    byte_vals = bytearray()
    for start in six.moves.xrange(0, num_bits, 8):
        curr_bits = bit_list[start:(start + 8)]
        char_val = sum(((val * digit) for (val, digit) in six.moves.zip(_POW2, curr_bits)))
        byte_vals.append(char_val)
    return bytes(byte_vals)

Converts an iterable of 1s and 0s to bytes.

Combines the list 8 at a time, treating each group of 8 bits
as a single byte.

Args:
bit_list (Sequence): Sequence of 1s and 0s.

Returns:
bytes: The decoded bytes.


def _assert_splits_match(nested_splits_lists):
    error_msg = 'Inputs must have identical ragged splits'
    for splits_list in nested_splits_lists:
        if len(splits_list) != len(nested_splits_lists[0]):
            raise ValueError(error_msg)
    return [check_ops.assert_equal(s1, s2, message=error_msg) for splits_list in nested_splits_lists[1:] for s1, s2 in zip(nested_splits_lists[0], splits_list)]

Checks that the given splits lists are identical.

Performs static tests to ensure that the given splits lists are identical,
and returns a list of control dependency op tensors that check that they are
fully identical.

Args:
nested_splits_lists: A list of nested_splits_lists, where each split_list is
a list of `splits` tensors from a `RaggedTensor`, ordered from outermost
ragged dimension to innermost ragged dimension.

Returns:
A list of control dependency op tensors.
Raises:
ValueError: If the splits are not identical.


def load_fasta_file(filename):
    with open(filename, 'r') as handle:
        records = list(SeqIO.parse(handle, 'fasta'))
    return records

Load a FASTA file and return the sequences as a list of SeqRecords

Args:
filename (str): Path to the FASTA file to load

Returns:
list: list of all sequences in the FASTA file as Biopython SeqRecord objects


def _timestamp_query_param_from_json(value, field):

    if _not_null(value, field):

        value = value.replace(" ", "T", 1)

        value = value.replace("Z", "")
        value = value.replace("+00:00", "")

        if "." in value:

            return datetime.datetime.strptime(value, _RFC3339_MICROS_NO_ZULU).replace(
                tzinfo=UTC
            )
        else:

            return datetime.datetime.strptime(value, _RFC3339_NO_FRACTION).replace(
                tzinfo=UTC
            )
    else:
        return None

Coerce 'value' to a datetime, if set or not nullable.

Args:
value (str): The timestamp.
field (.SchemaField): The field corresponding to the value.

Returns:
Optional[datetime.datetime]: The parsed datetime object from
``value`` if the ``field`` is not null (otherwise it is
:data:`None`).


def get_feature_variable_integer(self, feature_key, variable_key, user_id, attributes=None):
    variable_type = entities.Variable.Type.INTEGER
    return self._get_feature_variable_for_type(feature_key, variable_key, variable_type, user_id, attributes)

Returns value for a certain integer variable attached to a feature flag.

Args:
feature_key: Key of the feature whose variable's value is being accessed.
variable_key: Key of the variable whose value is to be accessed.
user_id: ID for user.
attributes: Dict representing user attributes.

Returns:
Integer value of the variable. None if:
- Feature key is invalid.
- Variable key is invalid.
- Mismatch with type of variable.


def __init__(self, server, sock, makefile=MakeFile):

        self.server = server
        self.socket = sock
        self.rfile = makefile(sock, 'rb', self.rbufsize)
        self.wfile = makefile(sock, 'wb', self.wbufsize)
        self.requests_seen = 0

        self.peercreds_enabled = self.server.peercreds_enabled
        self.peercreds_resolve_enabled = self.server.peercreds_resolve_enabled

        self.resolve_peer_creds = (
            lru_cache(maxsize=1)(self.resolve_peer_creds)
        )
        self.get_peer_creds = (
            lru_cache(maxsize=1)(self.get_peer_creds)
        )

Initialize HTTPConnection instance.

Args:
server (HTTPServer): web server object receiving this request
socket (socket._socketobject): the raw socket object (usually
TCP) for this connection
makefile (file): a fileobject class for reading from the socket


Applies a rotation to a vector. Written out by hand to avoid transfer to avoid AMP downcasting.

Args:
r: [*, 3, 3] rotation matrices
t: [*, 3] coordinate tensors
Returns:
[*, 3] rotated coordinates


def get_linear_schedule_with_warmup(optimizer, num_warmup_steps, num_training_steps, last_epoch=-1):
    lr_lambda = partial(_get_linear_schedule_with_warmup_lr_lambda, num_warmup_steps=num_warmup_steps, num_training_steps=num_training_steps)
    return LambdaLR(optimizer, lr_lambda, last_epoch)

Create a schedule with a learning rate that decreases linearly from the initial lr set in the optimizer to 0, after
a warmup period during which it increases linearly from 0 to the initial lr set in the optimizer.

Args:
optimizer ([`~torch.optim.Optimizer`]):
The optimizer for which to schedule the learning rate.
num_warmup_steps (`int`):
The number of steps for the warmup phase.
num_training_steps (`int`):
The total number of training steps.
last_epoch (`int`, *optional*, defaults to -1):
The index of the last epoch when resuming training.

Return:
`torch.optim.lr_scheduler.LambdaLR` with the appropriate schedule.


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 func_dump(func):
    if os.name == 'nt':
        raw_code = marshal.dumps(func.__code__).replace(b'\\', b'/')
        code = codecs.encode(raw_code, 'base64').decode('ascii')
    else:
        raw_code = marshal.dumps(func.__code__)
        code = codecs.encode(raw_code, 'base64').decode('ascii')
    defaults = func.__defaults__
    if func.__closure__:
        closure = tuple((c.cell_contents for c in func.__closure__))
    else:
        closure = None
    return (code, defaults, closure)

Serializes a user defined function.

Args:
func: the function to serialize.

Returns:
A tuple `(code, defaults, closure)`.


def BasenamePath(self, path):
    if path.endswith(self.PATH_SEPARATOR):
        path = path[:(- 1)]
    (_, _, basename) = path.rpartition(self.PATH_SEPARATOR)
    return basename

Determines the basename of the path.

Args:
path (str): path.

Returns:
str: basename of the path.


def output_shapes(self):
    return nest.map_structure(lambda component_spec: component_spec._to_legacy_output_shapes(), self._element_spec)

Returns the shape of each component of an element of this iterator.

Returns:
A nested structure of `tf.TensorShape` objects corresponding to each
component of an element of this dataset.


def setup_data_stream(
            self,
            connection_factory: Callable[[tuple], Connection],
            data_stream_factory: Callable[[Connection], DataStream]=DataStream) -> \
            DataStream:

        yield from self._control_stream.write_command(Command('TYPE', 'I'))
        reply = yield from self._control_stream.read_reply()

        self.raise_if_not_match('Binary mode', ReplyCodes.command_okay, reply)

        address = yield from self.passive_mode()

        connection = yield from connection_factory(address)

        connection.reset()

        yield from connection.connect()

        data_stream = data_stream_factory(connection)

        return data_stream

Create and setup a data stream.

This function will set up passive and binary mode and handle
connecting to the data connection.

Args:
connection_factory: A coroutine callback that returns a connection
data_stream_factory: A callback that returns a data stream

Coroutine.

Returns:
DataStream


def render(self, program: moderngl.Program, mode=None, vertices=-1, first=0, instances=1):

        vao = self.instance(program)

        if mode is None:
            mode = self.mode

        vao.render(mode, vertices=vertices, first=first, instances=instances)

Render the VAO.

Args:
program: The ``moderngl.Program``

Keyword Args:
mode: Override the draw mode (``TRIANGLES`` etc)
vertices (int): The number of vertices to transform
first (int): The index of the first vertex to start with
instances (int): The number of instances


def getText(page, output='text'):
    CheckParent(page)
    dl = page.getDisplayList()
    formats = ('text', 'html', 'json', 'xml', 'xhtml', 'dict', 'rawdict')
    images = (0, 1, 1, 0, 1, 1, 1)
    try:
        f = formats.index(output.lower())
    except:
        f = 0
    flags = (TEXT_PRESERVE_LIGATURES | TEXT_PRESERVE_WHITESPACE)
    if images[f]:
        flags |= TEXT_PRESERVE_IMAGES
    tp = dl.getTextPage(flags)
    t = tp._extractText(f)
    del dl
    del tp
    return t

Extract a document page's text.

Args:
output: (str) text, html, dict, json, rawdict, xhtml or xml.

Returns:
the output of TextPage methods extractText, extractHTML, extractDICT, extractJSON, extractRAWDICT, extractXHTML or etractXML respectively. Default and misspelling choice is "text".


def price(self, valuation_date, market, model=None, pricing_context=None, name=None):
    model = model or rc.InterestRateModelType.LOGNORMAL_RATE
    name = name or self._name + '_price'
    with tf.name_scope(name):
        valuation_date = dates.convert_to_date_tensor(valuation_date)
        if model == rc.InterestRateModelType.LOGNORMAL_RATE:
            caplet_prices = self._price_lognormal_rate(valuation_date, market, pricing_context)
        else:
            raise ValueError(f'Unsupported model {model}.')
        return tf.math.segment_sum(caplet_prices, self._contract_index)

Returns the present value of the Cap/Floor on the valuation date.

Args:
valuation_date: A scalar `DateTensor` specifying the date on which
valuation is being desired.
market: A namedtuple of type `InterestRateMarket` which contains the
necessary information for pricing the Cap/Floor.
model: An optional input of type `InterestRateModelType` to specify which
model to use for pricing.
Default value: `None` in which case `LOGNORMAL_RATE` model is used.
pricing_context: An optional input to provide additional parameters (such
as model parameters) relevant for pricing.
name: Python str. The name to give to the ops created by this function.
Default value: `None` which maps to `"price"`.

Returns:
A Rank 1 `Tensor` of real type containing the modeled price of each cap
(or floor) based on the input market data.

Raises:
ValueError: If an unsupported model is supplied to the function.


def _ReadBooleanDataTypeDefinition(
      self, definitions_registry, definition_values, definition_name,
      is_member=False):

    return self._ReadFixedSizeDataTypeDefinition(
        definitions_registry, definition_values,
        data_types.BooleanDefinition, definition_name,
        self._SUPPORTED_ATTRIBUTES_BOOLEAN, is_member=is_member,
        supported_size_values=(1, 2, 4))

Reads a boolean data type definition.

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

Returns:
BooleanDataTypeDefinition: boolean data type definition.


def list_inputs(self, args, screen_info=None):
    _ = screen_info
    parsed = self._arg_parsers['list_inputs'].parse_args(args)
    output = self._list_inputs_or_outputs(parsed.recursive, parsed.node_name, parsed.depth, parsed.control, parsed.op_type, do_outputs=False)
    node_name = debug_graphs.get_node_name(parsed.node_name)
    _add_main_menu(output, node_name=node_name, enable_list_inputs=False)
    return output

Command handler for inputs.

Show inputs to a given node.

Args:
args: Command-line arguments, excluding the command prefix, as a list of
str.
screen_info: Optional dict input containing screen information such as
cols.

Returns:
Output text lines as a RichTextLines object.


def get_assigned_value(self, name):

        message_type = type(self)
        try:
            field = message_type.field_by_name(name)
        except KeyError:
            raise AttributeError('Message %s has no field %s' % (
                message_type.__name__, name))
        return self.__tags.get(field.number)

Get the assigned value of an attribute.

Get the underlying value of an attribute. If value has not
been set, will not return the default for the field.

Args:
name: Name of attribute to get.

Returns:
Value of attribute, None if it has not been set.


def image_data_format():
    return _IMAGE_DATA_FORMAT

Returns the default image data format convention.

Returns:
A string, either `'channels_first'` or `'channels_last'`

Example:
>>> tf.keras.backend.image_data_format()
'channels_last'


def FormatTime(fmt, stime = None):

  precondition.AssertType(fmt, str)
  precondition.AssertOptionalType(stime, time.struct_time)

  if stime is None:
    strftime = time.strftime
  else:
    strftime = lambda fmt: time.strftime(fmt, stime)

  if PY2:
    return strftime(fmt.encode("ascii")).decode("ascii")
  else:
    return strftime(fmt)

A compatibility wrapper for the `strftime` function.

It is guaranteed to always take unicode string as an argument and return an
unicode string as a result.

Args:
fmt: A format string specifying formatting of the output.
stime: A time representation as returned by `gmtime` or `localtime`.

Returns:
A human-readable representation of `stime`.


def insert_bytes(fobj, size, offset, BUFFER_SIZE=(2 ** 16)):
    if ((size < 0) or (offset < 0)):
        raise ValueError
    fobj.seek(0, 2)
    filesize = fobj.tell()
    movesize = (filesize - offset)
    if (movesize < 0):
        raise ValueError
    resize_file(fobj, size, BUFFER_SIZE)
    if (mmap is not None):
        try:
            mmap_move(fobj, (offset + size), offset, movesize)
        except mmap.error:
            fallback_move(fobj, (offset + size), offset, movesize, BUFFER_SIZE)
    else:
        fallback_move(fobj, (offset + size), offset, movesize, BUFFER_SIZE)

Insert size bytes of empty space starting at offset.

fobj must be an open file object, open rb+ or
equivalent. Mutagen tries to use mmap to resize the file, but
falls back to a significantly slower method if mmap fails.

Args:
fobj (fileobj)
size (int): The amount of space to insert
offset (int): The offset at which to insert the space
Raises:
IOError


def get_jobs(self, name=None):
    if self.applicationResource:
        return self._get_elements(self.jobs, 'jobs', Job, None, name)
    else:
        return []

Retrieves jobs running on this resource in its instance.

Args:
name (str, optional): Only return jobs containing property **name** that matches `name`. `name` can be a
regular expression. If `name` is not supplied, then all jobs are returned.

Returns:
list(Job): A list of jobs matching the given `name`.

.. note:: If ``applicationResource`` is `False` an empty list is returned.
.. versionadded:: 1.9


def _load_variables_impl(config: Text, hosts: List[Tuple[int, Text]], variables: Dict[Text, Dict[Text, tf_variables.Variable]], table_config: tpu_embedding_v2_utils.TableConfig):

    def select_fn(host_id):

        def select_or_zeros(x):
            if host_id >= len(x.variables):
                return array_ops.zeros_like(x.variables[0])
            return x.variables[host_id]
        return select_or_zeros
    for host_id, host in enumerate(hosts):
        with ops.device(host):
            host_variables = nest.map_structure(select_fn(host_id), variables)
            for table in table_config:
                table.optimizer._load()(table_name=table.name, num_shards=len(hosts), shard_id=host_id, config=config, **host_variables[table.name])
                config = None

Load embedding tables to onto TPU for each table and host.

Args:
config: A serialized TPUEmbeddingConfiguration proto.
hosts: A list of CPU devices, on per host.
variables: A dictionary of dictionaries of TPUEmbeddingVariables. First key
is the table name, second key is 'parameters' or the optimizer slot name.
table_config: A list of tf.tpu.experimental.embedding.TableConfig objects.


def CopyFromDateTimeString(self, time_string):

    date_time_values = self._CopyDateTimeFromString(time_string)

    year = date_time_values.get('year', 0)
    month = date_time_values.get('month', 0)
    day_of_month = date_time_values.get('day_of_month', 0)
    hours = date_time_values.get('hours', 0)
    minutes = date_time_values.get('minutes', 0)
    seconds = date_time_values.get('seconds', 0)
    microseconds = date_time_values.get('microseconds', None)

    if year > 9999:
      raise ValueError('Unsupported year value: {0:d}.'.format(year))

    timestamp = self._GetNumberOfSecondsFromElements(
        year, month, day_of_month, hours, minutes, seconds)

    timestamp = float(timestamp) / definitions.SECONDS_PER_DAY
    timestamp += self._DELPHI_TO_POSIX_BASE
    if microseconds is not None:
      timestamp += float(microseconds) / definitions.MICROSECONDS_PER_DAY

    self._normalized_timestamp = None
    self._timestamp = timestamp
    self.is_local_time = False

Copies a Delphi TDateTime timestamp from a string.

Args:
time_string (str): date and time value formatted as:
YYYY-MM-DD hh:mm:ss.######[+-]##:##

Where # are numeric digits ranging from 0 to 9 and the seconds
fraction can be either 3 or 6 digits. The time of day, seconds
fraction and time zone offset are optional. The default time zone
is UTC.

Raises:
ValueError: if the time string is invalid or not supported.


def _NewMatchSection(self, val):
    section = {'criterion': val, 'config': {}}
    self.matches.append(section)
    self.section = section['config']
    self.processor = self._ParseMatchGrp

Create a new configuration section for each match clause.

Each match clause is added to the main config, and the criterion that will
trigger the match is recorded, as is the configuration.

Args:
val: The value following the 'match' keyword.


def _GetTimestamps(self, olecf_item):

    if not olecf_item:
      return None, None

    try:
      creation_time = olecf_item.get_creation_time_as_integer()
    except OverflowError as exception:
      logger.warning(
          'Unable to read the creation time with error: {0!s}'.format(
              exception))
      creation_time = 0

    try:
      modification_time = olecf_item.get_modification_time_as_integer()
    except OverflowError as exception:
      logger.warning(
          'Unable to read the modification time with error: {0!s}'.format(
              exception))
      modification_time = 0

    if not creation_time and not modification_time:
      return None, None

    if creation_time == 0xffffffffffffffff:
      creation_time = 0

    return creation_time, modification_time

Retrieves the timestamps from an OLECF item.

Args:
olecf_item (pyolecf.item): OLECF item.

Returns:
tuple[int, int]: creation and modification FILETIME timestamp.


def maybe_broadcast_structure(from_structure: Any, to_structure: Any) -> Any:

  flat_from = tf.nest.flatten(from_structure)
  flat_to = tf.nest.flatten(to_structure)
  if len(flat_from) == 1:
    flat_from *= len(flat_to)
  return tf.nest.pack_sequence_as(to_structure, flat_from)

Maybe broadcasts `from_structure` to `to_structure`.

If `from_structure` is a singleton, it is tiled to match the structure of
`to_structure`. Note that the elements in `from_structure` are not copied if
this tiling occurs.

Args:
from_structure: A structure.
to_structure: A structure.

Returns:
new_from_structure: Same structure as `to_structure`.


def _on_disconnect(self, result):

        success, _, context = self._parse_return(result)

        callback = context['callback']
        connection_id = context['connection_id']
        handle = context['handle']

        callback(connection_id, self.id, success, "No reason given")
        self._remove_connection(handle)

Callback called when disconnection command finishes

Args:
result (dict): result returned from diconnection command


def get_vertex(self, key):

    if key in self.vertex_map:
      return self.vertex_map[key]
    vertex = self.new_vertex()
    self.vertex_map[key] = vertex
    return vertex

Returns or Creates a Vertex mapped by key.

Args:
key: A string reference for a vertex.  May refer to a new Vertex in which
case it will be created.

Returns:
A the Vertex mapped to by key.


def tab(tab_name, element_list=None, section_list=None):
    _tab = {'Type': 'Tab', 'Title': tab_name}
    if (element_list is not None):
        if isinstance(element_list, list):
            _tab['Elements'] = element_list
        else:
            _tab['Elements'] = [element_list]
    if (section_list is not None):
        if isinstance(section_list, list):
            _tab['Sections'] = section_list
        elif ('Elements' not in section_list):
            _tab['Elements'] = element_list
        else:
            _tab['Elements'].append(element_list)
    return _tab

Returns a dictionary representing a new tab to display elements.
This can be thought of as a simple container for displaying multiple
types of information.

Args:
tab_name: The title to display
element_list: The list of elements to display. If a single element is
given it will be wrapped in a list.
section_list: A list of sections to display.

Returns:
A dictionary with metadata specifying that it is to be rendered
as a page containing multiple elements and/or tab.


def rotate_capture_handler_log(self, name):
    for (sc_key, sc) in self._stream_capturers.iteritems():
        for h in sc[0].capture_handlers:
            if (h['name'] == name):
                sc[0]._rotate_log(h)

Force a rotation of a handler's log file

Args:
name:
The name of the handler who's log file should be rotated.


def _CreateBudget(client):

  budget_service = client.GetService('BudgetService', version='v201809')

  operation = {
      'operand': {
          'name': 'Interplanetary Cruise Budget
          'deliveryMethod': 'STANDARD',
          'amount': {
              'microAmount': 500000
          }
      },
      'operator': 'ADD'
  }

  budget = budget_service.mutate([operation])['value'][0]

  print 'Budget with ID "%d" and name "%s" was created.' % (
      budget['budgetId'], budget['name'])

  return budget

Creates the budget.

Args:
client: an AdWordsClient instance.

Returns:
a suds.sudsobject.Object representation of the created budget.


def gene_panel(self, panel_id, version=None):
    query = {'panel_name': panel_id}
    if version:
        LOG.info('Fetch gene panel {0}, version {1} from database'.format(panel_id, version))
        query['version'] = version
        return self.panel_collection.find_one(query)
    else:
        LOG.info('Fetching gene panels %s from database', panel_id)
        res = self.panel_collection.find(query).sort('version', (- 1))
        if (res.count() > 0):
            return res[0]
        else:
            LOG.info('No gene panel found')
            return None

Fetch a gene panel.

If no panel is sent return all panels

Args:
panel_id (str): unique id for the panel
version (str): version of the panel. If 'None' latest version will be returned

Returns:
gene_panel: gene panel object


def equal_to_current(cls, json, fields_to_ignore=('id', 'change_date', 'changed_by')):
    info = model_meta.get_field_info(cls)
    for (field_name, relation_info) in info.relations.items():
        if (relation_info.to_many and (field_name in json)):
            json.pop(field_name)
    new_instance = cls(**json)
    key_field_args = tuple((getattr(new_instance, key) for key in cls.KEY_FIELDS))
    current = cls.current(*key_field_args)
    if (current.id is not None):
        return current.fields_equal(new_instance, fields_to_ignore)
    return False

Compares for equality this instance to a model instance constructed from the supplied JSON.
This will ignore any fields in `fields_to_ignore`.

Note that this method cannot handle fields with many-to-many associations, as those can only
be set on a saved model instance (and saving the model instance will create a new entry).
All many-to-many field entries will be removed before the equality comparison is done.

Args:
json: json representing an entry to compare
fields_to_ignore: List of fields that should not be compared for equality. By default
includes `id`, `change_date`, and `changed_by`.

Returns: True if the checked fields are all equivalent, else False


class PerceiverMultimodalPreprocessor(AbstractPreprocessor):

    def __init__(self, modalities: Mapping[str, PreprocessorType], mask_probs: Optional[Mapping[str, float]]=None, min_padding_size: int=2):
        super().__init__()
        self.modalities = nn.ModuleDict(modalities)
        self.min_padding_size = min_padding_size
        self.mask_probs = mask_probs if mask_probs is not None else {}
        self.padding = nn.ParameterDict({modality: nn.Parameter(torch.randn(1, self.num_channels - preprocessor.num_channels)) for modality, preprocessor in modalities.items()})
        self.mask = nn.ParameterDict({modality: nn.Parameter(torch.randn(1, self.num_channels)) for modality, _ in self.mask_probs.items()})

    @property
    def num_channels(self) -> int:
        max_channel_size = max((processor.num_channels for _, processor in self.modalities.items()))
        common_channel_size = max_channel_size + self.min_padding_size
        return common_channel_size

    def forward(self, inputs: Mapping[str, torch.Tensor], pos: Optional[torch.Tensor]=None, network_input_is_1d: bool=True, interpolate_pos_encoding: bool=False) -> PreprocessorOutputType:
        padded = {}
        modality_sizes = {}
        inputs_without_pos = {}
        for modality, preprocessor in self.modalities.items():
            output, _, inputs_without_pos[modality] = preprocessor(inputs[modality], pos=pos, network_input_is_1d=network_input_is_1d)
            batch_size, num_samples, num_channels = output.shape
            pos_enc = self.padding[modality].expand(batch_size, -1, -1)
            padding = torch.broadcast_to(pos_enc, [batch_size, num_samples, self.num_channels - num_channels])
            output_padded = torch.cat([output, padding], dim=2)
            if modality in self.mask_probs:
                mask_token = self.mask[modality].expand(batch_size, -1, -1)
                mask_prob = self.mask_probs[modality]
                mask = torch.bernoulli(torch.full([batch_size, num_samples], mask_prob))
                mask = torch.unsqueeze(mask, dim=2).to(mask_token.device)
                output_padded = (1 - mask) * output_padded + mask * mask_token
            padded[modality] = output_padded
            modality_sizes[modality] = output_padded.shape[1]
        padded_ls = [padded[k] for k in sorted(padded.keys())]
        final_inputs = torch.cat(padded_ls, dim=1)
        return (final_inputs, modality_sizes, inputs_without_pos)

Multimodal preprocessing for Perceiver Encoder.

Inputs for each modality are preprocessed, then padded with trainable position embeddings to have the same number
of channels.

Args:
modalities (`Mapping[str, PreprocessorType]`):
Dict mapping modality name to preprocessor.
mask_probs (`Dict[str, float]`):
Dict mapping modality name to masking probability of that modality.
min_padding_size (`int`, *optional*, defaults to 2):
The minimum padding size for all modalities. The final output will have num_channels equal to the maximum
channels across all modalities plus min_padding_size.


def _project_observable(self, input_key: str, input_observable: Any, get_hist_args: Dict[(str, Any)]=None, projection_name_args: Dict[(str, Any)]=None, **kwargs) -> Hist:
    if (get_hist_args is None):
        get_hist_args = copy.deepcopy(kwargs)
    if (projection_name_args is None):
        projection_name_args = copy.deepcopy(kwargs)
    get_hist_args.update({'observable': input_observable})
    hist = self.get_hist(**get_hist_args)
    projection_name_args.update(self.projection_information)
    projection_name_args.update(kwargs)
    projection_name_args.update({'input_key': input_key, 'input_observable': input_observable, 'input_hist': hist})
    projection_name = self.projection_name(**projection_name_args)
    logger.debug(f'hist: {hist}')
    for axis in self.additional_axis_cuts:
        logger.debug(f'Apply additional axis hist range: {axis.name}')
        axis.apply_range_set(hist)
    if (self.projection_dependent_cut_axes == []):
        self.projection_dependent_cut_axes.append([])
    duplicated_axes = [PDCA for PA in self.projection_axes for PDCA_group in self.projection_dependent_cut_axes for PDCA in PDCA_group if (PDCA.axis_type == PA.axis_type)]
    if duplicated_axes:
        raise ValueError(f'Axis {duplicated_axes} is in the projection axes and the projection dependent cut axes. This configuration is not allowed, as the range in the PDCA will be overwritten by the projection axes! Please revise your configuration.')
    hists = []
    for (i, axes) in enumerate(self.projection_dependent_cut_axes):
        for axis in axes:
            logger.debug(f'Apply projection dependent hist range: {axis.name}')
            axis.apply_range_set(hist)
        projected_hist = self.call_projection_function(hist)
        projected_hist.SetName(f'{projection_name}_{i}')
        hists.append(projected_hist)
        self.cleanup_cuts(hist, cut_axes=axes)
    self.cleanup_cuts(hist, cut_axes=self.additional_axis_cuts)
    output_hist = hists[0]
    for temp_hist in hists[1:]:
        output_hist.Add(temp_hist)
    output_hist.SetName(projection_name)
    output_hist.SetDirectory(0)
    return (output_hist, projection_name, projection_name_args)

Perform a projection for a single observable.

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

Args:
input_key: Key to describe the input observable.
input_observable: Observable to project from.
get_hist_args: Arguments to pass to ``get_hist(...)``. Made available so the args can be cached
to avoid a ``deepcopy`` when looping. Default: None. In this case, they will be retrieved
automatically.
projection_name_args: Arguments to pass to ``projection_name(...)``. Made available so the args
can be cached to avoid a ``deepcopy`` when looping. Default: None. In this case, they will be
retrieved automatically.
kwargs: Additional named args to be passed to projection_name(...) and output_key_name(...).
Returns:
The projected histogram.


def get(cls, user_agent=None, user_agent_config_yaml=None, user_agent_lookup=None, **kwargs):
    if (user_agent or user_agent_config_yaml or ('user_agent' in UserAgent._environment_variables(**kwargs))):
        return UserAgent._create(user_agent, user_agent_config_yaml, user_agent_lookup, **kwargs)
    if cls.user_agent:
        return cls.user_agent
    else:
        raise UserAgentError('You must either set the global user agent: UserAgent.set_global(...) or pass in user agent parameters!')

Get full user agent string from parameters if supplied falling back on global user agent if set.

Args:
user_agent (Optional[str]): User agent string. HDXPythonLibrary/X.X.X- is prefixed.
user_agent_config_yaml (Optional[str]): Path to YAML user agent configuration. Ignored if user_agent supplied. Defaults to ~/.useragent.yml.
user_agent_lookup (Optional[str]): Lookup key for YAML. Ignored if user_agent supplied.

Returns:
str: Full user agent string


def bin_to_mac(bin, size=6):

    if len(bin) != size:
        raise Exception("Invalid MAC address: %s" % (bin))
    return ':'.join([binascii.hexlify(o) for o in bin])

Convert 6 bytes into a MAC string.

Args:
bin (str): hex string of lenth 6.

Returns:
str: String representation of the MAC address in lower case.

Raises:
Exception: if ``len(bin)`` is not 6.


def _get_prop_from_modelclass(modelclass, name):
    if (name == '__key__'):
        return modelclass._key
    parts = name.split('.')
    (part, more) = (parts[0], parts[1:])
    prop = modelclass._properties.get(part)
    if (prop is None):
        if issubclass(modelclass, model.Expando):
            prop = model.GenericProperty(part)
        else:
            raise TypeError(('Model %s has no property named %r' % (modelclass._get_kind(), part)))
    while more:
        part = more.pop(0)
        if (not isinstance(prop, model.StructuredProperty)):
            raise TypeError(('Model %s has no property named %r' % (modelclass._get_kind(), part)))
        maybe = getattr(prop, part, None)
        if (isinstance(maybe, model.Property) and (maybe._name == part)):
            prop = maybe
        else:
            maybe = prop._modelclass._properties.get(part)
            if (maybe is not None):
                prop = getattr(prop, maybe._code_name)
            elif (issubclass(prop._modelclass, model.Expando) and (not more)):
                prop = model.GenericProperty()
                prop._name = name
            else:
                raise KeyError(('Model %s has no property named %r' % (prop._modelclass._get_kind(), part)))
    return prop

Helper for FQL parsing to turn a property name into a property object.

Args:
modelclass: The model class specified in the query.
name: The property name.  This may contain dots which indicate
sub-properties of structured properties.

Returns:
A Property object.

Raises:
KeyError if the property doesn't exist and the model clas doesn't
derive from Expando.


def _retrieve_problem(self, id_):

        future = Future(self, id_, self.return_matrix, None)
        self.client._poll(future)
        return future

Resume polling for a problem previously submitted.

Args:
id_: Identification of the query.

Returns:
:obj: `Future`


def to_CAG_agraph(self):
    CAG = self.to_CAG()
    A = nx.nx_agraph.to_agraph(CAG)
    A.graph_attr.update({'dpi': 227, 'fontsize': 20, 'fontname': 'Menlo'})
    A.node_attr.update({'shape': 'rectangle', 'color': '
    A.edge_attr.update({'color': '
    return A

Returns a variable-only view of the GrFN in the form of an AGraph.

Returns:
type: A CAG constructed via variable influence in the GrFN object.


def _blocking_poll(self, timeout=None):
    if self._result_set:
        return
    retry_ = self._retry.with_deadline(timeout)
    try:
        retry_(self._done_or_raise)()
    except exceptions.RetryError:
        raise concurrent.futures.TimeoutError('Operation did not complete within the designated timeout.')

Poll and wait for the Future to be resolved.

Args:
timeout (int):
How long (in seconds) to wait for the operation to complete.
If None, wait indefinitely.


def insert_data(self, data, include_index=False, index_name=None):
    max_rows_per_post = 500
    post_interval = 0.05
    if (not self.exists()):
        raise Exception(('Table %s does not exist.' % self._full_name))
    data_schema = _schema.Schema.from_data(data)
    if isinstance(data, list):
        if include_index:
            if (not index_name):
                index_name = 'Index'
            data_schema._add_field(index_name, 'INTEGER')
    table_schema = self.schema
    for data_field in data_schema:
        name = data_field.name
        table_field = table_schema[name]
        if (table_field is None):
            raise Exception(('Table does not contain field %s' % name))
        data_type = data_field.data_type
        table_type = table_field.data_type
        if (table_type != data_type):
            raise Exception(('Field %s in data has type %s but in table has type %s' % (name, data_type, table_type)))
    total_rows = len(data)
    total_pushed = 0
    job_id = uuid.uuid4().hex
    rows = []
    column_name_map = {}
    is_dataframe = isinstance(data, pandas.DataFrame)
    if is_dataframe:
        gen = data.reset_index(drop=(not include_index)).iterrows()
    else:
        gen = enumerate(data)
    for (index, row) in gen:
        if is_dataframe:
            row = row.to_dict()
        elif include_index:
            row[index_name] = index
        rows.append({'json': self._encode_dict_as_row(row, column_name_map), 'insertId': (job_id + str(index))})
        total_pushed += 1
        if ((total_pushed == total_rows) or (len(rows) == max_rows_per_post)):
            try:
                response = self._api.tabledata_insert_all(self._name_parts, rows)
            except Exception as e:
                raise e
            if ('insertErrors' in response):
                raise Exception(('insertAll failed: %s' % response['insertErrors']))
            time.sleep(post_interval)
            rows = []
    while True:
        self._info = self._api.tables_get(self._name_parts)
        if (('streamingBuffer' not in self._info) or ('estimatedRows' not in self._info['streamingBuffer']) or (int(self._info['streamingBuffer']['estimatedRows']) > 0)):
            break
        time.sleep(2)
    return self

Insert the contents of a Pandas DataFrame or a list of dictionaries into the table.

The insertion will be performed using at most 500 rows per POST, and at most 10 POSTs per
second, as BigQuery has some limits on streaming rates.

Args:
data: the DataFrame or list to insert.
include_index: whether to include the DataFrame or list index as a column in the BQ table.
index_name: for a list, if include_index is True, this should be the name for the index.
If not specified, 'Index' will be used.
Returns:
The table.
Raises:
Exception if the table doesn't exist, the table's schema differs from the data's schema,
or the insert failed.


def create_file_writer_v2(logdir, max_queue=None, flush_millis=None, filename_suffix=None, name=None, experimental_trackable=False, experimental_mesh=None):
    if logdir is None:
        raise ValueError('Argument `logdir` cannot be None')
    inside_function = ops.inside_function()
    with ops.name_scope(name, 'create_file_writer') as scope, ops.device('cpu:0'):
        with ops.init_scope():
            if context.executing_eagerly():
                _check_create_file_writer_args(inside_function, logdir=logdir, max_queue=max_queue, flush_millis=flush_millis, filename_suffix=filename_suffix)
            logdir = ops.convert_to_tensor(logdir, dtype=dtypes.string)
            if max_queue is None:
                max_queue = constant_op.constant(10)
            if flush_millis is None:
                flush_millis = constant_op.constant(2 * 60 * 1000)
            if filename_suffix is None:
                filename_suffix = constant_op.constant('.v2')

            def create_fn():
                if context.executing_eagerly():
                    shared_name = context.anonymous_name()
                else:
                    shared_name = ops.name_from_scope_name(scope)
                return gen_summary_ops.summary_writer(shared_name=shared_name, name=name)
            init_op_fn = functools.partial(gen_summary_ops.create_summary_file_writer, logdir=logdir, max_queue=max_queue, flush_millis=flush_millis, filename_suffix=filename_suffix)
            if experimental_trackable:
                return _TrackableResourceSummaryWriter(create_fn=create_fn, init_op_fn=init_op_fn, mesh=experimental_mesh)
            else:
                return _ResourceSummaryWriter(create_fn=create_fn, init_op_fn=init_op_fn, mesh=experimental_mesh)

Creates a summary file writer for the given log directory.

Args:
logdir: a string specifying the directory in which to write an event file.
max_queue: the largest number of summaries to keep in a queue; will flush
once the queue gets bigger than this. Defaults to 10.
flush_millis: the largest interval between flushes. Defaults to 120,000.
filename_suffix: optional suffix for the event file name. Defaults to `.v2`.
name: a name for the op that creates the writer.
experimental_trackable: a boolean that controls whether the returned writer
will be a `TrackableResource`, which makes it compatible with SavedModel
when used as a `tf.Module` property.
experimental_mesh: a `tf.experimental.dtensor.Mesh` instance. When running
with DTensor, the mesh (experimental_mesh.host_mesh()) will be used for
bringing all the DTensor logging from accelerator to CPU mesh.

Returns:
A SummaryWriter object.


def _extract_attrs(op, keys):
    kwargs = {}
    not_found = object()
    for k in keys:
        srcs = [getattr(op, k, not_found), getattr(op, '_' + k, not_found), getattr(op, 'parameters', {}).get(k, not_found)]
        if any((v is not not_found for v in srcs)):
            kwargs[k] = [v for v in srcs if v is not not_found][0]
        else:
            raise ValueError(f"Could not determine an appropriate value for field `{k}` in object  `{op}`. Looked for \n 1. an attr called `{k}`,\n 2. an attr called `_{k}`,\n 3. an entry in `op.parameters` with key '{k}'.")
        if k in op._composite_tensor_prefer_static_fields and kwargs[k] is not None:
            if tensor_util.is_tensor(kwargs[k]):
                static_val = tensor_util.constant_value(kwargs[k])
                if static_val is not None:
                    kwargs[k] = static_val
        if isinstance(kwargs[k], (np.ndarray, np.generic)):
            kwargs[k] = kwargs[k].tolist()
    return kwargs

Extract constructor kwargs to reconstruct `op`.

Args:
op: A `LinearOperator` instance.
keys: A Python `tuple` of strings indicating the names of the constructor
kwargs to extract from `op`.

Returns:
kwargs: A Python `dict` of kwargs to `op`'s constructor, keyed by `keys`.


def _normalize_edge(self, edge: EDGE) -> EDGE:

        def lower(n: GridQubit, m: GridQubit) -> bool:
            return n.row < m.row or (n.row == m.row and n.col < m.col)

        n1, n2 = edge
        return (n1, n2) if lower(n1, n2) else (n2, n1)

Gives unique representative of the edge.

Two edges are equivalent if they form an edge between the same nodes.
This method returns representative of this edge which can be compared
using equality operator later.

Args:
edge: Edge to normalize.

Returns:
Normalized edge with lexicographically lower node on the first
position.


def run(
        self,
        inputs: Dict[str, Union[float, Iterable]],
        covers: Dict[str, Union[float, Iterable]],
        torch_size: Optional[int] = None,
    ) -> Union[float, Iterable]:

        if len(covers) != len(self.cover_nodes):
            raise ValueError("Incorrect number of cover values.")

        for node_name, val in covers.items():
            self.nodes[node_name]["value"] = val

        return super().run(inputs, torch_size)

Executes the FIB over a particular set of inputs and returns the
result.
Args:
inputs: Input set where keys are the names of input nodes in the
GrFN and each key points to a set of input values (or just one).
Returns:
A set of outputs from executing the GrFN, one for every set of
inputs.


def add_work_item(self, work_item):

        with self._conn:
            self._conn.execute(
                , _work_item_to_row(work_item))

Add a WorkItems.

Args:
work_item: A WorkItem.


def from_http_status(status_code, message, **kwargs):

    error_class = exception_class_for_http_status(status_code)
    error = error_class(message, **kwargs)

    if error.code is None:
        error.code = status_code

    return error

Create a :class:`GoogleAPICallError` from an HTTP status code.

Args:
status_code (int): The HTTP status code.
message (str): The exception message.
kwargs: Additional arguments passed to the :class:`GoogleAPICallError`
constructor.

Returns:
GoogleAPICallError: An instance of the appropriate subclass of
:class:`GoogleAPICallError`.


def get_accounts(self, provider='aws'):
    url = '{gate}/credentials'.format(gate=API_URL)
    response = requests.get(url, verify=GATE_CA_BUNDLE, cert=GATE_CLIENT_CERT)
    assert response.ok, 'Failed to get accounts: {0}'.format(response.text)
    all_accounts = response.json()
    self.log.debug('Accounts in Spinnaker:\n%s', all_accounts)
    filtered_accounts = []
    for account in all_accounts:
        if (account['type'] == provider):
            filtered_accounts.append(account)
    if (not filtered_accounts):
        raise ForemastError('No Accounts matching {0}.'.format(provider))
    return filtered_accounts

Get Accounts added to Spinnaker.

Args:
provider (str): What provider to find accounts for.

Returns:
list: list of dicts of Spinnaker credentials matching _provider_.

Raises:
AssertionError: Failure getting accounts from Spinnaker.


def _send(self, **req_kwargs):
    auth_token = self._auth.getAuthToken()
    if (auth_token is None):
        raise exception.LoginException('Not logged in')
    req_kwargs.setdefault('headers', {'Authorization': ('OAuth ' + auth_token)})
    return self._session.request(**req_kwargs)

Send an authenticated request to a Google API.

Args:
**req_kwargs: Arbitrary keyword arguments to pass to Requests.

Return:
requests.Response: The raw response.

Raises:
LoginException: If :py:meth:`login` has not been called.


def predict(self, x_test):
    if self.model:
        lengths = map(len, x_test)
        x_test = self.p.transform(x_test)
        y_pred = self.model.predict(x_test)
        y_pred = self.p.inverse_transform(y_pred, lengths)
        return y_pred
    else:
        raise OSError('Could not find a model. Call load(dir_path).')

Returns the prediction of the model on the given test data.

Args:
x_test : array-like, shape = (n_samples, sent_length)
Test samples.

Returns:
y_pred : array-like, shape = (n_smaples, sent_length)
Prediction labels for x.


def _save_work_results(self, run_stats, scores, num_processed_images, filename):
    with open(filename, 'w') as f:
        writer = csv.writer(f)
        writer.writerow(['SubmissionID', 'ExternalSubmissionId', 'Score', 'CompletedBatches', 'BatchesWithError', 'ProcessedImages', 'MinEvalTime', 'MaxEvalTime', 'MedianEvalTime', 'MeanEvalTime', 'ErrorMsg'])
        for submission_id in sorted(iterkeys(run_stats)):
            stat = run_stats.get(submission_id, collections.defaultdict((lambda : float('NaN'))))
            external_id = self.submissions.get_external_id(submission_id)
            error_msg = ''
            while ((not error_msg) and stat['error_messages']):
                error_msg = stat['error_messages'].pop()
                if error_msg.startswith('Cant copy adversarial batch locally'):
                    error_msg = ''
            writer.writerow([submission_id, external_id, scores.get(submission_id, None), stat['completed'], stat['num_errors'], num_processed_images.get(submission_id, None), stat['min_eval_time'], stat['max_eval_time'], stat['median_eval_time'], stat['mean_eval_time'], error_msg])

Saves statistics about each submission.

Saved statistics include score; number of completed and failed batches;
min, max, average and median time needed to run one batch.

Args:
run_stats: dictionary with runtime statistics for submissions,
can be generated by WorkPiecesBase.compute_work_statistics
scores: dictionary mapping submission ids to scores
num_processed_images: dictionary with number of successfully processed
images by each submission, one of the outputs of
ClassificationBatches.compute_classification_results
filename: output filename


def __init__(self, live_api_processor: live_model.LiveProcessor, chattiness: float=1.0, unsafe_string_list: list[str] | None=None):
    self._processor = live_api_processor
    self._chattiness = chattiness
    self._commentator = CommentatorStateMachine()
    self.ttfts = collections.deque(maxlen=50)
    self._unsafe_string_list = unsafe_string_list
    if unsafe_string_list is not None:
        pattern = '|'.join((re.escape(s) for s in unsafe_string_list))
        self._processor += text.MatchProcessor(pattern=pattern, substream_input='output_transcription', substream_output='unsafe_regex', remove_from_input_stream=False, flush_fn=lambda x: x.get_metadata('generation_complete') or x.get_metadata('interrupted') or x.get_metadata('interrupt_request') or x.get_metadata('turn_complete') or x.get_metadata('go_away'))

Initializes the processor.

Args:
live_api_processor: The live API processor to use.
chattiness: Probability of triggering a comment when the model has
finished talking or every 3 seconds. Set to 0 to disable commenting.
unsafe_string_list: The strings to use for unsafe content. If None, the
processor will not block unsafe content. If set, the processor will
interrupt itself when it sees the string in the output.


def Create(path, password, generate_default_key=True):

        wallet = UserWallet(path=path, passwordKey=password, create=True)
        if generate_default_key:
            wallet.CreateKey()
        return wallet

Create a new user wallet.

Args:
path (str): A path indicating where to create or open the wallet e.g. "/Wallets/mywallet".
password (str): a 10 characters minimum password to secure the wallet with.

Returns:
UserWallet: a UserWallet instance.


def CheckForHeaderGuard(filename, clean_lines, error):
    raw_lines = clean_lines.lines_without_raw_strings
    for i in raw_lines:
        if Search('
            return
    for i in raw_lines:
        if Search('^\\s*
            return
    cppvar = GetHeaderGuardCPPVariable(filename)
    ifndef = ''
    ifndef_linenum = 0
    define = ''
    endif = ''
    endif_linenum = 0
    for (linenum, line) in enumerate(raw_lines):
        linesplit = line.split()
        if (len(linesplit) >= 2):
            if ((not ifndef) and (linesplit[0] == '
                ifndef = linesplit[1]
                ifndef_linenum = linenum
            if ((not define) and (linesplit[0] == '
                define = linesplit[1]
        if line.startswith('
            endif = line
            endif_linenum = linenum
    if ((not ifndef) or (not define) or (ifndef != define)):
        error(filename, 0, 'build/header_guard', 5, ('No
        return
    if (ifndef != cppvar):
        error_level = 0
        if (ifndef != (cppvar + '_')):
            error_level = 5
        ParseNolintSuppressions(filename, raw_lines[ifndef_linenum], ifndef_linenum, error)
        error(filename, ifndef_linenum, 'build/header_guard', error_level, ('
    ParseNolintSuppressions(filename, raw_lines[endif_linenum], endif_linenum, error)
    match = Match((('
    if match:
        if (match.group(1) == '_'):
            error(filename, endif_linenum, 'build/header_guard', 0, ('
        return
    no_single_line_comments = True
    for i in xrange(1, (len(raw_lines) - 1)):
        line = raw_lines[i]
        if Match('^(?:(?:\\\'(?:\\.|[^\\\'])*\\\')|(?:"(?:\\.|[^"])*")|[^\\\'"])*
            no_single_line_comments = False
            break
    if no_single_line_comments:
        match = Match((('
        if match:
            if (match.group(1) == '_'):
                error(filename, endif_linenum, 'build/header_guard', 0, ('
            return
    error(filename, endif_linenum, 'build/header_guard', 5, ('

Checks that the file contains a header guard.

Logs an error if no #ifndef header guard is present.  For other
headers, checks that the full pathname is used.

Args:
filename: The name of the C++ header file.
clean_lines: A CleansedLines instance containing the file.
error: The function to call with any errors found.


def indent_css(f, output):
    line_count = get_line_count(f)
    f = open(f, 'r+')
    output = open(output, 'r+')
    for line in range(line_count):
        string = f.readline().rstrip()
        if (len(string) > 0):
            if (string[(- 1)] == ';'):
                output.write((('    ' + string) + '\n'))
            else:
                output.write((string + '\n'))
    output.close()
    f.close()

Indentes css that has not been indented and saves it to a new file.
A new file is created if the output destination does not already exist.

Args:
f: string, path to file.

output: string, path/name of the output file (e.g. /directory/output.css).
print type(response.read())

Returns:
None.


def compact(self, accumulator, *args, **kwargs):
    return accumulator

Optionally returns a more compact representation of the accumulator.

This is called before an accumulator is sent across the wire, and can
be useful in cases where values are buffered or otherwise lazily
kept unprocessed when added to the accumulator.  Should return an
equivalent, though possibly modified, accumulator.

By default returns the accumulator unmodified.

Args:
accumulator: the current accumulator
*args: Additional arguments and side inputs.
**kwargs: Additional arguments and side inputs.


def __init__(self, attention_logit_mod, name="attention"):

    super(AttentiveRead, self).__init__(name=name)

    self._attention_logit_mod = attention_logit_mod

Initialize AttentiveRead module.

Args:
attention_logit_mod: Module that produces logit corresponding to a memory
slot's compatibility. Must map a [batch_size * memory_size,
memory_word_size + query_word_size]-shaped Tensor to a
[batch_size * memory_size, 1] shape Tensor.
name: string. Name for module.


def __init__(self, path):

    super(TaggingFile, self).__init__()
    self._path = path

Initializes a tagging file.

Args:
path (str): path to a file that contains one or more event tagging rules.


def register_index(self, index):

    self._indexes[index._name] = index
    self.create_index(index)
    return index

Registers a given index:

* Creates and opens an index for it (if it doesn't exist yet)
* Sets some default values on it (unless they're already set)

Args:
index (PonyWhoosh.Index): An instance of PonyWhoosh.Index class


def from_json(self, js, groups: Iterable[Group]):

        self.index = js["index"]
        self.groupIndex = js["groupIndex"]
        self.label = js["label"]
        self.functionalChannelType = FunctionalChannelType.from_str(
            js["functionalChannelType"], js["functionalChannelType"]
        )
        self.groups = []
        for id in js["groups"]:
            for g in groups:
                if g.id == id:
                    self.groups.append(g)
                    break

this function will load the functional channel object
from a json object and the given groups

Args:
js(dict): the json object
groups(Iterable[Group]): the groups for referencing


def iter_geno_marker(self, markers, return_index=False):
    if (self._mode != 'r'):
        raise UnsupportedOperation("not available in 'w' mode")
    if isinstance(markers, str):
        markers = [markers]
    if return_index:
        for marker in markers:
            (geno, seek) = self.get_geno_marker(marker, return_index=True)
            (yield (marker, geno, seek))
    else:
        for marker in markers:
            (yield (marker, self.get_geno_marker(marker)))

Iterates over genotypes for a list of markers.

Args:
markers (list): The list of markers to iterate onto.
return_index (bool): Wether to return the marker's index or not.

Returns:
tuple: The name of the marker as a string, and its genotypes as a
:py:class:`numpy.ndarray` (additive format).


def assemble_schedules(schedules, qobj_id=None, qobj_header=None, run_config=None):

    qobj_config = QasmQobjConfig()
    if run_config:
        qobj_config = QasmQobjConfig(**run_config.to_dict())

    instruction_converter = PulseQobjConverter
    instruction_converter = instruction_converter(PulseQobjInstruction, **run_config.to_dict())
    lo_converter = LoConfigConverter(PulseQobjExperimentConfig, run_config.qubit_lo_freq,
                                     run_config.meas_lo_freq, **run_config.to_dict())

    qobj_schedules = []
    user_pulselib = set()
    for idx, schedule in enumerate(schedules):

        qobj_instructions = []

        for shift, instruction in schedule.instructions:

            qobj_instructions.append(instruction_converter(shift, instruction))
            if isinstance(instruction, PulseInstruction):

                user_pulselib.add(instruction.command)

        qobj_experiment_header = QobjExperimentHeader(
            name=schedule.name or 'Experiment-%d' % idx
        )

        qobj_schedules.append({
            'header': qobj_experiment_header,
            'instructions': qobj_instructions
        })

    run_config.pulse_library = [QobjPulseLibrary(name=pulse.name, samples=pulse.samples)
                                for pulse in user_pulselib]

    experiments = []
    if len(run_config.schedule_los) == 1:
        lo_dict = run_config.schedule_los.pop()

        q_los = lo_converter.get_qubit_los(lo_dict)
        if q_los:
            run_config.qubit_lo_freq = q_los
        m_los = lo_converter.get_meas_los(lo_dict)
        if m_los:
            run_config.meas_lo_freq = m_los

    if run_config.schedule_los:

        if len(qobj_schedules) == 1:

            for lo_dict in run_config.schedule_los:
                experiments.append(PulseQobjExperiment(
                    instructions=qobj_schedules[0]['instructions'],
                    experimentheader=qobj_schedules[0]['header'],
                    experimentconfig=lo_converter(lo_dict)
                ))
        elif len(qobj_schedules) == len(run_config.schedule_los):

            for lo_dict, schedule in zip(run_config.schedule_los, qobj_schedules):
                experiments.append(PulseQobjExperiment(
                    instructions=schedule['instructions'],
                    experimentheader=schedule['header'],
                    experimentconfig=lo_converter(lo_dict)
                ))
        else:
            raise QiskitError('Invalid LO setting is specified. '
                              'The LO should be configured for each schedule, or '
                              'single setup for all schedules (unique), or '
                              'multiple setups for a single schedule (frequency sweep),'
                              'or no LO configured at all.')
    else:

        for schedule in qobj_schedules:
            experiments.append(PulseQobjExperiment(
                instructions=schedule['instructions'],
                experimentheader=schedule['header'],
            ))

    qobj_config = PulseQobjConfig(**run_config.to_dict())

    return PulseQobj(qobj_id=qobj_id,
                     config=qobj_config,
                     experiments=experiments,
                     header=qobj_header)

Assembles a list of schedules into a qobj which can be run on the backend.
Args:
schedules (list[Schedule]): schedules to assemble
qobj_id (int): identifier for the generated qobj
qobj_header (QobjHeader): header to pass to the results
run_config (RunConfig): configuration of the runtime environment
Returns:
PulseQobj: the Qobj to be run on the backends
Raises:
QiskitError: when invalid schedules or configs are provided


def _ExtractContentSettingsExceptions(self, exceptions_dict, parser_mediator):

    for permission in exceptions_dict:
      if permission not in self._EXCEPTIONS_KEYS:
        continue

      exception_dict = exceptions_dict.get(permission, {})
      for urls, url_dict in exception_dict.items():
        last_used = url_dict.get('last_used', None)
        if not last_used:
          continue

        primary_url, secondary_url = urls.split(',')

        event_data = ChromeContentSettingsExceptionsEventData()
        event_data.permission = permission
        event_data.primary_url = primary_url
        event_data.secondary_url = secondary_url

        timestamp = int(last_used * 1000000)
        date_time = dfdatetime_posix_time.PosixTimeInMicroseconds(
            timestamp=timestamp)
        event = time_events.DateTimeValuesEvent(
            date_time, definitions.TIME_DESCRIPTION_LAST_VISITED)
        parser_mediator.ProduceEventWithEventData(event, event_data)

Extracts site specific events.

Args:
exceptions_dict (dict): Permission exceptions data from Preferences file.
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.


def visualize_qualitative_analysis(inputs, model, samples=1, batch_size=3, length=8):
    average = (lambda dist: tf.reduce_mean(input_tensor=dist.mean(), axis=0))
    with tf.compat.v1.name_scope('val_reconstruction'):
        reconstruct = functools.partial(model.reconstruct, inputs=inputs, samples=samples)
        visualize_reconstruction(inputs, average(reconstruct()))
        visualize_reconstruction(inputs, average(reconstruct(sample_static=True)), name='static_prior')
        visualize_reconstruction(inputs, average(reconstruct(sample_dynamic=True)), name='dynamic_prior')
        visualize_reconstruction(inputs, average(reconstruct(swap_static=True)), name='swap_static')
        visualize_reconstruction(inputs, average(reconstruct(swap_dynamic=True)), name='swap_dynamic')
    with tf.compat.v1.name_scope('generation'):
        generate = functools.partial(model.generate, batch_size=batch_size, length=length, samples=samples)
        image_summary(average(generate(fix_static=True)), 'fix_static')
        image_summary(average(generate(fix_dynamic=True)), 'fix_dynamic')

Visualizes a qualitative analysis of a given model.

Args:
inputs: A tensor of the original inputs, of shape [batch, timesteps,
h, w, c].
model: A DisentangledSequentialVAE model.
samples: Number of samples to draw from the latent distributions.
batch_size: Number of sequences to generate.
length: Number of timesteps to generate for each sequence.


def participants(self, **kwargs):
    path = ('%s/%s/participants' % (self.manager.path, self.get_id()))
    return self.manager.gitlab.http_get(path, **kwargs)

List the participants.

Args:
all (bool): If True, return all the items, without pagination
per_page (int): Number of items to retrieve per request
page (int): ID of the page to return (starts with page 1)
as_list (bool): If set to False and no pagination option is
defined, return a generator instead of a list
**kwargs: Extra options to send to the server (e.g. sudo)

Raises:
GitlabAuthenticationError: If authentication is not correct
GitlabListError: If the list could not be retrieved

Returns:
RESTObjectList: The list of participants


def get_stdout(self, workflow_id, task_id):

        url = '%(wf_url)s/%(wf_id)s/tasks/%(task_id)s/stdout' % {
            'wf_url': self.workflows_url, 'wf_id': workflow_id, 'task_id': task_id
        }
        r = self.gbdx_connection.get(url)
        r.raise_for_status()

        return r.text

Get stdout for a particular task.

Args:
workflow_id (str): Workflow id.
task_id (str): Task id.

Returns:
Stdout of the task (string).