def IsHuntStarted(self):
    state = self.hunt_obj.Get(self.hunt_obj.Schema.STATE)
    if (state != 'STARTED'):
        return False
    if self.CheckExpiry():
        return False
    return True

Is this hunt considered started?

This method is used to check if new clients should be processed by
this hunt. Note that child flow responses are always processed but
new clients are not allowed to be scheduled unless the hunt is
started.

Returns:
If a new client is allowed to be scheduled on this hunt.


class EncodecOutput(ModelOutput):
    audio_codes: Optional[torch.LongTensor] = None
    audio_values: Optional[torch.FloatTensor] = None

Args:
audio_codes (`torch.LongTensor`  of shape `(batch_size, nb_chunks, chunk_length)`, *optional*):
Discret code embeddings computed using `model.encode`.
audio_values (`torch.FlaotTensor` of shape `(batch_size, sequence_length)`, *optional*)
Decoded audio values, obtained using the decoder part of Encodec.


def to_dc(data):
    root = odict['metadata':odict[('@xmlns:xsi':'http:
    for (key, val) in _convert_metadata(_remove_none(data)).iteritems():
        if (val is None):
            continue
        if (isinstance(val, basestring) and (not val.strip())):
            continue
        if isinstance(val, str):
            val = val.decode('utf-8')
        root['metadata'][key] = val
    return unparse(root, pretty=True, indent='    ')

Convert WA-KAT `data` to Dublin core XML.

Args:
data (dict): Nested WA-KAT data. See tests for example.

Returns:
unicode: XML with dublin core.


def call(self, input_ids: TFModelInputType | None=None, attention_mask: np.ndarray | tf.Tensor | None=None, position_ids: np.ndarray | tf.Tensor | None=None, output_attentions: Optional[bool]=None, output_hidden_states: Optional[bool]=None, return_dict: Optional[bool]=None, training: bool=False) -> Union[TFBaseModelOutputWithPooling, Tuple[tf.Tensor]]:
    outputs = self.groupvit(input_ids=input_ids, attention_mask=attention_mask, position_ids=position_ids, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict, training=training)
    return outputs

Returns:

Examples:

```python
>>> from transformers import CLIPTokenizer, TFGroupViTTextModel

>>> tokenizer = CLIPTokenizer.from_pretrained("nvidia/groupvit-gcc-yfcc")
>>> model = TFGroupViTTextModel.from_pretrained("nvidia/groupvit-gcc-yfcc")

>>> inputs = tokenizer(["a photo of a cat", "a photo of a dog"], padding=True, return_tensors="tf")

>>> outputs = model(**inputs)
>>> last_hidden_state = outputs.last_hidden_state
>>> pooled_output = outputs.pooler_output  # pooled (EOS token) states
```


def create_commit(profile, message, tree, parents):
    resource = '/commits'
    payload = {'message': message, 'tree': tree, 'parents': parents}
    data = api.post_request(profile, resource, payload)
    return prepare(data)

Create a commit.

Args:

profile
A profile generated from ``simplygithub.authentication.profile``.
Such profiles tell this module (i) the ``repo`` to connect to,
and (ii) the ``token`` to connect with.

message
The commit message to give to the commit.

tree
The SHA of the tree to assign to the commit.

parents
A list enumerating the SHAs of the new commit's parent commits.

Returns:
A dict with data about the commit.


def add_fileobj(self, fileobj, path, compress, flags=None):

        f = file_iter(fileobj)
        flags = flags or os.stat(path) & 0o777
        return self.add_stream(f, path, compress, flags)

Add the contents of a file object to the MAR file.

Args:
fileobj (file-like object): open file object
path (str): name of this file in the MAR file
compress (str): One of 'xz', 'bz2', or None. Defaults to None.
flags (int): permission of this file in the MAR file. Defaults to the permissions of `path`


def do_scan_trigger(sk, if_index, driver_id, mcid):
    _LOGGER.debug('Joining group %d.', mcid)
    ret = nl_socket_add_membership(sk, mcid)
    if (ret < 0):
        return ret
    msg = nlmsg_alloc()
    genlmsg_put(msg, 0, 0, driver_id, 0, 0, nl80211.NL80211_CMD_TRIGGER_SCAN, 0)
    nla_put_u32(msg, nl80211.NL80211_ATTR_IFINDEX, if_index)
    ssids_to_scan = nlmsg_alloc()
    nla_put(ssids_to_scan, 1, 0, b'')
    nla_put_nested(msg, nl80211.NL80211_ATTR_SCAN_SSIDS, ssids_to_scan)
    err = ctypes.c_int(1)
    results = ctypes.c_int((- 1))
    cb = libnl.handlers.nl_cb_alloc(libnl.handlers.NL_CB_DEFAULT)
    libnl.handlers.nl_cb_set(cb, libnl.handlers.NL_CB_VALID, libnl.handlers.NL_CB_CUSTOM, callback_trigger, results)
    libnl.handlers.nl_cb_err(cb, libnl.handlers.NL_CB_CUSTOM, error_handler, err)
    libnl.handlers.nl_cb_set(cb, libnl.handlers.NL_CB_ACK, libnl.handlers.NL_CB_CUSTOM, ack_handler, err)
    libnl.handlers.nl_cb_set(cb, libnl.handlers.NL_CB_SEQ_CHECK, libnl.handlers.NL_CB_CUSTOM, (lambda *_: libnl.handlers.NL_OK), None)
    _LOGGER.debug('Sending NL80211_CMD_TRIGGER_SCAN...')
    ret = nl_send_auto(sk, msg)
    if (ret < 0):
        return ret
    while (err.value > 0):
        _LOGGER.debug('Retrieving NL80211_CMD_TRIGGER_SCAN acknowledgement...')
        ret = nl_recvmsgs(sk, cb)
        if (ret < 0):
            return ret
    if (err.value < 0):
        error('Unknown error {0} ({1})'.format(err.value, errmsg[abs(err.value)]))
    while (results.value < 0):
        _LOGGER.debug('Retrieving NL80211_CMD_TRIGGER_SCAN final response...')
        ret = nl_recvmsgs(sk, cb)
        if (ret < 0):
            return ret
    if (results.value > 0):
        error('The kernel aborted the scan.')
    _LOGGER.debug('Leaving group %d.', mcid)
    return nl_socket_drop_membership(sk, mcid)

Issue a scan request to the kernel and wait for it to reply with a signal.

This function issues NL80211_CMD_TRIGGER_SCAN which requires root privileges.

The way NL80211 works is first you issue NL80211_CMD_TRIGGER_SCAN and wait for the kernel to signal that the scan is
done. When that signal occurs, data is not yet available. The signal tells us if the scan was aborted or if it was
successful (if new scan results are waiting). This function handles that simple signal.

May exit the program (sys.exit()) if a fatal error occurs.

Positional arguments:
sk -- nl_sock class instance (from nl_socket_alloc()).
if_index -- interface index (integer).
driver_id -- nl80211 driver ID from genl_ctrl_resolve() (integer).
mcid -- nl80211 scanning group ID from genl_ctrl_resolve_grp() (integer).

Returns:
0 on success or a negative error code.


def _from_list_record(data):
    return [Schema._get_field_entry(('Column%d' % (i + 1)), value) for (i, value) in enumerate(data)]

Infer a BigQuery table schema from a list of values.

Args:
data: The list of values.
Returns:
A list of dictionaries containing field 'name' and 'type' entries, suitable for use in a
BigQuery Tables resource schema.


def BuildArtifactsRegistry(cls, artifact_definitions_path, custom_artifacts_path):
    if (artifact_definitions_path and (not os.path.isdir(artifact_definitions_path))):
        raise errors.BadConfigOption('No such artifacts filter file: {0:s}.'.format(artifact_definitions_path))
    if (custom_artifacts_path and (not os.path.isfile(custom_artifacts_path))):
        raise errors.BadConfigOption('No such artifacts filter file: {0:s}.'.format(custom_artifacts_path))
    registry = artifacts_registry.ArtifactDefinitionsRegistry()
    reader = artifacts_reader.YamlArtifactsReader()
    try:
        registry.ReadFromDirectory(reader, artifact_definitions_path)
    except (KeyError, artifacts_errors.FormatError) as exception:
        raise errors.BadConfigOption('Unable to read artifact definitions from: {0:s} with error: {1!s}'.format(artifact_definitions_path, exception))
    if custom_artifacts_path:
        try:
            registry.ReadFromFile(reader, custom_artifacts_path)
        except (KeyError, artifacts_errors.FormatError) as exception:
            raise errors.BadConfigOption('Unable to read artifact definitions from: {0:s} with error: {1!s}'.format(custom_artifacts_path, exception))
    return registry

Build Find Specs from artifacts or filter file if available.

Args:
artifact_definitions_path (str): path to artifact definitions file.
custom_artifacts_path (str): path to custom artifact definitions file.

Returns:
artifacts.ArtifactDefinitionsRegistry: artifact definitions registry.

Raises:
RuntimeError: if no valid FindSpecs are built.


def get_input_shape_at(self, node_index):
    return self._get_node_attribute_at_index(node_index, 'input_shapes', 'input shape')

Retrieves the input shape(s) of a layer at a given node.

Args:
node_index: Integer, index of the node
from which to retrieve the attribute.
E.g. `node_index=0` will correspond to the
first time the layer was called.

Returns:
A shape tuple
(or list of shape tuples if the layer has multiple inputs).

Raises:
RuntimeError: If called in Eager mode.


def _prepare_4d_attention_mask_for_sdpa(mask: torch.Tensor, dtype: torch.dtype, tgt_len: Optional[int]=None):
    _, key_value_length = mask.shape
    tgt_len = tgt_len if tgt_len is not None else key_value_length
    is_tracing = torch.jit.is_tracing() or isinstance(mask, torch.fx.Proxy) or is_torchdynamo_compiling()
    if not is_tracing and torch.all(mask == 1):
        return None
    else:
        return AttentionMaskConverter._expand_mask(mask=mask, dtype=dtype, tgt_len=tgt_len)

Creates a non-causal 4D mask of shape `(batch_size, 1, query_length, key_value_length)` from a 2D mask of shape
`(batch_size, key_value_length)`

Args:
mask (`torch.Tensor`):
A 2D attention mask of shape `(batch_size, key_value_length)`
dtype (`torch.dtype`):
The torch dtype the created mask shall have.
tgt_len (`int`):
The target length or query length the created mask shall have.


def length(self):

    def ProcessContentRange(content_range):
        (_, _, range_spec) = content_range.partition(' ')
        (byte_range, _, _) = range_spec.partition('/')
        (start, _, end) = byte_range.partition('-')
        return ((int(end) - int(start)) + 1)
    if (('-content-encoding' in self.info) and ('content-range' in self.info)):
        return ProcessContentRange(self.info['content-range'])
    elif ('content-length' in self.info):
        return int(self.info.get('content-length'))
    elif ('content-range' in self.info):
        return ProcessContentRange(self.info['content-range'])
    return len(self.content)

Return the length of this response.

We expose this as an attribute since using len() directly can fail
for responses larger than sys.maxint.

Returns:
Response length (as int or long)


def _get_checksum():
    digest = hashlib.sha256()
    with open(RPM_PATH, 'rb') as rpm_db_fh:
        while True:
            buff = rpm_db_fh.read(4096)
            if (not buff):
                break
            digest.update(buff)
    return digest.hexdigest()

Get the checksum of the RPM Database.

Returns:
hexdigest


def get_open_file(self, file_des):

        if not is_int_type(file_des):
            raise TypeError('an integer is required')
        if (file_des >= len(self.open_files) or
                self.open_files[file_des] is None):
            self.raise_os_error(errno.EBADF, str(file_des))
        return self.open_files[file_des][0]

Return an open file.

Args:
file_des: File descriptor of the open file.

Raises:
OSError: an invalid file descriptor.
TypeError: filedes is not an integer.

Returns:
Open file object.


class MMBTConfig:

    def __init__(self, config, num_labels=None, modal_hidden_size=2048):
        self.__dict__ = config.__dict__
        self.modal_hidden_size = modal_hidden_size
        if num_labels:
            self.num_labels = num_labels

This is the configuration class to store the configuration of a [`MMBTModel`]. It is used to instantiate a MMBT
model according to the specified arguments, defining the model architecture.

Args:
config ([`PreTrainedConfig`]):
Config of the underlying Transformer models. Its values are copied over to use a single config.
num_labels (`int`, *optional*):
Size of final Linear layer for classification.
modal_hidden_size (`int`, *optional*, defaults to 2048):
Embedding dimension of the non-text modality encoder.


def _restore_and_log_checkpoint(self, actor):

        actor_id = self._worker.actor_id
        try:
            checkpoints = ray.actor.get_checkpoints_for_actor(actor_id)
            if len(checkpoints) > 0:

                checkpoint_id = actor.load_checkpoint(actor_id, checkpoints)
                if checkpoint_id is not None:

                    msg = (
                        "`load_checkpoint` must return a checkpoint id that " +
                        "exists in the `available_checkpoints` list, or eone.")
                    assert any(checkpoint_id == checkpoint.checkpoint_id
                               for checkpoint in checkpoints), msg

                    (self._worker.raylet_client.
                     notify_actor_resumed_from_checkpoint(
                         actor_id, checkpoint_id))
        except Exception:

            traceback_str = ray.utils.format_error_message(
                traceback.format_exc())
            ray.utils.push_error_to_driver(
                self._worker,
                ray_constants.CHECKPOINT_PUSH_ERROR,
                traceback_str,
                driver_id=self._worker.task_driver_id)

Restore an actor from a checkpoint if available and log any errors.

This should only be called on workers that have just executed an actor
creation task.

Args:
actor: The actor to restore from a checkpoint.


def GetPasswdMap(self, since=None):
    return PasswdUpdateGetter().GetUpdates(self, self.conf['passwd_url'], since)

Return the passwd map from this source.

Args:
since: Get data only changed since this timestamp (inclusive) or None
for all data.

Returns:
instance of passwd.PasswdMap


def evaluate(self, node: InstanceNode) -> XPathValue:
    return self._eval(XPathContext(node, node, 1, 1))

Evaluate the receiver and return the result.

Args:
node: Context node for XPath evaluation.

Raises:
XPathTypeError: If a subexpression of the receiver is of a wrong
type.


def __init__(self, cookie_identifier):

    data_type = '{0:s}:{1:s}'.format(self.DATA_TYPE, cookie_identifier)

    super(GoogleAnalyticsEventData, self).__init__(data_type=data_type)
    self.cookie_name = None
    self.domain_hash = None
    self.pages_viewed = None
    self.sessions = None
    self.sources = None
    self.url = None
    self.visitor_id = None

Initializes event data.

Args:
cookie_identifier (str): unique identifier of the cookie.


def wigner_data(q_result, meas_qubits, labels, shots=None):
    num = len(meas_qubits)
    dim = (2 ** num)
    p = [(0.5 + (0.5 * np.sqrt(3))), (0.5 - (0.5 * np.sqrt(3)))]
    parity = 1
    for i in range(num):
        parity = np.kron(parity, p)
    w = ([0] * len(labels))
    wpt = 0
    counts = [marginal_counts(q_result.get_counts(circ), meas_qubits) for circ in labels]
    for entry in counts:
        x = ([0] * dim)
        for i in range(dim):
            if (bin(i)[2:].zfill(num) in entry):
                x[i] = float(entry[bin(i)[2:].zfill(num)])
        if (shots is None):
            shots = np.sum(x)
        for i in range(dim):
            w[wpt] = (w[wpt] + ((x[i] / shots) * parity[i]))
        wpt += 1
    return w

Get the value of the Wigner function from measurement results.

Args:
q_result (Result): Results from execution of a state tomography
circuits on a backend.
meas_qubits (list[int]): a list of the qubit indexes measured.
labels (list[str]): a list of names of the circuits
shots (int): number of shots

Returns:
list: The values of the Wigner function at measured points in
phase space


def scrape_bandcamp_url(url, num_tracks=sys.maxsize, folders=False, custom_path=''):
    filenames = []
    album_data = get_bandcamp_metadata(url)
    if (type(album_data) is list):
        for album_url in album_data:
            filenames.append(scrape_bandcamp_url(album_url, num_tracks, folders, custom_path))
        return filenames
    artist = album_data['artist']
    album_name = album_data['album_name']
    if folders:
        if album_name:
            directory = ((artist + ' - ') + album_name)
        else:
            directory = artist
        directory = sanitize_filename(directory)
        directory = join(custom_path, directory)
        if (not exists(directory)):
            mkdir(directory)
    for (i, track) in enumerate(album_data['trackinfo']):
        if (i > (num_tracks - 1)):
            continue
        try:
            track_name = track['title']
            if track['track_num']:
                track_number = str(track['track_num']).zfill(2)
            else:
                track_number = None
            if (track_number and folders):
                track_filename = ('%s - %s.mp3' % (track_number, track_name))
            else:
                track_filename = ('%s.mp3' % track_name)
            track_filename = sanitize_filename(track_filename)
            if folders:
                path = join(directory, track_filename)
            else:
                path = join(custom_path, ((sanitize_filename(artist) + ' - ') + track_filename))
            if exists(path):
                puts_safe((colored.yellow('Track already downloaded: ') + colored.white(track_name)))
                continue
            if (not track['file']):
                puts_safe((colored.yellow('Track unavailble for scraping: ') + colored.white(track_name)))
                continue
            puts_safe((colored.green('Downloading') + colored.white((': ' + track_name))))
            path = download_file(track['file']['mp3-128'], path)
            album_year = album_data['album_release_date']
            if album_year:
                album_year = datetime.strptime(album_year, '%d %b %Y %H:%M:%S GMT').year
            tag_file(path, artist, track_name, album=album_name, year=album_year, genre=album_data['genre'], artwork_url=album_data['artFullsizeUrl'], track_number=track_number, url=album_data['url'])
            filenames.append(path)
        except Exception as e:
            puts_safe((colored.red('Problem downloading ') + colored.white(track_name)))
            print(e)
    return filenames

Pull out artist and track info from a Bandcamp URL.

Returns:
list: filenames to open


def get_categorical_feature_names(example):
    features = get_example_features(example)
    return sorted([feature_name for feature_name in features if (features[feature_name].WhichOneof('kind') == 'bytes_list')])

Returns a list of feature names for byte type features.

Args:
example: An example.

Returns:
A list of categorical feature names (e.g. ['education', 'marital_status'] )


def validate(self, institute, case, user, link, variant, validate_type):
    if (not (validate_type in SANGER_OPTIONS)):
        LOG.warning('Invalid validation string: %s', validate_type)
        LOG.info('Validation options: %s', ', '.join(SANGER_OPTIONS))
        return
    updated_variant = self.variant_collection.find_one_and_update({'_id': variant['_id']}, {'$set': {'validation': validate_type}}, return_document=pymongo.ReturnDocument.AFTER)
    self.create_event(institute=institute, case=case, user=user, link=link, category='variant', verb='validate', variant=variant, subject=variant['display_name'])
    return updated_variant

Mark validation status for a variant.

Arguments:
institute (dict): A Institute object
case (dict): Case object
user (dict): A User object
link (str): The url to be used in the event
variant (dict): A variant object
validate_type(str): The outcome of validation.
choices=('True positive', 'False positive')

Returns:
updated_variant(dict)


def IsInAlphabeticalOrder(self, clean_lines, linenum, header_path):

    if (self._last_header > header_path and
        Match(r'^\s*
      return False
    return True

Check if a header is in alphabetical order with the previous header.

Args:
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
header_path: Canonicalized header to be checked.

Returns:
Returns true if the header is in alphabetical order.


def __init__(self, coder=coders.FastPrimitivesCoder(), events=None, output_tags=None, endpoint=None):
    super().__init__()
    assert coder is not None
    self.coder = coder
    self.watermarks = {None: timestamp.MIN_TIMESTAMP}
    self.output_tags = set(output_tags) if output_tags else set()
    self._events = [] if events is None else list(events)
    self._endpoint = endpoint
    event_tags = set((e.tag for e in self._events if isinstance(e, (WatermarkEvent, ElementEvent))))
    assert event_tags.issubset(self.output_tags), '{} is not a subset of {}'.format(event_tags, output_tags)
    assert not (self._events and self._endpoint), 'Only either events or an endpoint can be given at once.'

Args:
coder: (apache_beam.Coder) the coder to encode/decode elements.
events: (List[Event]) a list of instructions for the TestStream to
execute. If specified, the events tags must exist in the output_tags.
output_tags: (List[str]) Initial set of outputs. If no event references an
output tag, no output will be produced for that tag.
endpoint: (str) a URL locating a TestStreamService.


def save_image(image_url, image_directory, image_name):
    image_type = get_image_type(image_url)
    if (image_type is None):
        raise ImageErrorException(image_url)
    full_image_file_name = os.path.join(image_directory, ((image_name + '.') + image_type))
    if os.path.exists(image_url):
        shutil.copy(image_url, full_image_file_name)
        return image_type
    try:
        with open(full_image_file_name, 'wb') as f:
            user_agent = 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:31.0) Gecko/20100101 Firefox/31.0'
            request_headers = {'User-Agent': user_agent}
            requests_object = requests.get(image_url, headers=request_headers)
            try:
                content = requests_object.content
                f.write(content)
            except AttributeError:
                raise ImageErrorException(image_url)
    except IOError:
        raise ImageErrorException(image_url)
    return image_type

Saves an online image from image_url to image_directory with the name image_name.
Returns the extension of the image saved, which is determined dynamically.

Args:
image_url (str): The url of the image.
image_directory (str): The directory to save the image in.
image_name (str): The file name to save the image as.

Raises:
ImageErrorException: Raised if unable to save the image at image_url


def GetProcessedTaskByIdentifier(self, task_identifier):

    with self._lock:
      task = self._tasks_processing.get(task_identifier, None)
      if not task:
        task = self._tasks_queued.get(task_identifier, None)
      if not task:
        task = self._tasks_abandoned.get(task_identifier, None)
      if not task:
        raise KeyError('Status of task {0:s} is unknown'.format(
            task_identifier))

    return task

Retrieves a task that has been processed.

Args:
task_identifier (str): unique identifier of the task.

Returns:
Task: a task that has been processed.

Raises:
KeyError: if the task was not processing, queued or abandoned.


def delete(self, key):
    self._cur_batch.delete(key)
    self._num_mutations += 1
    if (self._num_mutations >= MAX_MUTATIONS_IN_BATCH):
        self.commit()
        self.begin()

Adds deletion of the entity with given key to the mutation buffer.

If mutation buffer reaches its capacity then this method commit all pending
mutations from the buffer and emties it.

Args:
key: key of the entity which should be deleted


def output_stream(self, instruction_id, transform_id):
    raise NotImplementedError(type(self))

Returns an output stream writing elements to transform_id.

Args:
instruction_id: which instruction this stream belongs to
transform_id: the transform_id of the returned stream


def listup_sentence(self, data, counter=0):
    delimiter = self.delimiter_list[counter]
    sentence_list = []
    [sentence_list.append((sentence + delimiter)) for sentence in data.split(delimiter) if (sentence != '')]
    if ((counter + 1) < len(self.delimiter_list)):
        sentence_list_r = []
        [sentence_list_r.extend(self.listup_sentence(sentence, (counter + 1))) for sentence in sentence_list]
        sentence_list = sentence_list_r
    return sentence_list

Divide string into sentence list.

Args:
data:               string.
counter:            recursive counter.

Returns:
List of sentences.


def _create_plugin(self, config):

        if config is None:
            raise ValueError('No plugin config to create plugin from.')

        name = config.pop('name', None)
        if name is None:
            raise(cfg.AitConfigMissing('plugin name'))

        module_name = name.rsplit('.', 1)[0]
        class_name = name.rsplit('.', 1)[-1]
        if class_name in [x.name for x in (self.outbound_streams +
                                           self.inbound_streams +
                                           self.servers +
                                           self.plugins)]:
            raise ValueError(
                'Plugin "{}" already loaded. Only one plugin of a given name is allowed'.
                format(class_name)
            )

        plugin_inputs = config.pop('inputs', None)
        if plugin_inputs is None:
            log.warn('No plugin inputs specified for {}'.format(name))
            plugin_inputs = [ ]

        subscribers = config.pop('outputs', None)
        if subscribers is None:
            log.warn('No plugin outputs specified for {}'.format(name))
            subscribers = [ ]

        module = import_module(module_name)
        plugin_class = getattr(module, class_name)
        instance = plugin_class(plugin_inputs,
                                subscribers,
                                zmq_args={'zmq_context': self.broker.context,
                                          'zmq_proxy_xsub_url': self.broker.XSUB_URL,
                                          'zmq_proxy_xpub_url': self.broker.XPUB_URL},
                                **config
        )

        return instance

Creates a plugin from its config.

Params:
config:       plugin configuration as read by ait.config
Returns:
plugin:       a Plugin
Raises:
ValueError:   if any of the required config values are missing


def DEFINE_enum(name, default, enum_values, help, flag_values=FLAGS, module_name=None, **args):
    DEFINE_flag(EnumFlag(name, default, help, enum_values, **args), flag_values, module_name)

Registers a flag whose value can be any string from enum_values.

Args:
name: A string, the flag name.
default: The default value of the flag.
enum_values: A list of strings with the possible values for the flag.
help: A help string.
flag_values: FlagValues object with which the flag will be registered.
module_name: A string, the name of the Python module declaring this flag.
If not provided, it will be computed using the stack trace of this call.
**args: Dictionary with extra keyword args that are passed to the
Flag __init__.


def ParseFileObject(self, parser_mediator, file_object):

    pe_data = file_object.read()
    try:
      pefile_object = pefile.PE(data=pe_data, fast_load=True)
      pefile_object.parse_data_directories(
          directories=[
              pefile.DIRECTORY_ENTRY['IMAGE_DIRECTORY_ENTRY_IMPORT'],
              pefile.DIRECTORY_ENTRY['IMAGE_DIRECTORY_ENTRY_EXPORT'],
              pefile.DIRECTORY_ENTRY['IMAGE_DIRECTORY_ENTRY_RESOURCE'],
              pefile.DIRECTORY_ENTRY['IMAGE_DIRECTORY_ENTRY_DELAY_IMPORT'],])
    except:
      raise errors.UnableToParseFile()

    event_data = PEEventData()
    event_data.imphash = pefile_object.get_imphash()
    event_data.pe_type = self._GetPEType(pefile_object)
    event_data.section_names = self._GetSectionNames(pefile_object)

    event_data.data_type = 'pe:compilation:compilation_time'

    timestamp = getattr(pefile_object.FILE_HEADER, 'TimeDateStamp', None)

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

    for dll_name, timestamp in self._GetImportTimestamps(pefile_object):
      if timestamp:
        event_data.dll_name = dll_name
        event_data.data_type = 'pe:import:import_time'

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

    for dll_name, timestamp in self._GetDelayImportTimestamps(pefile_object):
      if timestamp:
        event_data.dll_name = dll_name
        event_data.data_type = 'pe:delay_import:import_time'

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

    event_data.dll_name = None

    for timestamp in self._GetResourceTimestamps(pefile_object):
      if timestamp:
        event_data.data_type = 'pe:resource:creation_time'

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

    timestamp = self._GetLoadConfigTimestamp(pefile_object)
    if timestamp:
      event_data.data_type = 'pe:load_config:modification_time'

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

Parses a Portable Executable (PE) file-like object.

Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
file_object (dfvfs.FileIO): a file-like object.

Raises:
UnableToParseFile: when the file cannot be parsed.


def get(self, page=0, size=10):

        dash_list = r_db.zrevrange(config.DASH_ID_KEY, 0, -1, True)
        id_list = dash_list[page * size : page * size + size]
        dash_meta = []
        data = []
        if id_list:
            dash_meta = r_db.hmget(config.DASH_META_KEY, [i[0] for i in id_list])
            data = [json.loads(i) for i in dash_meta]

        return build_response(dict(data=data, code=200))

Get dashboard meta info from in page `page` and page size is `size`.

Args:
page: page number.
size: size number.

Returns:
list of dict containing the dash_id and accordingly meta info.
maybe empty list [] when page * size > total dashes in db. that's reasonable.


def name(self, value):

        if value == self._defaults['name'] and 'name' in self._values:
            del self._values['name']
        else:
            self._values['name'] = value

The name property.

Args:
value (string). the property value.


def clean_video_data(_data):

    data = _data.copy()

    title = data.get('title')
    if title:
        data['title'] = clean_title(title)

    return data

Clean video data:
-> cleans title
-> ...

Args:
_data (dict): Information about the video.

Returns:
dict: Refined video data.


def _parse_logging(log_values: dict, service_config: dict):
    for (log_key, log_value) in log_values.items():
        if ('driver' in log_key):
            service_config['log_driver'] = log_value
        if ('options' in log_key):
            service_config['log_driver_options'] = log_value

Parse log key.

Args:
log_values (dict): logging configuration values
service_config (dict): Service specification


def Cancel(self, request, global_params=None):
    config = self.GetMethodConfig('Cancel')
    return self._RunMethod(config, request, global_params=global_params)

Cancels a build in progress.

Args:
request: (CancelBuildRequest) input message
global_params: (StandardQueryParameters, default: None) global arguments
Returns:
(Build) The response message.


def __init__(self,
                 *packages,
                 build_tree=True,
                 build_dependencies=True,
                 enforce_init=True):

        self.finder = Finder()
        self.specs = []
        self.not_found = []
        self.enforce_init = enforce_init

        specs = []
        for package in packages:
            spec = self.finder.find(package, enforce_init=enforce_init)
            if spec:
                specs.append(spec)
            else:
                self.not_found.append(package)

        if not specs:
            print('** dependenpy: DSM empty.', file=sys.stderr)

        self.specs = PackageSpec.combine(specs)

        for m in self.not_found:
            print('** dependenpy: Not found: %s.' % m, file=sys.stderr)

        super().__init__(build_tree)

        if build_tree and build_dependencies:
            self.build_dependencies()

Initialization method.

Args:
*packages (args): list of packages to search for.
build_tree (bool): auto-build the tree or not.
build_dependencies (bool): auto-build the dependencies or not.
enforce_init (bool):
if True, only treat directories if they contain an
``__init__.py`` file.


def AssertType(value, expected_type):

  if not isinstance(value, expected_type):
    message = "Expected type `%r`, but got value `%r` of type `%s`"
    message %= (expected_type, value, type(value))
    raise TypeError(message)

Ensures that given value has certain type.

Args:
value: A value to assert the type for.
expected_type: An expected type for the given value.

Raises:
TypeError: If given value does not have the expected type.


def get_simple_date(datestring):
    simple_date = re.compile('\\d{1,2}(\\.)\\d{1,2}')
    date = simple_date.search(datestring)
    if date:
        dates = date.group().split('.')
        if (len(dates[0]) == 1):
            dates[0] = add_zero(dates[0])
        if (len(dates[1]) == 1):
            dates[1] = add_zero(dates[1])
        if date_is_valid(dates):
            return ('.'.join(dates) + '.')
        return 'Failed'

Transforms a datestring into shorter date 7.9.2017 > 07.09

Expects the datestring to be format 07.09.2017. If this is not the
case, returns string "Failed".

Keyword arguments:
datestring -- a string

Returns:
String -- The date in format "dd.MM." or "Failed"


def _prepare_method(self, pandas_func, **kwargs):

        if self._is_transposed:

            def helper(df, internal_indices=[]):
                if len(internal_indices) > 0:
                    return pandas_func(
                        df.T, internal_indices=internal_indices, **kwargs
                    )
                return pandas_func(df.T, **kwargs)

        else:

            def helper(df, internal_indices=[]):
                if len(internal_indices) > 0:
                    return pandas_func(df, internal_indices=internal_indices, **kwargs)
                return pandas_func(df, **kwargs)

        return helper

Prepares methods given various metadata.
Args:
pandas_func: The function to prepare.

Returns
Helper function which handles potential transpose.


def _parse_by_pattern(self, lines, pattern):
    for line in lines:
        match = pattern.match(line)
        if match:
            params = match.groupdict()
            if (not params):
                params = match.groups()
            (yield self._create_output_from_match(params))

Match pattern line by line and return Results.

Use ``_create_output_from_match`` to convert pattern match groups to
Result instances.

Args:
lines (iterable): Output lines to be parsed.
pattern: Compiled pattern to match against lines.
result_fn (function): Receive results of one match and return a
Result.

Return:
generator: Result instances.


def _required_constraint_name(table: str, field, key):
    return '{table}_{field}_required_{postfix}'.format(table=table, field=field.column, postfix=key)

Gets the name for a CONSTRAINT that applies
to a single hstore key.

Arguments:
table:
The name of the table the field is
a part of.

field:
The hstore field to create a
UNIQUE INDEX for.

key:
The name of the hstore key
to create the name for.

Returns:
The name for the UNIQUE index.


def _ValidateCacheFileMetadataHeader(self, cache_file_metadata_header):
    return ((cache_file_metadata_header.key_size > 0) and (cache_file_metadata_header.key_size < self._MAXIMUM_URL_LENGTH) and (cache_file_metadata_header.format_version == 1) and (cache_file_metadata_header.last_fetched_time > 0) and (cache_file_metadata_header.fetch_count > 0))

Determines whether the cache file metadata header is valid.

Args:
cache_file_metadata_header (firefox_cache2_file_metadata_header): cache
file metadata header.

Returns:
bool: True if the cache file metadata header is valid.


def strip_alias(data_type):

    while hasattr(data_type, 'data_type'):
        if is_alias(data_type.data_type):
            data_type.data_type = data_type.data_type.data_type
            break
        data_type = data_type.data_type

Strip alias from a data_type chain - this function should be
used *after* aliases are resolved (see resolve_aliases fn):

Loops through given data type chain (unwraps types), replaces
first alias with underlying type, and then terminates.

Note: Stops on encountering the first alias as it assumes
intermediate aliases are already removed.

Args:
data_type (DataType): The target DataType chain to strip.
Return:
None


def times(self, factor):
    if (factor == 0):
        return self.__class__()
    if (factor < 0):
        raise ValueError('The factor must no be negative.')
    result = self.__copy__()
    _elements = result._elements
    for element in _elements:
        _elements[element] *= factor
    result._total *= factor
    return result

Return a new set with each element's multiplicity multiplied with the given scalar factor.

>>> ms = Multiset('aab')
>>> sorted(ms.times(2))
['a', 'a', 'a', 'a', 'b', 'b']

You can also use the ``*`` operator for the same effect:

>>> sorted(ms * 3)
['a', 'a', 'a', 'a', 'a', 'a', 'b', 'b', 'b']

For a variant of the operation which modifies the multiset in place see
:meth:`times_update`.

Args:
factor: The factor to multiply each multiplicity with.


def perturb_function(f, var, k, delta):
    num_elts = tf.size(var)
    old_value = var.read_value()
    perturbation_direction = tf.one_hot(k, num_elts, 1.0, 0.0, None, var.dtype)
    perturbation = tf.reshape(tf.cast(delta, var.dtype) * perturbation_direction, tf.shape(var))
    var.assign(old_value + perturbation)
    f_value = f()
    var.assign(old_value)
    return f_value

Evaluates the function with a specified variable perturbed.

Args:
f: Callable taking no arguments and returning a possibly nested structure
whose atomic elements are `tf.Tensor`.
var: `tf.Variable` to perturb.
k: Entry of `var` to perturb.
delta: Amount to perturb entry `k` of `var`.

Return:
f_value: Return of `f()` evaluated while `var` is perturbed.


def noise_get_fbm(
    n: tcod.noise.Noise,
    f: Sequence[float],
    oc: float,
    typ: int = NOISE_DEFAULT,
) -> float:

    return float(
        lib.TCOD_noise_get_fbm_ex(n.noise_c, ffi.new("float[4]", f), oc, typ)
    )

Return the fractal Brownian motion sampled from the ``f`` coordinate.

Args:
n (Noise): A Noise instance.
f (Sequence[float]): The point to sample the noise from.
typ (int): The noise algorithm to use.
octaves (float): The level of level.  Should be more than 1.

Returns:
float: The sampled noise value.


def add(self, text, checked=False, sort=None):

        if self.parent is None:
            raise exception.InvalidException('Item has no parent')
        node = self.parent.add(text, checked, sort)
        self.indent(node)
        return node

Add a new sub item to the list. This item must already be attached to a list.

Args:
text (str): The text.
checked (bool): Whether this item is checked.
sort (int): Item id for sorting.


def add_gene_ids(self, genes_list):

        orig_num_genes = len(self.genes)

        for g in list(set(genes_list)):
            if not self.genes.has_id(g):
                new_gene = GenePro(id=g, pdb_file_type=self.pdb_file_type, root_dir=self.genes_dir)
                if self.model:
                    self.model.genes.append(new_gene)
                else:
                    self.genes.append(new_gene)

        log.info('Added {} genes to GEM-PRO project'.format(len(self.genes)-orig_num_genes))

Add gene IDs manually into the GEM-PRO project.

Args:
genes_list (list): List of gene IDs as strings.


async def runCmdLine(self, line):

        opts = self.getCmdOpts(line)
        return await self.runCmdOpts(opts)

Run a line of command input for this command.

Args:
line (str): Line to execute

Examples:
Run the foo command with some arguments:

await foo.runCmdLine('foo --opt baz woot.com')


def getenv(key, value=None):

    key = path2fsn(key)
    if is_win and PY2:
        return environ.get(key, value)
    return os.getenv(key, value)

Like `os.getenv` but returns unicode under Windows + Python 2

Args:
key (pathlike): The env var to get
value (object): The value to return if the env var does not exist
Returns:
`fsnative` or `object`:
The env var or the passed value if it doesn't exist


def empty(shape, dtype=None):
    return backend.numpy.empty(shape, dtype=dtype)

Return a tensor of given shape and type filled with uninitialized data.

Args:
shape: Shape of the empty tensor.
dtype: Desired data type of the empty tensor.

Returns:
The empty tensor.


def get_jax_iterator(self):
    raise NotImplementedError

Get a Python iterable for the `DataAdapter`, that yields arrays that
that can be fed to JAX. NumPy arrays are preferred for performance.

Returns:
A Python iterator.


def add_file(self, file_obj):
    BalancedDiscStorage._check_interface(file_obj)
    file_hash = self._get_hash(file_obj)
    dir_path = self._create_dir_path(file_hash)
    final_path = os.path.join(dir_path, file_hash)

    def copy_to_file(from_file, to_path):
        with open(to_path, 'wb') as out_file:
            for part in self._get_file_iterator(from_file):
                out_file.write(part)
    try:
        copy_to_file(from_file=file_obj, to_path=final_path)
    except Exception:
        os.unlink(final_path)
        raise
    return PathAndHash(path=final_path, hash=file_hash)

Add new file into the storage.

Args:
file_obj (file): Opened file-like object.

Returns:
obj: Path where the file-like object is stored contained with hash\
in :class:`.PathAndHash` object.

Raises:
AssertionError: If the `file_obj` is not file-like object.
IOError: If the file couldn't be added to storage.


def _add_extension_value_to_message(extension: message.Message, msg: message.Message, message_field: descriptor.FieldDescriptor) -> None:
    if message_field.type != descriptor.FieldDescriptor.TYPE_MESSAGE:
        raise fhir_errors.InvalidFhirError(f'{msg.DESCRIPTOR.full_name} is not a FHIR extension type.')
    extension_field = extension.DESCRIPTOR.fields_by_name['extension']
    if proto_utils.field_content_length(extension, extension_field) > 0:
        raise fhir_errors.InvalidFhirError(f'No child extensions should be set on {extension.DESCRIPTOR.full_name}.')
    value_field = _get_populated_extension_value_field(extension)
    if annotation_utils.is_choice_type_field(message_field):
        choice_message = proto_utils.get_value_at_field(msg, message_field)
        choice_descriptor = choice_message.DESCRIPTOR
        for choice_field in choice_descriptor.fields:
            if value_field.message_type.full_name == choice_field.message_type.full_name:
                _add_extension_value_to_message(extension, choice_message, choice_field)
                return
        raise ValueError(f'No field on Choice Type {choice_descriptor.full_name} for extension {extension.DESCRIPTOR.full_name}.')
    if annotation_utils.has_fhir_valueset_url(message_field.message_type):
        typed_code = proto_utils.set_in_parent_or_add(msg, message_field)
        codes.copy_code(cast(Any, extension).value.code, typed_code)
        return
    if fhir_types.is_type_or_profile_of_coding(message_field.message_type):
        typed_coding = proto_utils.set_in_parent_or_add(msg, message_field)
        codes.copy_coding(cast(Any, extension).value.coding, typed_coding)
        return
    if not proto_utils.are_same_message_type(value_field.message_type, message_field.message_type):
        raise ValueError(f'Missing expected value of type {message_field.message_type.full_name} in extension {extension.DESCRIPTOR.full_name}.')
    value = proto_utils.get_value_at_field(cast(Any, extension).value, value_field)
    if proto_utils.field_is_repeated(message_field):
        proto_utils.append_value_at_field(msg, message_field, value)
    else:
        proto_utils.set_value_at_field(msg, message_field, value)

Serialize the provided extension and add it to the message.

Args:
extension: The FHIR extension to serialize.
msg: The message to add the serialized extension to.
message_field: The field on the message to set.

Raises:
InvalidFhirError: In the event that the field to be set is not a singular
message type, or if the provided extension is not singular (has nested
extensions).


def create_parser():
    parser = argparse.ArgumentParser(prog=pylink.__title__, description=pylink.__description__, epilog=pylink.__copyright__)
    parser.add_argument('--version', action='version', version=('%(prog)s ' + pylink.__version__))
    parser.add_argument('-v', '--verbose', action='count', default=0, help='increase output verbosity')
    kwargs = {}
    kwargs['title'] = 'command'
    kwargs['description'] = 'specify subcommand to run'
    kwargs['help'] = 'subcommands'
    subparsers = parser.add_subparsers(**kwargs)
    for command in commands():
        kwargs = {}
        kwargs['name'] = command.name
        kwargs['description'] = command.description
        kwargs['help'] = command.help
        subparser = subparsers.add_parser(**kwargs)
        subparser.set_defaults(command=command.run)
        command.add_arguments(subparser)
    return parser

Builds the command parser.

This needs to be exported in order for Sphinx to document it correctly.

Returns:
An instance of an ``argparse.ArgumentParser`` that parses all the
commands supported by the PyLink CLI.


def get_minimal_fba_flux(self, objective):

        vs_wt = self._v_wt.set(self._model.reactions)
        zs = self._z.set(self._model.reactions)

        wt_obj_flux = self.get_fba_obj_flux(objective)

        with self.constraints() as constr:
            constr.add(
                zs >= vs_wt, vs_wt >= -zs,
                self._v_wt[objective] >= wt_obj_flux)
            self._prob.set_objective(self._z.sum(self._model.reactions))
            result = self._solve(lp.ObjectiveSense.Minimize)

        fba_fluxes = {}
        for key in self._model.reactions:
            fba_fluxes[key] = result.get_value(self._v_wt[key])
        return fba_fluxes

Find the FBA solution that minimizes all the flux values.

Maximize the objective flux then minimize all other fluxes
while keeping the objective flux at the maximum.

Args:
objective: The objective reaction that is maximized.

Returns:
A dictionary of all the reactions and their minimized fluxes.


def get_rml_processors(es_defs):
    proc_defs = es_defs.get('kds_esRmlProcessor', [])
    if proc_defs:
        new_defs = []
        for proc in proc_defs:
            params = proc['kds_rmlProcessorParams'][0]
            proc_kwargs = {}
            if params.get('kds_rtn_format'):
                proc_kwargs['rtn_format'] = params.get('kds_rtn_format')[0]
            new_def = dict(name=proc['rdfs_label'][0], subj=params['kds_subjectKwarg'][0], proc_kwargs=proc_kwargs, force=proc.get('kds_forceNested', [False])[0], processor=CFG.rml.get_processor(proc['rdfs_label'][0], proc['kds_esRmlMapping'], proc['rdf_type'][0]))
            new_defs.append(new_def)
        es_defs['kds_esRmlProcessor'] = new_defs
    return es_defs

Returns the es_defs with the instaniated rml_processor

Args:
-----
es_defs: the rdf_class elacticsearch defnitions
cls_name: the name of the tied class


def _stdout_list_split(retcode, stdout='', splitstring='\n'):
    if (retcode == 0):
        ret = stdout.split(splitstring)
        return ret
    else:
        return False

Evaulates Open vSwitch command`s retcode value.

Args:
retcode: Value of retcode field from response, should be 0, 1 or 2.
stdout: Value of stdout filed from response.
splitstring: String used to split the stdout default new line.

Returns:
List or False.


def _get_domain(self):
    try:
        return self.libvirt_con.lookupByName(self._libvirt_name())
    except libvirt.libvirtError as e:
        raise vm_plugin.LagoVMDoesNotExistError(str(e))

Return the object representation of this provider VM.

Returns:
libvirt.virDomain: Libvirt domain object

Raises:
:exc:`~lago.plugins.vm.LagoFailedToGetVMStateError:
If the VM exist, but the query returned an error.


def isostr_to_datetime(dt_str):

    if len(dt_str) <= 20:
        return datetime.datetime.strptime(dt_str, "%Y-%m-%dT%H:%M:%SZ")
    else:
        dt_str = dt_str.split(".")
        return isostr_to_datetime("%sZ" % dt_str[0])

Converts iso formated text string into a datetime object

Args:
dt_str (str): ISO formated text string
Returns:
:obj:`datetime.datetime`


def issue(self, invoice_id, **kwargs):
    url = '{}/{}/issue'.format(self.base_url, invoice_id)
    return self.post_url(url, {}, **kwargs)

Issues an invoice in draft state

Args:
invoice_id : Id for delete the invoice
Returns:
Its response is the invoice entity, similar to create/update API response. Its status now would be issued.


def _load_methods(package):
    global _methods
    _methods[package] = None
    from acorn.config import settings
    from acorn.logging.descriptors import _obj_getattr
    spack = settings(package)
    if (spack is not None):
        if spack.has_section('analysis.methods'):
            _methods[package] = {}
            from importlib import import_module
            mappings = dict(spack.items('analysis.methods'))
            for (fqdn, target) in mappings.items():
                rootname = target.split('.')[0]
                root = import_module(rootname)
                caller = _obj_getattr(root, target)
                _methods[package][fqdn] = caller

Loads the mappings from method call result to analysis.

Args:
package (str): name of the package to load for.


def sg_reshape(tensor, opt):
    r
    assert opt.shape is not None, 'shape is mandatory.'
    return tf.reshape(tensor, opt.shape, name=opt.name)

r"""Reshapes a tensor.

See `tf.reshape()` in tensorflow.

Args:
tensor: A `Tensor` (automatically given by chain).
opt:
shape: A tuple/list of integers. The destination shape.
name: If provided, replace current tensor's name.

Returns:
A `Tensor`.


def __init__(self, config: Mask2FormerConfig, weight_dict: Dict[str, float]):
    super().__init__()
    requires_backends(self, ['scipy'])
    self.num_labels = config.num_labels
    self.weight_dict = weight_dict
    self.eos_coef = config.no_object_weight
    empty_weight = torch.ones(self.num_labels + 1)
    empty_weight[-1] = self.eos_coef
    self.register_buffer('empty_weight', empty_weight)
    self.num_points = config.train_num_points
    self.oversample_ratio = config.oversample_ratio
    self.importance_sample_ratio = config.importance_sample_ratio
    self.matcher = Mask2FormerHungarianMatcher(cost_class=1.0, cost_dice=config.dice_weight, cost_mask=config.mask_weight, num_points=self.num_points)

The Mask2Former Loss. The loss is computed very similar to DETR. The process happens in two steps: 1) we
compute hungarian assignment between ground truth masks and the outputs of the model 2) we supervise each pair
of matched ground-truth / prediction (supervise class and mask)

Args:
config (`Mask2FormerConfig`):
The configuration for Mask2Former model also containing loss calculation specific parameters.
weight_dict (`Dict[str, float]`):
A dictionary of weights to be applied to the different losses.


def create_saturated_interstitial_structure(interstitial_def, dist_tol=0.1):
    sga = SpacegroupAnalyzer(interstitial_def.bulk_structure.copy())
    sg_ops = sga.get_symmetry_operations(cartesian=True)
    saturated_defect_struct = interstitial_def.bulk_structure.copy()
    saturated_defect_struct.DISTANCE_TOLERANCE = dist_tol
    for sgo in sg_ops:
        new_interstit_coords = sgo.operate(interstitial_def.site.coords[:])
        poss_new_site = PeriodicSite(interstitial_def.site.specie, new_interstit_coords, saturated_defect_struct.lattice, to_unit_cell=True, coords_are_cartesian=True)
        try:
            saturated_defect_struct.append(poss_new_site.specie, poss_new_site.coords, coords_are_cartesian=True, validate_proximity=True)
        except ValueError:
            pass
    saturated_sga = SpacegroupAnalyzer(saturated_defect_struct)
    if (saturated_sga.get_space_group_number() != sga.get_space_group_number()):
        raise ValueError('Warning! Interstitial sublattice generation has changed space group symmetry. I recommend reducing dist_tol and trying again...')
    return saturated_defect_struct

this takes a Interstitial defect object and generates the
sublattice for it based on the structure's space group.
Useful for understanding multiplicity of an interstitial
defect in thermodynamic analysis.

NOTE: if large relaxation happens to interstitial or
defect involves a complex then there maybe additional
degrees of freedom that need to be considered for
the multiplicity.

Args:
dist_tol: changing distance tolerance of saturated structure,
allowing for possibly overlapping sites
but ensuring space group is maintained

Returns:
Structure object decorated with interstitial site equivalents


def latest_malicious(self, ips):

        api_name = 'opendns-latest_malicious'
        fmt_url_path = u'ips/{0}/latest_domains'
        return self._multi_get(api_name, fmt_url_path, ips)

Get the a list of malicious domains related to input ips.

Args:
ips: an enumerable of strings as ips
Returns:
An enumerable of strings for the malicious domains


def _quadratic_interpolation_step(x1, x2, x3, y1, y2, y3):
    r2 = (x2 - x1) / (y2 - y1)
    r3 = (x3 - x1) / (y3 - y1)
    return -x1 * tf.math.divide_no_nan(x3 * r3 - x2 * r2, r3 * r2 * (x3 - x2))

Returns the step size to use when using quadratic interpolation.

This function is meant for exclusive use by the `_brent_loop_body` function.
It does not guard against divisions by zero, and instead assumes that `y1` is
distinct from `y2` and `y3`. The `_brent_loop_body` function guarantees this
property.

Args:
x1: `Tensor` of any shape and real dtype containing the first position used
for extrapolation.
x2: `Tensor` of the same shape and dtype as `x1` containing the second
position used for extrapolation.
x3: `Tensor` of the same shape and dtype as `x1` containing the third
position used for extrapolation.
y1: `Tensor` containing the value of the interpolated function at `x1`.
y2: `Tensor` containing the value of interpolated function at `x2`.
y3: `Tensor` containing the value of interpolated function at `x3`.

Returns:
A `Tensor` with the same shape and dtype as `x1`.


def num_work_units_completed(self, name=None):
    if self._reader_ref.dtype == dtypes.resource:
        return gen_io_ops.reader_num_work_units_completed_v2(self._reader_ref, name=name)
    else:
        return gen_io_ops.reader_num_work_units_completed(self._reader_ref, name=name)

Returns the number of work units this reader has finished processing.

Args:
name: A name for the operation (optional).

Returns:
An int64 Tensor.


def _guess_fmt_from_bytes(inp):
    stripped = inp.strip()
    fmt = None
    ini_section_header_re = re.compile(b'^\\[([\\w-]+)\\]')
    if (len(stripped) == 0):
        fmt = 'yaml'
    elif stripped.startswith(b'<'):
        fmt = 'xml'
    else:
        for l in stripped.splitlines():
            line = l.strip()
            if ((not line.startswith(b'
                break
        if ini_section_header_re.match(line):
            fmt = 'ini'
        else:
            fmt = 'yaml'
    return fmt

Try to guess format of given bytestring.

Args:
inp: byte string to guess format of
Returns:
guessed format


def write(self, ostream, kmip_version=enums.KMIPVersion.KMIP_1_0):
    tstream = BytearrayStream()
    self.hashing_algorithm.write(tstream, kmip_version=kmip_version)
    self.digest_value.write(tstream, kmip_version=kmip_version)
    self.key_format_type.write(tstream, kmip_version=kmip_version)
    self.length = tstream.length()
    super(Digest, self).write(ostream, kmip_version=kmip_version)
    ostream.write(tstream.buffer)

Write the data encoding the Digest object to a stream.

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


def is_valid(self, addr, protocol='http', timeout=5):
    start = time.time()
    try:
        r = requests.get(self.test_url[protocol], timeout=timeout, proxies={protocol: ('http:
    except KeyboardInterrupt:
        raise
    except requests.exceptions.Timeout:
        return {'valid': False, 'msg': 'timeout'}
    except:
        return {'valid': False, 'msg': 'exception'}
    else:
        if (r.status_code == 200):
            response_time = (time.time() - start)
            return {'valid': True, 'response_time': response_time}
        else:
            return {'valid': False, 'msg': 'status code: {}'.format(r.status_code)}

Check if a proxy is valid

Args:
addr: A string in the form of 'ip:port'
protocol: Either 'http' or 'https', different test urls will be used
according to protocol.
timeout: A integer indicating the timeout of connecting the test url.

Returns:
dict: If the proxy is valid, returns {'valid': True, 'response_time': xx}
otherwise returns {'valid': False, 'msg': 'xxxxxx'}.


def Resolve(self, subject, attribute):
    for (_, value, timestamp) in self.ResolveMulti(subject, [attribute], timestamp=self.NEWEST_TIMESTAMP):
        return (value, timestamp)
    return (None, 0)

Retrieve a value set for a subject's attribute.

This method is easy to use but always gets the latest version of the
attribute. It is more flexible and efficient to use the other Resolve
methods.

Args:
subject: The subject URN.
attribute: The attribute.

Returns:
A (value, timestamp in microseconds) stored in the datastore cell, or
(None, 0). Value will be the same type as originally stored with Set().

Raises:
AccessError: if anything goes wrong.


def make_tar_stream(build_context, buffer):
    tf = tarfile.TarFile(fileobj=buffer, mode='w')
    for (context_path, fileobj) in build_context.items():
        if (getattr(fileobj, 'localpath', None) is not None):
            tf.add(fileobj.localpath, arcname=context_path)
        else:
            tar_add_bytes(tf, context_path, fileobj.read('rb'))
    tf.close()

Write a tar stream of the build context to the provided buffer

Args:
build_context (Mapping[str, pyccc.FileReferenceBase]): dict mapping filenames to file references
buffer (io.BytesIO): writable binary mode buffer


def scopes(self):
    if (not self.__scopes):
        self.__scopes = Scopes(self.__connection)
    return self.__scopes

Gets the Scopes API client.

Returns:
Scopes:


def convert_saved_model(saved_model_path, exported_names, show_debug_info=False):
    return pywrap_mlir.experimental_convert_saved_model_to_mlir(saved_model_path, exported_names, show_debug_info)

Converts a SavedModel to MLIR module.

Args:
saved_model_path: Path to SavedModel.
exported_names: Names to export.
show_debug_info: Whether to include locations in the emitted textual form.

Returns:
A textual representation of the MLIR module corresponding to the
SavedModel.


def check_missing(self, args):

        return [opt.name for opt in self
                if (opt.name not in args) and (opt.default is None)]

Returns the names of all options that are required but were not specified.

All options that don't have a default value are required in order to run the
workflow.

Args:
args (dict): A dictionary of the provided arguments that is checked for
missing options.

Returns:
list: A list with the names of the options that are missing from the
provided arguments.


def parse_package_string(path):

    parts = path.split('.')

    if parts[-1][0].isupper():
        return ".".join(parts[:-1]), parts[-1]

    return path, ""

Parse the effect package string.
Can contain the package python path or path to effect class in an effect package.

Examples::

# Path to effect pacakge
examples.cubes

# Path to effect class
examples.cubes.Cubes

Args:
path: python path to effect package. May also include effect class name.

Returns:
tuple: (package_path, effect_class)


def mark_bool_flags_as_mutual_exclusive(flag_names, required=False,
                                        flag_values=_flagvalues.FLAGS):

  for flag_name in flag_names:
    if not flag_values[flag_name].boolean:
      raise _exceptions.ValidationError(
          'Flag --{} is not Boolean, which is required for flags used in '
          'mark_bool_flags_as_mutual_exclusive.'.format(flag_name))

  def validate_boolean_mutual_exclusion(flags_dict):
    flag_count = sum(bool(val) for val in flags_dict.values())
    if flag_count == 1 or (not required and flag_count == 0):
      return True
    raise _exceptions.ValidationError(
        '{} one of ({}) must be True.'.format(
            'Exactly' if required else 'At most', ', '.join(flag_names)))

  register_multi_flags_validator(
      flag_names, validate_boolean_mutual_exclusion, flag_values=flag_values)

Ensures that only one flag among flag_names is True.

Args:
flag_names: [str], names of the flags.
required: bool. If true, exactly one flag must be True. Otherwise, at most
one flag can be True, and it is valid for all flags to be False.
flag_values: flags.FlagValues, optional FlagValues instance where the flags
are defined.


def get_type(mime=None, ext=None):
    for kind in types:
        if ((kind.extension is ext) or (kind.mime is mime)):
            return kind
    return None

Returns the file type instance searching by
MIME type or file extension.

Args:
ext: file extension string. E.g: jpg, png, mp4, mp3
mime: MIME string. E.g: image/jpeg, video/mpeg

Returns:
The matched file type instance. Otherwise None.


def _ensure_unique_tensor_objects(parameter_positions, args):
    s = set()
    for i, t in enumerate(args):
        if i in parameter_positions:
            tid = ops.tensor_id(t)
            if tid in s:
                args[i] = gen_array_ops.identity(args[i])
            else:
                s.add(tid)
    return args

Make each of the parameter_positions in args a unique tensor_lib.Tensor object.

Ensure that each parameter is treated independently.
For example:

def f(x, y): return x * y
g = gradients_function(f)
one = tf.constant(1.)

g(one, one) should return [1., 1.]
(even though the two arguments are the same Tensor object).

Args:
parameter_positions: List of indices into args defining the arguments to
differentiate against.
args: A list of arguments to the function to be differentiated.

Returns:
args, possibly edited in-place.


def get_special_tokens_mask(self, token_ids_0: List[int], token_ids_1: Optional[List[int]]=None, already_has_special_tokens: bool=False) -> List[int]:
    if already_has_special_tokens:
        return super().get_special_tokens_mask(token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=True)
    if token_ids_1 is None:
        return [1] + [0] * len(token_ids_0) + [1]
    return [1] + [0] * len(token_ids_0) + [1] + [0] * len(token_ids_1) + [1]

Retrieves sequence ids from a token list that has no special tokens added. This method is called when adding
special tokens using the tokenizer `prepare_for_model` or `encode_plus` methods.

Args:
token_ids_0 (`List[int]`):
List of IDs.
token_ids_1 (`List[int]`, *optional*):
Optional second list of IDs for sequence pairs.
already_has_special_tokens (`bool`, *optional*, defaults to `False`):
Whether or not the token list is already formatted with special tokens for the model.

Returns:
`List[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.


def custom_licenses(self):

        buf = (ctypes.c_char * self.MAX_BUF_SIZE)()
        result = self._dll.JLINK_EMU_GetLicenses(buf, self.MAX_BUF_SIZE)
        if result < 0:
            raise errors.JLinkException(result)
        return ctypes.string_at(buf).decode()

Returns a string of the installed licenses the J-Link has.

Args:
self (JLink): the ``JLink`` instance

Returns:
String of the contents of the custom licenses the J-Link has.


def _GetISO8601String(self, structure):
    time_zone_offset = structure.time_zone_offset
    try:
        time_zone_offset_hours = int(time_zone_offset[1:3], 10)
        time_zone_offset_minutes = int(time_zone_offset[3:5], 10)
    except (IndexError, TypeError, ValueError) as exception:
        raise ValueError('unable to parse time zone offset with error: {0!s}.'.format(exception))
    try:
        iso8601 = '{0:04d}-{1:02d}-{2:02d}T{3:02d}:{4:02d}:{5:02d}.{6:03d}{7:s}{8:02d}:{9:02d}'.format(structure.year, structure.month, structure.day, structure.hours, structure.minutes, structure.seconds, structure.microseconds, time_zone_offset[0], time_zone_offset_hours, time_zone_offset_minutes)
    except ValueError as exception:
        raise ValueError('unable to format date time string with error: {0!s}.'.format(exception))
    return iso8601

Retrieves an ISO 8601 date time string from the structure.

The date and time values in Google Drive Sync log files are formatted as:
"2018-01-24 18:25:08,454 -0800".

Args:
structure (pyparsing.ParseResults): structure of tokens derived from a
line of a text file.

Returns:
str: ISO 8601 date time string.

Raises:
ValueError: if the structure cannot be converted into a date time string.


def _get_model_field(self, name: str):

        field_name = self._normalize_field_name(name)

        if field_name == 'pk' and self.query.model._meta.pk:
            return self.query.model._meta.pk

        for field in self.query.model._meta.local_concrete_fields:
            if field.name == field_name or field.column == field_name:
                return field

        return None

Gets the field on a model with the specified name.

Arguments:
name:
The name of the field to look for.

This can be both the actual field name, or
the name of the column, both will work :)

Returns:
The field with the specified name or None if
no such field exists.


def get_test_data(train_samples, test_samples, input_shape, num_classes, random_seed=None):
    np.random.seed(random_seed)
    total_samples = train_samples + test_samples
    samples_per_class = total_samples
    y = np.array([i for i in range(num_classes) for _ in range(samples_per_class)], dtype=np.int32)
    extra_samples = total_samples - len(y)
    y_extra = np.array([i % num_classes for i in range(extra_samples)], dtype=np.int64)
    y = np.concatenate([y, y_extra])
    templates = 2 * num_classes * np.random.random((num_classes,) + input_shape)
    x = np.zeros((total_samples,) + input_shape, dtype=np.float32)
    for i in range(total_samples):
        x[i] = templates[y[i]] + np.random.normal(loc=0, scale=1.0, size=input_shape)
    indices = np.arange(total_samples)
    np.random.shuffle(indices)
    x, y = (x[indices], y[indices])
    x_train, y_train, x_test, y_test = ([], [], [], [])
    for cls in range(num_classes):
        cls_indices = np.where(y == cls)[0]
        np.random.shuffle(cls_indices)
        train_count = int(train_samples / num_classes)
        x_train.extend(x[cls_indices[:train_count]])
        y_train.extend(y[cls_indices[:train_count]])
        x_test.extend(x[cls_indices[train_count:]])
        y_test.extend(y[cls_indices[train_count:]])
    x_train, y_train = (np.array(x_train), np.array(y_train))
    x_test, y_test = (np.array(x_test), np.array(y_test))
    train_indices = np.arange(len(x_train))
    test_indices = np.arange(len(x_test))
    np.random.shuffle(train_indices)
    np.random.shuffle(test_indices)
    x_train, y_train = (x_train[train_indices], y_train[train_indices])
    x_test, y_test = (x_test[test_indices], y_test[test_indices])
    return ((x_train, y_train), (x_test, y_test))

Generates balanced, stratified synthetic test data to train a model on.

Args:
train_samples: Integer, how many training samples to generate.
test_samples: Integer, how many test samples to generate.
input_shape: Tuple of integers, shape of the inputs.
num_classes: Integer, number of classes for the data and targets.
random_seed: Integer, random seed used by Numpy to generate data.

Returns:
A tuple of Numpy arrays: `(x_train, y_train), (x_test, y_test)`.


def _geodetic_to_cartesian(cls, lat, lon, alt):
    C = (Earth.r / np.sqrt((1 - ((Earth.e * np.sin(lat)) ** 2))))
    S = ((Earth.r * (1 - (Earth.e ** 2))) / np.sqrt((1 - ((Earth.e * np.sin(lat)) ** 2))))
    r_d = ((C + alt) * np.cos(lat))
    r_k = ((S + alt) * np.sin(lat))
    norm = np.sqrt(((r_d ** 2) + (r_k ** 2)))
    return (norm * np.array([(np.cos(lat) * np.cos(lon)), (np.cos(lat) * np.sin(lon)), np.sin(lat)]))

Conversion from latitude, longitude and altitude coordinates to
cartesian with respect to an ellipsoid

Args:
lat (float): Latitude in radians
lon (float): Longitude in radians
alt (float): Altitude to sea level in meters

Return:
numpy.array: 3D element (in meters)


def masks_to_boxes(masks: torch.Tensor) -> torch.Tensor:
    if masks.numel() == 0:
        return torch.zeros((0, 4), device=masks.device)
    h, w = masks.shape[-2:]
    y = torch.arange(0, h, dtype=torch.float32, device=masks.device)
    x = torch.arange(0, w, dtype=torch.float32, device=masks.device)
    y, x = torch.meshgrid(y, x, indexing='ij')
    x_mask = masks * torch.unsqueeze(x, 0)
    x_max = x_mask.view(x_mask.shape[0], -1).max(-1)[0]
    x_min = torch.where(masks, x.unsqueeze(0), torch.tensor(100000000.0, device=masks.device)).view(masks.shape[0], -1).min(-1)[0]
    y_mask = masks * torch.unsqueeze(y, 0)
    y_max = y_mask.view(y_mask.shape[0], -1).max(-1)[0]
    y_min = torch.where(masks, y.unsqueeze(0), torch.tensor(100000000.0, device=masks.device)).view(masks.shape[0], -1).min(-1)[0]
    return torch.stack([x_min, y_min, x_max, y_max], 1)

Compute the bounding boxes around the provided panoptic segmentation masks.

Args:
masks: masks in format `[number_masks, height, width]` where N is the number of masks

Returns:
boxes: bounding boxes in format `[number_masks, 4]` in xyxy format


def most_specific_common_supertype(self, others: Sequence['TraceType']) -> Optional['TraceType']:

Returns the most specific supertype of `self` and `others`, if exists.

The returned `TraceType` is a supertype of `self` and `others`, that is,
they are all subtypes (see `is_subtype_of`) of it.
It is also most specific, that is, there it has no subtype that is also
a common supertype of `self` and `others`.

If `self` and `others` have no common supertype, this returns `None`.

Args:
others: A sequence of TraceTypes.

Example:
```python
class Dimension(TraceType):
def __init__(self, value: Optional[int]):
self.value = value

def most_specific_common_supertype(self, other):
# Either the value is the same or other has a generalized value that
# can represent any specific ones.
if self.value == other.value:
return self.value
else:
return Dimension(None)
```


def segment_text(text, seg_regex=SEG_REGEX):

    for m in seg_regex.finditer(text):
        yield m.group(0)

Return an iterator of segments in the text.

Args:
text (unicode): string of IPA Unicode text
seg_regex (_regex.Pattern): compiled regex defining a segment (base +
modifiers)

Return:
generator: segments in the input text


def __init__(self,
               tb_context,
               max_domain_discrete_len=10):

    self._tb_context = tb_context
    self._experiment_from_tag = None
    self._experiment_from_tag_lock = threading.Lock()
    self._max_domain_discrete_len = max_domain_discrete_len

Instantiates a context.

Args:
tb_context: base_plugin.TBContext. The "base" context we extend.
max_domain_discrete_len: int. Only used when computing the experiment
from the session runs. The maximum number of disticnt values a string
hyperparameter can have for us to populate its 'domain_discrete' field.
Typically, only tests should specify a value for this parameter.


def Match(self, file_entry):
    if (not file_entry):
        return False
    filename = file_entry.name.lower()
    return (filename == self._filename)

Determines if a file entry matches the filter.

Args:
file_entry (dfvfs.FileEntry): a file entry.

Returns:
bool: True if the file entry matches the filter.


def union(self, other):
    if (not isinstance(other, self.__class__)):
        m = 'You can only union striplogs with each other.'
        raise StriplogError(m)
    result = []
    for iv in deepcopy(self):
        for jv in other:
            if iv.any_overlaps(jv):
                iv = iv.union(jv)
        result.append(iv)
    return Striplog(result)

Makes a striplog of all unions.

Args:
Striplog. The striplog instance to union with.

Returns:
Striplog. The result of the union.


def from_tool_cancellation(cls, *, function_call_id: str, **kwargs) -> 'ProcessorPart':
    part = genai_types.Part.from_function_response(name='tool_cancellation', response={'function_call_id': function_call_id})
    if 'role' in kwargs and kwargs['role'].upper() != 'MODEL':
        logging.warning('Role {kwargs["role"]} is not supported for tool cancellation. Overriding it with the model role.')
    extra_args = kwargs
    extra_args['role'] = 'MODEL'
    return cls(part, **extra_args)

Constructs a ProcessorPart from a tool cancellation id.

The role is overridden to MODEL.

Args:
function_call_id: The id of the function call to be cancelled.
**kwargs: Additional arguments for the ProcessorPart constructor.

Returns:
A ProcessorPart of type tool cancellation.


def get_sites_in_sphere(self, pt, r):

        neighbors = []
        for site in self._sites:
            dist = site.distance_from_point(pt)
            if dist <= r:
                neighbors.append((site, dist))
        return neighbors

Find all sites within a sphere from a point.

Args:
pt (3x1 array): Cartesian coordinates of center of sphere.
r (float): Radius of sphere.

Returns:
[(site, dist) ...] since most of the time, subsequent processing
requires the distance.


def checkedThread(self, target: Callable[..., Any], args: Optional[tuple[Any, ...]]=None, kwargs: Optional[dict[str, Any]]=None) -> _CheckedThread:
    ret = TensorFlowTestCase._CheckedThread(self, target, args, kwargs)
    self._threads.append(ret)
    return ret

Returns a Thread wrapper that asserts 'target' completes successfully.

This method should be used to create all threads in test cases, as
otherwise there is a risk that a thread will silently fail, and/or
assertions made in the thread will not be respected.

Args:
target: A callable object to be executed in the thread.
args: The argument tuple for the target invocation. Defaults to ().
kwargs: A dictionary of keyword arguments for the target invocation.
Defaults to {}.

Returns:
A wrapper for threading.Thread that supports start() and join() methods.


def dispatch_for_types(op, *types):

    def decorator(func):
        _TypeBasedDispatcher(get_compatible_func(op, func), types).register(op)
        return func
    return decorator

Decorator to declare that a Python function overrides an op for a type.

The decorated function is used to override `op` if any of the arguments or
keyword arguments (including elements of lists or tuples) have one of the
specified types.

Example:

```python
@dispatch_for_types(math_ops.add, RaggedTensor, RaggedTensorValue)
def ragged_add(x, y, name=None): ...
```

Args:
op: Python function: the operation that should be overridden.
*types: The argument types for which this function should be used.


def __init__(self, values):

        if isinstance(values, list):
            self.values = [to_str(v) for v in values]
        else:
            self.values = [to_str(values)]

Initialize a ``CategoricalParameter``.

Args:
values (list or object): The possible values for the hyperparameter. This input will
be converted into a list of strings.


def logs(self, **kwargs):
    return self.client.api.logs(self.id, **kwargs)

Get logs from this container. Similar to the ``docker logs`` command.

The ``stream`` parameter makes the ``logs`` function return a blocking
generator you can iterate over to retrieve log output as it happens.

Args:
stdout (bool): Get ``STDOUT``. Default ``True``
stderr (bool): Get ``STDERR``. Default ``True``
stream (bool): Stream the response. Default ``False``
timestamps (bool): Show timestamps. Default ``False``
tail (str or int): Output specified number of lines at the end of
logs. Either an integer of number of lines or the string
``all``. Default ``all``
since (datetime or int): Show logs since a given datetime or
integer epoch (in seconds)
follow (bool): Follow log output. Default ``False``
until (datetime or int): Show logs that occurred before the given
datetime or integer epoch (in seconds)

Returns:
(generator or str): Logs from the container.

Raises:
:py:class:`docker.errors.APIError`
If the server returns an error.


def VerifyScripts(verifiable):

        try:
            hashes = verifiable.GetScriptHashesForVerifying()
        except Exception as e:
            logger.debug("couldn't get script hashes %s " % e)
            return False

        if len(hashes) != len(verifiable.Scripts):
            logger.debug(f"hash - verification script length mismatch ({len(hashes)}/{len(verifiable.Scripts)})")
            return False

        blockchain = GetBlockchain()

        for i in range(0, len(hashes)):
            verification = verifiable.Scripts[i].VerificationScript

            if len(verification) == 0:
                sb = ScriptBuilder()
                sb.EmitAppCall(hashes[i].Data)
                verification = sb.ms.getvalue()
            else:
                verification_hash = Crypto.ToScriptHash(verification, unhex=False)
                if hashes[i] != verification_hash:
                    logger.debug(f"hash {hashes[i]} does not match verification hash {verification_hash}")
                    return False

            state_reader = GetStateReader()
            script_table = CachedScriptTable(DBCollection(blockchain._db, DBPrefix.ST_Contract, ContractState))

            engine = ApplicationEngine(TriggerType.Verification, verifiable, script_table, state_reader, Fixed8.Zero())
            engine.LoadScript(verification)
            invocation = verifiable.Scripts[i].InvocationScript
            engine.LoadScript(invocation)

            try:
                success = engine.Execute()
                state_reader.ExecutionCompleted(engine, success)
            except Exception as e:
                state_reader.ExecutionCompleted(engine, False, e)

            if engine.ResultStack.Count != 1 or not engine.ResultStack.Pop().GetBoolean():
                Helper.EmitServiceEvents(state_reader)
                if engine.ResultStack.Count > 0:
                    logger.debug(f"Result stack failure! Count: {engine.ResultStack.Count} bool value: {engine.ResultStack.Pop().GetBoolean()}")
                else:
                    logger.debug(f"Result stack failure! Count: {engine.ResultStack.Count}")
                return False

            Helper.EmitServiceEvents(state_reader)

        return True

Verify the scripts of the provided `verifiable` object.

Args:
verifiable (neo.IO.Mixins.VerifiableMixin):

Returns:
bool: True if verification is successful. False otherwise.


def read(self, input_buffer, kmip_version=enums.KMIPVersion.KMIP_1_0):

        super(LocateResponsePayload, self).read(
            input_buffer,
            kmip_version=kmip_version
        )
        local_buffer = utils.BytearrayStream(input_buffer.read(self.length))

        if self.is_tag_next(enums.Tags.LOCATED_ITEMS, local_buffer):
            self._located_items = primitives.Integer(
                tag=enums.Tags.LOCATED_ITEMS
            )
            self._located_items.read(
                local_buffer,
                kmip_version=kmip_version
            )

        self._unique_identifiers = []
        while self.is_tag_next(enums.Tags.UNIQUE_IDENTIFIER, local_buffer):
            unique_identifier = primitives.TextString(
                tag=enums.Tags.UNIQUE_IDENTIFIER
            )
            unique_identifier.read(local_buffer, kmip_version=kmip_version)
            self._unique_identifiers.append(unique_identifier)

        self.is_oversized(local_buffer)

Read the data encoding the Locate response payload and decode it
into its constituent parts.

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


def verify_controller_module(module):
    required_attributes = ('create', 'destroy', 'MOBLY_CONTROLLER_CONFIG_NAME')
    for attr in required_attributes:
        if (not hasattr(module, attr)):
            raise signals.ControllerError(('Module %s missing required controller module attribute %s.' % (module.__name__, attr)))
        if (not getattr(module, attr)):
            raise signals.ControllerError(('Controller interface %s in %s cannot be null.' % (attr, module.__name__)))

Verifies a module object follows the required interface for
controllers.

The interface is explained in the docstring of
`base_test.BaseTestClass.register_controller`.

Args:
module: An object that is a controller module. This is usually
imported with import statements or loaded by importlib.

Raises:
ControllerError: if the module does not match the Mobly controller
interface, or one of the required members is null.


def __init__(self, cur_fst, cur_node):

        self.cur_node = cur_node
        self.cur_fst = cur_fst

Initialization function
Args:
sid (int): The state identifier
Returns:
None


def has_intersection(self, other):
    return bool(lib.SDL_HasIntersection(self._ptr, other._ptr))

Return whether this rectangle intersects with another rectangle.

Args:
other (Rect): The rectangle to test intersection with.

Returns:
bool: True if there is an intersection, False otherwise.


def _calculateCrcString(inputstring):
    _checkString(inputstring, description='input CRC string')
    register = 65535
    for char in inputstring:
        register = ((register >> 8) ^ _CRC16TABLE[((register ^ ord(char)) & 255)])
    return _numToTwoByteString(register, LsbFirst=True)

Calculate CRC-16 for Modbus.

Args:
inputstring (str): An arbitrary-length message (without the CRC).

Returns:
A two-byte CRC string, where the least significant byte is first.


def __init__(self, persistent=False, watch_accessed_variables=True):
    self._tape = None
    self._persistent = persistent
    self._watch_accessed_variables = watch_accessed_variables
    self._watched_variables = ()
    self._recording = False

Creates a new GradientTape.

Args:
persistent: Boolean controlling whether a persistent gradient tape
is created. False by default, which means at most one call can
be made to the gradient() method on this object.
watch_accessed_variables: Boolean controlling whether the tape will
automatically `watch` any (trainable) variables accessed while the tape
is active. Defaults to True meaning gradients can be requested from any
result computed in the tape derived from reading a trainable `Variable`.
If False users must explicitly `watch` any `Variable`s they want to
request gradients from.


def load_stereo_chemical_props() -> Tuple[Mapping[str, List[Bond]], Mapping[str, List[Bond]], Mapping[str, List[BondAngle]]]:
    stereo_chemical_props = resources.read_text('openfold.resources', 'stereo_chemical_props.txt')
    lines_iter = iter(stereo_chemical_props.splitlines())
    residue_bonds: Dict[str, List[Bond]] = {}
    next(lines_iter)
    for line in lines_iter:
        if line.strip() == '-':
            break
        bond, resname, bond_length, stddev = line.split()
        atom1, atom2 = bond.split('-')
        if resname not in residue_bonds:
            residue_bonds[resname] = []
        residue_bonds[resname].append(Bond(atom1, atom2, float(bond_length), float(stddev)))
    residue_bonds['UNK'] = []
    residue_bond_angles: Dict[str, List[BondAngle]] = {}
    next(lines_iter)
    next(lines_iter)
    for line in lines_iter:
        if line.strip() == '-':
            break
        bond, resname, angle_degree, stddev_degree = line.split()
        atom1, atom2, atom3 = bond.split('-')
        if resname not in residue_bond_angles:
            residue_bond_angles[resname] = []
        residue_bond_angles[resname].append(BondAngle(atom1, atom2, atom3, float(angle_degree) / 180.0 * np.pi, float(stddev_degree) / 180.0 * np.pi))
    residue_bond_angles['UNK'] = []

    def make_bond_key(atom1_name: str, atom2_name: str) -> str:

        return '-'.join(sorted([atom1_name, atom2_name]))
    residue_virtual_bonds: Dict[str, List[Bond]] = {}
    for resname, bond_angles in residue_bond_angles.items():
        bond_cache: Dict[str, Bond] = {}
        for b in residue_bonds[resname]:
            bond_cache[make_bond_key(b.atom1_name, b.atom2_name)] = b
        residue_virtual_bonds[resname] = []
        for ba in bond_angles:
            bond1 = bond_cache[make_bond_key(ba.atom1_name, ba.atom2_name)]
            bond2 = bond_cache[make_bond_key(ba.atom2_name, ba.atom3name)]
            gamma = ba.angle_rad
            length = np.sqrt(bond1.length ** 2 + bond2.length ** 2 - 2 * bond1.length * bond2.length * np.cos(gamma))
            dl_outer = 0.5 / length
            dl_dgamma = 2 * bond1.length * bond2.length * np.sin(gamma) * dl_outer
            dl_db1 = (2 * bond1.length - 2 * bond2.length * np.cos(gamma)) * dl_outer
            dl_db2 = (2 * bond2.length - 2 * bond1.length * np.cos(gamma)) * dl_outer
            stddev = np.sqrt((dl_dgamma * ba.stddev) ** 2 + (dl_db1 * bond1.stddev) ** 2 + (dl_db2 * bond2.stddev) ** 2)
            residue_virtual_bonds[resname].append(Bond(ba.atom1_name, ba.atom3name, length, stddev))
    return (residue_bonds, residue_virtual_bonds, residue_bond_angles)

Load stereo_chemical_props.txt into a nice structure.

Load literature values for bond lengths and bond angles and translate bond angles into the length of the opposite
edge of the triangle ("residue_virtual_bonds").

Returns:
residue_bonds: dict that maps resname --> list of Bond tuples residue_virtual_bonds: dict that maps resname -->
list of Bond tuples residue_bond_angles: dict that maps resname --> list of BondAngle tuples


def StartClients(cls, hunt_id, client_ids, token=None):

    token = token or access_control.ACLToken(username="Hunt", reason="hunting")

    with queue_manager.QueueManager(token=token) as flow_manager:
      for client_id in client_ids:

        state = rdf_flow_runner.RequestState(
            id=random.UInt32(),
            session_id=hunt_id,
            client_id=client_id,
            next_state="AddClient")

        flow_manager.QueueRequest(state)

        msg = rdf_flows.GrrMessage(
            session_id=hunt_id,
            request_id=state.id,
            response_id=1,
            auth_state=rdf_flows.GrrMessage.AuthorizationState.AUTHENTICATED,
            type=rdf_flows.GrrMessage.Type.STATUS,
            payload=rdf_flows.GrrStatus())

        flow_manager.QueueResponse(msg)

        flow_manager.QueueNotification(session_id=hunt_id)

This method is called by the foreman for each client it discovers.

Note that this function is performance sensitive since it is called by the
foreman for every client which needs to be scheduled.

Args:
hunt_id: The hunt to schedule.
client_ids: List of clients that should be added to the hunt.
token: An optional access token to use.


def data_period_end_day(self, value=None):

        if value is not None:
            try:
                value = str(value)
            except ValueError:
                raise ValueError(
                    'value {} need to be of type str '
                    'for field `data_period_end_day`'.format(value))
            if ',' in value:
                raise ValueError('value should not contain a comma '
                                 'for field `data_period_end_day`')

        self._data_period_end_day = value

Corresponds to IDD Field `data_period_end_day`

Args:
value (str): value for IDD Field `data_period_end_day`
if `value` is None it will not be checked against the
specification and is assumed to be a missing value

Raises:
ValueError: if `value` is not a valid value


def _get_parser_call_method(func):

    func_name = func.__name__
    parser = func.parser

    def inner_call(instance=None, args=None):

        _LOG.debug("Calling %s.parser.call", func_name)

        if func_name == "__init__":
            raise ParseThisError(("To use 'create_parser' on the"
                                  "'__init__' you need to decorate the "
                                  "class with '@parse_class'"))
        namespace = parser.parse_args(_get_args_to_parse(args, sys.argv))
        if instance is None:

            args_name = _get_args_name_from_parser(parser)
            return _call(func, args_name, namespace)
        return _call_method_from_namespace(instance, func_name, namespace)

    return inner_call

Returns the method that is linked to the 'call' method of the parser

Args:
func: the decorated function

Raises:
ParseThisError if the decorated method is __init__, __init__ can
only be decorated in a class decorated by parse_class


def capabilities(self):
    caps = []
    for cap in DeviceCapability:
        if self._libinput.libinput_device_has_capability(self._handle, cap):
            caps.append(cap)
    return tuple(caps)

A tuple of capabilities this device supports.

Returns:
(~libinput.constant.DeviceCapability): Device capabilities.


def control_dependencies(self, control_inputs):
    if control_inputs is None:
        return super().control_dependencies(control_inputs)
    filtered_control_inputs = []
    for c in control_inputs:
        if isinstance(c, indexed_slices.IndexedSlices) or (hasattr(c, '_handle') and hasattr(c, 'op')):
            c = c.op
        graph_element = ops._as_graph_element(c)
        if graph_element is None:
            graph_element = c
        if graph_element is not None and getattr(graph_element, 'graph', None) is not self:
            self._function_captures.control.add(graph_element)
        else:
            filtered_control_inputs.append(graph_element)
    return super().control_dependencies(filtered_control_inputs)

Handles control dependencies.

FuncGraph wraps Graph's control_dependencies logic by first filtering out
any external tensors / operations and storing them in the graph's
control_captures member. Any consumers of this function graph must then
decide how to handle the control captures.

Args:
control_inputs: A list of `Operation` or `Tensor` objects which must be
executed or computed before running the operations defined in the
context.  Can also be `None` to clear the control dependencies.

Returns:
A context manager that specifies control dependencies for all
operations constructed within the context.

Raises:
TypeError: If `control_inputs` is not a list of `Operation` or
`Tensor` objects.


def reverse(self, transfer_id, data={}, **kwargs):
    url = '{}/{}/reversals'.format(self.base_url, transfer_id)
    return self.post_url(url, data, **kwargs)

Reverse Transfer from given id

Args:
transfer_id : Id for which transfer object has to be reversed

Returns:
Transfer Dict which was reversed


def stations_listeners(stations):
    stations = (stations if isinstance(stations, (list, tuple)) else [stations])
    listeners = []
    for sta in stations:
        listeners.append(StationSignalListener(sta))
        listeners.append(StationMaxListener(sta))
        if (sta.mask is not None):
            listeners.append(StationMaskListener(sta))
    return listeners

Function for creating listeners for a a list of station

Args:
stations (iterable): List of TopocentricFrame
Return:
list of Listener


def url_to_dir_parts(url, include_protocol=False, include_hostname=False, alt_char=False):
    assert isinstance(url, str), 'Expect str. Got {}.'.format(type(url))
    url_split_result = urllib.parse.urlsplit(url)
    parts = []
    if include_protocol:
        parts.append(url_split_result.scheme)
    if include_hostname:
        hostname = url_split_result.hostname
        if url_split_result.port:
            if alt_char:
                port_delim = '+'
            else:
                port_delim = ':'
            hostname = '{0}{1}{2}'.format(hostname, port_delim, url_split_result.port)
        parts.append(hostname)
    for path_part in url_split_result.path.split('/'):
        if path_part:
            parts.append(path_part)
    if ((not url.endswith('/')) and parts):
        parts.pop()
    return parts

Return a list of directory parts from a URL.

Args:
url (str): The URL.
include_protocol (bool): If True, the scheme from the URL will be
included.
include_hostname (bool): If True, the hostname from the URL will be
included.
alt_char (bool): If True, the character for the port deliminator
will be ``+`` intead of ``:``.

This function does not include the filename and the paths are not
sanitized.

Returns:
list


def _try_to_clean_garbage(self, writer_spec, exclude_list=()):

    tmpl = string.Template(self._TMPFILE_PREFIX)
    prefix = tmpl.substitute(
        id=self.status.mapreduce_id, shard=self.status.shard)
    bucket = self._get_tmp_gcs_bucket(writer_spec)
    account_id = self._get_tmp_account_id(writer_spec)
    for f in cloudstorage.listbucket("/%s/%s" % (bucket, prefix),
                                     _account_id=account_id):
      if f.filename not in exclude_list:
        self._remove_tmpfile(f.filename, self.status.writer_spec)

Tries to remove any files created by this shard that aren't needed.

Args:
writer_spec: writer_spec for the MR.
exclude_list: A list of filenames (strings) that should not be
removed.


def _as_arg_names(names_str):
    names = re.split(',| ', names_str)
    names = [name.strip() for name in names if name.strip()]
    for name in names:
        if not _is_arg_name(name):
            return None
    if not names:
        return None
    return names

Converts names_str to a list of arg names.

Example:
_as_arg_names("a, b, c") == ["a", "b", "c"]

Args:
names_str: A string with multiple space or comma separated arg names.
Returns:
A list of arg names, or None if names_str doesn't look like a list of arg
names.


def query(self, minhash, size):
    for (i, index) in enumerate(self.indexes):
        u = self.uppers[i]
        if (u is None):
            continue
        (b, r) = self._get_optimal_param(u, size)
        for key in index[r]._query_b(minhash, b):
            (yield key)

Giving the MinHash and size of the query set, retrieve
keys that references sets with containment with respect to
the query set greater than the threshold.

Args:
minhash (datasketch.MinHash): The MinHash of the query set.
size (int): The size (number of unique items) of the query set.

Returns:
`iterator` of keys.


def get_collection(key, scope=None) -> list[Any]:
    return get_default_graph().get_collection(key, scope)

Wrapper for `Graph.get_collection()` using the default graph.

See `tf.Graph.get_collection`
for more details.

Args:
key: The key for the collection. For example, the `GraphKeys` class contains
many standard names for collections.
scope: (Optional.) If supplied, the resulting list is filtered to include
only items whose `name` attribute matches using `re.match`. Items without
a `name` attribute are never returned if a scope is supplied and the
choice or `re.match` means that a `scope` without special tokens filters
by prefix.

Returns:
The list of values in the collection with the given `name`, or
an empty list if no value has been added to that collection. The
list contains the values in the order under which they were
collected.

@compatibility(eager)
Collections are not supported when eager execution is enabled.
@end_compatibility


def RebuildHttpConnections(http):
    if getattr(http, 'connections', None):
        for conn_key in list(http.connections.keys()):
            if (':' in conn_key):
                del http.connections[conn_key]

Rebuilds all http connections in the httplib2.Http instance.

httplib2 overloads the map in http.connections to contain two different
types of values:
{ scheme string:  connection class } and
{ scheme + authority string : actual http connection }
Here we remove all of the entries for actual connections so that on the
next request httplib2 will rebuild them from the connection types.

Args:
http: An httplib2.Http instance.


def dump_json(json_info, json_file, overwrite=True):
    if overwrite:
        mode = 'w'
    else:
        mode = 'w+'
    try:
        with open(json_file, mode) as f:
            f.write(json.dumps(json_info))
    except BaseException as e:
        logging.error(e.message)

Dump a whole json record into the given file.

Overwrite the file if the overwrite flag set.

Args:
json_info (dict): Information dict to be dumped.
json_file (str): File path to be dumped to.
overwrite(boolean)


def simplify_replacements(replacements):
    if len(replacements) <= 1:
        return replacements
    replacements.sort(key=lambda x: len(x[0]))
    idx = 0
    while idx < len(replacements):
        old, new = replacements[idx]
        j = idx + 1
        while j < len(replacements):
            old_2, new_2 = replacements[j]
            if old_2.replace(old, new) == new_2:
                replacements.pop(j)
            else:
                j += 1
        idx += 1
    return replacements

Simplify a list of replacement patterns to make sure there are no needless ones.

For instance in the sequence "Bert->BertNew, BertConfig->BertNewConfig, bert->bert_new", the replacement
"BertConfig->BertNewConfig" is implied by "Bert->BertNew" so not needed.

Args:
replacements (`List[Tuple[str, str]]`): List of patterns (old, new)

Returns:
`List[Tuple[str, str]]`: The list of patterns simplified.


def on_execution(self, execution_index, execution):

Monitor method for top-level execution events.

Return values (if any) are ignored by the associated DebugDataReader.

Args:
execution_index: The index of the top-level execution event, as an int.
execution: An Execution data object, for a top-level op or function
execution event.