def _live_tensors(f, attr_name='inputs'):
    node, _ = parser.parse_entity(f, ())
    entity_info = transformer.EntityInfo(name=f.__name__, source_code=None, source_file=None, future_features=(), namespace=sys.modules[f.__module__].__dict__)
    ctx = transformer.Context(entity_info, None, None)
    graphs = cfg.build(node)
    node = qual_names.resolve(node)
    node = activity.resolve(node, ctx, None)
    node = reaching_fndefs.resolve(node, ctx, graphs)
    node = liveness.resolve(node, ctx, graphs)
    op_arg_name = anno.getanno(node.args.args[0], anno.Basic.QN)
    op_inputs_outputs_name = qual_names.QN(op_arg_name, attr=attr_name)
    special_tracker = _SubscriptUseTracker(ctx, (op_inputs_outputs_name,))
    node = special_tracker.visit(node)
    live_vars_in = anno.getanno(node.body[0], anno.Static.LIVE_VARS_IN)
    inputs_outputs_used_qns = set()
    for v in special_tracker.complex_reads:
        if v == op_inputs_outputs_name:
            return _ALL
    for v in live_vars_in:
        if v in special_tracker.reads:
            if v.has_subscript() and v.parent == op_inputs_outputs_name:
                inputs_outputs_used_qns.add(v)
            elif v == op_inputs_outputs_name:
                return _ALL
    function_calls_tracker = _FunctionCallsTracker(ctx, op_arg_name)
    node = function_calls_tracker.visit(node)
    input_output_indices = set()
    for called_f in function_calls_tracker.calls:
        child_indices = _live_tensors(called_f, attr_name=attr_name)
        if child_indices is _ALL:
            return _ALL
        input_output_indices |= child_indices
    for v in inputs_outputs_used_qns:
        assert v.has_subscript()
        _, subscript = v.qn
        if not subscript.is_simple():
            return _ALL
        subscript_val, = subscript.qn
        if not isinstance(subscript_val, qual_names.Literal) and (not isinstance(subscript_val.value, int)):
            return _ALL
        input_output_indices.add(subscript_val.value)
    return input_output_indices

Returns the indices of the used inputs.

Note: This currently only handles direct index accesses e.g. op.inputs[1].
If the function has slicing or list comprehension on attr_name then returns
_ALL. This ensure that this is correct even if inefficient.

Args:
f: A grad function, taking the op as first argument.
attr_name: op attr to track. "inputs" or "outputs".

Returns:
Either one of:
* set of integers representing individual indices of inputs used
* the value _ALL, if indices are used but cannot be determined which
* empty set, if no inputs are used


def run_std_server(self):
    config = tf.estimator.RunConfig()
    server = tf.train.Server(config.cluster_spec, job_name=config.task_type, task_index=config.task_id, protocol=config.protocol)
    server.join()

Starts a TensorFlow server and joins the serving thread.

Typically used for parameter servers.

Raises:
ValueError: if not enough information is available in the estimator's
config to create a server.


def get_extended_surface_mesh(self, repeat=(5, 5, 1)):
    surf_str = Structure.from_sites(self.surface_sites)
    surf_str.make_supercell(repeat)
    return surf_str

Gets an extended surface mesh for to use for adsorption
site finding by constructing supercell of surface sites

Args:
repeat (3-tuple): repeat for getting extended surface mesh


def tag(self, resource_id):

        self._request_uri = '{}/{}'.format(self._request_uri, self.tcex.safetag(resource_id))

Update the request URI to include the Tag for specific retrieval.

Args:
resource_id (string): The tag name.


def AddMemberDefinition(self, member_definition):

    self._byte_size = None
    self.members.append(member_definition)

    if self.sections:
      section_definition = self.sections[-1]
      section_definition.members.append(member_definition)

Adds a member definition.

Args:
member_definition (DataTypeDefinition): member data type definition.


def jt_aggregate(func, is_create=False, has_pk=False):

    def helper(kwargs, obj):
        'The helper function preceding actual function that aggregates\n        unified jt fields.\n        '
        unified_job_template = None
        for item in UNIFIED_JT:
            if (kwargs.get(item, None) is not None):
                jt_id = kwargs.pop(item)
                if (unified_job_template is None):
                    unified_job_template = (item, jt_id)
                else:
                    raise exc.UsageError('More than one unified job template fields provided, please tighten your criteria.')
        if (unified_job_template is not None):
            kwargs['unified_job_template'] = unified_job_template[1]
            obj.identity = tuple((list(obj.identity) + ['unified_job_template']))
            return '/'.join([UNIFIED_JT[unified_job_template[0]], str(unified_job_template[1]), 'schedules/'])
        elif is_create:
            raise exc.UsageError('You must provide exactly one unified job template field during creation.')

    def decorator_without_pk(obj, *args, **kwargs):
        old_endpoint = obj.endpoint
        new_endpoint = helper(kwargs, obj)
        if is_create:
            obj.endpoint = new_endpoint
        result = func(obj, *args, **kwargs)
        obj.endpoint = old_endpoint
        return result

    def decorator_with_pk(obj, pk=None, *args, **kwargs):
        old_endpoint = obj.endpoint
        new_endpoint = helper(kwargs, obj)
        if is_create:
            obj.endpoint = new_endpoint
        result = func(obj, *args, pk=pk, **kwargs)
        obj.endpoint = old_endpoint
        return result
    decorator = (decorator_with_pk if has_pk else decorator_without_pk)
    for item in CLICK_ATTRS:
        setattr(decorator, item, getattr(func, item, []))
    decorator.__doc__ = func.__doc__
    return decorator

Decorator to aggregate unified_jt-related fields.

Args:
func: The CURD method to be decorated.
is_create: Boolean flag showing whether this method is create.
has_pk: Boolean flag showing whether this method uses pk as argument.

Returns:
A function with necessary click-related attributes whose keyworded
arguments are aggregated.

Raises:
exc.UsageError: Either more than one unified jt fields are
provided, or none is provided when is_create flag is set.


def mount_share_at_path(share_path, mount_path):
    sh_url = CFURLCreateWithString(None, share_path, None)
    mo_url = CFURLCreateWithString(None, mount_path, None)
    open_options = {NetFS.kNAUIOptionKey: NetFS.kNAUIOptionNoUI}
    mount_options = {NetFS.kNetFSAllowSubMountsKey: True, NetFS.kNetFSMountAtMountDirKey: True}
    (result, output) = NetFS.NetFSMountURLSync(sh_url, mo_url, None, None, open_options, mount_options, None)
    if (result != 0):
        raise Exception(('Error mounting url "%s" at path "%s": %s' % (share_path, mount_path, output)))
    return str(output[0])

Mounts a share at the specified path

Args:
share_path: String URL with all auth info to connect to file share.
mount_path: Path to mount share on.

Returns:
The mount point or raises an error


def _from_string(cls, serialized):

        try:
            usage_key, aside_type = _split_keys_v1(serialized)
            return cls(UsageKey.from_string(usage_key), aside_type)
        except ValueError as exc:
            raise InvalidKeyError(cls, exc.args)

Return an instance of `cls` parsed from its `serialized` form.

Args:
cls: The :class:`OpaqueKey` subclass.
serialized (unicode): A serialized :class:`OpaqueKey`, with namespace already removed.

Raises:
InvalidKeyError: Should be raised if `serialized` is not a valid serialized key
understood by `cls`.


def get_raw_mempool(self, id=None, endpoint=None):

        return self._call_endpoint(GET_RAW_MEMPOOL, id=id, endpoint=endpoint)

Returns the tx that are in the memorypool of the endpoint
Args:
id: (int, optional) id to use for response tracking
endpoint: (RPCEndpoint, optional) endpoint to specify to use
Returns:
json object of the result or the error encountered in the RPC call


def delete_folder(self, folder_id, recursive=True):

        return self.__request("DELETE", "folders/%s" % (folder_id, ),
                        querystring={'recursive': unicode(recursive).lower()})

Delete an existing folder

Args:
folder_id (int): ID of the folder to delete.
recursive (bool): Delete all subfolder if True.

Returns:
dict. Response from Box.

Raises:
BoxError: An error response is returned from Box (status_code >= 400).

BoxHttpResponseError: Response from Box is malformed.

requests.exceptions.*: Any connection related problem.


def setup(template, version=None):

    temple.check.is_git_ssh_path(template)
    temple.check.not_in_git_repo()

    repo_path = temple.utils.get_repo_path(template)
    msg = (
        'You will be prompted for the parameters of your new project.'
        ' Please read the docs at https:
    ).format(repo_path)
    print(msg)

    cc_repo_dir, config = temple.utils.get_cookiecutter_config(template, version=version)

    if not version:
        with temple.utils.cd(cc_repo_dir):
            ret = temple.utils.shell('git rev-parse HEAD', stdout=subprocess.PIPE)
            version = ret.stdout.decode('utf-8').strip()

    _generate_files(repo_dir=cc_repo_dir, config=config, template=template, version=version)

Sets up a new project from a template

Note that the `temple.constants.TEMPLE_ENV_VAR` is set to 'setup' during the duration
of this function.

Args:
template (str): The git SSH path to a template
version (str, optional): The version of the template to use when updating. Defaults
to the latest version


def __init__(self, name=None):
    self._name = name
    self._items = []

Menu constructor.

Args:
name: (str or None) name of this menu.


def _write(self, save_path, options=None):
    write_start_time = time.time()
    if not self._initialized:
        self._ensure_initialized()
    else:
        self._queue.join()
        self._copy_to_cpu()
    self._check_async_thread_error()
    context.async_wait()
    self._save_file_prefix = save_path
    self._use_checkpoint_save = False
    self._checkpoint_options = copy.copy(options) if options else None
    if self._checkpoint_options:
        self._checkpoint_options.experimental_enable_async_checkpoint = False
    self._queue.put(True)
    write_end_time = time.time()
    metrics.AddCheckpointWriteDuration(api_label=_ASYNC_CHECKPOINT, microseconds=_get_duration_microseconds(write_start_time, write_end_time))
    return save_path

Save the checkpointed variables.

This method has exactly the same logic as save(), except it does not
increment the underlying save_counter, which is done by the caller, e.g.,
CheckpointManager.

Args:
save_path: The file prefix of the checkpoint file.
options: Optional CheckpointOption instance.

Returns:
The full path of the checkpoint file.


def get_field(self, field_type):

        for field in self.oxm_match_fields:
            if field.oxm_field == field_type:
                return field.oxm_value

        return None

Return the value for the 'field_type' field in oxm_match_fields.

Args:
field_type (~pyof.v0x04.common.flow_match.OxmOfbMatchField,
~pyof.v0x04.common.flow_match.OxmMatchFields):
The type of the OXM field you want the value.

Returns:
The integer number of the 'field_type' if it exists. Otherwise
return None.


def get_bond_order(sp1, sp2, dist, tol=0.2, default_bl=None):
    all_lengths = obtain_all_bond_lengths(sp1, sp2, default_bl)
    lengths_list = ([(all_lengths[1] * (1 + tol))] + [all_lengths[(idx + 1)] for idx in range(len(all_lengths))])
    trial_bond_order = 0
    while (trial_bond_order < len(lengths_list)):
        if (lengths_list[trial_bond_order] < dist):
            if (trial_bond_order == 0):
                return trial_bond_order
            else:
                low_bl = lengths_list[trial_bond_order]
                high_bl = lengths_list[(trial_bond_order - 1)]
                return (trial_bond_order - ((dist - low_bl) / (high_bl - low_bl)))
        trial_bond_order += 1
    if (dist < (lengths_list[(- 1)] * (1 - tol))):
        warnings.warn(('%.2f angstrom distance is too short for %s and %s' % (dist, sp1, sp2)))
    return (trial_bond_order - 1)

Calculate the bond order given the distance of 2 species

Args:
sp1 (Specie): First specie.
sp2 (Specie): Second specie.
dist: Their distance in angstrom
tol (float): Relative tolerance to test. Basically, the code
checks if the distance between the sites is larger than
(1 + tol) * the longest bond distance or smaller than
(1 - tol) * the shortest bond distance to determine if
they are bonded or the distance is too short.
Defaults to 0.2.
default_bl: If a particular type of bond does not exist, use this
bond length (bond order = 1). If None, a ValueError will be thrown.

Returns:
Float value of bond order. For example, for C-C bond in benzene,
return 1.7.


def fit(self, X):

        LOGGER.debug('Fitting Gaussian Copula')
        column_names = self.get_column_names(X)
        distribution_class = import_object(self.distribution)

        for column_name in column_names:
            self.distribs[column_name] = distribution_class()
            column = self.get_column(X, column_name)
            self.distribs[column_name].fit(column)

        self.covariance = self._get_covariance(X)
        self.fitted = True

Compute the distribution for each variable and then its covariance matrix.

Args:
X(numpy.ndarray or pandas.DataFrame): Data to model.

Returns:
None


def trace_stop(self):

        cmd = enums.JLinkTraceCommand.STOP
        res = self._dll.JLINKARM_TRACE_Control(cmd, 0)
        if (res == 1):
            raise errors.JLinkException('Failed to stop trace.')
        return None

Stops collecting trace data.

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

Returns:
``None``


def events_from_multifile_logdir(logdir):
    assert gfile.Exists(logdir)
    files = [file for file in gfile.ListDirectory(logdir) if 'tfevents' in file]
    return {file: events_from_file(os.path.join(logdir, file)) for file in files}

Returns map of filename to events for all `tfevents` files in the logdir.

Args:
logdir: The directory from which to load events.

Returns:
A dict mapping from relative filenames to lists of tf.Event protos.

Raises:
AssertionError: If logdir does not contain exactly one file.


def _restore_from_tensors(self, restored_tensors):
    raise NotImplementedError

Restores checkpointed values to this `Trackable`.

Please see the documentation for `Trackable._serialize_to_tensors`.

Args:
restored_tensors: A dictionary mapping names to tensors. The keys to this
dictionary matches the names passed to _serialize_to_tensors.

Returns:
An op that runs the restoration.


def generate_defect_structure(self, supercell=(1, 1, 1)):

        defect_structure = self.bulk_structure.copy()
        defect_structure.make_supercell(supercell)

        struct_for_defect_site = Structure( self.bulk_structure.copy().lattice,
                                             [self.site.specie],
                                             [self.site.frac_coords],
                                             to_unit_cell=True)
        struct_for_defect_site.make_supercell(supercell)
        defect_site = struct_for_defect_site[0]

        poss_deflist = sorted(
            defect_structure.get_sites_in_sphere(defect_site.coords, 2, include_index=True), key=lambda x: x[1])
        defindex = poss_deflist[0][2]
        defect_structure.remove_sites([defindex])
        defect_structure.set_charge(self.charge)
        return defect_structure

Returns Defective Vacancy structure, decorated with charge
Args:
supercell (int, [3x1], or [[]] (3x3)): supercell integer, vector, or scaling matrix


def adversary(self, name, **kwargs):
    group_obj = Adversary(name, **kwargs)
    return self._group(group_obj)

Add Adversary data to Batch object.

Args:
name (str): The name for this Group.
date_added (str, kwargs): The date timestamp the Indicator was created.
xid (str, kwargs): The external id for this Group.

Returns:
obj: An instance of Adversary.


def in_top_k(predictions, targets, k):
    return nn.in_top_k(predictions, targets, k)

Returns whether the `targets` are in the top `k` `predictions`.

Args:
predictions: A tensor of shape `(batch_size, classes)` and type `float32`.
targets: A 1D tensor of length `batch_size` and type `int32` or `int64`.
k: An `int`, number of top elements to consider.

Returns:
A 1D tensor of length `batch_size` and type `bool`.
`output[i]` is `True` if `predictions[i, targets[i]]` is within top-`k`
values of `predictions[i]`.


def status(self, **kwargs):

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

Get the status of the geo node.

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

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

Returns:
dict: The status of the geo node


def forward(self, inputs: torch.Tensor):
    if 'batch' in self.norm_mlp.lower():
        inputs_reshaped = torch.reshape(inputs, (inputs.shape[0] * inputs.shape[1], inputs.shape[2], inputs.shape[3]))
        inputs_reshaped = self.norm(inputs_reshaped)
        inputs = torch.reshape(inputs_reshaped, inputs.shape)
    else:
        inputs = self.norm(inputs)
    return inputs

Args:
inputs (`torch.Tensor` of shape `((batch_size, num_channels, num_patches, d_model))`):
Input to the normalization layer.
Returns:
`torch.Tensor` of shape `((batch_size, num_channels, num_patches, d_model))`


def get_passage(self, offset: int) -> BioCPassage or None:

        for passage in self.passages:
            if passage.offset == offset:
                return passage
        return None

Gets passage

Args:
offset: passage offset

Return:
the passage with specified offset


def banner_print(msg, color='', width=60, file=sys.stdout, logger=_LOG):
    if logger:
        logger.debug(ANSI_ESC_RE.sub('', msg))
    if CLI_QUIET:
        return
    lpad = (int(math.ceil((((width - _printed_len(msg)) - 2) / 2.0))) * '=')
    rpad = (int(math.floor((((width - _printed_len(msg)) - 2) / 2.0))) * '=')
    file.write('{sep}{color}{lpad} {msg} {rpad}{reset}{sep}{sep}'.format(sep=_linesep_for_file(file), color=color, lpad=lpad, msg=msg, rpad=rpad, reset=colorama.Style.RESET_ALL))
    file.flush()

Print the message as a banner with a fixed width.

Also logs the message (un-bannered) to the given logger at the debug level.

Args:
msg: The message to print.
color: Optional colorama color string to be applied to the message. You can
concatenate colorama color strings together in order to get any set of
effects you want.
width: Total width for the resulting banner.
file: A file object to which the banner text will be written. Intended for
use with CLI output file objects like sys.stdout.
logger: A logger to use, or None to disable logging.

Example:

>>> banner_print('Foo Bar Baz')

======================== Foo Bar Baz =======================


def get_items_by_ids(self, item_ids, item_type=None):
    urls = [urljoin(self.item_url, f'{i}.json') for i in item_ids]
    result = self._run_async(urls=urls)
    items = [Item(r) for r in result if r]
    if item_type:
        return [item for item in items if (item.item_type == item_type)]
    else:
        return items

Given a list of item ids, return all the Item objects

Args:
item_ids (obj): List of item IDs to query
item_type (str): (optional) Item type to filter results with

Returns:
List of `Item` objects for given item IDs and given item type


def remove(self, block_id):
    with self._mutex:
        entry = self._block_map[block_id]
        self._queue.remove(entry)

Remove a Processing Block from the queue.

Args:
block_id (str):


def _start_services_on_ads(ads):

    running_ads = []
    for ad in ads:
        running_ads.append(ad)
        start_logcat = not getattr(ad, KEY_SKIP_LOGCAT,
                                   DEFAULT_VALUE_SKIP_LOGCAT)
        try:
            ad.services.register(
                SERVICE_NAME_LOGCAT, logcat.Logcat, start_service=start_logcat)
        except Exception:
            is_required = getattr(ad, KEY_DEVICE_REQUIRED,
                                  DEFAULT_VALUE_DEVICE_REQUIRED)
            if is_required:
                ad.log.exception('Failed to start some services, abort!')
                destroy(running_ads)
                raise
            else:
                ad.log.exception('Skipping this optional device because some '
                                 'services failed to start.')

Starts long running services on multiple AndroidDevice objects.

If any one AndroidDevice object fails to start services, cleans up all
existing AndroidDevice objects and their services.

Args:
ads: A list of AndroidDevice objects whose services to start.


def isconst(cls, val):

        return isinstance(val, string_types) and \
               ((len(val) == 7 and val[0] == "

Whether the value is a string color literal.

Checks for a well-formed hexadecimal color value or a named color.

Args:
val (str) : the value to check

Returns:
True, if the value is a string color literal


def get_location(self, locations=None):
    countries = self.data.get('groups', None)
    if (not countries):
        return list()
    return [Locations.get_location_from_HDX_code(x['name'], locations=locations, configuration=self.configuration) for x in countries]

Return the dataset's location

Args:
locations (Optional[List[str]]): Valid locations list. Defaults to list downloaded from HDX.

Returns:
List[str]: list of locations or [] if there are none


def _update_seek(self, offset, whence):

        with self._seek_lock:
            if whence == SEEK_SET:
                self._seek = offset
            elif whence == SEEK_CUR:
                self._seek += offset
            elif whence == SEEK_END:
                self._seek = offset + self._size
            else:
                raise ValueError('whence value %s unsupported' % whence)
        return self._seek

Update seek value.

Args:
offset (int): Offset.
whence (int): Whence.

Returns:
int: Seek position.


def check_network_connection(server, port):

    logger = logging.getLogger(__name__)
    logger.debug("Checking network connection to server '%s'...", server)
    try:

        host = socket.gethostbyname(server)

        sock = socket.create_connection((host, port), 2)
        sock.close()
    except Exception:
        logger.debug("Network connection not working")
        return False
    logger.debug("Network connection working")
    return True

Checks if jasper can connect a network server.
Arguments:
server -- (optional) the server to connect with (Default:
"www.google.com")
Returns:
True or False


def Process(self, path):
    path = re.sub(self.SYSTEMROOT_RE, '%systemroot%', path, count=1)
    path = re.sub(self.SYSTEM32_RE, '%systemroot%\\\\system32', path, count=1)
    matches_iter = self.WIN_ENVIRON_REGEX.finditer(path)
    var_names = set((m.group(1).lower() for m in matches_iter))
    results = [path]
    for var_name in var_names:
        try:
            (var_regex, var_value) = self.vars_map[var_name]
        except KeyError:
            continue
        if isinstance(var_value, string_types):
            replacements = [var_value]
        else:
            replacements = var_value
        processed_results = []
        for result in results:
            for repl in replacements:
                processed_results.append(var_regex.sub((lambda _: repl), result))
        results = processed_results
    return results

Processes a given path.

Args:
path: Path (as a string) to post-process.

Returns:
A list of paths with environment variables replaced with their
values. If the mapping had a list of values for a particular variable,
instead of just one value, then all possible replacements will be
returned.


def getConParams(virtualhost):
    return pika.ConnectionParameters(host=settings.RABBITMQ_HOST, port=int(settings.RABBITMQ_PORT), virtual_host=virtualhost, credentials=pika.PlainCredentials(settings.RABBITMQ_USER_NAME, settings.RABBITMQ_USER_PASSWORD))

Connection object builder.

Args:
virtualhost (str): selected virtualhost in rabbitmq

Returns:
pika.ConnectionParameters: object filled by `constants` from
:class:`edeposit.amqp.settings`.


def __init__(
        self,
        function_approximator,
        batch_size=4,
        map_size=(10, 10),
        memory_num=4,
        repeating_penalty=0.5,
        enemy_num=2,
        enemy_init_dist=5
    ):

        self.__map_arr = self.__create_map(map_size)
        self.__agent_pos = self.START_POS

        self.__enemy_num = enemy_num
        self.__enemy_pos_list = [None] * enemy_num
        self.__enemy_init_dist = enemy_init_dist
        self.__create_enemy(self.__map_arr)

        self.__reward_list = []
        self.__route_memory_list = []
        self.__memory_num = memory_num
        self.__repeating_penalty = repeating_penalty

        self.__batch_size = batch_size

        super().__init__(function_approximator)
        self.__inferencing_flag = False

Init.

Args:
function_approximator:  is-a `FunctionApproximator`.
map_size:               Size of map.
memory_num:             The number of step of agent's memory.
repeating_penalty:      The value of penalty in the case that agent revisit.
enemy_num:              The number of enemies.
enemy_init_dist:        Minimum euclid distance of initial position of agent and enemies.


def __init__(self, app_id=None):

        self.valid = Valid(app_id)
        self.request = RequestBody()
        self.response = ResponseBody()
        self.logic = dict()
        self.launch = self.register('LaunchRequest')
        self.intent = self.register
        self.session_ended = self.register('SessionEndedRequest')

Inits a Skill class with proxy request and response.

Args:
app_id: str, default None. Skill application ID, declare
to validate against application ID in the request.


def __init__(self, func=None, *, animation_gen, step=.1):

        if not callable(func):
            raise TypeError("argument 'func' for {!r} must be "
                            "callable".format(self.__class__.__name__))
        self._raise_if_annotated(func)
        self._func = func
        self._animation_gen = animation_gen
        self._step = step
        functools.update_wrapper(self, func)

Constructor.

Args:
func: If Animate is used without kwargs, then the
function it decorates is passed in here. Otherwise, this is None.
This argument should NOT be given directly via keyword assignment.
animation_gen: A generator that yields strings for the animation.
step: Seconds between each animation frame.


def make_prior(num_topics, initial_value):

    def _softplus_inverse(x):
        return np.log(np.expm1(x))
    logit_concentration = tf.compat.v1.get_variable('logit_concentration', shape=[1, num_topics], initializer=tf.compat.v1.initializers.constant(_softplus_inverse(initial_value)))
    concentration = _clip_dirichlet_parameters(tf.nn.softplus(logit_concentration))

    def prior():
        return tfd.Dirichlet(concentration=concentration, name='topics_prior')
    prior_variables = [logit_concentration]
    return (prior, prior_variables)

Create the prior distribution.

Args:
num_topics: Number of topics.
initial_value: The starting value for the prior parameters.

Returns:
prior: A `callable` that returns a `tf.distribution.Distribution`
instance, the prior distribution.
prior_variables: A `list` of `Variable` objects, the trainable parameters
of the prior.


def __init__(self, environ, base_paths=None):

    self.headers = util.get_headers_from_environ(environ)
    self.http_method = environ['REQUEST_METHOD']
    self.url_scheme = environ['wsgi.url_scheme']
    self.server = environ['SERVER_NAME']
    self.port = environ['SERVER_PORT']
    self.path = environ['PATH_INFO']
    self.request_uri = environ.get('REQUEST_URI')
    if self.request_uri is not None and len(self.request_uri) < len(self.path):
      self.request_uri = None
    self.query = environ.get('QUERY_STRING')
    self.body = environ['wsgi.input'].read()
    if self.body and self.headers.get('CONTENT-ENCODING') == 'gzip':

      try:
        self.body = zlib.decompress(self.body, 16 + zlib.MAX_WBITS)
      except zlib.error:
        pass
    if _METHOD_OVERRIDE in self.headers:

      self.http_method = self.headers[_METHOD_OVERRIDE]
      del self.headers[_METHOD_OVERRIDE]
    self.source_ip = environ.get('REMOTE_ADDR')
    self.relative_url = self._reconstruct_relative_url(environ)

    if not base_paths:
      base_paths = set()
    elif isinstance(base_paths, list):
      base_paths = set(base_paths)

    for base_path in base_paths:
      if self.path.startswith(base_path):
        self.path = self.path[len(base_path):]
        if self.request_uri is not None:
          self.request_uri = self.request_uri[len(base_path):]
        self.base_path = base_path
        break
    else:
      raise ValueError('Invalid request path: %s' % self.path)

    if self.query:
      self.parameters = urlparse.parse_qs(self.query, keep_blank_values=True)
    else:
      self.parameters = {}
    self.body_json = self._process_req_body(self.body) if self.body else {}
    self.request_id = None

    if isinstance(self.body_json, list):
      if len(self.body_json) != 1:
        _logger.warning('Batch requests with more than 1 element aren\'t '
                        'supported in devappserver2.  Only the first element '
                        'will be handled.  Found %d elements.',
                        len(self.body_json))
      else:
        _logger.info('Converting batch request to single request.')
      self.body_json = self.body_json[0]
      self.body = json.dumps(self.body_json)
      self._is_batch = True
    else:
      self._is_batch = False

Constructor.

Args:
environ: An environ dict for the request as defined in PEP-333.

Raises:
ValueError: If the path for the request is invalid.


def tag(self, name, formatter=None):

        tag = Tag(name, formatter)
        for tag_data in self._tags:
            if tag_data.name == name:
                tag = tag_data
                break
        else:
            self._tags.append(tag)
        return tag

Return instance of Tag.

Args:
name (str): The value for this tag.
formatter (method, optional): A method that take a tag value and returns a
formatted tag.

Returns:
obj: An instance of Tag.


def ticker(self, contract: Contract) -> Ticker:

        return self.wrapper.tickers.get(id(contract))

Get ticker of the given contract. It must have been requested before
with reqMktData with the same contract object. The ticker may not be
ready yet if called directly after :meth:`.reqMktData`.

Args:
contract: Contract to get ticker for.


def owned_by(self, owner, also_check_group=False):
    if also_check_group:
        return ((self.owner == owner) and (self.group == owner))
    else:
        return (self.owner == owner)

Checks if the specified user or user and group own the file.

Args:
owner (str): the user (or group) name for which we ask about ownership
also_check_group (bool): if set to True, both user owner and group owner checked
if set to False, only user owner checked

Returns:
bool: True if owner of the file is the specified owner


def get_mock_ads(num):
    ads = []
    for i in range(num):
        ad = mock.MagicMock(name='AndroidDevice', serial=str(i), h_port=None)
        ad.skip_logcat = False
        ads.append(ad)
    return ads

Generates a list of mock AndroidDevice objects.

The serial number of each device will be integer 0 through num - 1.

Args:
num: An integer that is the number of mock AndroidDevice objects to
create.


def _request(self, method, resource_uri, **kwargs):
    data = kwargs.get('data')
    response = method((self.API_BASE_URL + resource_uri), json=data, headers=self.headers)
    response.raise_for_status()
    return response.json()

Perform a method on a resource.

Args:
method: requests.`method`
resource_uri: resource endpoint
Raises:
HTTPError
Returns:
JSON Response


def release_docs_side_effect(content):
    result = content.replace('{', '{{').replace('}', '}}')
    result = result.replace('{{version}}', '{version}')
    result = result.replace('{{circleci_build}}', '{circleci_build}')
    result = result.replace('{{travis_build}}', '{travis_build}')
    result = result.replace('{{appveyor_build}}', '{appveyor_build}')
    result = result.replace('{{coveralls_build}}', '{coveralls_build}')
    return result

Updates the template so that curly braces are escaped correctly.

Args:
content (str): The template for ``docs/index.rst.release.template``.

Returns:
str: The updated template with properly escaped curly braces.


def rep1(parser: Union[Parser, Sequence[Input]]) -> RepeatedOnceParser:

    if isinstance(parser, str):
        parser = lit(parser)
    return RepeatedOnceParser(parser)

Match a parser one or more times repeatedly.

This matches ``parser`` multiple times in a row. If it matches as least
once, it returns a list of values from each time ``parser`` matched. If it
does not match ``parser`` at all, it fails.

Args:
parser: Parser or literal


def _from_row_partition(cls, values, row_partition, validate=True):
    if not isinstance(row_partition, RowPartition):
        raise TypeError(f'Argument `row_partition` must be a RowPartition. Received {row_partition}.')
    if not isinstance(validate, bool):
        raise TypeError(f'Argument `validate` must have type bool. Received {validate}.')
    values, row_partition = cls._convert_values_and_partition(values, row_partition, 'partition')
    if row_partition._has_precomputed_value_rowids():
        value_rowids_shape = row_partition.value_rowids().shape
        values.shape[:1].assert_is_compatible_with(value_rowids_shape)
    if validate:
        msg = 'Arguments to _from_row_partition do not form a valid RaggedTensor'
        nvals = _nrows(values, row_partition.dtype)
        checks = [check_ops.assert_equal(math_ops.cast(row_partition.nvals(), row_partition.dtype), nvals, message=msg)]
        if not isinstance(values, RaggedTensor):
            checks.append(check_ops.assert_rank_at_least(values, 1))
        row_partition = row_partition._with_dependencies(checks)
    return cls(values=values, internal=True, row_partition=row_partition)

Creates a `RaggedTensor` with a row partition.

This is used as a way for RaggedTensors to share row partitions.

The outer dimension of values must be equal to `partition.nvals()`.

Args:
values: A potentially ragged tensor.
row_partition: a `RowPartition`: can be shared between tensors.
validate: If true, then use assertions to check that the arguments form a
valid `RaggedTensor`.

Returns:
A `RaggedTensor`.  `result.rank = values.rank + 1`.
`result.ragged_rank = values.ragged_rank + 1`.

Raises:
ValueError: If partition.nvals() != _nrows(values)


def __init__(self, *, allow_partial: bool, accessor_writable: bool, sealed: bool, root_path: Optional[utils.KeyPath], init_super: bool=True):
    self._set_raw_attr('_allow_partial', allow_partial)
    self._set_raw_attr('_accessor_writable', accessor_writable)
    self._set_raw_attr('_sealed', sealed)
    self._set_raw_attr('_sym_parent', None)
    self._set_raw_attr('_sym_path', root_path or utils.KeyPath())
    self._set_raw_attr('_sym_puresymbolic', None)
    self._set_raw_attr('_sym_missing_values', None)
    self._set_raw_attr('_sym_nondefault_values', None)
    origin = Origin(None, '__init__') if flags.is_tracking_origin() else None
    self._set_raw_attr('_sym_origin', origin)
    if init_super:
        super().__init__()
    else:
        object.__init__(self)

Constructor.

Args:
allow_partial: Whether to allow required fields to be MISSING_VALUE or
partial.
accessor_writable: Whether to allow write access via attributes. This flag
is useful when we want to enforce update of fields using `rebind`
method, which leads to better trackability and batched field update
notification.
sealed: Whether object is sealed that cannot be changed. This flag is
useful when we don't want downstream to modify the object.
root_path: KeyPath of current object in its context (object tree).
init_super: If True, call super.__init__, otherwise short-circuit. This
flag is useful when user want to explicitly implement `__init__` for
multi-inheritance, which is needed to pass different arguments to
different bases. Please see `symbolic_test.py#testMultiInheritance`
for more details.


def is_scalar(value):

    return np.isscalar(value) or (isinstance(value, np.ndarray) and (len(np.squeeze(value).shape) == 0))

Test if the given value is a scalar.

This function also works with memory mapped array values, in contrast to the numpy is_scalar method.

Args:
value: the value to test for being a scalar value

Returns:
boolean: if the given value is a scalar or not


def remove_option(self, section, name, value=None):
    if self._is_live():
        raise RuntimeError('Submitted units cannot update their options')
    removed = 0
    for option in list(self._data['options']):
        if (option['section'] == section):
            if (option['name'] == name):
                if ((value is None) or (option['value'] == value)):
                    self._data['options'].remove(option)
                    removed += 1
    if (removed > 0):
        return True
    return False

Remove an option from a unit

Args:
section (str): The section to remove from.
name (str): The item to remove.
value (str, optional): If specified, only the option matching this value will be removed
If not specified, all options with ``name`` in ``section`` will be removed

Returns:
True: At least one item was removed
False: The item requested to remove was not found


def determine_alert(self, action_schedule, issue_creation_time, last_alert):

        issue_age = time.time() - issue_creation_time
        alert_schedule_lookup = {pytimeparse.parse(action_time): action_time for action_time in action_schedule}
        alert_schedule = sorted(alert_schedule_lookup.keys())
        last_alert_time = pytimeparse.parse(last_alert)

        for alert_time in alert_schedule:
            if last_alert_time < alert_time <= issue_age and last_alert_time != alert_time:
                return alert_schedule_lookup[alert_time]
        else:
            return None

Determine if we need to trigger an alert

Args:
action_schedule (`list`): A list contains the alert schedule
issue_creation_time (`int`): Time we create the issue
last_alert (`str`): Time we sent the last alert

Returns:
(`None` or `str`)
None if no alert should be sent. Otherwise return the alert we should send


def update(self, identity, params=None, headers=None):
    path = self._sub_url_params('/payments/:identity', {'identity': identity})
    if (params is not None):
        params = {self._envelope_key(): params}
    response = self._perform_request('PUT', path, params, headers, retry_failures=True)
    return self._resource_for(response)

Update a payment.

Updates a payment object. This accepts only the metadata parameter.

Args:
identity (string): Unique identifier, beginning with "PM".
params (dict, optional): Request body.

Returns:
ListResponse of Payment instances


def parameter_attention(x, total_key_depth, total_value_depth, output_depth, memory_rows, num_heads, dropout_rate, name=None):
    with tf.variable_scope(name, default_name='parameter_attention', values=[x]):
        head_size_k = (total_key_depth
        head_size_v = (total_value_depth
        var_shape_k = [num_heads, memory_rows, head_size_k]
        var_shape_v = [num_heads, memory_rows, head_size_v]
        k = tf.get_variable('k', var_shape_k, initializer=tf.random_normal_initializer(0, ((output_depth ** (- 0.5)) * (num_heads ** 0.5))))
        v = tf.get_variable('v', var_shape_v, initializer=tf.random_normal_initializer(0, ((output_depth ** (- 0.5)) * (output_depth ** 0.5))))
        batch_size = common_layers.shape_list(x)[0]
        length = common_layers.shape_list(x)[1]
        q = common_layers.dense(x, total_key_depth, use_bias=False, name='q_transform')
        if dropout_rate:
            v = tf.nn.dropout(v, (1.0 - dropout_rate), noise_shape=[num_heads, memory_rows, 1])
        q = tf.reshape(q, [batch_size, length, num_heads, head_size_k])
        q = tf.transpose(q, [2, 0, 1, 3])
        q = tf.reshape(q, [num_heads, (batch_size * length), head_size_k])
        weights = tf.matmul(q, k, transpose_b=True)
        weights = tf.nn.softmax(weights)
        y = tf.matmul(weights, v)
        y = tf.reshape(y, [num_heads, batch_size, length, head_size_v])
        y = tf.transpose(y, [1, 2, 0, 3])
        y = tf.reshape(y, [batch_size, length, total_value_depth])
        y.set_shape([None, None, total_value_depth])
        y = common_layers.dense(y, output_depth, use_bias=False, name='output_transform')
        return y

Attention over parameters.

We use the same multi-headed attention as in the other layers, but the memory
keys and values are model parameters. There are no linear transformation on
the keys or values.

We are also a bit more careful about memory usage, since the number of
memory positions may be very large.

Args:
x: a Tensor with shape [batch, length_q, channels]
total_key_depth: an integer
total_value_depth: an integer
output_depth: an integer
memory_rows: an integer
num_heads: an integer dividing total_key_depth and total_value_depth
dropout_rate: a floating point number
name: an optional string

Returns:
A Tensor with shape [batch, length_q, output_depth].


def fixings(self, date: types.DateTensor, fixing_type: curve_types.RateIndexCurve) -> Tuple[tf.Tensor, daycount_conventions.DayCountConventions]:
    index_type = fixing_type.index.type.value
    currency = fixing_type.currency.value
    if isinstance(date, tf.Tensor):
        date = dateslib.dates_from_tensor(date)
    else:
        date = dateslib.convert_to_date_tensor(date)
    try:
        curve_data = self._market_data_dict['rates'][currency][index_type]
        fixing_dates = curve_data['fixing_dates']
        fixing_rates = curve_data['fixing_rates']
    except KeyError:
        return (tf.zeros(tf.shape(date.ordinal()), dtype=self._dtype, name='fixings'), None)
    if isinstance(fixing_dates, tf.Tensor):
        fixing_dates = dateslib.dates_from_tensor(fixing_dates)
    else:
        fixing_dates = dateslib.convert_to_date_tensor(fixing_dates)
    if 'fixing_daycount' not in curve_data:
        raise ValueError(f'`fixing_daycount` should be specified for {index_type}.')
    fixing_daycount = curve_data['fixing_daycount']
    fixing_daycount = daycount_conventions.DayCountConventions(fixing_daycount)
    fixing_rates = tf.convert_to_tensor(fixing_rates, dtype=self._dtype)
    fixing_dates_ordinal = fixing_dates.ordinal()
    date_ordinal = date.ordinal()
    batch_shape = tf.shape(date_ordinal)[:-1]
    fixing_dates_ordinal += tf.expand_dims(tf.zeros(batch_shape, dtype=tf.int32), axis=-1)
    inds = tf.searchsorted(fixing_dates_ordinal, date_ordinal)
    inds = tf.maximum(inds, 0)
    inds = tf.minimum(inds, tf.shape(fixing_dates_ordinal)[-1] - 1)
    return (tf.gather(fixing_rates, inds), fixing_daycount)

Returns past fixings of the market rates at the specified dates.

The fixings are represented asannualized simple rates. When fixings are not
provided for a curve, they are assumed to be zero for any date. Otherwise,
it is assumed that the fixings are a left-continuous piecewise-constant
of time with jumps being the supplied fixings.

Args:
date: The dates at which the fixings are computed. Should precede the
valuation date. When passed as an integet `Tensor`, should be of shape
`batch_shape + [3]` and contain `[year, month, day]` for each date.
fixing_type: Rate index curve type for which the fixings are computed.

Returns:
A `Tensor` of the same shape of `date` and of `self.dtype` dtype.
Represents fixings at the requested `date`.


def to_las3(self, use_descriptions=False, dlm=",", source="Striplog"):

        data = self.to_csv(use_descriptions=use_descriptions,
                           dlm=dlm,
                           header=False)

        return templates.section.format(name='Lithology',
                                        short="LITH",
                                        source=source,
                                        data=data)

Returns an LAS 3.0 section string.

Args:
use_descriptions (bool): Whether to use descriptions instead
of summaries, if available.
dlm (str): The delimiter.
source (str): The sourse of the data.

Returns:
str: A string forming Lithology section of an LAS3 file.


def next_state_fluent_ordering(self) -> List[str]:
    key = (lambda x: x.name)
    return [cpf.name for cpf in sorted(self.state_cpfs, key=key)]

The list of next state-fluent names in canonical order.

Returns:
List[str]: A list of fluent names.


def items_purchased(self, category=None):

        return self._items(commerce.Cart.STATUS_PAID, category=category)

Aggregates the items that this user has purchased.

Arguments:
category (Optional[models.inventory.Category]): the category
of items to restrict to.

Returns:
[ProductAndQuantity, ...]: A list of product-quantity pairs,
aggregating like products from across multiple invoices.


def repository_tree(self, path='', ref='', recursive=False, **kwargs):
    gl_path = ('/projects/%s/repository/tree' % self.get_id())
    query_data = {'recursive': recursive}
    if path:
        query_data['path'] = path
    if ref:
        query_data['ref'] = ref
    return self.manager.gitlab.http_list(gl_path, query_data=query_data, **kwargs)

Return a list of files in the repository.

Args:
path (str): Path of the top folder (/ by default)
ref (str): Reference to a commit or branch
recursive (bool): Whether to get the tree recursively
all (bool): If True, return all the items, without pagination
per_page (int): Number of items to retrieve per request
page (int): ID of the page to return (starts with page 1)
as_list (bool): If set to False and no pagination option is
defined, return a generator instead of a list
**kwargs: Extra options to send to the server (e.g. sudo)

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

Returns:
list: The representation of the tree


def _execute(self, command, data=None, unpack=True):

        if not data:
            data = {}
        if self.session_id is not None:
            data.setdefault('session_id', self.session_id)
        data = self._wrap_el(data)
        res = self.remote_invoker.execute(command, data)
        ret = WebDriverResult.from_object(res)
        ret.raise_for_status()
        ret.value = self._unwrap_el(ret.value)
        if not unpack:
            return ret
        return ret.value

Private method to execute command.

Args:
command(Command): The defined command.
data(dict): The uri variable and body.
uppack(bool): If unpack value from result.

Returns:
The unwrapped value field in the json response.


def to_json(self, **kwargs):
    from keras.src.saving import serialization_lib
    model_config = serialization_lib.serialize_keras_object(self)
    return json.dumps(model_config, **kwargs)

Returns a JSON string containing the network configuration.

To load a network from a JSON save file, use
`keras.models.model_from_json(json_string, custom_objects={...})`.

Args:
**kwargs: Additional keyword arguments to be passed to
`json.dumps()`.

Returns:
A JSON string.


def search(self, query_term):
    fedora_search_url = '/'.join([self.base_url, 'rest', 'fcr:search'])
    fedora_search_url = '{}?{}'.format(fedora_search_url, urllib.parse.urlencode({'q': query_term}))
    search_request = urllib.request.Request(fedora_search_url, method='GET')
    search_request.add_header('Accept', 'text/turtle')
    try:
        search_response = urllib.request.urlopen(search_request)
    except urllib.error.URLError as error:
        raise error
    fedora_results = rdflib.Graph().parse(data=search_response.read(), format='turtle')
    return fedora_results

DEPRECIATED
Method takes a query term and searches Fedora Repository using SPARQL
search endpoint and returns a RDF graph of the search results.

Args:
query_term(str): String to search repository

Returns:
rdflib.Graph()


def _select_in_voltage_range(self, min_voltage=None, max_voltage=None):
    min_voltage = (min_voltage if (min_voltage is not None) else self.min_voltage)
    max_voltage = (max_voltage if (max_voltage is not None) else self.max_voltage)
    return list(filter((lambda p: (min_voltage <= p.voltage <= max_voltage)), self.voltage_pairs))

Selects VoltagePairs within a certain voltage range.

Args:
min_voltage (float): The minimum allowable voltage for a given
step.
max_voltage (float): The maximum allowable voltage allowable for a
given step.

Returns:
A list of VoltagePair objects


def from_rfc3339(cls, stamp):

        with_nanos = _RFC3339_NANOS.match(stamp)
        if with_nanos is None:
            raise ValueError(
                "Timestamp: {}, does not match pattern: {}".format(
                    stamp, _RFC3339_NANOS.pattern
                )
            )
        bare = datetime.datetime.strptime(
            with_nanos.group("no_fraction"), _RFC3339_NO_FRACTION
        )
        fraction = with_nanos.group("nanos")
        if fraction is None:
            nanos = 0
        else:
            scale = 9 - len(fraction)
            nanos = int(fraction) * (10 ** scale)
        return cls(
            bare.year,
            bare.month,
            bare.day,
            bare.hour,
            bare.minute,
            bare.second,
            nanosecond=nanos,
            tzinfo=pytz.UTC,
        )

Parse RFC 3339-compliant timestamp, preserving nanoseconds.

Args:
stamp (str): RFC 3339 stamp, with up to nanosecond precision

Returns:
:class:`DatetimeWithNanoseconds`:
an instance matching the timestamp string

Raises:
ValueError: if `stamp` does not match the expected format


def tf2():
    if tf.__version__.startswith('2.'):
        return tf
    elif (hasattr(tf, 'compat') and hasattr(tf.compat, 'v2')):
        return tf.compat.v2
    raise ImportError('cannot import tensorflow 2.0 API')

Provide the root module of a TF-2.0 API for use within TensorBoard.

Returns:
The root module of a TF-2.0 API, if available.

Raises:
ImportError: if a TF-2.0 API is not available.


def _starts_with_drive_letter(self, file_path):
    colon = self._matching_string(file_path, ':')
    return (self.is_windows_fs and (len(file_path) >= 2) and file_path[:1].isalpha and (file_path[1:2] == colon))

Return True if file_path starts with a drive letter.

Args:
file_path: the full path to be examined.

Returns:
`True` if drive letter support is enabled in the filesystem and
the path starts with a drive letter.


def add_timeline_to_sketch(self, sketch_id, index_id):
    resource_url = '{0:s}/sketches/{1:d}/timelines/'.format(self.api_base_url, sketch_id)
    form_data = {'timeline': [index_id]}
    self.session.post(resource_url, json=form_data)

Associate the specified timeline and sketch.

Args:
sketch_id (int): ID of sketch
index_id (int): ID of timeline to add to sketch


def get_most_severe_consequence(transcripts):
    most_severe_consequence = None
    most_severe_score = None
    for transcript in transcripts:
        for consequence in transcript['consequence'].split('&'):
            logger.debug('Checking severity score for consequence: {0}'.format(consequence))
            severity_score = SEVERITY_DICT.get(consequence)
            logger.debug('Severity score found: {0}'.format(severity_score))
            if (severity_score != None):
                if most_severe_score:
                    if (severity_score < most_severe_score):
                        most_severe_consequence = consequence
                        most_severe_score = severity_score
                else:
                    most_severe_consequence = consequence
                    most_severe_score = severity_score
    return most_severe_consequence

Get the most severe consequence

Go through all transcripts and get the most severe consequence

Args:
transcripts (list): A list of transcripts to evaluate

Returns:
most_severe_consequence (str): The most severe consequence


def to_numpy_array(self, image, rescale=None, channel_first=True):
    self._ensure_format_supported(image)
    if isinstance(image, PIL.Image.Image):
        image = np.array(image)
    if is_torch_tensor(image):
        image = image.numpy()
    rescale = isinstance(image.flat[0], np.integer) if rescale is None else rescale
    if rescale:
        image = self.rescale(image.astype(np.float32), 1 / 255.0)
    if channel_first and image.ndim == 3:
        image = image.transpose(2, 0, 1)
    return image

Converts `image` to a numpy array. Optionally rescales it and puts the channel dimension as the first
dimension.

Args:
image (`PIL.Image.Image` or `np.ndarray` or `torch.Tensor`):
The image to convert to a NumPy array.
rescale (`bool`, *optional*):
Whether or not to apply the scaling factor (to make pixel values floats between 0. and 1.). Will
default to `True` if the image is a PIL Image or an array/tensor of integers, `False` otherwise.
channel_first (`bool`, *optional*, defaults to `True`):
Whether or not to permute the dimensions of the image to put the channel dimension first.


def SetCodepage(self, codepage):

    try:
      codecs.getencoder(codepage)
      self._codepage = codepage
    except LookupError:
      raise ValueError('Unsupported codepage: {0:s}'.format(codepage))

Sets the codepage.

Args:
codepage (str): codepage.

Raises:
ValueError: if the codepage is not supported.


def parse_page(raw_page):
    ret = {'title': get_title(raw_page), 'id': get_id(raw_page)}
    if (':' in ret['title']):
        return None
    ret['revisions'] = get_revisions(raw_page)
    return ret

Create a dictionary with title, id, and list of revisions.

The dictionary contains:
"title": a string
"id": an integer
"revisions": a list of strings

Args:
raw_page: a string

Returns:
a dictionary, or None in the case of an error.


def on_created(self, event):

        self._logger.debug('Detected create event on watched path: %s', event.src_path)

        self._process_event(event)

Function called everytime a new file is created.

Args:
event: Event to process.


def getlibversion():

    status, major_v, minor_v, release, info = _C.Hgetlibversion()
    _checkErr('getlibversion', status, "cannot get lib version")
    return major_v, minor_v, release, info

Get the library version info.

Args:
no argument
Returns:
4-element tuple with the following components:
-major version number (int)
-minor version number (int)
-complete library version number (int)
-additional information (string)

C library equivalent : Hgetlibversion


def _get_batches_of_transformed_samples(self, index_array):
    batch_x = np.zeros((len(index_array),) + self.image_shape, dtype=self.dtype)
    filepaths = self.filepaths
    for i, j in enumerate(index_array):
        img = image_utils.load_img(filepaths[j], color_mode=self.color_mode, target_size=self.target_size, interpolation=self.interpolation, keep_aspect_ratio=self.keep_aspect_ratio)
        x = image_utils.img_to_array(img, data_format=self.data_format)
        if hasattr(img, 'close'):
            img.close()
        if self.image_data_generator:
            params = self.image_data_generator.get_random_transform(x.shape)
            x = self.image_data_generator.apply_transform(x, params)
            x = self.image_data_generator.standardize(x)
        batch_x[i] = x
    if self.save_to_dir:
        for i, j in enumerate(index_array):
            img = image_utils.array_to_img(batch_x[i], self.data_format, scale=True)
            fname = '{prefix}_{index}_{hash}.{format}'.format(prefix=self.save_prefix, index=j, hash=np.random.randint(10000000.0), format=self.save_format)
            img.save(os.path.join(self.save_to_dir, fname))
    if self.class_mode == 'input':
        batch_y = batch_x.copy()
    elif self.class_mode in {'binary', 'sparse'}:
        batch_y = np.empty(len(batch_x), dtype=self.dtype)
        for i, n_observation in enumerate(index_array):
            batch_y[i] = self.classes[n_observation]
    elif self.class_mode == 'categorical':
        batch_y = np.zeros((len(batch_x), len(self.class_indices)), dtype=self.dtype)
        for i, n_observation in enumerate(index_array):
            batch_y[i, self.classes[n_observation]] = 1.0
    elif self.class_mode == 'multi_output':
        batch_y = [output[index_array] for output in self.labels]
    elif self.class_mode == 'raw':
        batch_y = self.labels[index_array]
    else:
        return batch_x
    if self.sample_weight is None:
        return (batch_x, batch_y)
    else:
        return (batch_x, batch_y, self.sample_weight[index_array])

Gets a batch of transformed samples.

Args:
index_array: Array of sample indices to include in batch.
Returns:
A batch of transformed samples.


def logaddexp(x1, x2):
    if any_symbolic_tensors((x1, x2)):
        return Logaddexp().symbolic_call(x1, x2)
    return backend.numpy.logaddexp(x1, x2)

Logarithm of the sum of exponentiations of the inputs.

Calculates `log(exp(x1) + exp(x2))`.

Args:
x1: Input tensor.
x2: Input tensor.

Returns:
Output tensor, element-wise logarithm of the sum of exponentiations
of the inputs.


def __setattr__(self, __key: Hashable, __value: Any) -> None:

        try:
            self[__key] = __value
        except Exception as err:
            raise AttributeError(str(err))

Support item assignment via dot notation.

Args:
__key: Key to set value for
__value: Value to set key to


def start_queue_runners(self, sess, queue_runners=None):
    if context.executing_eagerly():
        raise RuntimeError('Queues are not compatible with eager execution.')
    if queue_runners is None:
        queue_runners = self._graph.get_collection(ops.GraphKeys.QUEUE_RUNNERS)
    threads = []
    for qr in queue_runners:
        threads.extend(qr.create_threads(sess, coord=self._coord, daemon=True, start=True))
    return threads

Start threads for `QueueRunners`.

Note that the queue runners collected in the graph key `QUEUE_RUNNERS`
are already started automatically when you create a session with the
supervisor, so unless you have non-collected queue runners to start
you do not need to call this explicitly.

Args:
sess: A `Session`.
queue_runners: A list of `QueueRunners`. If not specified, we'll use the
list of queue runners gathered in the graph under the key
`GraphKeys.QUEUE_RUNNERS`.

Returns:
The list of threads started for the `QueueRunners`.

Raises:
RuntimeError: If called with eager execution enabled.

@compatibility(eager)
Queues are not compatible with eager execution. To ingest data when eager
execution is enabled, use the `tf.data` API.
@end_compatibility


def __init__(self, api_key):

        self.session = Session()
        self.session.auth = HTTPBasicAuth(api_key, 'NoPassBecauseKey!')
        self._load_apis()

Initialize a new HelpScout client.

Args:
api_key (str): The API key to use for this session.


def _strip_leading_zeros(coeffs, threshold=_COEFFICIENT_THRESHOLD):
    while (np.abs(coeffs[(- 1)]) < threshold):
        coeffs = coeffs[:(- 1)]
    return coeffs

r"""Strip leading zero coefficients from a polynomial.

.. note::

This assumes the polynomial :math:`f` defined by ``coeffs``
has been normalized (via :func:`.normalize_polynomial`).

Args:
coeffs (numpy.ndarray): ``d + 1``-array of coefficients in monomial /
power basis.
threshold (Optional[float]): The point :math:`\tau` below which a
a coefficient will be considered to be numerically zero.

Returns:
numpy.ndarray: The same coefficients without any unnecessary zero
terms.


def __init__(self, learning_rate=0.001, rho=0.95, epsilon=1e-08, use_locking=False, name='Adadelta'):
    super(AdadeltaOptimizer, self).__init__(use_locking, name)
    self._lr = learning_rate
    self._rho = rho
    self._epsilon = epsilon
    self._lr_t = None
    self._rho_t = None
    self._epsilon_t = None

Construct a new Adadelta optimizer.

Args:
learning_rate: A `Tensor` or a floating point value. The learning rate.
To match the exact form in the original paper use 1.0.
rho: A `Tensor` or a floating point value. The decay rate.
epsilon: A `Tensor` or a floating point value.  A constant epsilon used
to better conditioning the grad update.
use_locking: If `True` use locks for update operations.
name: Optional name prefix for the operations created when applying
gradients.  Defaults to "Adadelta".


def __init__(self, channel):

        self.CreateTopic = channel.unary_unary(
            "/google.pubsub.v1.Publisher/CreateTopic",
            request_serializer=google_dot_cloud_dot_pubsub__v1_dot_proto_dot_pubsub__pb2.Topic.SerializeToString,
            response_deserializer=google_dot_cloud_dot_pubsub__v1_dot_proto_dot_pubsub__pb2.Topic.FromString,
        )
        self.UpdateTopic = channel.unary_unary(
            "/google.pubsub.v1.Publisher/UpdateTopic",
            request_serializer=google_dot_cloud_dot_pubsub__v1_dot_proto_dot_pubsub__pb2.UpdateTopicRequest.SerializeToString,
            response_deserializer=google_dot_cloud_dot_pubsub__v1_dot_proto_dot_pubsub__pb2.Topic.FromString,
        )
        self.Publish = channel.unary_unary(
            "/google.pubsub.v1.Publisher/Publish",
            request_serializer=google_dot_cloud_dot_pubsub__v1_dot_proto_dot_pubsub__pb2.PublishRequest.SerializeToString,
            response_deserializer=google_dot_cloud_dot_pubsub__v1_dot_proto_dot_pubsub__pb2.PublishResponse.FromString,
        )
        self.GetTopic = channel.unary_unary(
            "/google.pubsub.v1.Publisher/GetTopic",
            request_serializer=google_dot_cloud_dot_pubsub__v1_dot_proto_dot_pubsub__pb2.GetTopicRequest.SerializeToString,
            response_deserializer=google_dot_cloud_dot_pubsub__v1_dot_proto_dot_pubsub__pb2.Topic.FromString,
        )
        self.ListTopics = channel.unary_unary(
            "/google.pubsub.v1.Publisher/ListTopics",
            request_serializer=google_dot_cloud_dot_pubsub__v1_dot_proto_dot_pubsub__pb2.ListTopicsRequest.SerializeToString,
            response_deserializer=google_dot_cloud_dot_pubsub__v1_dot_proto_dot_pubsub__pb2.ListTopicsResponse.FromString,
        )
        self.ListTopicSubscriptions = channel.unary_unary(
            "/google.pubsub.v1.Publisher/ListTopicSubscriptions",
            request_serializer=google_dot_cloud_dot_pubsub__v1_dot_proto_dot_pubsub__pb2.ListTopicSubscriptionsRequest.SerializeToString,
            response_deserializer=google_dot_cloud_dot_pubsub__v1_dot_proto_dot_pubsub__pb2.ListTopicSubscriptionsResponse.FromString,
        )
        self.ListTopicSnapshots = channel.unary_unary(
            "/google.pubsub.v1.Publisher/ListTopicSnapshots",
            request_serializer=google_dot_cloud_dot_pubsub__v1_dot_proto_dot_pubsub__pb2.ListTopicSnapshotsRequest.SerializeToString,
            response_deserializer=google_dot_cloud_dot_pubsub__v1_dot_proto_dot_pubsub__pb2.ListTopicSnapshotsResponse.FromString,
        )
        self.DeleteTopic = channel.unary_unary(
            "/google.pubsub.v1.Publisher/DeleteTopic",
            request_serializer=google_dot_cloud_dot_pubsub__v1_dot_proto_dot_pubsub__pb2.DeleteTopicRequest.SerializeToString,
            response_deserializer=google_dot_protobuf_dot_empty__pb2.Empty.FromString,
        )

Constructor.

Args:
channel: A grpc.Channel.


def load_recipe(self, recipe):
    self.recipe = recipe
    for module_description in recipe['modules']:
        module_name = module_description['name']
        module = self.config.get_module(module_name)(self)
        self._module_pool[module_name] = module

Populates the internal module pool with modules declared in a recipe.

Args:
recipe: Dict, recipe declaring modules to load.


def _list_like_func(self, func, axis, *args, **kwargs):
    func_prepared = self._prepare_method((lambda df: pandas.DataFrame(df.apply(func, axis, *args, **kwargs))))
    new_data = self._map_across_full_axis(axis, func_prepared)
    new_index = ([(f if isinstance(f, string_types) else f.__name__) for f in func] if (axis == 0) else self.index)
    new_columns = ([(f if isinstance(f, string_types) else f.__name__) for f in func] if (axis == 1) else self.columns)
    return self.__constructor__(new_data, new_index, new_columns)

Apply list-like function across given axis.

Args:
func: The function to apply.
axis: Target axis to apply the function along.

Returns:
A new PandasQueryCompiler.


def weighting_function(max_num_bins: int, up: torch.Tensor, reg_scale: int) -> torch.Tensor:
    upper_bound1 = abs(up[0]) * abs(reg_scale)
    upper_bound2 = abs(up[0]) * abs(reg_scale) * 2
    step = (upper_bound1 + 1) ** (2 / (max_num_bins - 2))
    left_values = [-step ** i + 1 for i in range(max_num_bins
    right_values = [step ** i - 1 for i in range(1, max_num_bins
    values = [-upper_bound2] + left_values + [torch.zeros_like(up[0][None])] + right_values + [upper_bound2]
    values = torch.cat(values, 0)
    return values

Generates the non-uniform Weighting Function W(n) for bounding box regression.

Args:
max_num_bins (int): Max number of the discrete bins.
up (Tensor): Controls upper bounds of the sequence,
where maximum offset is ±up * H / W.
reg_scale (float): Controls the curvature of the Weighting Function.
Larger values result in flatter weights near the central axis W(max_num_bins/2)=0
and steeper weights at both ends.
Returns:
Tensor: Sequence of Weighting Function.


def add_to_loader(loader_cls: Type, classes: List[Type]) -> None:

    if not isinstance(classes, list):
        classes = [classes]

    for class_ in classes:
        tag = '!{}'.format(class_.__name__)
        if issubclass(class_, enum.Enum):
            loader_cls.add_constructor(tag, EnumConstructor(class_))
        elif issubclass(class_, str) or issubclass(class_, UserString):
            loader_cls.add_constructor(tag, UserStringConstructor(class_))
        else:
            loader_cls.add_constructor(tag, Constructor(class_))

        if not hasattr(loader_cls, '_registered_classes'):
            loader_cls._registered_classes = dict()
        loader_cls._registered_classes[tag] = class_

Registers one or more classes with a YAtiML loader.

Once a class has been registered, it can be recognized and \
constructed when reading a YAML text.

Args:
loader_cls: The loader to register the classes with.
classes: The class(es) to register, a plain Python class or a \
list of them.


def seconds(value: Union[int, float]) -> Duration:
    return float(value)

Converts input value from seconds to a `Duration` in seconds.

Since the `Duration` object is equivalent to a `float` value in seconds,
this method does nothing else than casting the input to `float`. It may be
used in order to make the code more explicit.

Explicit time units:
```python
>>> duration = tp.duration.seconds(3)
>>> duration
3.0

>>> # Usage in a window operation
>>> a = tp.event_set(
...     timestamps=[1, 2, 6],
...     features={"f1": [1, 5, -5]},
... )
>>> a.moving_sum(window_length=duration)
indexes: ...
timestamps: [1. 2. 6.]
'f1': [ 1 6 -5]
...

```

Args:
value: Number of seconds.

Returns:
Same number of seconds.


def deprecate_moved_module(deprecated_name, new_module, deletion_version):

    def getter(name):
        if getter not in _PRINTED_WARNING and _PRINT_DEPRECATION_WARNINGS:
            _PRINTED_WARNING[getter] = True
            _log_deprecation('Please fix your imports. Module %s has been moved to %s. The old module will be deleted in version %s.', deprecated_name, new_module.__name__, deletion_version)
        return getattr(new_module, name)
    return getter

Logs a warning when a module that has been moved to a new location is used.

Copy the following code into the old module:

```
import deprecation
import new_module

__getattr__ = deprecation.deprecate_moved_module(
__name__, new_module, "2.9")  # adjust version number.
```

Args:
deprecated_name: Name of old module.
new_module: Module to replace the old module.
deletion_version: Version of TensorFlow in which the old module will be
removed.

Returns:
A function that logs a warning and returns the symbol from the new module.
Set this function as the module's `__getattr__`.


def pretty_print_fhir_to_json_string(fhir_proto: message.Message, *, indent_size: int=2) -> str:
    printer = _json_printer.JsonPrinter.pretty_printer(_PRIMITIVE_HANDLER, indent_size=indent_size)
    return printer.print(fhir_proto)

Returns a FHIR JSON representation with spaces and newlines.

Args:
fhir_proto: The proto to serialize into a "pretty" JSON string.
indent_size: An integer denoting the size of space indentation for lexical
scoping. Defaults to 2.

Returns:
A FHIR JSON string representation with spaces and newlines.


def _create_delegate_handler(delegate):

    @coroutine
    def handler(*args):
        (yield)
        (yield delegate.send(Transition(args, delegate)))
    return handler

Creates a handler function that creates a co-routine that can yield once with the given
positional arguments to the delegate as a transition.

Args:
delegate (Coroutine): The co-routine to delegate to.

Returns:
A :class:`callable` handler that returns a co-routine that ignores the data it receives
and sends with the arguments given to the handler as a :class:`Transition`.


def maybe_get_static_value(x, dtype=None):

  if x is None:
    return x
  try:

    x_ = tf.get_static_value(x)
  except TypeError:
    x_ = x
  if x_ is None or dtype is None:
    return x_
  return np.array(x_, dtype)

Helper which tries to return a static value.

Given `x`, extract it's value statically, optionally casting to a specific
dtype. If this is not possible, None is returned.

Args:
x: `Tensor` for which to extract a value statically.
dtype: Optional dtype to cast to.

Returns:
Statically inferred value if possible, otherwise None.


def __init__(self, columns: list[str], min_value: float=0.0, max_value: float=1.0, name: Optional[str]=None):
    super().__init__(columns)
    self.min_value = min_value
    self.max_value = max_value
    self.name = name
    if self.max_value <= self.min_value:
        raise ValueError('max_value must be greater than min_value')

This function applies a scaling transformation on the given columns
of incoming data. The transformation scales the input values to the
range [min_value, max_value].

Args:
columns: A list of column names to apply the transformation on.
min_value: The minimum value of the output range.
max_value: The maximum value of the output range.
name: A name for the operation (optional).


def SaveTransaction(self, tx):
    coins = self.GetCoins()
    changed = []
    added = []
    deleted = []
    found_coin = False
    for input in tx.inputs:
        coin = None
        for coinref in coins:
            test_coin = coinref.Reference
            if (test_coin == input):
                coin = coinref
        if (coin is None):
            return False
        if ((coin.State & CoinState.Spent) > 0):
            return False
        elif ((coin.State & CoinState.Confirmed) == 0):
            return False
        coin.State |= CoinState.Spent
        coin.State &= (~ CoinState.Confirmed)
        changed.append(coin)
    for (index, output) in enumerate(tx.outputs):
        state = self.CheckAddressState(output.ScriptHash)
        key = CoinReference(tx.Hash, index)
        if ((state & AddressState.InWallet) > 0):
            newcoin = Coin.CoinFromRef(coin_ref=key, tx_output=output, state=CoinState.Unconfirmed)
            self._coins[key] = newcoin
            if ((state & AddressState.WatchOnly) > 0):
                newcoin.State |= CoinState.WatchOnly
            added.append(newcoin)
    if isinstance(tx, ClaimTransaction):
        for claim in tx.Claims:
            claim_coin = self._coins[claim]
            claim_coin.State |= CoinState.Claimed
            claim_coin.State &= (~ CoinState.Confirmed)
            changed.append(claim_coin)
    self.OnSaveTransaction(tx, added, changed, deleted)
    return True

This method is used to after a transaction has been made by this wallet.  It updates the states of the coins
In the wallet to reflect the new balance, but the coins remain in a ``CoinState.UNCONFIRMED`` state until
The transaction has been processed by the network.

The results of these updates can be used by overriding the ``OnSaveTransaction`` method, and, for example
persisting the results to a database.

Args:
tx (Transaction): The transaction that has been made by this wallet.

Returns:
bool: True is successfully processes, otherwise False if input is not in the coin list, already spent or not confirmed.


def __init__(self, metadata=0, metadata_mask=0):

        super().__init__(InstructionType.OFPIT_WRITE_METADATA)
        self.metadata = metadata
        self.metadata_mask = metadata_mask

Create InstructionWriteMetadata with the optional parameters below.

Args:
metadata (int): Metadata value to write.
metadata_mask (int): Metadata write bitmask.


def run_profilers(run_object, prof_config, verbose=False):
    if (len(prof_config) > len(set(prof_config))):
        raise AmbiguousConfigurationError(('Profiler configuration %s is ambiguous' % prof_config))
    available_profilers = {opt for (opt, _) in _PROFILERS}
    for option in prof_config:
        if (option not in available_profilers):
            raise BadOptionError(('Unknown option: %s' % option))
    run_stats = OrderedDict()
    present_profilers = ((o, p) for (o, p) in _PROFILERS if (o in prof_config))
    for (option, prof) in present_profilers:
        curr_profiler = prof(run_object)
        if verbose:
            print(('Running %s...' % curr_profiler.__class__.__name__))
        run_stats[option] = curr_profiler.run()
    return run_stats

Runs profilers on run_object.

Args:
run_object: An object (string or tuple) for profiling.
prof_config: A string with profilers configuration.
verbose: True if info about running profilers should be shown.
Returns:
An ordered dictionary with collected stats.
Raises:
AmbiguousConfigurationError: when prof_config is ambiguous.
BadOptionError: when unknown options are present in configuration.


def create_token_type_ids_from_sequences(self, token_ids_0: List[int], token_ids_1: Optional[List[int]]=None) -> List[int]:
    sep = [self.sep_token_id]
    if token_ids_1 is None:
        return len(token_ids_0 + sep) * [0]
    return len(token_ids_0 + sep + sep + token_ids_1 + sep) * [0]

Create a mask from the two sequences passed to be used in a sequence-pair classification task. XLMProphetNet
does not make use of token type ids, therefore a list of zeros is returned.

Args:
token_ids_0 (`List[int]`):
List of IDs.
token_ids_1 (`List[int]`, *optional*):
Optional second list of IDs for sequence pairs.

Returns:
`List[int]`: List of zeros.


def broadcast_structure(to_structure, from_structure):
    from_parts = tf.nest.flatten(from_structure)
    if (len(from_parts) == 1):
        from_structure = tf.nest.map_structure((lambda _: from_parts[0]), to_structure)
    return from_structure

Broadcasts `from_structure` to `to_structure`.

This is useful for downstream usage of `zip` or `tf.nest.map_structure`.

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

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

Returns:
new_from_structure: Same structure as `to_structure`.

#### Example:

```python
a_structure = ['a', 'b', 'c']
b_structure = broadcast_structure(a_structure, 'd')
# -> ['d', 'd', 'd']
c_structure = tf.nest.map_structure(
lambda a, b: a + b, a_structure, b_structure)
# -> ['ad', 'bd', 'cd']
```


def __init__(self, item_cls, data):

        super(ResourceList, self).__init__()
        if data is not None:

            data = json.loads(data) if type(data) is not dict else data
            paging = data['list_info']
            raw_items = data.get(self.items_keys[item_cls.__name__])

            if raw_items:

                for raw_item in raw_items:
                    self.append(item_cls(raw_item))

                self.page = paging['page']
                self.num_pages = paging['num_pages']
                self.num_results = paging['num_results']
                self.page_size = paging['page_size']

Initialization of the list

Args:
item_cls (str): Object class matching the list items
data (str or dict): A dictionary or raw JSON string that is returned by a request.


def __init__(self, resolver_context, file_object=None):

    if file_object:
      raise ValueError('File object value set.')

    super(RawFile, self).__init__(resolver_context)
    self._file_objects = []

Initializes a file-like object.

Args:
resolver_context (Context): resolver context.
file_object (Optional[FileIO]): file-like object.

Raises:
ValueError: when file_object is set.


def write_bit(self, registeraddress, value, functioncode=5):

        _checkFunctioncode(functioncode, [5, 15])
        _checkInt(value, minvalue=0, maxvalue=1, description='input value')
        self._genericCommand(functioncode, registeraddress, value)

Write one bit to the slave.

Args:
* registeraddress (int): The slave register address (use decimal numbers, not hex).
* value (int): 0 or 1
* functioncode (int): Modbus function code. Can be 5 or 15.

Returns:
None

Raises:
ValueError, TypeError, IOError


def logical_or(x1, x2):
    if any_symbolic_tensors((x1, x2)):
        return LogicalOr().symbolic_call(x1, x2)
    return backend.numpy.logical_or(x1, x2)

Computes the element-wise logical OR of the given input tensors.

Zeros are treated as `False` and non-zeros are treated as `True`.

Args:
x1: Input tensor.
x2: Input tensor.

Returns:
Output tensor, element-wise logical OR of the inputs.


def _call_api(self, verb, url, **request_kwargs):

        api = 'https:
        auth_headers = {'Authorization': 'token {}'.format(self.api_token)}
        headers = {**auth_headers, **request_kwargs.pop('headers', {})}
        return getattr(requests, verb)(api, headers=headers, **request_kwargs)

Perform a github API call

Args:
verb (str): Can be "post", "put", or "get"
url (str): The base URL with a leading slash for Github API (v3)
auth (str or HTTPBasicAuth): A Github API token or a HTTPBasicAuth object


def _build_insert_compiler(self, rows: List[Dict]):

        objs = []
        field_count = len(rows[0])
        for index, row in enumerate(rows):
            if field_count != len(row):
                raise SuspiciousOperation((
                    'In bulk upserts, you cannot have rows with different field '
                    'configurations. Row {0} has a different field config than '
                    'the first row.'
                ).format(index))

            objs.append(self.model(**row))

        self._for_write = True

        insert_fields, update_fields = self._get_upsert_fields(rows[0])

        query = PostgresInsertQuery(self.model)
        query.conflict_action = self.conflict_action
        query.conflict_target = self.conflict_target
        query.index_predicate = self.index_predicate
        query.values(objs, insert_fields, update_fields)

        connection = django.db.connections[self.db]
        compiler = PostgresInsertCompiler(query, connection, self.db)

        return compiler

Builds the SQL compiler for a insert query.

Arguments:
rows:
A list of dictionaries, where each entry
describes a record to insert.

Returns:
The SQL compiler for the insert.


def to_yaml(obj):

    if not isinstance(obj, CompoundValue) and hasattr(obj, 'transfer'):
        if hasattr(obj, 'message'):
            payload = obj.message
            header = 'Message'
        elif hasattr(obj, 'request'):
            payload = obj.request
            header = 'Request'
        elif hasattr(obj, 'response'):
            payload = obj.response
            header = 'Response'
        else:
            raise ValueError('Cannot generate YAML representation for %r' % type(obj))

        prefix = '
                 (header,
                  obj.transfer.source_node_id or 'Anon',
                  obj.transfer.dest_node_id or 'All',
                  obj.transfer.ts_monotonic, obj.transfer.ts_real)

        return prefix + _to_yaml_impl(payload)
    else:
        return _to_yaml_impl(obj)

This function returns correct YAML representation of a UAVCAN structure (message, request, or response), or
a DSDL entity (array or primitive), or a UAVCAN transfer, with comments for human benefit.
Args:
obj:            Object to convert.

Returns: Unicode string containing YAML representation of the object.


def densifying_unary(default_value):

    def wrap_densifying_unary(func):

        @functools.wraps(func)
        def sparse_wrapper(x, *args, **kwargs):
            if isinstance(x, tf.SparseTensor):
                sparse_output = sparse_with_values(x, func(x.values, *args, **kwargs))
                return sparse_to_dense(sparse_output, tf.cast(default_value, sparse_output.values.dtype))
            elif isinstance(x, tf.IndexedSlices):
                sparse_output_values = func(x.values, *args, **kwargs)
                output = tf.fill(x.dense_shape, tf.cast(default_value, sparse_output_values.dtype))
                return tf.tensor_scatter_nd_update(output, tf.expand_dims(x.indices, 1), sparse_output_values)
            return func(x, *args, **kwargs)
        return sparse_wrapper
    return wrap_densifying_unary

Decorator to add support for `tf.SparseTensor` and `tf.IndexedSlices` to
a non-zero-preserving element-wise unary operator.

There are requirements on the operator for this decorator to work correctly:

- The operator must be element-wise
- The operator must be unary (one input tensor and one output tensor)
- The operator must return a tensor of the same shape.

Additional arguments to the function (besides the input tensor) are
supported. The returned result is a dense tensor and contains
`default_value` outside of the indices of the input tensor.

Args:
default_value: The value to use outside of indices. It must be the value
that the operator returns for zero values.
Returns:
Wrapped function that supports `tf.SparseTensor` and `tf.IndexedSlices`.


def query(self, query):

    cursor = self.child_datastore.query(query)

    cursor._iterable = deserialized_gen(self.serializer, cursor._iterable)

    return cursor

Returns an iterable of objects matching criteria expressed in `query`
De-serializes values on the way out, using a :ref:`deserialized_gen` to
avoid incurring the cost of de-serializing all data at once, or ever, if
iteration over results does not finish (subject to order generator
constraint).

Args:
query: Query object describing the objects to return.

Raturns:
iterable cursor with all objects matching criteria


def update(self, webhookId, name=None, targetUrl=None, **request_parameters):
    check_type(webhookId, basestring, may_be_none=False)
    check_type(name, basestring)
    check_type(targetUrl, basestring)
    put_data = dict_from_items_with_values(request_parameters, name=name, targetUrl=targetUrl)
    json_data = self._session.put(((API_ENDPOINT + '/') + webhookId), json=put_data)
    return self._object_factory(OBJECT_TYPE, json_data)

Update a webhook, by ID.

Args:
webhookId(basestring): The webhook ID.
name(basestring): A user-friendly name for this webhook.
targetUrl(basestring): The URL that receives POST requests for
each event.
**request_parameters: Additional request parameters (provides
support for parameters that may be added in the future).

Returns:
Webhook: A Webhook object with the updated Webex Teams webhook
details.

Raises:
TypeError: If the parameter types are incorrect.
ApiError: If the Webex Teams cloud returns an error.


class Partition(PTransformWithSideInputs):

    class ApplyPartitionFnFn(DoFn):

        def process(self, element, partitionfn, n, *args, **kwargs):
            partition = partitionfn.partition_for(element, n, *args, **kwargs)
            if not 0 <= partition < n:
                raise ValueError('PartitionFn specified out-of-bounds partition index: %d not in [0, %d)' % (partition, n))
            yield pvalue.TaggedOutput(str(partition), element)

    def make_fn(self, fn, has_side_inputs):
        return fn if isinstance(fn, PartitionFn) else CallableWrapperPartitionFn(fn)

    def expand(self, pcoll):
        n = int(self.args[0])
        args, kwargs = util.insert_values_in_args(self.args, self.kwargs, self.side_inputs)
        return pcoll | ParDo(self.ApplyPartitionFnFn(), self.fn, *args, **kwargs).with_outputs(*[str(t) for t in range(n)])

Split a PCollection into several partitions.

Uses the specified PartitionFn to separate an input PCollection into the
specified number of sub-PCollections.

When apply()d, a Partition() PTransform requires the following:

Args:
partitionfn: a PartitionFn, or a callable with the signature described in
CallableWrapperPartitionFn.
n: number of output partitions.

The result of this PTransform is a simple list of the output PCollections
representing each of n partitions, in order.


def design_stat_cooling(self, value='Cooling'):
    if (value is not None):
        try:
            value = str(value)
        except ValueError:
            raise ValueError('value {} need to be of type str for field `design_stat_cooling`'.format(value))
        if (',' in value):
            raise ValueError('value should not contain a comma for field `design_stat_cooling`')
        vals = set()
        vals.add('Cooling')
        if (value not in vals):
            raise ValueError('value {} is not an accepted value for field `design_stat_cooling`'.format(value))
    self._design_stat_cooling = value

Corresponds to IDD Field `design_stat_cooling`

Args:
value (str): value for IDD Field `design_stat_cooling`
Accepted values are:
- Cooling
Default value: Cooling
if `value` is None it will not be checked against the
specification and is assumed to be a missing value

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


def __init__(self, path):

        self.me = Path(path)
        self.tag = 'dict'
        self.value = []

init

Args:
path (str): The absolute path of the plist


def from_json(cls, key, scopes, subject=None):
    credentials_type = key['type']
    if (credentials_type != 'service_account'):
        raise ValueError(('key: expected type service_account (got %s)' % credentials_type))
    email = key['client_email']
    key = OpenSSL.crypto.load_privatekey(OpenSSL.crypto.FILETYPE_PEM, key['private_key'])
    return cls(key=key, email=email, scopes=scopes, subject=subject)

Alternate constructor intended for using JSON format of private key.

Args:
key (dict) - Parsed JSON with service account credentials.
scopes (Union[str, collections.Iterable[str]]) -
List of permissions that the application requests.
subject (str) - The email address of the user for which
the application is requesting delegated access.

Returns:
ServiceAccount


def str2fl(x):

    def helper_to_fl(s_):
        ' deals with odd string imports converts to float'
        if (s_ == ''):
            return 'null'
        elif (',' in s_):
            s_ = s_.replace(',', '')
        try:
            return float(s_)
        except:
            return s_
    fl_lst = []
    if isinstance(x[0], str):
        for xi in range(len(x)):
            fl_lst.append(helper_to_fl(x[xi]))
    elif isinstance(x[0], list):
        for xi in range(len(x)):
            fl_lst.append(str2fl(x[xi]))
    else:
        return False
    return fl_lst

Recurses through lists and converts lists of string to float

Args:
x: string or list of strings


def searchFor(page, text, hit_max = 16, quads = False):

    CheckParent(page)
    dl = page.getDisplayList()
    tp = dl.getTextPage()

    rlist = tp.search(text, hit_max = hit_max, quads = quads)
    dl = None
    tp = None
    return rlist

Search for a string on a page.

Args:
text: string to be searched for
hit_max: maximum hits
quads: return quads instead of rectangles
Returns:
a list of rectangles or quads, each containing one occurrence.


def PureDotProductAttention(dropout=0.0, mode='train'):

  def init_fun(_, input_shapes):
    q_shape, _, v_shape, _ = input_shapes
    output_shape = q_shape[:-1] + (v_shape[-1],)
    return output_shape, ()
  def apply_fun(params, inputs, **kwargs):
    del params
    q, k, v, mask = inputs
    rng = kwargs.get('rng', None)
    return DotProductAttention(q, k, v, mask,
                               dropout=dropout, mode=mode, rng=rng)
  return init_fun, apply_fun

Pure single-headed self-attention.

Args:
dropout: float: dropout rate
mode: str: 'train' or 'eval'

Returns:
Pure single-headed attention layer. (No Dense transforms on input.)


def add_region_location(self, region, locations=None, use_live=True):
    return self.add_country_locations(Country.get_countries_in_region(region, exception=HDXError, use_live=use_live), locations=locations)

Add all countries in a region. If a 3 digit UNStats M49 region code is not provided, value is parsed as a
region name. If any country is already added, it is ignored.

Args:
region (str): M49 region, intermediate region or subregion to add
locations (Optional[List[str]]): Valid locations list. Defaults to list downloaded from HDX.
use_live (bool): Try to get use latest country data from web rather than file in package. Defaults to True.

Returns:
bool: True if all countries in region added or False if any already present.


def __init__(self, step):

        logger.debug("starting")

        self.description = None
        self.foreach_items = None
        self.in_parameters = None
        self.retry_decorator = None
        self.run_me = True
        self.skip_me = False
        self.swallow_me = False
        self.name = None
        self.while_decorator = None

        if isinstance(step, dict):
            self.name = step['name']
            logger.debug(f"{self.name} is complex.")

            self.in_parameters = step.get('in', None)

            self.description = step.get('description', None)
            if self.description:
                logger.info(f"{self.name}: {self.description}")

            self.foreach_items = step.get('foreach', None)

            retry_definition = step.get('retry', None)
            if retry_definition:
                self.retry_decorator = RetryDecorator(retry_definition)

            self.run_me = step.get('run', True)

            self.skip_me = step.get('skip', False)

            self.swallow_me = step.get('swallow', False)

            while_definition = step.get('while', None)
            if while_definition:
                self.while_decorator = WhileDecorator(while_definition)

        else:

            logger.debug(f"{step} is a simple string.")
            self.name = step

        self.module = pypyr.moduleloader.get_module(self.name)
        try:
            self.run_step_function = getattr(self.module, 'run_step')
        except AttributeError:
            logger.error(f"The step {self.name} in module {self.module} "
                         "doesn't have a run_step(context) function.")
            raise

        logger.debug("done")

Initialize the class. No duh, huh?.

You can happily expect the initializer to initialize all
member attributes.

Args:
step: a string or a dict. This is the actual step as it exists in
the pipeline yaml - which is to say it can just be a string
for a simple step, or a dict for a complex step.


def orphan_entry(self, rval: RawObject) -> 'ArrayEntry':
    val = self.entry_from_raw(rval)
    return ArrayEntry(0, EmptyList(), EmptyList(), val, None, self, val.timestamp)

Return an isolated entry of the receiver.

Args:
rval: Raw object to be used for the returned entry.


def lookup_rest_method(self, orig_request):

    method_name, method, params = self.config_manager.lookup_rest_method(
        orig_request.path, orig_request.request_uri, orig_request.http_method)
    orig_request.method_name = method_name
    return method, params

Looks up and returns rest method for the currently-pending request.

Args:
orig_request: An ApiRequest, the original request from the user.

Returns:
A tuple of (method descriptor, parameters), or (None, None) if no method
was found for the current request.


def addSources(self, *sources):

        self._sources.extend(sources)

        debug.logger & debug.flagCompiler and debug.logger(
            'current MIB source(s): %s' % ', '.join([str(x) for x in self._sources]))

        return self

Add more ASN.1 MIB source repositories.

MibCompiler.compile will invoke each of configured source objects
in order of their addition asking each to fetch MIB module specified
by name.

Args:
sources: reader object(s)

Returns:
reference to itself (can be used for call chaining)


def _get_snpeff_transcript(self, transcript_info):
    transcript = Transcript(hgnc_symbol=transcript_info.get('Gene_Name'), transcript_id=transcript_info.get('Feature'), ensembl_id=transcript_info.get('Gene_ID'), biotype=transcript_info.get('Transcript_BioType'), consequence=transcript_info.get('Annotation'), exon=transcript_info.get('Rank'), HGVSc=transcript_info.get('HGVS.c'), HGVSp=transcript_info.get('HGVS.p'))
    return transcript

Create a transcript based on the snpeff annotation

Args:
transcript_info (dict): A dict with snpeff info

Returns:
transcript (puzzle.models.Transcript): A Transcripts


def _CopyFileObjectToTemporaryFile(self, file_object, temporary_file):
    file_object.seek(0, os.SEEK_SET)
    data = file_object.read(self._READ_BUFFER_SIZE)
    while data:
        temporary_file.write(data)
        data = file_object.read(self._READ_BUFFER_SIZE)

Copies the contents of the file-like object to a temporary file.

Args:
file_object (dfvfs.FileIO): file-like object.
temporary_file (file): temporary file.


def _generate_api_config_with_root(self, request):
    actual_root = self._get_actual_root(request)
    generator = api_config.ApiConfigGenerator()
    api = request.body_json['api']
    version = request.body_json['version']
    lookup_key = (api, version)
    service_factories = self._backend.api_name_version_map.get(lookup_key)
    if (not service_factories):
        return None
    service_classes = [service_factory.service_class for service_factory in service_factories]
    config_dict = generator.get_config_dict(service_classes, hostname=actual_root)
    for config in config_dict.get('items', []):
        lookup_key_with_root = (config.get('name', ''), config.get('version', ''), actual_root)
        self._config_manager.save_config(lookup_key_with_root, config)
    return config_dict

Generate an API config with a specific root hostname.

This uses the backend object and the ApiConfigGenerator to create an API
config specific to the hostname of the incoming request. This allows for
flexible API configs for non-standard environments, such as localhost.

Args:
request: An ApiRequest, the transformed request sent to the Discovery API.

Returns:
A string representation of the generated API config.


def set_back(self, x: int, y: int, r: int, g: int, b: int) -> None:

        i = self.width * y + x
        self.back_r[i] = r
        self.back_g[i] = g
        self.back_b[i] = b

Set the background color of one cell.

Args:
x (int): X position to change.
y (int): Y position to change.
r (int): Red background color, from 0 to 255.
g (int): Green background color, from 0 to 255.
b (int): Blue background color, from 0 to 255.


Element-wise tanh.

Args:
x: A tensor or variable.

Returns:
A tensor.


def _slice_single_param(param, param_ndims_to_matrix_ndims, slices, batch_shape):
    param = _broadcast_parameter_with_batch_shape(param, param_ndims_to_matrix_ndims, array_ops.ones_like(batch_shape))
    if hasattr(param, 'batch_shape_tensor'):
        param_batch_shape = param.batch_shape_tensor()
    else:
        param_batch_shape = array_ops.shape(param)
    param_batch_rank = array_ops.size(param_batch_shape)
    param_batch_shape = param_batch_shape[:param_batch_rank - param_ndims_to_matrix_ndims]
    if tensor_util.constant_value(array_ops.size(batch_shape)) != 0 and tensor_util.constant_value(array_ops.size(param_batch_shape)) == 0:
        return param
    param_slices = _sanitize_slices(slices, intended_shape=batch_shape, deficient_shape=param_batch_shape)
    if param_ndims_to_matrix_ndims > 0:
        if Ellipsis not in [slc for slc in slices if not tensor_util.is_tensor(slc)]:
            param_slices.append(Ellipsis)
        param_slices += [slice(None)] * param_ndims_to_matrix_ndims
    return param.__getitem__(tuple(param_slices))

Slices into the batch shape of a single parameter.

Args:
param: The original parameter to slice; either a `Tensor` or an object
with batch shape (LinearOperator).
param_ndims_to_matrix_ndims: `int` number of right-most dimensions used for
inferring matrix shape of the `LinearOperator`. For non-Tensor
parameters, this is the number of this param's batch dimensions used by
the matrix shape of the parent object.
slices: iterable of slices received by `__getitem__`.
batch_shape: The parameterized object's batch shape `Tensor`.

Returns:
new_param: Instance of the same type as `param`, batch-sliced according to
`slices`.


def _find_op(graph: ops.Graph, op_name: Optional[str]) -> Optional[ops.Operation]:
    if not op_name:
        return None
    init_op = graph.get_operation_by_name(op_name)
    logging.debug('Op found in the graph: %s', op_name)
    return init_op

Finds the operation with `op_name`.

Args:
graph: The graph to find from.
op_name: Name of the node.

Returns:
The operation that corresponds to `op_name`. Returns None iff op_name is an
empty string or None.

Raises:
ValueError: `op_name` is malformed.


def delete_url(self, url, token=''):
    if (token == ''):
        token = self._user_token
    return requests.delete(url, headers={'Authorization': 'Token {}'.format(token)}, verify=False)

Returns a delete resquest object taking in a url and user token.

Arguments:
url (str): The url to make post to
token (str): The authentication token

Returns:
obj: Delete request object


def is_mod_class(mod, cls):

    return inspect.isclass(cls) and inspect.getmodule(cls) == mod

Checks if a class in a module was declared in that module.

Args:
mod: the module
cls: the class


def extraterrestrial_horizontal_radiation(self, value=9999.0):
    if (value is not None):
        try:
            value = float(value)
        except ValueError:
            raise ValueError('value {} need to be of type float for field `extraterrestrial_horizontal_radiation`'.format(value))
        if (value < 0.0):
            raise ValueError('value need to be greater or equal 0.0 for field `extraterrestrial_horizontal_radiation`')
    self._extraterrestrial_horizontal_radiation = value

Corresponds to IDD Field `extraterrestrial_horizontal_radiation`

Args:
value (float): value for IDD Field `extraterrestrial_horizontal_radiation`
Unit: Wh/m2
value >= 0.0
Missing value: 9999.0
if `value` is None it will not be checked against the
specification and is assumed to be a missing value

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