def load_manual_sequence(self, seq, ident=None, write_fasta_file=False, outdir=None, set_as_representative=False, force_rewrite=False):
    if write_fasta_file:
        if (not outdir):
            outdir = self.sequence_dir
            if (not outdir):
                raise ValueError('Output directory must be specified')
        outfile = op.join(outdir, '{}.faa'.format(ident))
    else:
        outfile = None
    if (isinstance(seq, str) or isinstance(seq, Seq)):
        if (not ident):
            raise ValueError('ID must be specified if sequence is a string or Seq object')
        manual_sequence = SeqProp(id=ident, seq=seq)
    else:
        if (not ident):
            ident = seq.id
        else:
            seq.id = ident
        manual_sequence = SeqProp(id=ident, seq=seq, name=seq.name, description=seq.description)
    if write_fasta_file:
        manual_sequence.write_fasta_file(outfile=outfile, force_rerun=force_rewrite)
    self.sequences.append(manual_sequence)
    if set_as_representative:
        self.representative_sequence = manual_sequence
    return self.sequences.get_by_id(ident)

Load a manual sequence given as a string and optionally set it as the representative sequence.
Also store it in the sequences attribute.

Args:
seq (str, Seq, SeqRecord): Sequence string, Biopython Seq or SeqRecord object
ident (str): Optional identifier for the sequence, required if seq is a string. Also will override existing
IDs in Seq or SeqRecord objects if set.
write_fasta_file (bool): If this sequence should be written out to a FASTA file
outdir (str): Path to output directory
set_as_representative (bool): If this sequence should be set as the representative one
force_rewrite (bool): If the FASTA file should be overwritten if it already exists

Returns:
SeqProp: Sequence that was loaded into the ``sequences`` attribute


def is_finite(val_1, val_2=None):
    val_1_finite = (tf.math.is_finite(val_1.f) & tf.math.is_finite(val_1.df))
    if (val_2 is not None):
        return ((val_1_finite & tf.math.is_finite(val_2.f)) & tf.math.is_finite(val_2.df))
    return val_1_finite

Checks if the supplied values are finite.

Args:
val_1: A namedtuple instance with the function value and derivative,
as returned e.g. by value_and_gradients_function evaluations.
val_2: (Optional) A namedtuple instance with the function value and
derivative, as returned e.g. by value_and_gradients_function evaluations.

Returns:
is_finite: Scalar boolean `Tensor` indicating whether the function value
and the derivative in `val_1` (and optionally in `val_2`) are all finite.


def load_variable(ckpt_dir_or_file, name):
    if name.endswith(':0'):
        name = name[:-2]
    reader = load_checkpoint(ckpt_dir_or_file)
    return reader.get_tensor(name)

Returns the tensor value of the given variable in the checkpoint.

When the variable name is unknown, you can use `tf.train.list_variables` to
inspect all the variable names.

Example usage:

```python
import tensorflow as tf
a = tf.Variable(1.0)
b = tf.Variable(2.0)
ckpt = tf.train.Checkpoint(var_list={'a': a, 'b': b})
ckpt_path = ckpt.save('tmp-ckpt')
var= tf.train.load_variable(
ckpt_path, 'var_list/a/.ATTRIBUTES/VARIABLE_VALUE')
print(var)  # 1.0
```

Args:
ckpt_dir_or_file: Directory with checkpoints file or path to checkpoint.
name: Name of the variable to return.

Returns:
A numpy `ndarray` with a copy of the value of this variable.


def send(self, data_to_send):

        request_payload = json.dumps([ a.write() for a in data_to_send ])

        request = HTTPClient.Request(self._service_endpoint_uri, bytearray(request_payload, 'utf-8'), { 'Accept': 'application/json', 'Content-Type' : 'application/json; charset=utf-8' })
        try:
            response = HTTPClient.urlopen(request, timeout=self._timeout)
            status_code = response.getcode()
            if 200 <= status_code < 300:
                return
        except HTTPError as e:
            if e.getcode() == 400:
                return
        except Exception as e:
            pass

        for data in data_to_send:
            self._queue.put(data)

Immediately sends the data passed in to :func:`service_endpoint_uri`. If the service request fails, the
passed in items are pushed back to the :func:`queue`.

Args:
data_to_send (Array): an array of :class:`contracts.Envelope` objects to send to the service.


def get_text_config(self, decoder=False) -> 'PretrainedConfig':
    decoder_possible_text_config_names = ('decoder', 'generator', 'text_config')
    encoder_possible_text_config_names = ('text_encoder',)
    if decoder:
        possible_text_config_names = decoder_possible_text_config_names
    else:
        possible_text_config_names = encoder_possible_text_config_names + decoder_possible_text_config_names
    valid_text_config_names = []
    for text_config_name in possible_text_config_names:
        if hasattr(self, text_config_name):
            text_config = getattr(self, text_config_name, None)
            if text_config is not None:
                valid_text_config_names += [text_config_name]
    if len(valid_text_config_names) > 1:
        raise ValueError(f'Multiple valid text configs were found in the model config: {valid_text_config_names}. In this case, using `get_text_config()` would be ambiguous. Please specify the desied text config directly.')
    elif len(valid_text_config_names) == 1:
        config_to_return = getattr(self, valid_text_config_names[0])
    else:
        config_to_return = self
    return config_to_return

Returns the config that is meant to be used with text IO. On most models, it is the original config instance
itself. On specific composite models, it is under a set of valid names.

Args:
decoder (`Optional[bool]`, *optional*, defaults to `False`):
If set to `True`, then only search for decoder config names.


def create_list(self, list_json):
    return trolly.list.List(trello_client=self, list_id=list_json['id'], name=list_json['name'], data=list_json)

Create List object from JSON object

Returns:
List: The list from the given `list_json`.


def view_edit(name=None):
    response.set_header('Cache-control', 'no-cache')
    response.set_header('Pragma', 'no-cache')
    if (name is None):
        return template('edit', type='edit', name=name, extended_name=None, is_repo=check_repo(), history=[], gitref=None, today=datetime.datetime.now().strftime('%Y%m%d'), content='')
    else:
        files = glob.glob('{0}.rst'.format(name))
        if (len(files) > 0):
            file_handle = open(files[0], 'r')
            return template('edit', type='edit', name=name, extended_name=None, is_repo=check_repo(), history=[], gitref=None, today=datetime.datetime.now().strftime('%Y%m%d'), content=file_handle.read())
        else:
            return abort(404)

Edit or creates a new page.

.. note:: this is a bottle view

if no page name is given, creates a new page.

Keyword Arguments:
:name: (str) -- name of the page (OPTIONAL)

Returns:
bottle response object


def normalize_expression(self, expression_parts):

        expression_parts[3] = expression_parts[3].replace("?", "*")
        expression_parts[5] = expression_parts[5].replace("?", "*")

        if expression_parts[0].startswith("0/"):
            expression_parts[0] = expression_parts[
                0].replace("0/", "*/")

        if expression_parts[1].startswith("0/"):
            expression_parts[1] = expression_parts[
                1].replace("0/", "*/")

        if expression_parts[2].startswith("0/"):
            expression_parts[2] = expression_parts[
                2].replace("0/", "*/")

        if expression_parts[3].startswith("1/"):
            expression_parts[3] = expression_parts[3].replace("1/", "*/")

        if expression_parts[4].startswith("1/"):
            expression_parts[4] = expression_parts[
                4].replace("1/", "*/")

        if expression_parts[5].startswith("1/"):
            expression_parts[5] = expression_parts[5].replace("1/", "*/")

        if expression_parts[6].startswith("1/"):
            expression_parts[6] = expression_parts[6].replace("1/", "*/")

        if self._options.day_of_week_start_index_zero is False:
            expression_parts[5] = self.decrease_days_of_week(expression_parts[5])

        if expression_parts[3] == "?":
            expression_parts[3] = "*"

        for day_number in self._cron_days:
            expression_parts[5] = expression_parts[5].upper().replace(self._cron_days[day_number], str(day_number))

        for month_number in self._cron_months:
            expression_parts[4] = expression_parts[4].upper().replace(
                self._cron_months[month_number], str(month_number))

        if expression_parts[0] == "0":
            expression_parts[0] = ''

        length = len(expression_parts)
        for i in range(length):

            if expression_parts[i] == "*/1":
                expression_parts[i] = "*"

            if "/" in expression_parts[i] and any(exp in expression_parts[i] for exp in ['*', '-', ',']) is False:
                choices = {
                    4: "12",
                    5: "6",
                    6: "9999"
                }

                step_range_through = choices.get(i)

                if step_range_through is not None:
                    parts = expression_parts[i].split('/')
                    expression_parts[i] = "{0}-{1}/{2}".format(parts[0], step_range_through, parts[1])

Converts cron expression components into consistent, predictable formats.
Args:
expression_parts: A 7 part string array, one part for each component of the cron expression
Returns:
None


def execute(command, cwd=os.path.curdir, **options):

    process = subprocess.Popen(shlex.split(command), cwd=cwd, **options)
    stdout, stderr = process.communicate()
    return process, stdout, stderr

Run the system command with optional options.

Args:
* command: system command.
* cwd: current working directory.
* verbose: direct options for :func:`subprocess.Popen`.

Returns:
Opened process, standard output & error.


async def upload_artifacts(context, files):

    def to_upload_future(target_path):
        path = os.path.join(context.config['artifact_dir'], target_path)
        (content_type, content_encoding) = compress_artifact_if_supported(path)
        return asyncio.ensure_future(retry_create_artifact(context, path, target_path=target_path, content_type=content_type, content_encoding=content_encoding))
    tasks = list(map(to_upload_future, files))
    (await raise_future_exceptions(tasks))

Compress and upload the requested files from ``artifact_dir``, preserving relative paths.

Compression only occurs with files known to be supported.

This function expects the directory structure in ``artifact_dir`` to remain
the same.  So if we want the files in ``public/...``, create an
``artifact_dir/public`` and put the files in there.

Args:
context (scriptworker.context.Context): the scriptworker context.
files (list of str): files that should be uploaded as artifacts

Raises:
Exception: any exceptions the tasks raise.


def add_vtep(self, name, vtep, vlan=None):

        if not vlan:
            cmd = 'vxlan flood vtep add {}'.format(vtep)
        else:
            cmd = 'vxlan vlan {} flood vtep add {}'.format(vlan, vtep)
        return self.configure_interface(name, cmd)

Adds a new VTEP endpoint to the global or local flood list

EosVersion:
4.13.7M

Args:
name (str): The name of the interface to configure
vtep (str): The IP address of the remote VTEP endpoint to add
vlan (str): The VLAN ID associated with this VTEP.  If the VLAN
keyword is used, then the VTEP is configured as a local flood
endpoing

Returns:
True if the command completes successfully


def _document_path(self):
    if (self._document_path_internal is None):
        if (self._client is None):
            raise ValueError('A document reference requires a `client`.')
        self._document_path_internal = _get_document_path(self._client, self._path)
    return self._document_path_internal

Create and cache the full path for this document.

Of the form:

``projects/{project_id}/databases/{database_id}/...
documents/{document_path}``

Returns:
str: The full document path.

Raises:
ValueError: If the current document reference has no ``client``.


def get(self, resource):

        return self.service.get(
            resource, self.url_prefix, self.auth, self.session,
            self.session_send_opts)

Get attributes of the data model object named by the given resource.

Args:
resource (intern.resource.boss.BossResource): resource.name as well as any parents must be identified to succeed.

Returns:
(intern.resource.boss.BossResource): Returns resource of type requested on success.

Raises:
requests.HTTPError on failure.


def make_tables(grammar, precedence):
    ACTION = {}
    GOTO = {}
    labels = {}

    def get_label(closure):
        if (closure not in labels):
            labels[closure] = len(labels)
        return labels[closure]

    def resolve_shift_reduce(lookahead, s_action, r_action):
        (s_assoc, s_level) = precedence[lookahead]
        (r_assoc, r_level) = precedence[r_action[1]]
        if (s_level < r_level):
            return r_action
        elif ((s_level == r_level) and (r_assoc == LEFT)):
            return r_action
        else:
            return s_action
    (initial, closures, goto) = grammar.closures()
    for closure in closures:
        label = get_label(closure)
        for rule in closure:
            (new_action, lookahead) = (None, rule.lookahead)
            if (not rule.at_end):
                symbol = rule.rhs[rule.pos]
                is_terminal = (symbol in grammar.terminals)
                has_goto = (symbol in goto[closure])
                if (is_terminal and has_goto):
                    next_state = get_label(goto[closure][symbol])
                    (new_action, lookahead) = (('shift', next_state), symbol)
            elif ((rule.production == grammar.start) and rule.at_end):
                new_action = ('accept',)
            elif rule.at_end:
                new_action = ('reduce', rule.production)
            if (new_action is None):
                continue
            prev_action = ACTION.get((label, lookahead))
            if ((prev_action is None) or (prev_action == new_action)):
                ACTION[(label, lookahead)] = new_action
            else:
                types = (prev_action[0], new_action[0])
                if (types == ('shift', 'reduce')):
                    chosen = resolve_shift_reduce(lookahead, prev_action, new_action)
                elif (types == ('reduce', 'shift')):
                    chosen = resolve_shift_reduce(lookahead, new_action, prev_action)
                else:
                    raise TableConflictError(prev_action, new_action)
                ACTION[(label, lookahead)] = chosen
        for symbol in grammar.nonterminals:
            if (symbol in goto[closure]):
                GOTO[(label, symbol)] = get_label(goto[closure][symbol])
    return (get_label(initial), ACTION, GOTO)

Generates the ACTION and GOTO tables for the grammar.

Returns:
action - dict[state][lookahead] = (action, ...)
goto - dict[state][just_reduced] = new_state


def VerifyStructure(self, parser_mediator, line):

    try:
      structure = self._LOG_LINE.parseString(line)
    except pyparsing.ParseException:
      logger.debug('Not a Sophos Anti-Virus log file')
      return False

    if ' ' not in (line[8], line[15]):
      logger.debug('Not a Sophos Anti-Virus log file')
      return False

    try:
      dfdatetime_time_elements.TimeElements(
          time_elements_tuple=structure.date_time)
    except ValueError:
      logger.debug((
          'Not a Sophos Anti-Virus log file, invalid date and time: '
          '{0!s}').format(structure.date_time))
      return False

    return True

Verify that this file is a Sophos Anti-Virus log file.

Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfVFS.
line (str): line from a text file.

Returns:
bool: True if the line is in the expected format, False if not.


def from_concrete_function(concrete_fn, specialized_flat_specs: Optional[List[tensor_spec.TensorSpec]]=None):
    context.ensure_initialized()
    fn_name = concrete_fn.name
    filtered_flat_specs = specialized_flat_specs or list(nest.flatten(concrete_fn.structured_input_signature))
    if not all((s.shape.is_fully_defined() for s in filtered_flat_specs)):
        raise ValueError(f'Only support static input shape but got inputs = {concrete_fn.inputs}')

    def compiler_ir_generator(stage='hlo', device_name=None, platform_name=None):

        if device_name is not None:
            if platform_name is not None:
                raise ValueError('device_name and platform_name cannot be provided at the same time.')
            warnings.warn('device_name is being deprecated. Use platform_name.')
        device_name = maybe_get_device_name(device_name)
        res_bytes = context.context().get_compiler_ir(device_name=device_name, platform_name=platform_name, function_name=fn_name, flat_args=filtered_flat_specs, captured_inputs=concrete_fn.captured_inputs, stage=stage)
        if stage in ('stablehlo_serialized', 'hlo_serialized', 'optimized_hlo_serialized', 'optimized_hlo_proto_serialized'):
            return res_bytes
        else:
            return res_bytes.decode('utf-8')
    return compiler_ir_generator

Generate the Compiler Ir from tf concrete function with TensorSpec.

Args:
concrete_fn: returned by using get_concrete_function.
specialized_flat_specs: specialized flat tf.TensorSpecs for function args.

Returns:
Function callable that generate the HLO text.

Raises:
ValueError: if concrete_fn is not "compilable" without concrete
inputs.


def artifact(self, counter, stage, job, stage_counter=1):

        return Artifact(self.server, self.name, counter, stage, job, stage_counter)

Helper to instantiate an :class:`gocd.api.artifact.Artifact` object

Args:
counter (int): The pipeline counter to get the artifact for
stage: Stage name
job: Job name
stage_counter: Defaults to 1

Returns:
Artifact: :class:`gocd.api.artifact.Artifact` object


def _GetUnifiedDiff(before, after, filename='code'):
    before = before.splitlines()
    after = after.splitlines()
    return '\n'.join(difflib.unified_diff(before, after, filename, filename, '(original)', '(reformatted)', lineterm='')) + '\n'

Get a unified diff of the changes.

Arguments:
before: (unicode) The original source code.
after: (unicode) The reformatted source code.
filename: (unicode) The code's filename.

Returns:
The unified diff text.


def flatten(array: _ArrayT, pattern: str) -> tuple[_ArrayT, _Shape]:
    array, (batch_shape,) = einops.pack([array], pattern.replace('...', '*'))
    return (array, tuple(batch_shape))

Flatten an array along custom dimensions.

Uses `einops` syntax.

```python
flat_x, batch_shape = enp.flatten(x, '... h w c')
y = enp.unflatten(y, batch_shape, '... h w c')
```

* `x.shape == (h, w, c)`       -> `flat_x.shape == (1, h, w, c)`
* `x.shape == (b, h, w, c)`    -> `flat_x.shape == (b, h, w, c)`
* `x.shape == (b, n, h, w, c)` -> `flat_x.shape == (b * n, h, w, c)`

Args:
array: Array to flatten.
pattern: Einops pattern to flatten the array.

Returns:
Tuple of (flattened array, batch shape).


def _update_flags(compiler_flags, remove_flags=()):

    for flag in GFORTRAN_SHARED_FLAGS:
        if flag not in compiler_flags:
            compiler_flags.append(flag)
    if DEBUG_ENV in os.environ:
        to_add = GFORTRAN_DEBUG_FLAGS
        to_remove = GFORTRAN_OPTIMIZE_FLAGS
    else:
        to_add = GFORTRAN_OPTIMIZE_FLAGS
        if os.environ.get(WHEEL_ENV) is None:
            to_add += (GFORTRAN_NATIVE_FLAG,)
        to_remove = GFORTRAN_DEBUG_FLAGS
    for flag in to_add:
        if flag not in compiler_flags:
            compiler_flags.append(flag)
    return [
        flag
        for flag in compiler_flags
        if not (flag in to_remove or flag in remove_flags)
    ]

Update a given set of compiler flags.

Args:
compiler_flags (List[str]): Existing flags associated with a compiler.
remove_flags (Optional[Container[str]]): A container of flags to remove
that will override any of the defaults.

Returns:
List[str]: The modified list (i.e. some flags added and some removed).


def target_code_to_name(code):

    TARGET_NAMES = {v: k for k, v in TARGET_CODES.items()}
    return TARGET_NAMES[code]

Converts an int target code to a target name

Since self.TARGET_CODES is a 1:1 mapping, perform a reverse lookup
to get the more readable name.

Args:
code: Value from self.TARGET_CODES

Returns:
String target name corresponding to the given code.


def delete_customer(self, customer_id):
    return self.client._delete((self.url + 'customers/{}'.format(customer_id)), headers=self.get_headers())

Removes a user from the system.

Args:
customer_id: Identifier of the client to be deleted.

Returns:


def _convert_schemas(mapping, schemas):
    schemas = deepcopy(schemas)
    for schema in schemas:
        for fk in schema.get('foreignKeys', []):
            resource = fk['reference']['resource']
            if (resource != 'self'):
                if (resource not in mapping):
                    message = 'Not resource "%s" for foreign key "%s"'
                    message = (message % (resource, fk))
                    raise ValueError(message)
                fk['reference']['resource'] = mapping[resource]
    return schemas

Convert schemas to be compatible with storage schemas.

Foreign keys related operations.

Args:
mapping (dict): mapping between resource name and table name
schemas (list): schemas

Raises:
ValueError: if there is no resource
for some foreign key in given mapping

Returns:
list: converted schemas


def subscribe(self, subject, callback, queue=''):

        s = Subscription(
            sid=self._next_sid,
            subject=subject,
            queue=queue,
            callback=callback,
            connetion=self
        )

        self._subscriptions[s.sid] = s
        self._send('SUB %s %s %d' % (s.subject, s.queue, s.sid))
        self._next_sid += 1

        return s

Subscribe will express interest in the given subject. The subject can
have wildcards (partial:*, full:>). Messages will be delivered to the
associated callback.

Args:
subject (string): a string with the subject
callback (function): callback to be called


def to_dict(cls):
    return dict(((item.name, item.number) for item in iter(cls)))

Make dictionary version of enumerated class.

Dictionary created this way can be used with def_num.

Returns:
A dict (name) -> number


def __call__(self, *args: Union[str, 'Image.Image', List['Image.Image'], List[str]], **kwargs: Any) -> List[Any]:
    return super().__call__(*args, **kwargs)

Extract the features of the input(s).

Args:
images (`str`, `List[str]`, `PIL.Image` or `List[PIL.Image]`):
The pipeline handles three types of images:

- A string containing a http link pointing to an image
- A string containing a local path to an image
- An image loaded in PIL directly

The pipeline accepts either a single image or a batch of images, which must then be passed as a string.
Images in a batch must all be in the same format: all as http links, all as local paths, or all as PIL
images.
timeout (`float`, *optional*, defaults to None):
The maximum time in seconds to wait for fetching images from the web. If None, no timeout is used and
the call may block forever.
Return:
A nested list of `float`: The features computed by the model.


def remove(path, dir_fd=None):
    system = get_instance(path)
    if (system.is_locator(path) or (path[(- 1)] == '/')):
        raise is_a_directory_error(("Is a directory: '%s'" % path))
    system.remove(path)

Remove a file.

Equivalent to "os.remove" and "os.unlink".

Args:
path (path-like object): Path or URL.
dir_fd: directory descriptors;
see the os.remove() description for how it is interpreted.
Not supported on cloud storage objects.


def pop(self, name, defval=None):

        valu = self.info.pop(name, defval)
        lkey = self.pref + name.encode('utf8')
        self.slab.pop(lkey, db=self.db)
        return valu

Pop a name from the SlabDict.

Args:
name (str): The name to remove.
defval (obj): The default value to return if the name is not present.

Returns:
object: The object stored in the SlabDict, or defval if the object was not present.


def validate_session(self, token, remote='127.0.0.1', proxy=None):
    params = {'validationFactors': [{'name': 'remote_address', 'value': remote}]}
    if proxy:
        params['validation-factors']['validationFactors'].append({'name': 'X-Forwarded-For', 'value': proxy})
    url = (self.rest_url + ('/session/%s' % token))
    response = self._post(url, data=json.dumps(params), params={'expand': 'user'})
    if (not response.ok):
        return None
    return response.json()

Validate a session token.

Validate a previously acquired session token against the
Crowd server. This may be a token provided by a user from
a http cookie or by some other means.

Args:
token: The session token.

remote: The remote address of the user.

proxy: Value of X-Forwarded-For server header

Returns:
dict:
A dict mapping of user attributes if the application
authentication was successful. See the Crowd
documentation for the authoritative list of attributes.

None: If authentication failed.


def parse_relations(
    belstr: str, char_locs: CharLocs, parsed: Parsed, errors: Errors
) -> Tuple[Parsed, Errors]:

    quotes = char_locs["quotes"]
    quoted_range = set([i for start, end in quotes.items() for i in range(start, end)])

    for match in relations_pattern_middle.finditer(belstr):
        (start, end) = match.span(1)

        end = end - 1
        if start != end:
            test_range = set(range(start, end))
        else:
            test_range = set(start)

        if test_range.intersection(quoted_range):
            continue

        span_key = (start, end)
        parsed[span_key] = {
            "type": "Relation",
            "name": match.group(1),
            "span": (start, end),
        }

    for match in relations_pattern_end.finditer(belstr):
        (start, end) = match.span(1)
        log.debug(f"Relation-end {match}")
        end = end - 1
        if start != end:
            test_range = set(range(start, end))
        else:
            test_range = set(start)

        if test_range.intersection(quoted_range):
            continue

        span_key = (start, end)
        parsed[span_key] = {
            "type": "Relation",
            "name": match.group(1),
            "span": (start, end),
        }

    return parsed, errors

Parse relations from BEL string

Args:
belstr: BEL string as one single string (not list of chars)
char_locs: paren, comma and quote char locations
parsed: data structure for parsed functions, relations, nested
errors: error messages

Returns:
(parsed, errors):


def as_session(name_or_func):

    if callable(name_or_func):
        func = name_or_func
        name = func.__name__
        name = "".join([(' ' + x) if x.isupper() else x for x in name])
        name = name.replace('_', ' ')
        return as_session(name)(func)
    else:
        name = name_or_func

    def get_func(func):
        @wraps(func)
        def wrapper(*args, **kwargs):
            start()
            title(name)
            result = func(*args, **kwargs)
            end()
            return result
        return wrapper
    return get_func

print start/title/end info before and after the function call

Args:
title: title will show after the start, if has any


def _read_git_tags(default_version=DEFAULT_VERSION, git_command=('git', 'tag')):
    try:
        current_tags = check_output(git_command).splitlines()
    except Exception:
        raise
    if (not current_tags[0]):
        warnings.warn('Unable to resolve current version', exceptions.ProsperDefaultVersionWarning)
        return default_version
    latest_version = semantic_version.Version(default_version)
    for tag in current_tags:
        tag_str = decode(tag, 'utf-8').replace('v', '')
        try:
            tag_ver = semantic_version.Version(tag_str)
        except Exception:
            continue
        if (tag_ver > latest_version):
            latest_version = tag_ver
    return str(latest_version)

tries to find current git tag

Notes:
git_command exposed for testing null case

Args:
default_version (str): what version to make
git_command (:obj:`list`): subprocess command

Retruns:
str: latest version found, or default

Warns:
exceptions.ProsperDefaultVersionWarning: git version not found


def save_pkl(filename=None, times=None):

    if times is None:
        if not f.root.stopped:
            times = collapse.collapse_times()
        else:
            times = f.root.times
    else:
        if isinstance(times, (list, tuple)):
            for t in times:
                if not isinstance(t, Times):
                    raise TypeError("Expected single Times instance or list/tuple of Times instances for param 'times'.")
        elif not isinstance(times, Times):
            raise TypeError("Expected single Times instance or list/tuple of Times instances for param 'times'.")
    if filename is not None:
        with open(str(filename), 'wb') as file:
            pickle.dump(times, file)
    else:
        return pickle.dumps(times)

Serialize and / or save a Times data object using pickle (cPickle).

Args:
filename (None, optional): Filename to dump to. If not provided,
returns serialized object.
times (None, optional): object to dump.  If non provided, uses
current root.

Returns:
pkl: Pickled Times data object, only if no filename provided.

Raises:
TypeError: If 'times' is not a Times object or a list of tuple of
them.


async def receive(self, timeout: float = None) -> Union[Message, None]:

        if timeout:
            coro = self.queue.get()
            try:
                msg = await asyncio.wait_for(coro, timeout=timeout)
            except asyncio.TimeoutError:
                msg = None
        else:
            try:
                msg = self.queue.get_nowait()
            except asyncio.QueueEmpty:
                msg = None
        return msg

Receives a message for this behaviour.
If timeout is not None it returns the message or "None"
after timeout is done.

Args:
timeout (float): number of seconds until return

Returns:
spade.message.Message: a Message or None


def transform(self, program: moderngl.Program, buffer: moderngl.Buffer, mode=None, vertices=(- 1), first=0, instances=1):
    vao = self.instance(program)
    if (mode is None):
        mode = self.mode
    vao.transform(buffer, mode=mode, vertices=vertices, first=first, instances=instances)

Transform vertices. Stores the output in a single buffer.

Args:
program: The ``moderngl.Program``
buffer: The ``moderngl.buffer`` to store the output

Keyword Args:
mode: Draw mode (for example ``moderngl.POINTS``)
vertices (int): The number of vertices to transform
first (int): The index of the first vertex to start with
instances (int): The number of instances


def resolve_lookups(variable, context, provider):

    resolved_lookups = {}
    for lookup in variable.lookups:
        try:
            handler = LOOKUP_HANDLERS[lookup.type]
        except KeyError:
            raise UnknownLookupType(lookup)
        try:
            resolved_lookups[lookup] = handler(
                value=lookup.input,
                context=context,
                provider=provider,
            )
        except Exception as e:
            raise FailedVariableLookup(variable.name, lookup, e)
    return resolved_lookups

Resolve a set of lookups.

Args:
variable (:class:`stacker.variables.Variable`): The variable resolving
it's lookups.
context (:class:`stacker.context.Context`): stacker context
provider (:class:`stacker.provider.base.BaseProvider`): subclass of the
base provider

Returns:
dict: dict of Lookup -> resolved value


def reduce_by(self, package_request):
    self.solver.reduction_broad_tests_count += 1
    if self.package_request.conflict:
        return (self, [])
    (new_slice, reductions) = self.variant_slice.reduce_by(package_request)
    if (new_slice is None):
        self.solver.reductions_count += 1
        if self.pr:
            reqstr = _short_req_str(package_request)
            self.pr('%s was reduced to nothing by %s', self, reqstr)
            self.pr.br()
        return (None, reductions)
    if (new_slice is not self.variant_slice):
        self.solver.reductions_count += 1
        scope = self._copy(new_slice)
        if self.pr:
            reqstr = _short_req_str(package_request)
            self.pr('%s was reduced to %s by %s', self, scope, reqstr)
            self.pr.br()
        return (scope, reductions)
    return (self, [])

Reduce this scope wrt a package request.

Returns:
A (_PackageScope, [Reduction]) tuple, where the scope is a new
scope copy with reductions applied, or self if there were no
reductions, or None if the scope was completely reduced.


def infer_graph(inputs: Optional[Set[EventSetNode]], outputs: Set[EventSetNode]) -> Graph:
    graph = Graph()
    graph.outputs.update(outputs)
    pending_nodes: Set[EventSetNode] = outputs.copy()
    done_nodes: Set[EventSetNode] = set()
    missing_nodes: Set[EventSetNode] = set()
    while pending_nodes:
        node = next(iter(pending_nodes))
        pending_nodes.remove(node)
        assert node not in done_nodes
        graph.add_node(node)
        if inputs is not None and node in inputs:
            graph.inputs.add(node)
            continue
        if node.creator is None:
            if inputs is not None:
                missing_nodes.add(node)
            else:
                graph.inputs.add(node)
            continue
        graph.add_operator(node.creator)
        for input_node in node.creator.inputs.values():
            if input_node in done_nodes:
                continue
            pending_nodes.add(input_node)
        for output_node in node.creator.outputs.values():
            graph.add_node(output_node)
    if missing_nodes:
        raise ValueError(f'The following input nodes are required but not provided as input:\n{missing_nodes}')
    for e in graph.nodes:
        graph.add_sampling(e.sampling_node)
        for f in e.feature_nodes:
            graph.add_feature(f)
    return graph

Extracts the nodes in between the output and input nodes.

If inputs is set, fails if outputs cannot be computed from `inputs`.
If inputs is not set, infers the required set of inputs.

Args:
inputs: Set of available input nodes. If None, inputs are inferred.
outputs: Set of expected output nodes.

Returns:
The inferred graph.

Raises:
ValueError: If there are repeated nodes in the `inputs`; an
unexpected type of input is provided; an unnamed node is inferred
as input; or some nodes are required but not provided.


def CreateAdGroup(client, campaign_id):

  ad_group_service = client.GetService('AdGroupService', 'v201809')

  adgroup = {

      'adGroupType': 'SHOPPING_SHOWCASE_ADS',
      'campaignId': campaign_id,
      'name': 'AdGroup

      'biddingStrategyConfiguration': {

          'biddingStrategyType': 'MANUAL_CPC',

          'bids': [{
              'xsi_type': 'CpcBid',
              'bid': {
                  'microAmount': 100000
              }
          }]
      }
  }

  adgroup_operations = {
      'operator': 'ADD',
      'operand': adgroup
  }

  adgroup = ad_group_service.mutate(adgroup_operations)['value'][0]

  print ('AdGroup with name "%s" and ID "%s" was added.'
         % (adgroup['name'], adgroup['id']))

  return adgroup

Creates an AdGroup for the given shopping campaign ID.

Args:
client: an AdWordsClient instance.
campaign_id: the str ID of a shopping campaign.

Returns:
The created AdGroup as a sudsobject.


def handle_or_else(self, orelse, test):

        if isinstance(orelse[0], ast.If):
            control_flow_node = self.visit(orelse[0])

            control_flow_node.test.label = 'el' + control_flow_node.test.label

            test.connect(control_flow_node.test)
            return control_flow_node.last_nodes
        else:
            else_connect_statements = self.stmt_star_handler(
                orelse,
                prev_node_to_avoid=self.nodes[-1]
            )
            test.connect(else_connect_statements.first_statement)
            return else_connect_statements.last_statements

Handle the orelse part of an if or try node.

Args:
orelse(list[Node])
test(Node)

Returns:
The last nodes of the orelse branch.


def _save_model(self, epoch, batch, logs):
    filepath = self._get_file_path(epoch, batch, logs)
    try:
        if self._should_save_model(epoch, batch, logs, filepath):
            dirname = os.path.dirname(filepath)
            if dirname and (not file_utils.exists(dirname)):
                file_utils.makedirs(dirname)
            if self.save_weights_only:
                self.model.save_weights(filepath, overwrite=True)
            else:
                self.model.save(filepath, overwrite=True)
    except IsADirectoryError:
        raise IOError(f'Please specify a non-directory filepath for ModelCheckpoint. Filepath used is an existing directory: {filepath}')
    except IOError as e:
        if 'is a directory' in str(e.args[0]).lower():
            raise IOError(f'Please specify a non-directory filepath for ModelCheckpoint. Filepath used is an existing directory: f{filepath}')
        raise e

Saves the model.

Args:
epoch: the epoch this iteration is in.
batch: the batch this iteration is in. `None` if the `save_freq`
is set to `"epoch"`.
logs: the `logs` dict passed in to `on_batch_end` or `on_epoch_end`.


def delete(self):
    cmd = self.command_builder('ntp source', disable=True)
    return self.configure(cmd)

Delete the NTP source entry from the node.

Returns:
True if the operation succeeds, otherwise False.


def build_inputs_with_special_tokens(self, token_ids_0: List[int], token_ids_1: Optional[List[int]]=None) -> List[int]:
    if token_ids_1 is None:
        return self.prefix_tokens + token_ids_0 + self.suffix_tokens
    return self.prefix_tokens + token_ids_0 + token_ids_1 + self.suffix_tokens

Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
adding special tokens. The special tokens depend on calling set_lang.

An MBART sequence has the following format, where `X` represents the sequence:

- `input_ids` (for encoder) `X [eos, src_lang_code]`
- `decoder_input_ids`: (for decoder) `X [eos, tgt_lang_code]`

BOS is never used. Pairs of sequences are not the expected use case, but they will be handled without a
separator.

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

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


def interconnects(self):
    if (not self.__interconnects):
        self.__interconnects = Interconnects(self.__connection)
    return self.__interconnects

Gets the Interconnects API client.

Returns:
Interconnects:


def __init__(self, rate, validate_args=False, allow_nan_stats=True, name='Exponential'):
    parameters = dict(locals())
    with ops.name_scope(name, values=[rate]) as name:
        self._rate = ops.convert_to_tensor(rate, name='rate')
    super(Exponential, self).__init__(concentration=array_ops.ones([], dtype=self._rate.dtype), rate=self._rate, allow_nan_stats=allow_nan_stats, validate_args=validate_args, name=name)
    self._parameters = parameters
    self._graph_parents += [self._rate]

Construct Exponential distribution with parameter `rate`.

Args:
rate: Floating point tensor, equivalent to `1 / mean`. Must contain only
positive values.
validate_args: Python `bool`, default `False`. When `True` distribution
parameters are checked for validity despite possibly degrading runtime
performance. When `False` invalid inputs may silently render incorrect
outputs.
allow_nan_stats: Python `bool`, default `True`. When `True`, statistics
(e.g., mean, mode, variance) use the value "`NaN`" to indicate the
result is undefined. When `False`, an exception is raised if one or
more of the statistic's batch members are undefined.
name: Python `str` name prefixed to Ops created by this class.


def max_neighbor(self, in_lon, in_lat, radius=0.05):
    out_data = np.zeros((self.data.shape[0], in_lon.shape[0], in_lon.shape[1]))
    in_tree = cKDTree(np.vstack((in_lat.ravel(), in_lon.ravel())).T)
    out_indices = np.indices(out_data.shape[1:])
    out_rows = out_indices[0].ravel()
    out_cols = out_indices[1].ravel()
    for d in range(self.data.shape[0]):
        nz_points = np.where((self.data[d] > 0))
        if (len(nz_points[0]) > 0):
            nz_vals = self.data[d][nz_points]
            nz_rank = np.argsort(nz_vals)
            original_points = cKDTree(np.vstack((self.lat[nz_points[0][nz_rank]], self.lon[nz_points[1][nz_rank]])).T)
            all_neighbors = original_points.query_ball_tree(in_tree, radius, p=2, eps=0)
            for (n, neighbors) in enumerate(all_neighbors):
                if (len(neighbors) > 0):
                    out_data[(d, out_rows[neighbors], out_cols[neighbors])] = nz_vals[nz_rank][n]
    return out_data

Finds the largest value within a given radius of a point on the interpolated grid.

Args:
in_lon: 2D array of longitude values
in_lat: 2D array of latitude values
radius: radius of influence for largest neighbor search in degrees

Returns:
Array of interpolated data


def FileEntryExistsByPathSpec(self, path_spec):

    store_index = vshadow.VShadowPathSpecGetStoreIndex(path_spec)

    if store_index is None:
      location = getattr(path_spec, 'location', None)
      return location is not None and location == self.LOCATION_ROOT

    return 0 <= store_index < self._vshadow_volume.number_of_stores

Determines if a file entry for a path specification exists.

Args:
path_spec (PathSpec): path specification.

Returns:
bool: True if the file entry exists.


def _create_L_ind(self, L):
    if issparse(L):
        L = L.todense()
    L_ind = np.zeros((self.n, (self.m * self.k)))
    for y in range(1, (self.k + 1)):
        L_ind[(:, (y - 1)::self.k)] = np.where((L == y), 1, 0)
    return L_ind

Convert a label matrix with labels in 0...k to a one-hot format

Args:
L: An [n,m] scipy.sparse label matrix with values in {0,1,...,k}

Returns:
L_ind: An [n,m*k] dense np.ndarray with values in {0,1}

Note that no column is required for 0 (abstain) labels.


def __init__(self, context):

    self.multiplexer = context.multiplexer
    self.logdir = context.logdir
    self._handlers = None
    self.readers = {}
    self.run_paths = None
    self._configs = {}
    self.old_num_run_paths = None
    self.config_fpaths = None
    self.tensor_cache = LRUCache(_TENSOR_CACHE_CAPACITY)

    self._is_active = False

    self._thread_for_determining_is_active = None

    if self.multiplexer:
      self.run_paths = self.multiplexer.RunPaths()

Instantiates ProjectorPlugin via TensorBoard core.

Args:
context: A base_plugin.TBContext instance.


def _get(self, rec_id=None, upstream=None):
    if rec_id:
        self.record_url = self.__class__.get_record_url(rec_id)
        self.debug_logger.debug('GET {} record with ID {}: {}'.format(self.__class__.__name__, rec_id, self.record_url))
        response = requests.get(url=self.record_url, headers=HEADERS, verify=False)
        if ((not response.ok) and (response.status_code == requests.codes.NOT_FOUND)):
            raise RecordNotFound("Search for {} record with ID '{}' returned no results.".format(self.__class__.__name__, rec_id))
        self.write_response_html_to_file(response, 'get_bob.html')
        response.raise_for_status()
        return response.json()
    elif upstream:
        rec_json = self.__class__.find_by({'upstream_identifier': upstream}, require=True)
        self.record_url = self.__class__.get_record_url(rec_json['id'])
    return rec_json

Fetches a record by the record's ID or upstream_identifier.

Raises:
`pulsarpy.models.RecordNotFound`: A record could not be found.


def batch(self, timelimit=None):

        from .launcher import BatchLauncher

        prev_dir = os.path.join(*self.workdir.split(os.path.sep)[:-1])
        prev_dir = os.path.join(os.path.sep, prev_dir)
        workdir = os.path.join(prev_dir, os.path.basename(self.workdir) + "_batch")

        return BatchLauncher(workdir=workdir, flows=self).submit(timelimit=timelimit)

Run the flow in batch mode, return exit status of the job script.
Requires a manager.yml file and a batch_adapter adapter.

Args:
timelimit: Time limit (int with seconds or string with time given with the slurm convention:
"days-hours:minutes:seconds"). If timelimit is None, the default value specified in the
`batch_adapter` entry of `manager.yml` is used.


def UpdateTaskAsPendingMerge(self, task):
    with self._lock:
        is_abandoned = (task.identifier in self._tasks_abandoned)
        is_processing = (task.identifier in self._tasks_processing)
        is_queued = (task.identifier in self._tasks_queued)
        if ((not is_queued) and (not is_processing) and (not is_abandoned)):
            raise KeyError('Status of task {0:s} is unknown.'.format(task.identifier))
        if (is_abandoned and task.has_retry):
            raise KeyError('Will not merge a task {0:s} with retry task.'.format(task.identifier))
        if is_queued:
            logger.debug('Task {0:s} was queued, now merging.'.format(task.identifier))
            del self._tasks_queued[task.identifier]
        if is_processing:
            logger.debug('Task {0:s} was processing, now merging.'.format(task.identifier))
            del self._tasks_processing[task.identifier]
        if is_abandoned:
            logger.debug('Task {0:s} was abandoned, now merging.'.format(task.identifier))
            del self._tasks_abandoned[task.identifier]
        self._tasks_pending_merge.PushTask(task)
        self.SampleTaskStatus(task, 'pending_merge')
        task.UpdateProcessingTime()
        self._UpdateLatestProcessingTime(task)

Updates the task manager to reflect the task is ready to be merged.

Args:
task (Task): task.

Raises:
KeyError: if the task was not queued, processing or abandoned, or
the task was abandoned and has a retry task.


def assertDTypeEqual(self, target, expected_dtype):
    target = self._GetNdArray(target)
    if not isinstance(target, list):
        arrays = [target]
    for arr in arrays:
        self.assertEqual(arr.dtype, expected_dtype)

Assert ndarray data type is equal to expected.

Args:
target: The numpy `ndarray`, or anything that can be converted into a
numpy `ndarray` (including Tensor).
expected_dtype: Expected data type.


def find(self, query=None, func=None, labels=None, colors=None, pinned=None, archived=None, trashed=False):
    if (labels is not None):
        labels = [(i.id if isinstance(i, _node.Label) else i) for i in labels]
    return (node for node in self.all() if (((query is None) or ((isinstance(query, six.string_types) and ((query in node.title) or (query in node.text))) or (isinstance(query, Pattern) and (query.search(node.title) or query.search(node.text))))) and ((func is None) or func(node)) and ((labels is None) or ((not labels) and (not node.labels.all())) or any(((node.labels.get(i) is not None) for i in labels))) and ((colors is None) or (node.color in colors)) and ((pinned is None) or (node.pinned == pinned)) and ((archived is None) or (node.archived == archived)) and ((trashed is None) or (node.trashed == trashed))))

Find Notes based on the specified criteria.

Args:
query (Union[_sre.SRE_Pattern, str, None]): A str or regular expression to match against the title and text.
func (Union[callable, None]): A filter function.
labels (Union[List[str], None]): A list of label ids or objects to match. An empty list matches notes with no labels.
colors (Union[List[str], None]): A list of colors to match.
pinned (Union[bool, None]): Whether to match pinned notes.
archived (Union[bool, None]): Whether to match archived notes.
trashed (Union[bool, None]): Whether to match trashed notes.

Return:
List[gkeepapi.node.TopLevelNode]: Results.


def Collect(self, knowledge_base, artifact_definition, searcher, file_system):
    for source in artifact_definition.sources:
        if (source.type_indicator not in (artifact_definitions.TYPE_INDICATOR_FILE, artifact_definitions.TYPE_INDICATOR_PATH)):
            continue
        for path in source.paths:
            path_segments = path.split(source.separator)
            find_spec = file_system_searcher.FindSpec(location_glob=path_segments[1:], case_sensitive=False)
            for path_specification in searcher.Find(find_specs=[find_spec]):
                self._ParsePathSpecification(knowledge_base, searcher, file_system, path_specification, source.separator)

Collects values using a file artifact definition.

Args:
knowledge_base (KnowledgeBase): to fill with preprocessing information.
artifact_definition (artifacts.ArtifactDefinition): artifact definition.
searcher (dfvfs.FileSystemSearcher): file system searcher to preprocess
the file system.
file_system (dfvfs.FileSystem): file system to be preprocessed.

Raises:
PreProcessFail: if the preprocessing fails.


def belspec_yaml2json(yaml_fn: str, json_fn: str) -> str:

    try:
        spec_dict = yaml.load(open(yaml_fn, "r").read(), Loader=yaml.SafeLoader)

        spec_dict["admin"] = {}
        spec_dict["admin"]["version_underscored"] = spec_dict["version"].replace(".", "_")
        spec_dict["admin"]["parser_fn"] = yaml_fn.replace(".yaml", "_parser.py")

        add_relations(spec_dict)

        add_functions(spec_dict)

        add_namespaces(spec_dict)

        enhance_function_signatures(spec_dict)

        add_function_signature_help(spec_dict)

        with open(json_fn, "w") as f:
            json.dump(spec_dict, f)

    except Exception as e:
        log.error(
            "Warning: BEL Specification {yaml_fn} could not be read. Cannot proceed.".format(
                yaml_fn
            )
        )
        sys.exit()

    return spec_dict["version"]

Enhance BEL specification and save as JSON file

Load all BEL Specification YAML files and convert to JSON files
after enhancing them.  Also create a bel_versions.json file with
all available BEL versions for fast loading.

Args:
yaml_fn: original YAML version of BEL Spec
json_fn: enhanced JSON version of BEL Spec
Returns:
str: version of BEL Spec


def map(self, op: Callable[[T], U]) -> 'Union[Result[U, E], Result[T, E]]':

        return self._type.Ok(op(cast(T, self._val))) if self._is_ok else self

Applies a function to the contained :meth:`Result.Ok` value.

Args:
op: The function to apply to the :meth:`Result.Ok` value.

Returns:
A :class:`Result` with its success value as the function result
if `self` is an :meth:`Result.Ok` value, otherwise returns
`self`.

Examples:
>>> Ok(1).map(lambda x: x * 2)
Ok(2)
>>> Err(1).map(lambda x: x * 2)
Err(1)


def _sparse_or_dense_matmul_onehot(sparse_or_dense_matrix, col_index):

  if isinstance(sparse_or_dense_matrix,
                (tf.SparseTensor, tf.compat.v1.SparseTensorValue)):

    num_rows = _get_shape(sparse_or_dense_matrix)[-2]
    batch_shape = _get_shape(sparse_or_dense_matrix)[:-2]
    slice_start = tf.concat([tf.zeros_like(batch_shape), [0, col_index]],
                            axis=0)
    slice_size = tf.concat([batch_shape, [num_rows, 1]], axis=0)

    sparse_slice = tf.sparse.slice(sparse_or_dense_matrix,
                                   tf.cast(slice_start, tf.int64),
                                   tf.cast(slice_size, tf.int64))

    output_shape = tf.concat([batch_shape, [num_rows]], axis=0)
    return tf.reshape(tf.sparse.to_dense(sparse_slice), output_shape)
  else:
    return tf.gather(sparse_or_dense_matrix, col_index, axis=-1)

Returns a (dense) column of a Tensor or SparseTensor.

Args:
sparse_or_dense_matrix: matrix-shaped, `float` `Tensor` or `SparseTensor`.
col_index: scalar, `int` `Tensor` representing the index of the desired
column.

Returns:
column: vector-shaped, `float` `Tensor` with the same dtype as
`sparse_or_dense_matrix`, representing the `col_index`th column of
`sparse_or_dense_matrix`.


def filter_with_theta(image, theta, sigma=1.0, filter_size=9):
    x = np.arange((((- filter_size)
    g = np.array([np.exp(((- (x ** 2)) / (2 * (sigma ** 2))))])
    gp = np.array([((- (x / sigma)) * np.exp(((- (x ** 2)) / (2 * (sigma ** 2)))))])
    ix = convolve2d(image, (- gp), mode='same', boundary='fill', fillvalue=0)
    ix = convolve2d(ix, g.T, mode='same', boundary='fill', fillvalue=0)
    iy = convolve2d(image, g, mode='same', boundary='fill', fillvalue=0)
    iy = convolve2d(iy, (- gp.T), mode='same', boundary='fill', fillvalue=0)
    output = ((np.cos(theta) * ix) + (np.sin(theta) * iy))
    gt_filter = np.matmul(g.T, gp)
    gt_filter = ((np.cos(theta) * gt_filter) + (np.sin(theta) * gt_filter.T))
    return (output, gt_filter)

Implements a steerable Gaussian filter.

This function can be used to evaluate the first
directional derivative of an image, using the
method outlined in

W. T. Freeman and E. H. Adelson, "The Design
and Use of Steerable Filters", IEEE PAMI, 1991.

It evaluates the directional derivative of the input
image I, oriented at THETA degrees with respect to the
image rows. The standard deviation of the Gaussian kernel
is given by SIGMA (assumed to be equal to unity by default).

Args:
image: any input image (only one channel)
theta: orientation of filter [0, 2 * pi]
sigma (float, optional): standard derivation of Gaussian
filter_size (int, optional): filter support

Returns:
filtered image and the filter


def random_line_data(chars_per_line=80):

    return ''.join(__random.choice(__string.ascii_letters) for x in range(chars_per_line))

Function to create a line of a random string
Args:
chars_per_line: An integer that says how many characters to return

Returns:
A String


def resolve_image_exif(self, image_url):

        files = self.mets.find_files(url=image_url)
        if files:
            image_filename = self.download_file(files[0]).local_filename
        else:
            image_filename = self.download_url(image_url)

        if image_url not in self.image_cache['exif']:
            self.image_cache['exif'][image_url] = OcrdExif(Image.open(image_filename))
        return self.image_cache['exif'][image_url]

Get the EXIF metadata about an image URL as :class:`OcrdExif`

Args:
image_url (string) : URL of image

Return
:class:`OcrdExif`


def _convert_tf2_model(flags):
    if flags.saved_model_dir:
        converter = lite.TFLiteConverterV2.from_saved_model(flags.saved_model_dir, signature_keys=_parse_array(flags.saved_model_signature_key), tags=_parse_set(flags.saved_model_tag_set))
    elif flags.keras_model_file:
        model = keras_deps.get_load_model_function()(flags.keras_model_file)
        converter = lite.TFLiteConverterV2.from_keras_model(model)
    converter.experimental_new_converter = flags.experimental_new_converter
    if flags.experimental_new_quantizer is not None:
        converter.experimental_new_quantizer = flags.experimental_new_quantizer
    tflite_model = converter.convert()
    with gfile.GFile(flags.output_file, 'wb') as f:
        f.write(tflite_model)

Calls function to convert the TensorFlow 2.0 model into a TFLite model.

Args:
flags: argparse.Namespace object.

Raises:
ValueError: Unsupported file format.


def parse_response(service, response, search_type):

    _LOG.debug('Parse response "%s" from service "%s" of type "%s"', response,
               service, search_type)
    items = []

    if 'searchResult' in response:
        response = response['searchResult']
    elif 'getMetadataResult' in response:
        response = response['getMetadataResult']
    else:
        raise ValueError('"response" should contain either the key '
                         '"searchResult" or "getMetadataResult"')

    search_metadata = {
        'number_returned': response['count'],
        'total_matches': None,
        'search_type': search_type,
        'update_id': None,
    }

    for result_type in ('mediaCollection', 'mediaMetadata'):

        result_type_proper = result_type[0].upper() + result_type[1:]
        raw_items = response.get(result_type, [])

        if isinstance(raw_items, OrderedDict):
            raw_items = [raw_items]

        for raw_item in raw_items:

            class_key = result_type_proper + raw_item['itemType'].title()
            cls = get_class(class_key)
            items.append(cls.from_music_service(service, raw_item))
    return SearchResult(items, **search_metadata)

Parse the response to a music service query and return a SearchResult

Args:
service (MusicService): The music service that produced the response
response (OrderedDict): The response from the soap client call
search_type (str): A string that indicates the search type that the
response is from

Returns:
SearchResult: A SearchResult object


def _has_next_page(self):
    if (self.page_number == 0):
        return True
    if (self.max_results is not None):
        if (self.num_results >= self.max_results):
            return False
    return (True if self.next_page_token else False)

Determines whether or not there are more pages with results.

Returns:
bool: Whether the iterator has more pages.


def _read_wrappers(self, name):

        io_attr = getattr(self._io, name)

        def read_wrapper(*args, **kwargs):

            self._io.seek(self._read_seek, self._read_whence)
            ret_value = io_attr(*args, **kwargs)
            self._read_seek = self._io.tell()
            self._read_whence = 0
            self._io.seek(0, 2)
            return ret_value

        return read_wrapper

Wrap a stream attribute in a read wrapper.

Returns a read_wrapper which tracks our own read pointer since the
stream object has no concept of a different read and write pointer.

Args:
name: The name of the attribute to wrap. Should be a read call.

Returns:
The read_wrapper function.


def run(self, include_reset=True, accelerated=True):
    self._start_tick = self.tick_count
    if self._check_stop_conditions(self.sensor_graph):
        return
    if include_reset:
        pass
    i = None
    for (i, stim) in enumerate(self.stimuli):
        if (stim.time != 0):
            break
        reading = IOTileReading(self.tick_count, stim.stream.encode(), stim.value)
        self.sensor_graph.process_input(stim.stream, reading, self.rpc_executor)
    if ((i is not None) and (i > 0)):
        self.stimuli = self.stimuli[i:]
    while (not self._check_stop_conditions(self.sensor_graph)):
        now = monotonic()
        next_tick = (now + 1.0)
        self.tick_count += 1
        i = None
        for (i, stim) in enumerate(self.stimuli):
            if (stim.time != self.tick_count):
                break
            reading = IOTileReading(self.tick_count, stim.stream.encode(), stim.value)
            self.sensor_graph.process_input(stim.stream, reading, self.rpc_executor)
        if ((i is not None) and (i > 0)):
            self.stimuli = self.stimuli[i:]
        self._check_additional_ticks(self.tick_count)
        if ((self.tick_count % 10) == 0):
            reading = IOTileReading(self.tick_count, system_tick.encode(), self.tick_count)
            self.sensor_graph.process_input(system_tick, reading, self.rpc_executor)
            reading = IOTileReading(self.tick_count, battery_voltage.encode(), int((self.voltage * 65536)))
            self.sensor_graph.process_input(battery_voltage, reading, self.rpc_executor)
        now = monotonic()
        if ((not accelerated) and (now < next_tick)):
            time.sleep((next_tick - now))

Run this sensor graph until a stop condition is hit.

Multiple calls to this function are useful only if
there has been some change in the stop conditions that would
cause the second call to not exit immediately.

Args:
include_reset (bool): Start the sensor graph run with
a reset event to match what would happen when an
actual device powers on.
accelerated (bool): Whether to run this sensor graph as
fast as possible or to delay tick events to simulate
the actual passage of wall clock time.


def disconnect_async(self, conn_id, callback):

        found_handle = None

        for handle, conn in self._connections.items():
            if conn['connection_id'] == conn_id:
                found_handle = handle

        if found_handle is None:
            callback(conn_id, self.id, False, 'Invalid connection_id')
            return

        self._command_task.async_command(['_disconnect', found_handle], self._on_disconnect,
                                         {'connection_id': conn_id, 'handle': found_handle,
                                          'callback': callback})

Asynchronously disconnect from a device that has previously been connected

Args:
conn_id (int): a unique identifier for this connection on the DeviceManager
that owns this adapter.
callback (callable): A function called as callback(conn_id, adapter_id, success, failure_reason)
when the disconnection finishes.  Disconnection can only either succeed or timeout.


def set_dtype_conversion_mode(dtype_conversion_mode) -> None:
    global _dtype_conversion_mode
    _dtype_conversion_mode = _get_promo_mode_enum(dtype_conversion_mode)

Enables the specified dtype conversion mode.

Args:
dtype_conversion_mode: a string that specifies dtype conversion mode. This
string corresponds to a PromoMode Enum and can be 'off', 'legacy', 'safe'
or 'all'.


def register(self, username=""):

        if not username:
            username = utils.mxid2localpart(self.identity)
        content = {
            "type": "m.login.application_service",
            "username": username,
        }
        return self._send("POST", "/register", content,
                          api_path=MATRIX_V2_API_PATH)

Performs /register with type: m.login.application_service

Args:
username(str): Username to register.


def _read_ipv6_opts_options(self, length):
    counter = 0
    optkind = list()
    options = dict()
    while (counter < length):
        code = self._read_unpack(1)
        if (not code):
            break
        (abbr, desc) = _IPv6_Opts_OPT.get(code, ('None', 'Unassigned'))
        data = _IPv6_Opts_PROC(abbr)(self, code, desc=desc)
        enum = _OPT_TYPE.get(code)
        counter += data['length']
        if (enum in optkind):
            if isinstance(options[abbr], tuple):
                options[abbr] += (Info(data),)
            else:
                options[abbr] = (Info(options[abbr]), Info(data))
        else:
            optkind.append(enum)
            options[abbr] = data
    if (counter != length):
        raise ProtocolError(f'{self.alias}: invalid format')
    return (tuple(optkind), options)

Read IPv6_Opts options.

Positional arguments:
* length -- int, length of options

Returns:
* dict -- extracted IPv6_Opts options


def lists(self, **kwargs):
    path = self._get_path('lists')
    response = self._GET(path, kwargs)
    self._set_attrs_to_values(response)
    return response

Gets the top-level lists available from the API.

Returns:
A dict respresentation of the JSON returned from the API.


def _get_client_by_id(self, client_id):
    client = self.grr_api.Client(client_id)
    print('Checking for client approval')
    self._check_approval_wrapper(client, client.ListFlows)
    print('{0:s}: Client approval is valid'.format(client_id))
    return client.Get()

Get GRR client dictionary and make sure valid approvals exist.

Args:
client_id: GRR client ID.

Returns:
GRR API Client object


def _write_submit_script(self, template, script_filename, job_name, configs):
    try:
        submit_script = Template(template).substitute(jobname=job_name, **configs)
        with open(script_filename, 'w') as f:
            f.write(submit_script)
    except KeyError as e:
        logger.error('Missing keys for submit script : %s', e)
        raise SchedulerMissingArgs(e.args, self.sitename)
    except IOError as e:
        logger.error('Failed writing to submit script: %s', script_filename)
        raise ScriptPathError(script_filename, e)
    except Exception as e:
        print('Template : ', template)
        print('Args : ', job_name)
        print('Kwargs : ', configs)
        logger.error('Uncategorized error: %s', e)
        raise e
    return True

Generate submit script and write it to a file.

Args:
- template (string) : The template string to be used for the writing submit script
- script_filename (string) : Name of the submit script
- job_name (string) : job name
- configs (dict) : configs that get pushed into the template

Returns:
- True: on success

Raises:
SchedulerMissingArgs : If template is missing args
ScriptPathError : Unable to write submit script out


def depth(self, local: bool=True) -> int:
    G = self.graph
    if (not local):

        def remove_local(dagc: DAGCircuit) -> Generator[(Operation, None, None)]:
            for elem in dagc:
                if (dagc.graph.degree[elem] > 2):
                    (yield elem)
        G = DAGCircuit(remove_local(self)).graph
    return (nx.dag_longest_path_length(G) - 1)

Return the circuit depth.

Args:
local:  If True include local one-qubit gates in depth
calculation. Else return the multi-qubit gate depth.


def mkfile_uchroot(filepath, root="."):

    from benchbuild.utils.uchroot import no_args, uretry

    uchroot = no_args()
    uchroot = uchroot["-E", "-A", "-C", "-w", "/", "-r"]
    uchroot = uchroot[os.path.abspath(root)]
    uretry(uchroot["--", "/bin/touch", filepath])

Create a file inside a uchroot env.

You will want to use this when you need to create a file with apropriate
rights inside a uchroot container with subuid/subgid handling enabled.

Args:
filepath:
The filepath that should be created. Absolute inside the
uchroot container.
root:
The root PATH of the container filesystem as seen outside of
the container.


def locate_point(nodes, x_val, y_val):
    zero1 = (_curve_helpers.full_reduce(nodes[([0], :)]) - x_val)
    zero2 = (_curve_helpers.full_reduce(nodes[([1], :)]) - y_val)
    if (zero1.shape[1] > zero2.shape[1]):
        (zero1, zero2) = (zero2, zero1)
    if (zero1.shape[1] == 1):
        (zero1, zero2) = (zero2, zero1)
    power_basis1 = poly_to_power_basis(zero1[(0, :)])
    all_roots = roots_in_unit_interval(power_basis1)
    if (all_roots.size == 0):
        return None
    power_basis2 = normalize_polynomial(poly_to_power_basis(zero2[(0, :)]))
    near_zero = np.abs(polynomial.polyval(all_roots, power_basis2))
    index = np.argmin(near_zero)
    if (near_zero[index] < _ZERO_THRESHOLD):
        return all_roots[index]
    return None

r"""Find the parameter corresponding to a point on a curve.

.. note::

This assumes that the curve :math:`B(s, t)` defined by ``nodes``
lives in :math:`\mathbf{R}^2`.

Args:
nodes (numpy.ndarray): The nodes defining a B |eacute| zier curve.
x_val (float): The :math:`x`-coordinate of the point.
y_val (float): The :math:`y`-coordinate of the point.

Returns:
Optional[float]: The parameter on the curve (if it exists).


def ic45(msg):

    d = hex2bin(data(msg))
    if d[9] == '0':
        return None

    ic = bin2int(d[10:12])
    return ic

Icing.

Args:
msg (String): 28 bytes hexadecimal message string

Returns:
int: Icing level. 0=NIL, 1=Light, 2=Moderate, 3=Severe


def reset_trial(self, trial, new_config, new_experiment_tag):

        trial.experiment_tag = new_experiment_tag
        trial.config = new_config
        trainable = trial.runner
        with warn_if_slow("reset_config"):
            reset_val = ray.get(trainable.reset_config.remote(new_config))
        return reset_val

Tries to invoke `Trainable.reset_config()` to reset trial.

Args:
trial (Trial): Trial to be reset.
new_config (dict): New configuration for Trial
trainable.
new_experiment_tag (str): New experiment name
for trial.

Returns:
True if `reset_config` is successful else False.


def get_context_from_cmdln(args, desc='Run scriptworker'):
    context = Context()
    parser = argparse.ArgumentParser(description=desc)
    parser.add_argument('config_path', type=str, nargs='?', default='scriptworker.yaml', help='the path to the config file')
    parsed_args = parser.parse_args(args)
    (context.config, credentials) = create_config(config_path=parsed_args.config_path)
    update_logging_config(context)
    return (context, credentials)

Create a Context object from args.

Args:
args (list): the commandline args.  Generally sys.argv

Returns:
tuple: ``scriptworker.context.Context`` with populated config, and
credentials frozendict


def usergroups_users_update(
        self, *, usergroup: str, users: List[str], **kwargs
    ) -> SlackResponse:

        self._validate_xoxp_token()
        kwargs.update({"usergroup": usergroup, "users": users})
        return self.api_call("usergroups.users.update", json=kwargs)

Update the list of users for a User Group

Args:
usergroup (str): The encoded ID of the User Group to update.
e.g. 'S0604QSJC'
users (list): A list user IDs that represent the entire list of
users for the User Group. e.g. ['U060R4BJ4', 'U060RNRCZ']


def video_augmentation(features, hue=False, saturate=False, contrast=False):

  inputs, targets = features["inputs"], features["targets"]
  in_steps = common_layers.shape_list(inputs)[0]

  video = tf.concat((inputs, targets), axis=0)
  if hue:
    video = tf.image.random_hue(video, max_delta=0.2)
  if saturate:
    video = tf.image.random_saturation(video, lower=0.5, upper=1.5)
  if contrast:
    video = tf.image.random_contrast(video, lower=0.5, upper=1.5)
  features["inputs"], features["targets"] = video[:in_steps], video[in_steps:]
  return features

Augments video with optional hue, saturation and constrast.

Args:
features: dict, with keys "inputs", "targets".
features["inputs"], 4-D Tensor, shape=(THWC)
features["targets"], 4-D Tensor, shape=(THWC)
hue: bool, apply hue_transform.
saturate: bool, apply saturation transform.
contrast: bool, apply constrast transform.
Returns:
augment_features: dict with transformed "inputs" and "targets".


def _find_workflows(mcs, attrs):
    workflows = {}
    for (attribute, value) in attrs.items():
        if isinstance(value, Workflow):
            workflows[attribute] = StateField(value)
    return workflows

Finds all occurrences of a workflow in the attributes definitions.

Returns:
dict(str => StateField): maps an attribute name to a StateField
describing the related Workflow.


def search_features(self, search):

        if isinstance(search, string_types):
            search = [search]
        search = [s.replace('*', '.*') for s in search]
        cols = list(self.data.columns)
        results = []
        for s in search:
            results.extend([f for f in cols if re.match(s + '$', f)])
        return list(set(results))

Returns all features that match any of the elements in the input
list.

Args:
search (str, list): A string or list of strings defining the query.

Returns:
A list of matching feature names.


def _ParseTensorName(tensor_name):
    components = tensor_name.split(':')
    if len(components) == 2:
        try:
            output_index = int(components[1])
        except ValueError:
            raise ValueError(f'Cannot convert {tensor_name!r} to a tensor name. Second component of the name following the `:` should be an int. Got {components[1]}.')
        return (components[0], output_index)
    elif len(components) == 1:
        return (components[0], 0)
    else:
        raise ValueError(f"Cannot convert '{tensor_name}' to a tensor name. Tensor names should not contain more than 1 `:`. Obtained {len(components) - 1}")

Parses a tensor name into an operation name and output index.

This function will canonicalize tensor names as follows:

* "foo:0"       -> ("foo", 0)
* "foo:7"       -> ("foo", 7)
* "foo"         -> ("foo", 0)
* "foo:bar:baz" -> ValueError

Args:
tensor_name: The name of a tensor.

Returns:
A tuple containing the operation name, and the output index.

Raises:
ValueError: If `tensor_name' cannot be interpreted as the name of a tensor.


def _run_single(self, thread_id, agent, environment, deterministic=False, max_episode_timesteps=(- 1), episode_finished=None, testing=False, sleep=None):
    old_episode_finished = False
    if ((episode_finished is not None) and (len(getargspec(episode_finished).args) == 1)):
        old_episode_finished = True
    episode = 0
    while (not self.should_stop):
        state = environment.reset()
        agent.reset()
        (self.global_timestep, self.global_episode) = (agent.timestep, agent.episode)
        episode_reward = 0
        time_step = 0
        time_start = time.time()
        while True:
            (action, internals, states) = agent.act(states=state, deterministic=deterministic, buffered=False)
            reward = 0
            for repeat in xrange(self.repeat_actions):
                (state, terminal, step_reward) = environment.execute(action=action)
                reward += step_reward
                if terminal:
                    break
            if (not testing):
                agent.atomic_observe(states=state, actions=action, internals=internals, reward=reward, terminal=terminal)
            if (sleep is not None):
                time.sleep(sleep)
            time_step += 1
            episode_reward += reward
            if (terminal or (time_step == max_episode_timesteps)):
                break
            if self.should_stop:
                return
        self.global_timestep += time_step
        self.episode_list_lock.acquire()
        self.episode_rewards.append(episode_reward)
        self.episode_timesteps.append(time_step)
        self.episode_times.append((time.time() - time_start))
        self.episode_list_lock.release()
        if (episode_finished is not None):
            if old_episode_finished:
                summary_data = {'thread_id': thread_id, 'episode': episode, 'timestep': time_step, 'episode_reward': episode_reward}
                if (not episode_finished(summary_data)):
                    return
            elif (not episode_finished(self, thread_id)):
                return
        episode += 1

The target function for a thread, runs an agent and environment until signaled to stop.
Adds rewards to shared episode rewards list.

Args:
thread_id (int): The ID of the thread that's running this target function.
agent (Agent): The Agent object that this particular thread uses.
environment (Environment): The Environment object that this particular thread uses.
max_episode_timesteps (int): Max. number of timesteps per episode. Use -1 or 0 for non-limited episodes.
episode_finished (callable): Function called after each episode that takes an episode summary spec and
returns False, if this single run should terminate after this episode.
Can be used e.g. to set a particular mean reward threshold.


def _MergeIdentical(self, a, b):

    if a != b:
      raise MergeError("values must be identical ('%s' vs '%s')" %
                       (transitfeed.EncodeUnicode(a),
                        transitfeed.EncodeUnicode(b)))
    return b

Tries to merge two values. The values are required to be identical.

Args:
a: The first value.
b: The second value.

Returns:
The trivially merged value.

Raises:
MergeError: The values were not identical.


def element(self, using, value):

        return self._execute(Command.FIND_ELEMENT, {
            'using': using,
            'value': value
        })

Find an element in the current context.

Support:
Android iOS Web(WebView)

Args:
using(str): The element location strategy.
value(str): The value of the location strategy.

Returns:
WebElement Object.

Raises:
WebDriverException.


def filter_by_analysis_period(self, analysis_period):
    self._check_analysis_period(analysis_period)
    _filtered_data = self.filter_by_moys(analysis_period.moys)
    _filtered_data.header._analysis_period = analysis_period
    return _filtered_data

Filter a Data Collection based on an analysis period.

Args:
analysis period: A Ladybug analysis period

Return:
A new Data Collection with filtered data


def word_fts(self, word):

        return list(map(self.fts, self.segs(word)))

Return featural analysis of `word`

Args:
word (unicode):  one or more IPA segments

Returns:
list: list of lists (value, feature) tuples where each inner list
corresponds to a segment in `word`


def path_walk(
    p: tcod.path.AStar, recompute: bool
) -> Union[Tuple[int, int], Tuple[None, None]]:

    x = ffi.new("int *")
    y = ffi.new("int *")
    if lib.TCOD_path_walk(p._path_c, x, y, recompute):
        return x[0], y[0]
    return None, None

Return the next (x, y) point in a path, or (None, None) if it's empty.

When ``recompute`` is True and a previously valid path reaches a point
where it is now blocked, a new path will automatically be found.

Args:
p (AStar): An AStar instance.
recompute (bool): Recompute the path automatically.
Returns:
Union[Tuple[int, int], Tuple[None, None]]:
A single (x, y) point, or (None, None)


def apply_region_configs(env_config):

    new_config = env_config.copy()
    for region in env_config.get('regions', REGIONS):
        if isinstance(env_config.get('regions'), dict):
            region_specific_config = env_config['regions'][region]
            new_config[region] = dict(DeepChainMap(region_specific_config, env_config))
        else:
            new_config[region] = env_config.copy()
    LOG.debug('Region Specific Config:\n%s', new_config)
    return new_config

Override default env configs with region specific configs and nest
all values under a region

Args:
env_config (dict): The environment specific config.

Return:
dict: Newly updated dictionary with region overrides applied.


def read(self, face, *, alignment=1) -> bytes:

        return self.mglo.read(face, alignment)

Read a face from the cubemap texture.

Args:
face (int): The face to read.

Keyword Args:
alignment (int): The byte alignment of the pixels.


def get_merged_env(self, include_os=False):

        env = {}
        if include_os:
            env.update(os.environ.copy())
        for level in range(3):
            env.update(self.pipeline.data.env_list[level].copy())
        return env

Copying and merging environment variables.

Args:
include_os (bool): when true then include the environment variables (default: False)

Returns:
dict: environment variables as defined in the pipeline
(optional including system environment variables).


def set_permitted_ip(address=None, deploy=False):

    if not address:
        raise CommandExecutionError("Address option must not be empty.")

    ret = {}

    query = {'type': 'config',
             'action': 'set',
             'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/permitted-ip',
             'element': '<entry name=\'{0}\'></entry>'.format(address)}

    ret.update(__proxy__['panos.call'](query))

    if deploy is True:
        ret.update(commit())

    return ret

Add an IPv4 address or network to the permitted IP list.

CLI Example:

Args:
address (str): The IPv4 address or network to allow access to add to the Palo Alto device.

deploy (bool): If true then commit the full candidate configuration, if false only set pending change.

.. code-block:: bash

salt '*' panos.set_permitted_ip 10.0.0.1
salt '*' panos.set_permitted_ip 10.0.0.0/24
salt '*' panos.set_permitted_ip 10.0.0.1 deploy=True


def StatFS(self, path=None):

    if platform.system() == "Windows":
      raise RuntimeError("os.statvfs not available on Windows")

    local_path = client_utils.CanonicalPathToLocalPath(path or self.path)

    return os.statvfs(local_path)

Call os.statvfs for a given list of rdf_paths.

OS X and Linux only.

Note that a statvfs call for a network filesystem (e.g. NFS) that is
unavailable, e.g. due to no network, will result in the call blocking.

Args:
path: a Unicode string containing the path or None. If path is None the
value in self.path is used.

Returns:
posix.statvfs_result object
Raises:
RuntimeError: if called on windows


def _PromptUserForPartitionIdentifiers(self, volume_system, volume_identifiers):
    print_header = True
    while True:
        if print_header:
            self._PrintTSKPartitionIdentifiersOverview(volume_system, volume_identifiers)
            print_header = False
        lines = self._textwrapper.wrap(self._USER_PROMPT_TSK)
        self._output_writer.Write('\n'.join(lines))
        self._output_writer.Write('\n\nPartition identifiers: ')
        try:
            selected_volumes = self._ReadSelectedVolumes(volume_system, prefix='p')
            if (selected_volumes and (not set(selected_volumes).difference(volume_identifiers))):
                break
        except ValueError:
            pass
        self._output_writer.Write('\n')
        lines = self._textwrapper.wrap('Unsupported partition identifier(s), please try again or abort with Ctrl^C.')
        self._output_writer.Write('\n'.join(lines))
        self._output_writer.Write('\n\n')
    return selected_volumes

Prompts the user to provide partition identifiers.

Args:
volume_system (dfvfs.TSKVolumeSystem): volume system.
volume_identifiers (list[str]): volume identifiers including prefix.

Returns:
list[str]: selected volume identifiers including prefix or None.


def write_data(data):
    sorted_dict = sort_recursive(data)
    with open(_datafile, 'w') as file:
        _json.dump(sorted_dict, file, indent=2)

Write the data to the data.json file

Args:
data (dict): The updated data dictionary for Modis


def get_tensor_device(self, tensor_name):
    tensor = self._name_to_tensor(tensor_name)
    if isinstance(tensor, tf.Tensor):
        return tensor.device
    else:
        return None

The device of a tensor.

Note that only tf tensors have device assignments.

Args:
tensor_name: a string, name of a tensor in the graph.

Returns:
a string or None, representing the device name.


def _add_op_node(self, op, qargs, cargs, condition=None):
    node_properties = {'type': 'op', 'op': op, 'name': op.name, 'qargs': qargs, 'cargs': cargs, 'condition': condition}
    self._max_node_id += 1
    new_node = DAGNode(data_dict=node_properties, nid=self._max_node_id)
    self._multi_graph.add_node(new_node)
    self._id_to_node[self._max_node_id] = new_node

Add a new operation node to the graph and assign properties.

Args:
op (Instruction): the operation associated with the DAG node
qargs (list): list of quantum wires to attach to.
cargs (list): list of classical wires to attach to.
condition (tuple or None): optional condition (ClassicalRegister, int)


def set_load_handler(load_handler: Optional[Callable[..., Any]]) -> Optional[Callable[..., Any]]:
    if load_handler and (not callable(load_handler)):
        raise ValueError('`load_handler` must be callable.')
    global _LOAD_HANDLER
    old_handler = _LOAD_HANDLER
    _LOAD_HANDLER = load_handler
    return old_handler

Sets global load handler.

Args:
load_handler: A callable object that takes arbitrary arguments and returns
a value. `symbolic.load` method will pass through all arguments to this
handler and return its return value.

Returns:
Previous global load handler.


def request(self, batch: Sequence[Any], model: aiplatform.Endpoint, inference_args: Optional[dict[str, Any]]=None) -> Iterable[PredictionResult]:
    prediction = model.predict(instances=list(batch), parameters=inference_args)
    return utils._convert_to_result(batch, prediction.predictions, prediction.deployed_model_id)

Sends a prediction request to a Vertex AI endpoint containing batch
of inputs and matches that input with the prediction response from
the endpoint as an iterable of PredictionResults.

Args:
batch: a sequence of any values to be passed to the Vertex AI endpoint.
Should be encoded as the model expects.
model: an aiplatform.Endpoint object configured to access the desired
model.
inference_args: any additional arguments to send as part of the
prediction request.

Returns:
An iterable of Predictions.


def commutator(A, B=None):
    if B:
        return ((A * B) - (B * A))
    return (SPre(A) - SPost(A))

Commutator of `A` and `B`

If ``B != None``, return the commutator :math:`[A,B]`, otherwise return
the super-operator :math:`[A,\cdot]`.  The super-operator :math:`[A,\cdot]`
maps any other operator ``B`` to the commutator :math:`[A, B] = A B - B A`.

Args:
A: The first operator to form the commutator of.
B: The second operator to form the commutator of, or None.

Returns:
SuperOperator: The linear superoperator :math:`[A,\cdot]`


def _locate_point(nodes, degree, x_val, y_val):
    candidates = [(1.0, 1.0, 1.0, nodes)]
    for _ in six.moves.xrange((MAX_LOCATE_SUBDIVISIONS + 1)):
        next_candidates = []
        for candidate in candidates:
            update_locate_candidates(candidate, next_candidates, x_val, y_val, degree)
        candidates = next_candidates
    if (not candidates):
        return None
    (s_approx, t_approx) = mean_centroid(candidates)
    (s, t) = newton_refine(nodes, degree, x_val, y_val, s_approx, t_approx)
    actual = _surface_helpers.evaluate_barycentric(nodes, degree, ((1.0 - s) - t), s, t)
    expected = np.asfortranarray([x_val, y_val])
    if (not _helpers.vector_close(actual.ravel(order='F'), expected, eps=LOCATE_EPS)):
        (s, t) = newton_refine(nodes, degree, x_val, y_val, s, t)
    return (s, t)

r"""Locate a point on a surface.

.. note::

There is also a Fortran implementation of this function, which
will be used if it can be built.

Does so by recursively subdividing the surface and rejecting
sub-surfaces with bounding boxes that don't contain the point.
After the sub-surfaces are sufficiently small, uses Newton's
method to narrow in on the pre-image of the point.

Args:
nodes (numpy.ndarray): Control points for B |eacute| zier surface
(assumed to be two-dimensional).
degree (int): The degree of the surface.
x_val (float): The :math:`x`-coordinate of a point
on the surface.
y_val (float): The :math:`y`-coordinate of a point
on the surface.

Returns:
Optional[Tuple[float, float]]: The :math:`s` and :math:`t`
values corresponding to ``x_val`` and ``y_val`` or
:data:`None` if the point is not on the ``surface``.


def get_structure_by_formula(self, formula, **kwargs):

        structures = []
        sql = 'select file, sg from data where formula="- %s -"' % \
              Composition(formula).hill_formula
        text = self.query(sql).split("\n")
        text.pop(0)
        for l in text:
            if l.strip():
                cod_id, sg = l.split("\t")
                r = requests.get("http:
                                 % cod_id.strip())
                try:
                    s = Structure.from_str(r.text, fmt="cif", **kwargs)
                    structures.append({"structure": s, "cod_id": int(cod_id),
                                       "sg": sg})
                except Exception:
                    import warnings
                    warnings.warn("\nStructure.from_str failed while parsing CIF file:\n%s" % r.text)
                    raise

        return structures

Queries the COD for structures by formula. Requires mysql executable to
be in the path.

Args:
cod_id (int): COD id.
kwargs: All kwargs supported by
:func:`pymatgen.core.structure.Structure.from_str`.

Returns:
A list of dict of the format
[{"structure": Structure, "cod_id": cod_id, "sg": "P n m a"}]


def Substitute(self, pattern):
    if isinstance(pattern, bytes):
        substs = [re.escape(subst.encode('ascii')) for subst in self._substs]
        regex = re.compile(b'|'.join(substs))

        def Replacement(match):
            key = match.group(0).decode('ascii')
            return self._substs[key].encode('utf-8')
    elif isinstance(pattern, Text):
        substs = [re.escape(subst) for subst in self._substs]
        regex = re.compile('|'.join(substs))

        def Replacement(match):
            key = match.group(0)
            return self._substs[key]
    else:
        raise TypeError("Unexpected pattern type '{}'".format(type(pattern)))
    if (not substs):
        return pattern
    else:
        return regex.sub(Replacement, pattern)

Formats given pattern with this substitution environment.

A pattern can contain placeholders for variables (`%%foo%%`) and scopes
(`%%bar.baz%%`) that are replaced with concrete values in this substiution
environment (specified in the constructor).

Args:
pattern: A pattern with placeholders to substitute.

Returns:
A pattern with placeholders substituted with concrete values.


def assert_almost_equal(first, second, places=None, msg=None, delta=None, extras=None):
    _call_unittest_assertion(_pyunit_proxy.assertAlmostEqual, first, second, places=places, msg=msg, delta=delta, extras=extras)

Asserts that first is almost equal to second.

Fails if the two objects are unequal as determined by their difference
rounded to the given number of decimal places (default 7) and
comparing to zero, or by comparing that the difference between the two
objects is more than the given delta.
If the two objects compare equal then they automatically compare
almost equal.

Args:
first: The first value to compare.
second: The second value to compare.
places: How many decimal places to take into account for comparison.
Note that decimal places (from zero) are usually not the same
as significant digits (measured from the most significant digit).
msg: A string that adds additional info about the failure.
delta: Delta to use for comparison instead of decimal places.
extras: An optional field for extra information to be included in
test result.


def document(obj, doc):
    try:
        obj.__doc__ = doc
    except AttributeError:
        _EXTRA_DOCS[id(obj)] = doc

Adds a docstring to typealias by overriding the `__doc__` attribute.

Note: Overriding `__doc__` is only possible after python 3.7.

Args:
obj: Typealias object that needs to be documented.
doc: Docstring of the typealias. It should follow the standard pystyle
docstring rules.


def process_buffer(buffer, n_channels):
    samples = np.concatenate(buffer)
    if (n_channels > 1):
        samples = samples.reshape(((- 1), n_channels)).T
        samples = librosa.to_mono(samples)
    return samples

Merge the read blocks and resample if necessary.

Args:
buffer (list): A list of blocks of samples.
n_channels (int): The number of channels of the input data.

Returns:
np.array: The samples


def clip_action(action, space):
    if isinstance(space, gym.spaces.Box):
        return np.clip(action, space.low, space.high)
    elif isinstance(space, gym.spaces.Tuple):
        if (type(action) not in (tuple, list)):
            raise ValueError('Expected tuple space for actions {}: {}'.format(action, space))
        out = []
        for (a, s) in zip(action, space.spaces):
            out.append(clip_action(a, s))
        return out
    else:
        return action

Called to clip actions to the specified range of this policy.

Arguments:
action: Single action.
space: Action space the actions should be present in.

Returns:
Clipped batch of actions.


def market(self, accountID, **kwargs):
    return self.create(accountID, order=MarketOrderRequest(**kwargs))

Shortcut to create a Market Order in an Account

Args:
accountID : The ID of the Account
kwargs : The arguments to create a MarketOrderRequest

Returns:
v20.response.Response containing the results from submitting
the request


def _parse_schema(schema, method):

    if method and schema.get('readOnly', False):
        return _READONLY_PROPERTY

    if 'allOf' in schema:
        schema_ = copy.deepcopy(schema['allOf'][0])
        for x in schema['allOf'][1:]:
            _dict_merge(schema_, x)

        return _parse_schema(schema_, method)

    if 'oneOf' in schema:

        return _parse_schema(schema['oneOf'][0], method)

    if 'enum' in schema:

        return schema['enum'][0]

    schema_type = schema.get('type', 'object')

    if schema_type == 'array':

        if 'oneOf' in schema['items']:
            return [
                _parse_schema(x, method) for x in schema['items']['oneOf']]

        return [_parse_schema(schema['items'], method)]

    if schema_type == 'object':
        if method and all(v.get('readOnly', False)
                          for v in schema['properties'].values()):
            return _READONLY_PROPERTY

        results = []
        for name, prop in schema.get('properties', {}).items():
            result = _parse_schema(prop, method)
            if result != _READONLY_PROPERTY:
                results.append((name, result))

        return collections.OrderedDict(results)

    if (schema_type, schema.get('format')) in _TYPE_MAPPING:
        return _TYPE_MAPPING[(schema_type, schema.get('format'))]

    return _TYPE_MAPPING[(schema_type, None)]

Convert a Schema Object to a Python object.

Args:
schema: An ``OrderedDict`` representing the schema object.


def put(self, rid, data, raise_on_error=True):
    response_data = None
    headers = {'Content-Type': 'application/json', 'DB-Method': 'PUT'}
    url = '/v2/exchange/db/{}/{}/{}'.format(self.domain, self.data_type, rid)
    r = self.tcex.session.post(url, json=data, headers=headers)
    self.tcex.log.debug('datastore put status code: {}'.format(r.status_code))
    if (r.ok and ('application/json' in r.headers.get('content-type', ''))):
        response_data = r.json()
    else:
        error = (r.text or r.reason)
        self.tcex.handle_error(805, ['put', r.status_code, error], raise_on_error)
    return response_data

Update the data for the provided Id.

Args:
rid (str): The record identifier.
data (dict): A search query
raise_on_error (bool): If True and not r.ok this method will raise a RunTimeError.

Returns:
object : Python request response.


def __init__(self, uri='mongodb:

        self.sample_collection = 'samples'
        self.worker_cap = worker_cap
        self.samples_cap = samples_cap

        self.database_name = database
        self.uri = 'mongodb:
        self.mongo = pymongo.MongoClient(self.uri, use_greenlets=True)
        self.database = self.mongo.get_default_database()

        self.gridfs_handle = gridfs.GridFS(self.database)

        self.last_ops_run = time.time()
        self.periodic_ops()

        print '\t- WorkBench DataStore connected: %s:%s' % (self.uri, self.database_name)

Initialization for the Workbench data store class.

Args:
uri: Connection String for DataStore backend.
database: Name of database.
worker_cap: MBs in the capped collection.
samples_cap: MBs of sample to be stored.


def __init__(self, output_writer, tool_name):

    super(StatusView, self).__init__()
    self._artifact_filters = None
    self._filter_file = None
    self._have_ansi_support = not win32console
    self._mode = self.MODE_WINDOW
    self._output_writer = output_writer
    self._source_path = None
    self._source_type = None
    self._stdout_output_writer = isinstance(
        output_writer, tools.StdoutOutputWriter)
    self._storage_file_path = None
    self._tool_name = tool_name

    if win32console:
      kernel32 = ctypes.windll.kernel32
      stdout_handle = kernel32.GetStdHandle(self._WINAPI_STD_OUTPUT_HANDLE)
      result = kernel32.SetConsoleMode(
          stdout_handle, self._WINAPI_ANSI_CONSOLE_MODE)
      self._have_ansi_support = result != 0

Initializes a status view.

Args:
output_writer (OutputWriter): output writer.
tool_name (str): namd of the tool.


def _tzinfome(tzinfo):

  if not isinstance(tzinfo, datetime.tzinfo):
    try:
      tzinfo = pytz.timezone(tzinfo)
      assert tzinfo.zone in pytz.all_timezones
    except AttributeError:
      raise pytz.UnknownTimeZoneError("Unknown timezone! %s" % tzinfo)
  return tzinfo

Gets a tzinfo object from a string.

Args:
tzinfo: A string (or string like) object, or a datetime.tzinfo object.

Returns:
An datetime.tzinfo object.

Raises:
UnknownTimeZoneError: If the timezone given can't be decoded.


def add(self, name, value, bitmask=DEFMASK):
    _add_enum_member(self._eid, name, value, bitmask)

Add an enum member

Args:
name: Name of the member
value: value of the member
bitmask: bitmask. Only use if enum is a bitfield.


def _test_tensorflow_vs_numpy(self, x_np):
    y_np = self._total_variation_np(x_np)
    self._test(x_np, y_np)

Test the TensorFlow implementation against a numpy implementation.

Args:
x_np: Numpy array with 3 or 4 dimensions.


def movies_in_theaters(self, **kwargs):
    path = self._get_path('movies_in_theaters')
    response = self._GET(path, kwargs)
    self._set_attrs_to_values(response)
    return response

Gets the movies currently in theaters from the API.

Args:
page_limit (optional): number of movies to show per page, default=16
page (optional): results page number, default=1
country (optional): localized data for selected country, default="us"

Returns:
A dict respresentation of the JSON returned from the API.


def compiler(name):
    pinfo = __get_paths()
    _compiler = local[name]
    _compiler = _compiler.setenv(PATH=pinfo['path'], LD_LIBRARY_PATH=pinfo['ld_library_path'])
    return _compiler

Get a usable clang++ plumbum command.

This searches for a usable clang++ in the llvm binary path

Returns:
plumbum Command that executes clang++


def AddMonths(start_date, months):

  current_date = start_date
  i = 0
  while i < months:
    month_days = calendar.monthrange(current_date.year, current_date.month)[1]
    current_date += timedelta(days=month_days)
    i += 1
  return current_date

A simple convenience utility for adding months to a given start date.

This increments the months by adding the number of days in the current month
to the current month, for each month.

Args:
start_date: date The date months are being added to.
months: int The number of months to add.

Returns:
A date equal to the start date incremented by the given number of months.


def update_non_slot(self, colocate_with, fn, args=(), kwargs=None, group=True):
    _require_cross_replica_or_default_context_extended(self)
    if kwargs is None:
        kwargs = {}
    fn = autograph.tf_convert(fn, autograph_ctx.control_status_ctx(), convert_by_default=False)
    with self._container_strategy().scope():
        return self._update_non_slot(colocate_with, fn, args, kwargs, group)

Runs `fn(*args, **kwargs)` on `colocate_with` devices.

Used to update non-slot variables.

DEPRECATED: TF 1.x ONLY.

Args:
colocate_with: Devices returned by `non_slot_devices()`.
fn: Function to execute.
args: Tuple or list. Positional arguments to pass to `fn()`.
kwargs: Dict with keyword arguments to pass to `fn()`.
group: Boolean. Defaults to True. If False, the return value will be
unwrapped.

Returns:
Return value of `fn`, possibly merged across devices.