def __init__(self, channel):

        self.BatchAnnotateImages = channel.unary_unary(
            "/google.cloud.vision.v1p3beta1.ImageAnnotator/BatchAnnotateImages",
            request_serializer=google_dot_cloud_dot_vision__v1p3beta1_dot_proto_dot_image__annotator__pb2.BatchAnnotateImagesRequest.SerializeToString,
            response_deserializer=google_dot_cloud_dot_vision__v1p3beta1_dot_proto_dot_image__annotator__pb2.BatchAnnotateImagesResponse.FromString,
        )
        self.AsyncBatchAnnotateFiles = channel.unary_unary(
            "/google.cloud.vision.v1p3beta1.ImageAnnotator/AsyncBatchAnnotateFiles",
            request_serializer=google_dot_cloud_dot_vision__v1p3beta1_dot_proto_dot_image__annotator__pb2.AsyncBatchAnnotateFilesRequest.SerializeToString,
            response_deserializer=google_dot_longrunning_dot_operations__pb2.Operation.FromString,
        )

Constructor.

Args:
channel: A grpc.Channel.


def put(self, url, params=None, data=None, files=None, **kwargs):
    return self.call_api('PUT', url, params=params, data=data, files=files, **kwargs)

Call the API with a PUT request.

Args:
url (str): Resource location relative to the base URL.
params (dict or None): Query-string parameters.
data (dict or None): Request body contents.
files (dict or None: Files to be passed to the request.

Returns:
An instance of ResultParser or ErrorParser.


def _GetUsers(self, key_path_suffix):
    (user_key_name, _, key_path_suffix) = key_path_suffix.partition(definitions.KEY_PATH_SEPARATOR)
    if (user_key_name == '.DEFAULT'):
        search_key_name = 'S-1-5-18'
    else:
        search_key_name = user_key_name
    user_profile_list_key = self.GetKeyByPath(self._USER_PROFILE_LIST_KEY_PATH)
    if (not user_profile_list_key):
        return None
    for user_profile_key in user_profile_list_key.GetSubkeys():
        if (search_key_name == user_profile_key.name):
            profile_path_value = user_profile_key.GetValueByName('ProfileImagePath')
            if (not profile_path_value):
                break
            profile_path = profile_path_value.GetDataAsObject()
            if (not profile_path):
                break
            key_name_upper = user_profile_key.name.upper()
            if key_name_upper.endswith('_CLASSES'):
                profile_path = '\\'.join([profile_path, 'AppData', 'Local', 'Microsoft', 'Windows', 'UsrClass.dat'])
            else:
                profile_path = '\\'.join([profile_path, 'NTUSER.DAT'])
            profile_path_upper = profile_path.upper()
            registry_file = self._GetCachedUserFileByPath(profile_path_upper)
            if (not registry_file):
                break
            key_path_prefix = definitions.KEY_PATH_SEPARATOR.join(['HKEY_USERS', user_key_name])
            key_path = ''.join([key_path_prefix, key_path_suffix])
            registry_file.SetKeyPathPrefix(key_path_prefix)
            return registry_file.GetKeyByPath(key_path)
    return None

Virtual key callback to determine the users sub keys.

Args:
key_path_suffix (str): users Windows Registry key path suffix with
leading path separator.

Returns:
WinRegistryKey: the users Windows Registry key or None if not available.


def remove_item(self, val):
    return cache.lrem(self.key, json.dumps(val))

Removes given item from the list.

Args:
val: Item

Returns:
Cache backend response.


def save_optimizer_weights_to_hdf5_group(hdf5_group, optimizer):
    if isinstance(optimizer, optimizers.Optimizer):
        symbolic_weights = optimizer.variables
    else:
        symbolic_weights = getattr(optimizer, 'weights')
    if symbolic_weights:
        weights_group = hdf5_group.create_group('optimizer_weights')
        weight_names = [str(w.path).encode('utf8') for w in symbolic_weights]
        save_attributes_to_hdf5_group(weights_group, 'weight_names', weight_names)
        weight_values = [backend.convert_to_numpy(w) for w in symbolic_weights]
        for name, val in zip(weight_names, weight_values):
            param_dset = weights_group.create_dataset(name, val.shape, dtype=val.dtype)
            if not val.shape:
                param_dset[()] = val
            else:
                param_dset[:] = val

Saves optimizer weights of a optimizer to a HDF5 group.

Args:
hdf5_group: HDF5 group.
optimizer: optimizer instance.


def _use_widgets(objs):

    from ..models.widgets import Widget
    return _any(objs, lambda obj: isinstance(obj, Widget))

Whether a collection of Bokeh objects contains a any Widget

Args:
objs (seq[Model or Document]) :

Returns:
bool


def _loop_exits_early(loop):

    loop_nodes = (astroid.For, astroid.While)
    definition_nodes = (astroid.FunctionDef, astroid.ClassDef)
    inner_loop_nodes = [
        _node
        for _node in loop.nodes_of_class(loop_nodes, skip_klass=definition_nodes)
        if _node != loop
    ]
    return any(
        _node
        for _node in loop.nodes_of_class(astroid.Break, skip_klass=definition_nodes)
        if _get_break_loop_node(_node) not in inner_loop_nodes
    )

Returns true if a loop may ends up in a break statement.

Args:
loop (astroid.For, astroid.While): the loop node inspected.

Returns:
bool: True if the loop may ends up in a break statement, False otherwise.


def get(self, dash_id):

        return make_response(render_template('dashboard.html', dash_id=dash_id, api_root=config.app_host))

Just return the dashboard id in the rendering html.

JS will do other work [ajax and rendering] according to the dash_id.

Args:
dash_id: dashboard id.

Returns:
rendered html.


def post_process(self, outputs, target_sizes):
    warnings.warn('`post_process` is deprecated and will be removed in v5 of Transformers, please use `post_process_object_detection` instead, with `threshold=0.` for equivalent results.', FutureWarning)
    logits, boxes = (outputs.logits, outputs.pred_boxes)
    if len(logits) != len(target_sizes):
        raise ValueError('Make sure that you pass in as many target sizes as the batch dimension of the logits')
    if target_sizes.shape[1] != 2:
        raise ValueError('Each element of target_sizes must contain the size (h, w) of each image of the batch')
    probs = torch.max(logits, dim=-1)
    scores = torch.sigmoid(probs.values)
    labels = probs.indices
    boxes = center_to_corners_format(boxes)
    img_h, img_w = target_sizes.unbind(1)
    scale_fct = torch.stack([img_w, img_h, img_w, img_h], dim=1).to(boxes.device)
    boxes = boxes * scale_fct[:, None, :]
    results = [{'scores': s, 'labels': l, 'boxes': b} for s, l, b in zip(scores, labels, boxes)]
    return results

Converts the raw output of [`OwlViTForObjectDetection`] into final bounding boxes in (top_left_x, top_left_y,
bottom_right_x, bottom_right_y) format.

Args:
outputs ([`OwlViTObjectDetectionOutput`]):
Raw outputs of the model.
target_sizes (`torch.Tensor` of shape `(batch_size, 2)`):
Tensor containing the size (h, w) of each image of the batch. For evaluation, this must be the original
image size (before any data augmentation). For visualization, this should be the image size after data
augment, but before padding.
Returns:
`List[Dict]`: A list of dictionaries, each dictionary containing the scores, labels and boxes for an image
in the batch as predicted by the model.


def _assert_obj_type(pub, name="pub", obj_type=DBPublication):

    if not isinstance(pub, obj_type):
        raise InvalidType(
            "`%s` have to be instance of %s, not %s!" % (
                name,
                obj_type.__name__,
                pub.__class__.__name__
            )
        )

Make sure, that `pub` is instance of the `obj_type`.

Args:
pub (obj): Instance which will be checked.
name (str): Name of the instance. Used in exception. Default `pub`.
obj_type (class): Class of which the `pub` should be instance. Default
:class:`.DBPublication`.

Raises:
InvalidType: When the `pub` is not instance of `obj_type`.


def equals(self, rhs):

    for comparator in self._comparators:
      if comparator.equals(rhs):
        return True

    return False

Checks whether any Comparator is equal to rhs.

Args:
# rhs: can be anything

Returns:
bool


def _merge(d, u):

    for k, v in u.items():

        if isinstance(v, collections.Mapping):
            d[k] = _merge(d.get(k, {}), v)

        elif isinstance(d, collections.MutableMapping):
            d[k] = v

        else:
            d = {k: v}

    return d

Merge two dictionaries (or DotDicts) together.

Args:
d: The dictionary/DotDict to merge into.
u: The source of the data to merge.


def next_population(self, population, fitnesses):

        return [self._next_solution() for _ in range(self._population_size)]

Make a new population after each optimization iteration.

Args:
population: The population current population of solutions.
fitnesses: The fitness associated with each solution in the population
Returns:
list; a list of solutions.


def gpio_set(self, pins, states):
    if (len(pins) != len(states)):
        raise ValueError('Length mismatch between pins and states.')
    size = len(pins)
    indices = (ctypes.c_uint8 * size)(*pins)
    states = (ctypes.c_uint8 * size)(*states)
    result_states = (ctypes.c_uint8 * size)()
    result = self._dll.JLINK_EMU_GPIO_SetState(ctypes.byref(indices), ctypes.byref(states), ctypes.byref(result_states), size)
    if (result < 0):
        raise errors.JLinkException(result)
    return list(result_states)

Sets the state for one or more user-controllable GPIOs.

For each of the given pins, sets the the corresponding state based on
the index.

Args:
self (JLink): the ``JLink`` instance
pins (list): list of GPIO indices
states (list): list of states to set

Returns:
A list of updated states.

Raises:
JLinkException: on error.
ValueError: if ``len(pins) != len(states)``


def value_from_message(self, message):

        message = super(DateTimeField, self).value_from_message(message)
        if message.time_zone_offset is None:
            return datetime.datetime.utcfromtimestamp(
                message.milliseconds / 1000.0)

        milliseconds = (message.milliseconds -
                        60000 * message.time_zone_offset)

        timezone = util.TimeZoneOffset(message.time_zone_offset)
        return datetime.datetime.fromtimestamp(milliseconds / 1000.0,
                                               tz=timezone)

Convert DateTimeMessage to a datetime.

Args:
A DateTimeMessage instance.

Returns:
A datetime instance.


def seed(self, initial_seed: Union[None, tf.Tensor]):
    if initial_seed is None:
        self._update_seed.assign(True)
    else:
        self._update_seed.assign(False)
    self._seed.assign(tfp.random.sanitize_seed(initial_seed))

Sets a new value of the random seed.

Args:
initial_seed: see `self.seed` for details.


def locked_put(self, credentials):

        serialized = credentials.to_json()
        self._dictionary[self._key] = serialized

Save the credentials to the dictionary.

Args:
credentials: A :class:`oauth2client.client.OAuth2Credentials`
instance.


def sub_location(self, nbr):

        assert nbr > -1, "Sub location number must be greater or equal to 0!"
        assert nbr < self.nbr_of_sub_locations() - 1, "Sub location number must be lower than %d!" % self.nbr_of_sub_locations() - 1
        return self._locations_list[nbr]

Return a given sub location, 0-based.

Args:
nbr:

Returns:


def _check_condition(self, name, condition):
    if ((condition is not None) and (condition[0].name not in self.cregs)):
        raise DAGCircuitError(('invalid creg in condition for %s' % name))

Verify that the condition is valid.

Args:
name (string): used for error reporting
condition (tuple or None): a condition tuple (ClassicalRegister,int)

Raises:
DAGCircuitError: if conditioning on an invalid register


def l1_regression_loss(y, target, name=None):
    with tf.name_scope(name, 'l1_regression', [y, target]) as scope:
        y = tf.convert_to_tensor(y, name='y')
        target = tf.convert_to_tensor(target, name='target')
        return reduce_batch_sum(tf.abs((y - target)), name=scope)

Calculates the sum of absolute errors between y and target.

Args:
y: the calculated values.
target: the desired values.
name: the name for this op, defaults to l1_regression
Returns:
A tensorflow op.


async def get_frozen(self, *args, **kwargs):
    super().validate(*args, **kwargs)
    if kwargs.get('message'):
        kwargs = json.loads(kwargs.get('message'))
    coinids = kwargs.get('coinids')
    uid = kwargs.get('uid')
    address = kwargs.get('address')
    try:
        coinid = coinid.replace('TEST', '')
    except:
        pass
    try:
        uid = int(uid)
    except:
        return (await self.error_400('User id must be integer. '))
    if ((not uid) and address):
        uid = (await self.get_uid_by_address(address=address, coinid=coinid))
        if isinstance(uid, dict):
            return uid
    if (not all([types, uid])):
        return (await self.error_400('Get frozen. Missed required fields.'))
    if isinstance(types, list):
        actives = {}
        for coinid in coinids:
            database = self.client[self.collection]
            collection = database[coinid]
            balance = (await collection.find_one({'uid': uid}))
            if (not balance):
                return (await self.error_404(('Get frozen. Balance with uid:%s and type:%s not found' % (uid, coinid))))
            actives[coinid] = int(balance['amount_frozen'])
    if isinstance(coinids, str):
        actives = {}
        for coinid in self.types:
            database = self.client[coinid]
            collection = database[self.collection]
            balance = (await collection.find_one({'uid': uid}))
            if (not balance):
                return (await self.error_404(('Get frozen. Balance with uid:%s and type:%s not found' % (uid, coinid))))
            actives[coinid] = int(balance['amount_frozen'])
    return actives

Get frozen users balance

Accepts:
- uid [integer] (users id)
- types [list | string] (array with needed types or "all")

Returns:
{
type [string] (blockchain type): amount
}


def _compute_start_end(df, start, end):

    result = {}
    time_dict = {'start': start, 'end': end}
    totals = df.groupby('date').agg({'value': sum}).reset_index()
    for time_name, time in time_dict.items():
        if not totals[totals['date'] == time['id']].empty:
            value = totals.loc[
                totals['date'] == time['id'], 'value'
            ].values[0]
        else:
            value = 0
        result[time_name] = pd.DataFrame([{
            'value': value,
            'label': time['label'],
            'groups': time['label']
        }])
    return result['start'], result['end']

Compute two dataframes with value for start and end
Args:
totals(dataframe):

Returns: Dataframe, Dataframe


def gc_velocity_update(particle, social, state):
    gbest = state.swarm[gbest_idx(state.swarm)].position
    if (not np.array_equal(gbest, particle.position)):
        return std_velocity(particle, social, state)
    rho = state.params['rho']
    inertia = state.params['inertia']
    v_max = state.params['v_max']
    size = particle.position.size
    r2 = state.rng.uniform(0.0, 1.0, size)
    velocity = __gc_velocity_equation__(inertia, rho, r2, particle, gbest)
    return __clamp__(velocity, v_max)

Guaranteed convergence velocity update.

Args:
particle: cipy.algorithms.pso.Particle: Particle to update the velocity
for.
social: cipy.algorithms.pso.Particle: The social best for the particle.
state: cipy.algorithms.pso.State: The state of the PSO algorithm.

Returns:
numpy.ndarray: the calculated velocity.


def post_file(self, url, filename, file_stream, *args, **kwargs):
    res = self._conn.post(url, files={filename: file_stream}, headers=self._prepare_headers(**kwargs))
    if ((res.status_code == 200) or (res.status_code == 201)):
        return res.text
    else:
        return None

Uploads file to provided url.

Returns contents as text

Args:
**url**: address where to upload file

**filename**: Name of the uploaded file

**file_stream**: file like object to upload

.. versionadded:: 0.3.2
**additional_headers**: (optional) Additional headers
to be used with request

Returns:
string


def _slice_length(value_length, slice_key):
    zeros = array_ops.zeros(value_length, dtype=dtypes.bool)
    return array_ops.size(zeros[slice_key], out_type=value_length.dtype)

Computes the number of elements in a slice of a value with a given length.

Returns the equivalent of: `len(range(value_length)[slice_key])`

Args:
value_length: Scalar int `Tensor`: the length of the value being sliced.
slice_key: A `slice` object used to slice elements from the value.

Returns:
The number of elements in the sliced value.


def send_messages(cls, http_request, message_requests):

        deduplicated_messages = set(message_requests)
        for msg_type, text in deduplicated_messages:
            message_function = getattr(messages, msg_type)
            message_function(http_request, text)

Deduplicate any outgoing message requests, and send the remainder.

Args:
http_request: The HTTP request in whose response we want to embed the messages
message_requests: A list of undeduplicated messages in the form of tuples of message type
and text- for example, ('error', 'Something went wrong')


def _show_signature_def_map_keys(saved_model_dir, tag_set):
    signature_def_map = get_signature_def_map(saved_model_dir, tag_set)
    print('The given SavedModel MetaGraphDef contains SignatureDefs with the following keys:')
    for signature_def_key in sorted(signature_def_map.keys()):
        print('SignatureDef key: "%s"' % signature_def_key)

Prints the keys for each SignatureDef in the SignatureDef map.

Prints the list of SignatureDef keys from the SignatureDef map specified by
the given tag-set and SavedModel directory.

Args:
saved_model_dir: Directory containing the SavedModel to inspect.
tag_set: Group of tag(s) of the MetaGraphDef to get SignatureDef map from,
in string format, separated by ','. For tag-set contains multiple tags,
all tags must be passed in.


def render(self, fname=''):

        import qnet.visualization.circuit_pyx as circuit_visualization
        from tempfile import gettempdir
        from time import time, sleep

        if not fname:

            tmp_dir = gettempdir()
            fname = os.path.join(tmp_dir, "tmp_{}.png".format(hash(time)))

        if circuit_visualization.draw_circuit(self, fname):
            done = False
            for k in range(20):
                if os.path.exists(fname):

                    done = True
                    break
                else:
                    sleep(.5)
            if done:
                return fname

        raise CannotVisualize()

Render the circuit expression and store the result in a file

Args:
fname (str): Path to an image file to store the result in.

Returns:
str: The path to the image file


def describe_training_job(self, TrainingJobName):

        if TrainingJobName not in LocalSagemakerClient._training_jobs:
            error_response = {'Error': {'Code': 'ValidationException', 'Message': 'Could not find local training job'}}
            raise ClientError(error_response, 'describe_training_job')
        else:
            return LocalSagemakerClient._training_jobs[TrainingJobName].describe()

Describe a local training job.

Args:
TrainingJobName (str): Training job name to describe.

Returns: (dict) DescribeTrainingJob Response.


def external_ids(self, **kwargs):

        path = self._get_id_path('external_ids')

        response = self._GET(path, kwargs)
        self._set_attrs_to_values(response)
        return response

Get the external ids for a specific movie id.

Args:
language: (optional) ISO 639-1 code.
append_to_response: (optional) Comma separated, any movie method.

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


def _execute_bundle(self, runner_execution_context: execution.FnApiRunnerExecutionContext, bundle_context_manager: execution.BundleContextManager, bundle_input: DataInput) -> beam_fn_api_pb2.InstructionResponse:
    worker_handler_manager = runner_execution_context.worker_handler_manager
    worker_handler_manager.register_process_bundle_descriptor(bundle_context_manager.process_bundle_descriptor)
    bundle_manager = self._get_bundle_manager(bundle_context_manager)
    last_result, deferred_inputs, newly_set_timers, watermark_updates = self._run_bundle(runner_execution_context, bundle_context_manager, bundle_input, bundle_context_manager.stage_data_outputs, bundle_context_manager.stage_timer_outputs, bundle_manager)
    for pc_name, watermark in watermark_updates.items():
        _BUNDLE_LOGGER.debug('Update: %s %s', pc_name, watermark)
        runner_execution_context.watermark_manager.set_pcoll_watermark(pc_name, watermark)
    if deferred_inputs:
        assert runner_execution_context.watermark_manager.get_stage_node(bundle_context_manager.stage.name).output_watermark() < timestamp.MAX_TIMESTAMP, 'wrong timestamp for %s. ' % runner_execution_context.watermark_manager.get_stage_node(bundle_context_manager.stage.name)
        runner_execution_context.queues.ready_inputs.enque((bundle_context_manager.stage.name, DataInput(deferred_inputs, {})))
    self._enqueue_set_timers(runner_execution_context, bundle_context_manager, newly_set_timers, bundle_input)
    if not deferred_inputs and (not newly_set_timers):
        for _, output_pc in bundle_context_manager.stage_data_outputs.items():
            _, update_output_pc = translations.split_buffer_id(output_pc)
            runner_execution_context.watermark_manager.get_pcoll_node(update_output_pc).set_produced_watermark(timestamp.MAX_TIMESTAMP)
    data_side_input = runner_execution_context.side_input_descriptors_by_stage.get(bundle_context_manager.stage.name, {})
    runner_execution_context.commit_side_inputs_to_state(data_side_input)
    buffers_to_clean = set()
    known_consumers = set()
    for transform_id, buffer_id in bundle_context_manager.stage_data_outputs.items():
        for consuming_stage_name, consuming_transform in runner_execution_context.buffer_id_to_consumer_pairs.get(buffer_id, []):
            buffer = runner_execution_context.pcoll_buffers.get(buffer_id, None)
            if buffer_id in runner_execution_context.pcoll_buffers and buffer_id not in buffers_to_clean:
                buffers_to_clean.add(buffer_id)
            elif buffer and buffer_id in buffers_to_clean:
                runner_execution_context.pcoll_buffers[buffer_id] = buffer.copy()
                buffer = runner_execution_context.pcoll_buffers[buffer_id]
            if buffer_id not in runner_execution_context.pcoll_buffers:
                buffer = bundle_context_manager.get_buffer(buffer_id, transform_id)
                runner_execution_context.pcoll_buffers[buffer_id] = buffer
                buffers_to_clean.add(buffer_id)
            if (consuming_stage_name, consuming_transform, buffer_id) in known_consumers:
                continue
            else:
                known_consumers.add((consuming_stage_name, consuming_transform, buffer_id))
            runner_execution_context.queues.watermark_pending_inputs.enque(((consuming_stage_name, timestamp.MAX_TIMESTAMP), DataInput({consuming_transform: buffer}, {})))
    for bid in buffers_to_clean:
        if bid in runner_execution_context.pcoll_buffers:
            del runner_execution_context.pcoll_buffers[bid]
    return last_result

Execute a bundle end-to-end.

Args:
runner_execution_context (execution.FnApiRunnerExecutionContext): An
object containing execution information for the pipeline.
bundle_context_manager (execution.BundleContextManager): A description of
the stage to execute, and its context.
bundle_input: The set of buffers to input into this bundle


def validate_probability(p: float, p_str: str) -> float:
    if (p < 0):
        raise ValueError('{} was less than 0.'.format(p_str))
    elif (p > 1):
        raise ValueError('{} was greater than 1.'.format(p_str))
    return p

Validates that a probability is between 0 and 1 inclusively.

Args:
p: The value to validate.
p_str: What to call the probability in error messages.

Returns:
The probability p if the probability if valid.

Raises:
ValueError if the probability is invalid.


def user(self, id):

        json = self.skype.conn("POST", "{0}/batch/profiles".format(SkypeConnection.API_PROFILE),
                               auth=SkypeConnection.Auth.SkypeToken, json={"usernames": [id]}).json()
        if json and "status" not in json[0]:
            return self.merge(SkypeUser.fromRaw(self.skype, json[0]))
        else:
            return None

Retrieve public information about a user.

Args:
id (str): user identifier to lookup

Returns:
SkypeUser: resulting user object


def initialize(self, session_creator, session_init):

        assert isinstance(session_creator, tfv1.train.SessionCreator), session_creator
        assert isinstance(session_init, SessionInit), session_init
        session_init._setup_graph()

        logger.info("Creating the session ...")

        self.sess = session_creator.create_session()
        self.initialize_hooks()

        if self.is_chief:
            logger.info("Initializing the session ...")
            session_init._run_init(self.sess)
        else:
            if not isinstance(session_init, JustCurrentSession):
                logger.warn("This is not a chief worker, 'session_init' was ignored!")

        self.sess.graph.finalize()
        logger.info("Graph Finalized.")

Create the session and set `self.sess`.
Call `self.initiailize_hooks()`
Finalize the graph.

It must be called after callbacks are setup.

Args:
session_creator (tf.train.SessionCreator):
session_init (sessinit.SessionInit):


def get_help_datapacks(filepath, prefix='!'):
    help_contents = get_help_data(filepath)
    datapacks = []
    for d in help_contents:
        heading = d
        content = ''
        if ('commands' in d.lower()):
            for c in help_contents[d]:
                if ('name' not in c):
                    continue
                content += '- `'
                command = (prefix + c['name'])
                content += '{}'.format(command)
                if ('params' in c):
                    for param in c['params']:
                        content += ' [{}]'.format(param)
                content += '`: '
                if ('description' in c):
                    content += c['description']
                content += '\n'
        else:
            content += help_contents[d]
        datapacks.append((heading, content, False))
    return datapacks

Load help text from a file and give it as datapacks

Args:
filepath (str): The file to load help text from
prefix (str): The prefix to use for commands

Returns:
datapacks (list): The datapacks from the file


def _GetHashes(self, target_queue, max_hashes):

    hashes = []
    for _ in range(0, max_hashes):
      try:
        item = target_queue.get_nowait()
      except Queue.Empty:
        continue
      hashes.append(item)
    return hashes

Retrieves a list of items from a queue.

Args:
target_queue (Queue.queue): queue to retrieve hashes from.
max_hashes (int): maximum number of items to retrieve from the
target_queue.

Returns:
list[object]: list of at most max_hashes elements from the target_queue.
The list may have no elements if the target_queue is empty.


def execute_until_false(method, interval_s):
    interval = Interval(method, stop_if_false=True)
    interval.start(interval_s)
    return interval

Executes a method forever until the method returns a false value.

Args:
method: The callable to execute.
interval_s: The number of seconds to start the execution after each method
finishes.
Returns:
An Interval object.


def default(self, obj):

        if isinstance(obj, datetime):
            return obj.isoformat()

        if issubclass(obj.__class__, Enum.__class__):
            return obj.value

        to_json = getattr(obj, 'to_json', None)
        if to_json:
            out = obj.to_json()
            if issubclass(obj.__class__, Model):
                out.update({'__type': obj.__class__.__name__})

            return out

        return JSONEncoder.default(self, obj)

Default object encoder function

Args:
obj (:obj:`Any`): Object to be serialized

Returns:
JSON string


def get_equilibrium_reaction_energy(self, entry):

        if entry not in self.stable_entries:
            raise ValueError("Equilibrium reaction energy is available only "
                             "for stable entries.")
        if entry.is_element:
            return 0
        entries = [e for e in self.stable_entries if e != entry]
        modpd = PhaseDiagram(entries, self.elements)
        return modpd.get_decomp_and_e_above_hull(entry,
                                                 allow_negative=True)[1]

Provides the reaction energy of a stable entry from the neighboring
equilibrium stable entries (also known as the inverse distance to
hull).

Args:
entry: A PDEntry like object

Returns:
Equilibrium reaction energy of entry. Stable entries should have
equilibrium reaction energy <= 0.


def to_sparse(self, name=None):
    with ops.name_scope(name, 'RaggedToSparse', [self]):
        result = gen_ragged_conversion_ops.ragged_tensor_to_sparse(self.nested_row_splits, self.flat_values, name=name)
        return sparse_tensor.SparseTensor(result.sparse_indices, result.sparse_values, result.sparse_dense_shape)

Converts this `RaggedTensor` into a `tf.sparse.SparseTensor`.

Example:

>>> rt = tf.ragged.constant([[1, 2, 3], [4], [], [5, 6]])
>>> print(rt.to_sparse())
SparseTensor(indices=tf.Tensor(
[[0 0] [0 1] [0 2] [1 0] [3 0] [3 1]],
shape=(6, 2), dtype=int64),
values=tf.Tensor([1 2 3 4 5 6], shape=(6,), dtype=int32),
dense_shape=tf.Tensor([4 3], shape=(2,), dtype=int64))

Args:
name: A name prefix for the returned tensors (optional).

Returns:
A SparseTensor with the same values as `self`.


def put(self, resource):

        endpoint = self.endpoint

        if resource.id:
            endpoint = self._build_url(endpoint, resource.id)

        response = self.api.execute("PUT", endpoint, json=resource.as_dict())

        if not response.ok:
            raise Error.parse(response.json())

        return self._cls.parse(response.json())

Edits an existing resource

Args:
resource - gophish.models.Model - The resource instance


def _build_options(options):
    opts = tfprof_options_pb2.OptionsProto()
    opts.max_depth = options.get('max_depth', 10)
    opts.min_bytes = options.get('min_bytes', 0)
    opts.min_peak_bytes = options.get('min_peak_bytes', 0)
    opts.min_residual_bytes = options.get('min_residual_bytes', 0)
    opts.min_output_bytes = options.get('min_output_bytes', 0)
    opts.min_micros = options.get('min_micros', 0)
    opts.min_accelerator_micros = options.get('min_accelerator_micros', 0)
    opts.min_cpu_micros = options.get('min_cpu_micros', 0)
    opts.min_params = options.get('min_params', 0)
    opts.min_float_ops = options.get('min_float_ops', 0)
    opts.min_occurrence = options.get('min_occurrence', 0)
    opts.step = options.get('step', -1)
    opts.order_by = options.get('order_by', 'name')
    for p in options.get('account_type_regexes', []):
        opts.account_type_regexes.append(p)
    for p in options.get('start_name_regexes', []):
        opts.start_name_regexes.append(p)
    for p in options.get('trim_name_regexes', []):
        opts.trim_name_regexes.append(p)
    for p in options.get('show_name_regexes', []):
        opts.show_name_regexes.append(p)
    for p in options.get('hide_name_regexes', []):
        opts.hide_name_regexes.append(p)
    opts.account_displayed_op_only = options.get('account_displayed_op_only', False)
    for p in options.get('select', []):
        opts.select.append(p)
    opts.output = options.get('output', 'stdout')
    opts.dump_to_file = options.get('dump_to_file', '')
    return opts

Build tfprof.OptionsProto.

Args:
options: A dictionary of options.

Returns:
tfprof.OptionsProto.


def ParseFileObject(self, parser_mediator, file_object):

    filename = parser_mediator.GetFilename()
    if not filename.startswith('INFO2'):
      return

    file_header_map = self._GetDataTypeMap('recycler_info2_file_header')

    try:
      file_header, _ = self._ReadStructureFromFileObject(
          file_object, 0, file_header_map)
    except (ValueError, errors.ParseError) as exception:
      raise errors.UnableToParseFile((
          'Unable to parse Windows Recycler INFO2 file header with '
          'error: {0!s}').format(exception))

    if file_header.unknown1 != 5:
      parser_mediator.ProduceExtractionWarning('unsupported format signature.')
      return

    file_entry_size = file_header.file_entry_size
    if file_entry_size not in (280, 800):
      parser_mediator.ProduceExtractionWarning(
          'unsupported file entry size: {0:d}'.format(file_entry_size))
      return

    file_offset = file_object.get_offset()
    file_size = file_object.get_size()

    while file_offset < file_size:
      self._ParseInfo2Record(
          parser_mediator, file_object, file_offset, file_entry_size)

      file_offset += file_entry_size

Parses a Windows Recycler INFO2 file-like object.

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

Raises:
UnableToParseFile: when the file cannot be parsed.


def random_positive_definite_matrix(shape, dtype, oversampling_ratio=4, force_well_conditioned=False):
    dtype = dtypes.as_dtype(dtype)
    if not tensor_util.is_tf_type(shape):
        shape = tensor_shape.TensorShape(shape)
        shape.dims[-1].assert_is_compatible_with(shape.dims[-2])
    shape = shape.as_list()
    n = shape[-2]
    s = oversampling_ratio * shape[-1]
    wigner_shape = shape[:-2] + [n, s]
    with ops.name_scope('random_positive_definite_matrix'):
        wigner = random_normal(wigner_shape, dtype=dtype, stddev=math_ops.cast(1 / np.sqrt(s), dtype.real_dtype))
        wishart = math_ops.matmul(wigner, wigner, adjoint_b=True)
        if force_well_conditioned:
            wishart += linalg_ops.eye(n, dtype=dtype)
            wishart /= math_ops.cast(2, dtype)
        return wishart

[batch] positive definite Wisart matrix.

A Wishart(N, S) matrix is the S sample covariance matrix of an N-variate
(standard) Normal random variable.

Args:
shape:  `TensorShape` or Python list.  Shape of the returned matrix.
dtype:  `TensorFlow` `dtype` or Python dtype.
oversampling_ratio: S / N in the above.  If S < N, the matrix will be
singular (unless `force_well_conditioned is True`).
force_well_conditioned:  Python bool.  If `True`, add `1` to the diagonal
of the Wishart matrix, then divide by 2, ensuring most eigenvalues are
close to 1.

Returns:
`Tensor` with desired shape and dtype.


def _Extract(self, source_path_specs, destination_path, output_writer, skip_duplicates=True):
    output_writer.Write('Extracting file entries.\n')
    path_spec_generator = self._path_spec_extractor.ExtractPathSpecs(source_path_specs, resolver_context=self._resolver_context)
    for path_spec in path_spec_generator:
        self._ExtractFileEntry(path_spec, destination_path, output_writer, skip_duplicates=skip_duplicates)

Extracts files.

Args:
source_path_specs (list[dfvfs.PathSpec]): path specifications to extract.
destination_path (str): path where the extracted files should be stored.
output_writer (CLIOutputWriter): output writer.
skip_duplicates (Optional[bool]): True if files with duplicate content
should be skipped.


def __init__(self, channel):
    self.Echo = channel.unary_unary('/proto.echo.v1.EchoService/Echo', request_serializer=proto_dot_echo_dot_v1_dot_echo__pb2.EchoRequest.SerializeToString, response_deserializer=proto_dot_echo_dot_v1_dot_echo__pb2.EchoResponse.FromString)

Constructor.

Args:
channel: A grpc.Channel.


def init_database(connection=None, dbname=None):
    connection = (connection or connect())
    dbname = (dbname or bigchaindb.config['database']['name'])
    create_database(connection, dbname)
    create_tables(connection, dbname)

Initialize the configured backend for use with BigchainDB.

Creates a database with :attr:`dbname` with any required tables
and supporting indexes.

Args:
connection (:class:`~bigchaindb.backend.connection.Connection`): an
existing connection to use to initialize the database.
Creates one if not given.
dbname (str): the name of the database to create.
Defaults to the database name given in the BigchainDB
configuration.


def replace_parameters(context, nb, parameters):

    nb = copy.deepcopy(nb)

    param_content = DagsterTranslator.codify(parameters)

    newcell = nbformat.v4.new_code_cell(source=param_content)
    newcell.metadata['tags'] = ['injected-parameters']

    param_cell_index = _find_first_tagged_cell_index(nb, 'parameters')
    injected_cell_index = _find_first_tagged_cell_index(nb, 'injected-parameters')
    if injected_cell_index >= 0:

        before = nb.cells[:injected_cell_index]
        after = nb.cells[injected_cell_index + 1 :]
        check.int_value_param(param_cell_index, -1, 'param_cell_index')

    elif param_cell_index >= 0:

        before = nb.cells[:param_cell_index]
        after = nb.cells[param_cell_index + 1 :]
    else:

        context.log.debug(
            (
                'Warning notebook has no parameters cell, '
                'so first cell must import dagstermill and call dm.register_repo()'
            )
        )
        before = nb.cells[:1]
        after = nb.cells[1:]

    nb.cells = before + [newcell] + after
    nb.metadata.papermill['parameters'] = parameters

    return nb

Assigned parameters into the appropiate place in the input notebook
Args:
nb (NotebookNode): Executable notebook object
parameters (dict): Arbitrary keyword arguments to pass to the notebook parameters.


def apply_transformation(self, structure):

        sga = SpacegroupAnalyzer(structure, symprec=self.symprec,
                                 angle_tolerance=self.angle_tolerance)
        return sga.get_conventional_standard_structure(international_monoclinic=self.international_monoclinic)

Returns most primitive cell for structure.

Args:
structure: A structure

Returns:
The same structure in a conventional standard setting


def _kl_deterministic_distribution(a, b, name=None):

  with tf.name_scope(name or "kl_deterministic_distribution"):
    return -b.log_prob(a.loc)

Calculate the batched KL divergence `KL(a || b)` with `a` Deterministic.

Args:
a: instance of a Deterministic distribution object.
b: instance of a Distribution distribution object.
name: (optional) Name to use for created operations. Default is
"kl_deterministic_distribution".

Returns:
Batchwise `KL(a || b)`.


def GetEntries(self, parser_mediator, data=None, **unused_kwargs):
    for (key, value) in iter(data.items()):
        if (not ('.torrent' in key)):
            continue
        caption = value.get('caption')
        path = value.get('path')
        seedtime = value.get('seedtime')
        if ((not caption) or (not path) or (seedtime < 0)):
            raise errors.WrongBencodePlugin(self.NAME)
    for (torrent, value) in iter(data.items()):
        if (not ('.torrent' in torrent)):
            continue
        event_data = UTorrentEventData()
        event_data.caption = value.get('caption', None)
        event_data.path = value.get('path', None)
        seedtime = value.get('seedtime', None)
        (event_data.seedtime, _) = divmod(seedtime, 60)
        for (event_key, event_value) in iter(value.items()):
            if (event_key == 'added_on'):
                date_time = dfdatetime_posix_time.PosixTime(timestamp=event_value)
                event = time_events.DateTimeValuesEvent(date_time, definitions.TIME_DESCRIPTION_ADDED)
                parser_mediator.ProduceEventWithEventData(event, event_data)
            elif (event_key == 'completed_on'):
                date_time = dfdatetime_posix_time.PosixTime(timestamp=event_value)
                event = time_events.DateTimeValuesEvent(date_time, definitions.TIME_DESCRIPTION_FILE_DOWNLOADED)
                parser_mediator.ProduceEventWithEventData(event, event_data)
            elif (event_key == 'modtimes'):
                for modtime in event_value:
                    if (not modtime):
                        continue
                    date_time = dfdatetime_posix_time.PosixTime(timestamp=modtime)
                    event = time_events.DateTimeValuesEvent(date_time, definitions.TIME_DESCRIPTION_MODIFICATION)
                    parser_mediator.ProduceEventWithEventData(event, event_data)

Extracts uTorrent active torrents.

This is the main parsing engine for the plugin. It determines if
the selected file is the proper file to parse and extracts current
running torrents.

interface.Process() checks for the given BENCODE_KEYS set, ensures
that it matches, and then passes the bencoded data to this function for
parsing. This plugin then parses the entire set of bencoded data to extract
the variable file-name keys to retrieve their values.

uTorrent creates a file, resume.dat, and a backup, resume.dat.old, to
for all active torrents. This is typically stored in the user's
application data folder.

These files, at a minimum, contain a '.fileguard' key and a dictionary
with a key name for a particular download with a '.torrent' file
extension.

Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
data (Optional[dict[str, object]]): bencode data values.


def to_geotiff(arr, path='./output.tif', proj=None, spec=None, bands=None, **kwargs):
    assert has_rasterio, 'To create geotiff images please install rasterio'
    try:
        img_md = arr.rda.metadata['image']
        x_size = img_md['tileXSize']
        y_size = img_md['tileYSize']
    except (AttributeError, KeyError):
        x_size = kwargs.get('chunk_size', 256)
        y_size = kwargs.get('chunk_size', 256)
    try:
        tfm = (kwargs['transform'] if ('transform' in kwargs) else arr.affine)
    except:
        tfm = None
    dtype = (arr.dtype.name if (arr.dtype.name != 'int8') else 'uint8')
    if ((spec is not None) and (spec.lower() == 'rgb')):
        if (bands is None):
            bands = arr._rgb_bands
        if (not arr.options.get('dra')):
            from gbdxtools.rda.interface import RDA
            rda = RDA()
            dra = rda.HistogramDRA(arr)
            arr = dra.aoi(bbox=arr.bounds)
        arr = arr[(bands, ...)].astype(np.uint8)
        dtype = 'uint8'
    elif (bands is not None):
        arr = arr[(bands, ...)]
    meta = {'width': arr.shape[2], 'height': arr.shape[1], 'count': arr.shape[0], 'dtype': dtype, 'driver': 'GTiff', 'transform': tfm}
    if (proj is not None):
        meta['crs'] = {'init': proj}
    if (('tiled' in kwargs) and kwargs['tiled']):
        meta.update(blockxsize=x_size, blockysize=y_size, tiled='yes')
    with rasterio.open(path, 'w', **meta) as dst:
        writer = rio_writer(dst)
        result = store(arr, writer, compute=False)
        result.compute(scheduler=threaded_get)
    return path

Write out a geotiff file of the image

Args:
path (str): path to write the geotiff file to, default is ./output.tif
proj (str): EPSG string of projection to reproject to
spec (str): if set to 'rgb', write out color-balanced 8-bit RGB tif
bands (list): list of bands to export. If spec='rgb' will default to RGB bands

Returns:
str: path the geotiff was written to


def console_set_background_flag(con: tcod.console.Console, flag: int) -> None:

    lib.TCOD_console_set_background_flag(_console(con), flag)

Change the default blend mode for this console.

Args:
con (Console): Any Console instance.
flag (int): Blend mode to use by default.

.. deprecated:: 8.5
Set :any:`Console.default_bg_blend` instead.


def max_substring(words, position=0, _last_letter=''):
    try:
        letter = [word[position] for word in words]
    except IndexError:
        return _last_letter
    if (all(((l == letter[0]) for l in letter)) is True):
        _last_letter += max_substring(words, position=(position + 1), _last_letter=letter[0])
        return _last_letter
    else:
        return _last_letter

Finds max substring shared by all strings starting at position

Args:

words (list): list of unicode of all words to compare

position (int): starting position in each word to begin analyzing
for substring

_last_letter (unicode): last common letter, only for use
internally unless you really know what
you are doing

Returns:
unicode: max str common to all words

Examples:
.. code-block:: Python

>>> max_substring(['aaaa', 'aaab', 'aaac'])
'aaa'
>>> max_substring(['abbb', 'bbbb', 'cbbb'], position=1)
'bbb'
>>> max_substring(['abc', 'bcd', 'cde'])
''


def is_complex_code(self, contract):

        is_complex = self._is_complex_code(contract)

        result = red('Yes') if is_complex else green('No')

        return "\tComplex code? {}\n".format(result)

Check if the code is complex
Heuristic, the code is complex if:
- One function has a cyclomatic complexity > 7
Args:
contract


def set_tf_cuda_clang(environ_cp):
    question = 'Do you want to use clang as CUDA compiler?'
    yes_reply = 'Clang will be used as CUDA compiler.'
    no_reply = 'nvcc will be used as CUDA compiler.'
    set_action_env_var(environ_cp, 'TF_CUDA_CLANG', None, True, question=question, yes_reply=yes_reply, no_reply=no_reply, bazel_config_name='cuda_clang')

set TF_CUDA_CLANG action_env.

Args:
environ_cp: copy of the os.environ.


def _get_analytic_path(path: str, elem_id: str) -> str:
    extension_slice_names = _EXTENSION_SLICE_NAMES_RE.findall(elem_id)
    if extension_slice_names:
        extension_path_elements = _EXTENSION_PATH_ELEMENTS_RE.finditer(path)
        index_adjustment = 0
        for slice_name, path_element in zip(extension_slice_names, extension_path_elements):
            start = path_element.start(1) + index_adjustment
            end = path_element.end(1) + index_adjustment
            path = path[:start] + slice_name + path[end:]
            index_adjustment += len(slice_name) - 9
    path = path.replace('[x]', '')
    return path

Builds a usable FHIRPath given an element path and id.

Removes choice type indicators '[x]'

Some element definitions reference attributes from extension slices. These
elements will have ids like 'Foo.extension:someExtension' but
paths like 'Foo.extension' We want to treat these paths as
'Foo.someExtension' so we replace the 'extension' part of the
path with the slice name.

Args:
path: The path attribute from the element definition to clean.
elem_id: The id attribute from the element definition to clean.

Returns:
The cleaned path name.


def tdist95conf_level(df):
    df = int(round(df))
    highest_table_df = len(_T_DIST_95_CONF_LEVELS)
    if (df >= 200):
        return 1.96
    if (df >= 100):
        return 1.984
    if (df >= 80):
        return 1.99
    if (df >= 60):
        return 2.0
    if (df >= 50):
        return 2.009
    if (df >= 40):
        return 2.021
    if (df >= highest_table_df):
        return _T_DIST_95_CONF_LEVELS[(highest_table_df - 1)]
    return _T_DIST_95_CONF_LEVELS[df]

Approximate the 95% confidence interval for Student's T distribution.

Given the degrees of freedom, returns an approximation to the 95%
confidence interval for the Student's T distribution.

Args:
df: An integer, the number of degrees of freedom.

Returns:
A float.


def _update_output_shapes(self, incoming_output_shapes: List[TensorShape]):
    nest.assert_same_structure(self._output_shapes, incoming_output_shapes)
    updated_output_shapes = []
    for old_output_shape, incoming_output_shape in zip(self._output_shapes, incoming_output_shapes):
        if old_output_shape:
            updated_output_shapes.append(old_output_shape)
        else:
            updated_output_shapes.append(incoming_output_shape)
    self._output_shapes = updated_output_shapes

Update the existing output shapes based on the new output shapes.

The existing output shapes always have higher piority than the new incoming
output shapes.
Args:
incoming_output_shapes: nested structure of TensorShape to override the
existing output shapes.


def evaluate_layout(self, layout):

    layout_dict = {}
    if layout:
      for pair in layout.split(";"):
        mtf_dimension_name, mesh_dimension_name = pair.split(":", 1)
        if (mtf_dimension_name in
            self._layout_validator.splittable_mtf_dimension_names):
          layout_dict[mtf_dimension_name] = mesh_dimension_name
        else:
          logging.warning("Skipping unsplittable dimension %s.",
                          mtf_dimension_name)

    tensor_memory = {}
    for tensor_name in self._graph.get_all_tensor_names():
      if self._graph.is_tensor_on_canonical_device(tensor_name):
        tensor_memory[tensor_name] = self._graph.get_tensor_size(
            tensor_name, layout_dict,
            self._layout_validator.mesh_dimension_name_to_size)
      else:
        tensor_memory[tensor_name] = 0.0

    peak_memory_usage = 0.0
    for tensor_names in self._get_memory_contents():
      memory_usage = 0.0
      for tensor_name in tensor_names:
        memory_usage += tensor_memory[tensor_name]
      peak_memory_usage = max(peak_memory_usage, memory_usage)
    return peak_memory_usage

The current objective value for the given layout.

TODO(joshuawang): The current function does not check that the given
layout is valid.

Args:
layout: a string, representing a layout to evaluate (e.g.
"d_ff:m1;heads:m2").

Returns:
A float, the objective value.


def EnablePlugins(self, plugin_includes):

    self._plugins = []
    if not self._plugin_classes:
      return

    default_plugin_name = '{0:s}_default'.format(self.NAME)
    for plugin_name, plugin_class in iter(self._plugin_classes.items()):
      if plugin_name == default_plugin_name:
        self._default_plugin = plugin_class()
        continue

      if plugin_includes and plugin_name not in plugin_includes:
        continue

      plugin_object = plugin_class()
      self._plugins.append(plugin_object)

Enables parser plugins.

Args:
plugin_includes (list[str]): names of the plugins to enable, where None
or an empty list represents all plugins. Note the default plugin, if
it exists, is always enabled and cannot be disabled.


async def _find(self, rpcmethod):
    log.info('crawling network with nearest: %s', str(tuple(self.nearest)))
    count = self.alpha
    if (self.nearest.get_ids() == self.last_ids_crawled):
        count = len(self.nearest)
    self.last_ids_crawled = self.nearest.get_ids()
    dicts = {}
    for peer in self.nearest.get_uncontacted()[:count]:
        dicts[peer.id] = rpcmethod(peer, self.node)
        self.nearest.mark_contacted(peer)
    found = (await gather_dict(dicts))
    return (await self._nodes_found(found))

Get either a value or list of nodes.

Args:
rpcmethod: The protocol's callfindValue or call_find_node.

The process:
1. calls find_* to current ALPHA nearest not already queried nodes,
adding results to current nearest list of k nodes.
2. current nearest list needs to keep track of who has been queried
already sort by nearest, keep KSIZE
3. if list is same as last time, next call should be to everyone not
yet queried
4. repeat, unless nearest list has all been queried, then ur done


def __ge__(self, other: 'TensorFluent') -> 'TensorFluent':

        return self._binary_op(self, other, tf.greater_equal, tf.float32)

Returns a TensorFluent for the greater-then-or-equal relational operator.

Args:
self: The first operand.
other: The second operand.


def handle(self, client, subhooks=()):
    new_data = self.fetch(client)
    updated = {}
    if (not subhooks):
        subhooks = [self.name]
    for subhook in subhooks:
        new_key = self.extract_key(new_data, subhook)
        if (new_key != self.previous_keys.get(subhook)):
            updated[subhook] = new_key
    if updated:
        logger.debug('Hook %s: data changed from %r to %r', self.name, self.previous_keys, updated)
        self.previous_keys.update(updated)
        return (True, new_data)
    return (False, None)

Handle a new update.

Fetches new data from the client, then compares it to the previous
lookup.

Returns:
(bool, new_data): whether changes occurred, and the new value.


def tv_list(self, **kwargs):

        path = self._get_path('tv_list')

        response = self._GET(path, kwargs)
        self._set_attrs_to_values(response)
        return response

Get the list of TV genres.

Args:
language: (optional) ISO 639-1 code.

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


def _search_forward_n_swaps(layout, gates, coupling_map, depth=SEARCH_DEPTH, width=SEARCH_WIDTH):
    (gates_mapped, gates_remaining) = _map_free_gates(layout, gates, coupling_map)
    base_step = {'layout': layout, 'swaps_added': 0, 'gates_mapped': gates_mapped, 'gates_remaining': gates_remaining}
    if ((not gates_remaining) or (depth == 0)):
        return base_step
    possible_swaps = coupling_map.get_edges()

    def _score_swap(swap):
        'Calculate the relative score for a given SWAP.'
        trial_layout = layout.copy()
        trial_layout.swap(*swap)
        return _calc_layout_distance(gates, coupling_map, trial_layout)
    ranked_swaps = sorted(possible_swaps, key=_score_swap)
    (best_swap, best_step) = (None, None)
    for swap in ranked_swaps[:width]:
        trial_layout = layout.copy()
        trial_layout.swap(*swap)
        next_step = _search_forward_n_swaps(trial_layout, gates_remaining, coupling_map, (depth - 1), width)
        if ((best_swap is None) or (_score_step(next_step) > _score_step(best_step))):
            (best_swap, best_step) = (swap, next_step)
    best_swap_gate = _swap_ops_from_edge(best_swap, layout)
    return {'layout': best_step['layout'], 'swaps_added': (1 + best_step['swaps_added']), 'gates_remaining': best_step['gates_remaining'], 'gates_mapped': ((gates_mapped + best_swap_gate) + best_step['gates_mapped'])}

Search for SWAPs which allow for application of largest number of gates.

Arguments:
layout (Layout): Map from virtual qubit index to physical qubit index.
gates (list): Gates to be mapped.
coupling_map (CouplingMap): CouplingMap of the target backend.
depth (int): Number of SWAP layers to search before choosing a result.
width (int): Number of SWAPs to consider at each layer.
Returns:
dict: Describes solution step found.
layout (Layout): Virtual to physical qubit map after SWAPs.
gates_remaining (list): Gates that could not be mapped.
gates_mapped (list): Gates that were mapped, including added SWAPs.


def resources_from_resource_arguments(default_num_cpus, default_num_gpus, default_resources, runtime_num_cpus, runtime_num_gpus, runtime_resources):
    if (runtime_resources is not None):
        resources = runtime_resources.copy()
    elif (default_resources is not None):
        resources = default_resources.copy()
    else:
        resources = {}
    if (('CPU' in resources) or ('GPU' in resources)):
        raise ValueError("The resources dictionary must not contain the key 'CPU' or 'GPU'")
    assert (default_num_cpus is not None)
    resources['CPU'] = (default_num_cpus if (runtime_num_cpus is None) else runtime_num_cpus)
    if (runtime_num_gpus is not None):
        resources['GPU'] = runtime_num_gpus
    elif (default_num_gpus is not None):
        resources['GPU'] = default_num_gpus
    return resources

Determine a task's resource requirements.

Args:
default_num_cpus: The default number of CPUs required by this function
or actor method.
default_num_gpus: The default number of GPUs required by this function
or actor method.
default_resources: The default custom resources required by this
function or actor method.
runtime_num_cpus: The number of CPUs requested when the task was
invoked.
runtime_num_gpus: The number of GPUs requested when the task was
invoked.
runtime_resources: The custom resources requested when the task was
invoked.

Returns:
A dictionary of the resource requirements for the task.


def frames_to_ms(frames, fps):

    if fps <= 0:
        raise ValueError("Framerate must be positive number (%f)." % fps)

    return int(round(frames * (1000 / fps)))

Convert frame-based duration to milliseconds.

Arguments:
frames: Number of frames (should be int).
fps: Framerate (must be a positive number, eg. 23.976).

Returns:
Number of milliseconds (rounded to int).

Raises:
ValueError: fps was negative or zero.


def _load_example(filename, filepath, sdk: SdkEnum) -> Optional[Example]:
    logging.debug('inspecting file %s', filepath)
    extension = filepath.split(os.extsep)[-1]
    if extension == Config.SDK_TO_EXTENSION[sdk]:
        logging.debug('sdk %s matched extension %s', api_pb2.Sdk.Name(sdk), extension)
        tag = get_tag(filepath)
        if tag is not None:
            logging.debug('playground-beam tag found')
            return _get_example(filepath, filename, tag, sdk)
    return None

Check file by filepath for matching to beam example. If file is beam example,

Args:
filename: name of the file.
filepath: path to the file.
sdk: sdk that using to find examples for the specific sdk.

Returns:
If the file is an example, return Example object
If it's not, return None
In case of error, raise Exception


def random_unitary(dim, seed=None):

    if dim == 0 or not math.log2(dim).is_integer():
        raise QiskitError("Desired unitary dimension not a positive power of 2.")
    matrix = np.zeros([dim, dim], dtype=complex)
    for j in range(dim):
        if j == 0:
            a = random_state(dim, seed)
        else:
            a = random_state(dim)
        matrix[:, j] = np.copy(a)

        i = j-1
        while i >= 0:
            dc = np.vdot(matrix[:, i], a)
            matrix[:, j] = matrix[:, j]-dc*matrix[:, i]
            i = i - 1

        matrix[:, j] = matrix[:, j] * (1.0 / np.sqrt(np.vdot(matrix[:, j], matrix[:, j])))
    return Operator(matrix)

Return a random dim x dim unitary Operator from the Haar measure.

Args:
dim (int): the dim of the state space.
seed (int): Optional. To set a random seed.

Returns:
Operator: (dim, dim) unitary operator.

Raises:
QiskitError: if dim is not a positive power of 2.


def ProcessClientResourcesStats(self, client_id, status):

    if hasattr(status, "child_session_id"):
      flow_path = status.child_session_id
    else:
      flow_path = "aff4:/%s/flows/%s" % (status.client_id, status.flow_id)

    resources = rdf_client_stats.ClientResources()
    resources.client_id = client_id
    resources.session_id = flow_path
    resources.cpu_usage.user_cpu_time = status.cpu_time_used.user_cpu_time
    resources.cpu_usage.system_cpu_time = status.cpu_time_used.system_cpu_time
    resources.network_bytes_sent = status.network_bytes_sent
    self.context.usage_stats.RegisterResources(resources)

Process status message from a client and update the stats.

Args:
client_id: Client id.
status: The status object returned from the client.


def __init__(self, k_range, query_spec):

    self._key_range = k_range
    self._query_spec = query_spec
    self._cursor = None
    self._query = None

Init.

Args:
k_range: a key_range.KeyRange object that defines the entity keys to
operate on. KeyRange object already contains a namespace.
query_spec: a model.query_spec object that defines how to retrieve
entities from datastore.


def remove(self, workflow_id):

        try:
            db = self._client[self.database]
            fs = GridFSProxy(GridFS(db.unproxied_object))

            for grid_doc in fs.find({"workflow_id": workflow_id},
                                    no_cursor_timeout=True):
                fs.delete(grid_doc._id)

            col = db[WORKFLOW_DATA_COLLECTION_NAME]
            return col.delete_one({"_id": ObjectId(workflow_id)})

        except ConnectionFailure:
            raise DataStoreNotConnected()

Removes a document specified by its id from the data store.

All associated GridFs documents are deleted as well.

Args:
workflow_id (str): The id of the document that represents a workflow run.

Raises:
DataStoreNotConnected: If the data store is not connected to the server.


def comparator(objective):
    if isinstance(objective, Minimum):
        return (lambda l, r: (l < r))
    else:
        return (lambda l, r: (l > r))

Higher order function creating a compare function for objectives.

Args:
objective (cipy.algorithms.core.Objective): The objective to create a
compare for.

Returns:
callable: Function accepting two objectives to compare.

Examples:
>>> a = Minimum(0.1)
>>> b = Minimum(0.2)
>>> compare = comparator(a)
>>> comparison = compare(a, b) # False


def url_to_filename(url):

    if url.startswith('/'):
        url = url[1:]
    if url.endswith('/'):
        url = url[:-1]

    url = remove_pardir_symbols(url)

    url = replace_dots_to_underscores_at_last(url)
    return url

Safely translate url to relative filename

Args:
url (str): A target url string

Returns:
str


def insert(self, index: int, moment_or_operation_tree: Union[(ops.Moment, ops.OP_TREE)], strategy: InsertStrategy=InsertStrategy.EARLIEST) -> int:
    moments_and_operations = list(ops.flatten_op_tree(ops.transform_op_tree(moment_or_operation_tree, self._device.decompose_operation, preserve_moments=True), preserve_moments=True))
    for moment_or_op in moments_and_operations:
        if isinstance(moment_or_op, ops.Moment):
            self._device.validate_moment(cast(ops.Moment, moment_or_op))
        else:
            self._device.validate_operation(cast(ops.Operation, moment_or_op))
    k = max(min((index if (index >= 0) else (len(self._moments) + index)), len(self._moments)), 0)
    for moment_or_op in moments_and_operations:
        if isinstance(moment_or_op, ops.Moment):
            self._moments.insert(k, moment_or_op)
            k += 1
        else:
            p = self._pick_or_create_inserted_op_moment_index(k, moment_or_op, strategy)
            while (p >= len(self._moments)):
                self._moments.append(ops.Moment())
            self._moments[p] = self._moments[p].with_operation(moment_or_op)
            self._device.validate_moment(self._moments[p])
            k = max(k, (p + 1))
            if (strategy is InsertStrategy.NEW_THEN_INLINE):
                strategy = InsertStrategy.INLINE
    return k

Inserts operations into the circuit.
Operations are inserted into the moment specified by the index and
'InsertStrategy'.
Moments within the operation tree are inserted intact.

Args:
index: The index to insert all of the operations at.
moment_or_operation_tree: The moment or operation tree to insert.
strategy: How to pick/create the moment to put operations into.

Returns:
The insertion index that will place operations just after the
operations that were inserted by this method.

Raises:
ValueError: Bad insertion strategy.


def RemoveForwardedIp(self, address, interface):

    ip = netaddr.IPNetwork(address)
    self._RunIfconfig(args=[interface, '-alias', str(ip.ip)])

Delete an IP address on the network interface.

Args:
address: string, the IP address to configure.
interface: string, the output device to use.


def _add_encoded(self, encoded):

        if self.public_key != encoded.public_key:
            raise ValueError("Attempted to add numbers encoded against "
                             "different public keys!")

        a, b = self, encoded
        if a.exponent > b.exponent:
            a = self.decrease_exponent_to(b.exponent)
        elif a.exponent < b.exponent:
            b = b.decrease_exponent_to(a.exponent)

        encrypted_scalar = a.public_key.raw_encrypt(b.encoding, 1)

        sum_ciphertext = a._raw_add(a.ciphertext(False), encrypted_scalar)
        return EncryptedNumber(a.public_key, sum_ciphertext, a.exponent)

Returns E(a + b), given self=E(a) and b.

Args:
encoded (EncodedNumber): an :class:`EncodedNumber` to be added
to `self`.

Returns:
EncryptedNumber: E(a + b), calculated by encrypting b and
taking the product of E(a) and E(b) modulo
:attr:`~PaillierPublicKey.n` ** 2.

Raises:
ValueError: if scalar is out of range or precision.


def slice_vec(expr, start, stop):

    weld_obj = WeldObject(encoder_, decoder_)

    expr_var = weld_obj.update(expr)
    if isinstance(expr, WeldObject):
        expr_var = expr.obj_id
        weld_obj.dependencies[expr_var] = expr

    weld_template =
    weld_obj.weld_code = weld_template % {"expr":expr_var,
                                          "start":start,
                                          "stop":stop}
    return weld_obj

Slices the vector.

Args:
expr (WeldObject)
start (Long)
stop (Long)


def _ReadEnumerationDataTypeDefinition(self, definitions_registry, definition_values, definition_name, is_member=False):
    if is_member:
        error_message = 'data type not supported as member'
        raise errors.DefinitionReaderError(definition_name, error_message)
    values = definition_values.get('values')
    if (not values):
        error_message = 'missing values'
        raise errors.DefinitionReaderError(definition_name, error_message)
    definition_object = self._ReadSemanticDataTypeDefinition(definitions_registry, definition_values, data_types.EnumerationDefinition, definition_name, self._SUPPORTED_DEFINITION_VALUES_ENUMERATION)
    last_name = None
    for enumeration_value in values:
        aliases = enumeration_value.get('aliases', None)
        description = enumeration_value.get('description', None)
        name = enumeration_value.get('name', None)
        number = enumeration_value.get('number', None)
        if ((not name) or (number is None)):
            if last_name:
                error_location = 'after: {0:s}'.format(last_name)
            else:
                error_location = 'at start'
            error_message = '{0:s} missing name or number'.format(error_location)
            raise errors.DefinitionReaderError(definition_name, error_message)
        else:
            try:
                definition_object.AddValue(name, number, aliases=aliases, description=description)
            except KeyError as exception:
                error_message = '{0!s}'.format(exception)
                raise errors.DefinitionReaderError(definition_name, error_message)
        last_name = name
    return definition_object

Reads an enumeration data type definition.

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

Returns:
EnumerationDataTypeDefinition: enumeration data type definition.

Raises:
DefinitionReaderError: if the definitions values are missing or if
the format is incorrect.


def search(cls, *, limit=100, page=1, accounts=None, locations=None, resources=None, properties=None, include_disabled=False, return_query=False):
    qry = db.Resource.order_by(Resource.resource_id).filter((Resource.resource_type_id == ResourceType.get(cls.resource_type).resource_type_id))
    if (not include_disabled):
        qry = qry.join(Account, (Resource.account_id == Account.account_id)).filter((Account.enabled == 1))
    if session:
        qry = qry.filter(Resource.account_id.in_(session['accounts']))
    if accounts:
        qry = qry.filter(Resource.account_id.in_([Account.get(acct).account_id for acct in accounts]))
    if locations:
        qry = qry.filter(Resource.location.in_(locations))
    if resources:
        qry = qry.filter(Resource.resource_id.in_(resources))
    if properties:
        for (prop_name, value) in properties.items():
            alias = aliased(ResourceProperty)
            qry = qry.join(alias, (Resource.resource_id == alias.resource_id))
            if (type(value) == list):
                where_clause = []
                for item in value:
                    where_clause.append((alias.value == item))
                qry = qry.filter(and_((alias.name == prop_name), or_(*where_clause)).self_group())
            else:
                qry = qry.filter(and_((alias.name == prop_name), (alias.value == value)).self_group())
    if return_query:
        return qry
    total = qry.count()
    qry = qry.limit(limit)
    qry = qry.offset((((page - 1) * limit) if (page > 1) else 0))
    return (total, [cls(x) for x in qry.all()])

Search for resources based on the provided filters. If `return_query` a sub-class of `sqlalchemy.orm.Query`
is returned instead of the resource list.

Args:
limit (`int`): Number of results to return. Default: 100
page (`int`): Pagination offset for results. Default: 1
accounts (`list` of `int`): A list of account id's to limit the returned resources to
locations (`list` of `str`): A list of locations as strings to limit the search for
resources ('list' of `str`): A list of resource_ids
properties (`dict`): A `dict` containing property name and value pairs. Values can be either a str or a list
of strings, in which case a boolean OR search is performed on the values
include_disabled (`bool`): Include resources from disabled accounts. Default: False
return_query (`bool`): Returns the query object prior to adding the limit and offset functions. Allows for
sub-classes to amend the search feature with extra conditions. The calling function must handle pagination
on its own

Returns:
`list` of `Resource`, `sqlalchemy.orm.Query`


def copy(self):
    return BinaryQuadraticModel(self.linear, self.quadratic, self.offset, self.vartype, **self.info)

Create a copy of a BinaryQuadraticModel.

Returns:
:class:`.BinaryQuadraticModel`

Examples:

>>> bqm = dimod.BinaryQuadraticModel({1: 1, 2: 2}, {(1, 2): 0.5}, 0.5, dimod.SPIN)
>>> bqm2 = bqm.copy()


def submit(self, job):

        self._check_job(job)

        if job.workingdir is None:
            job.workingdir = self.default_wdir
        job.imageid = du.create_provisioned_image(self.client, job.image,
                                                  job.workingdir, job.inputs)

        container_args = self._generate_container_args(job)

        job.rundata.container = self.client.create_container(job.imageid, **container_args)
        self.client.start(job.rundata.container)
        job.rundata.containerid = job.rundata.container['Id']
        job.jobid = job.rundata.containerid

Submit job to the engine

Args:
job (pyccc.job.Job): Job to submit


def Unzip(iterable):
    lefts = []
    rights = []
    for (left, right) in iterable:
        lefts.append(left)
        rights.append(right)
    return (lefts, rights)

Unzips specified iterable of pairs to pair of two iterables.

This function is an inversion of the standard `zip` function and the following
hold:

* ∀ l, r. l, r == unzip(zip(l, r))
* ∀ p. p == zip(unzip(p))

Examples:
>>> Unzip([("foo", 1), ("bar", 2), ("baz", 3)])
(["foo", "bar", "baz"], [1, 2, 3])

Args:
iterable: An iterable of pairs to unzip.

Returns:
A pair of iterables after unzipping.


def get_sorted_structure(self, key=None, reverse=False):
    sites = sorted(self, key=key, reverse=reverse)
    return self.__class__.from_sites(sites, charge=self._charge)

Get a sorted copy of the structure. The parameters have the same
meaning as in list.sort. By default, sites are sorted by the
electronegativity of the species.

Args:
key: Specifies a function of one argument that is used to extract
a comparison key from each list element: key=str.lower. The
default value is None (compare the elements directly).
reverse (bool): If set to True, then the list elements are sorted
as if each comparison were reversed.


def from_keras_model(cls, model):
    TFLiteConverterBase._set_original_model_type(conversion_metadata_fb.ModelType.KERAS_MODEL)
    return TFLiteKerasModelConverterV2(model)

Creates a TFLiteConverter object from a Keras model.

Args:
model: tf.Keras.Model

Returns:
TFLiteConverter object.


def find_noncopyable_vars(class_type, already_visited_cls_vars=None):
    assert isinstance(class_type, class_declaration.class_t)
    logger = utils.loggers.cxx_parser
    mvars = class_type.variables((lambda v: (not v.type_qualifiers.has_static)), recursive=False, allow_empty=True)
    noncopyable_vars = []
    if (already_visited_cls_vars is None):
        already_visited_cls_vars = []
    message = ('__contains_noncopyable_mem_var - %s - TRUE - ' + 'contains const member variable')
    for mvar in mvars:
        var_type = type_traits.remove_reference(mvar.decl_type)
        if type_traits.is_const(var_type):
            no_const = type_traits.remove_const(var_type)
            if (type_traits.is_fundamental(no_const) or is_enum(no_const)):
                logger.debug((message + '- fundamental or enum'), var_type.decl_string)
                noncopyable_vars.append(mvar)
            if is_class(no_const):
                logger.debug((message + ' - class'), var_type.decl_string)
                noncopyable_vars.append(mvar)
            if type_traits.is_array(no_const):
                logger.debug((message + ' - array'), var_type.decl_string)
                noncopyable_vars.append(mvar)
        if type_traits.is_pointer(var_type):
            continue
        if class_traits.is_my_case(var_type):
            cls = class_traits.get_declaration(var_type)
            if (cls in already_visited_cls_vars):
                continue
            already_visited_cls_vars.append(cls)
            if is_noncopyable(cls, already_visited_cls_vars):
                logger.debug((message + ' - class that is not copyable'), var_type.decl_string)
                noncopyable_vars.append(mvar)
    logger.debug(("__contains_noncopyable_mem_var - %s - FALSE - doesn't " + 'contain noncopyable members'), class_type.decl_string)
    return noncopyable_vars

Returns list of all `noncopyable` variables.

If an already_visited_cls_vars list is provided as argument, the returned
list will not contain these variables. This list will be extended with
whatever variables pointing to classes have been found.

Args:
class_type (declarations.class_t): the class to be searched.
already_visited_cls_vars (list): optional list of vars that should not
be checked a second time, to prevent infinite recursions.

Returns:
list: list of all `noncopyable` variables.


def get_alignment_df_from_file(alignment_file, a_seq_id=None, b_seq_id=None):
    alignments = list(AlignIO.parse(alignment_file, 'emboss'))
    alignment_df = pd.DataFrame(columns=['id_a', 'id_b', 'type', 'id_a_aa', 'id_a_pos', 'id_b_aa', 'id_b_pos'])
    for alignment in alignments:
        if (not a_seq_id):
            a_seq_id = list(alignment)[0].id
        a_seq = str(list(alignment)[0].seq)
        if (not b_seq_id):
            b_seq_id = list(alignment)[1].id
        b_seq = str(list(alignment)[1].seq)
        df = get_alignment_df(a_seq, b_seq, a_seq_id, b_seq_id)
        alignment_df = alignment_df.append(df).reset_index(drop=True)
    return alignment_df

Get a Pandas DataFrame of the Needle alignment results. Contains all positions of the sequences.

Args:
alignment_file:
a_seq_id: Optional specification of the ID of the reference sequence
b_seq_id: Optional specification of the ID of the aligned sequence

Returns:
Pandas DataFrame: all positions in the alignment


def log(cls, x: 'TensorFluent') -> 'TensorFluent':
    return cls._unary_op(x, tf.log, tf.float32)

Returns a TensorFluent for the log function.

Args:
x: The input fluent.

Returns:
A TensorFluent wrapping the log function.


def _ParseTriggerStartTime(self, parser_mediator, trigger):
    time_elements_tuple = (trigger.start_date.year, trigger.start_date.month, trigger.start_date.day_of_month, trigger.start_time.hours, trigger.start_time.minutes, 0)
    date_time = None
    if (time_elements_tuple != (0, 0, 0, 0, 0, 0)):
        try:
            date_time = dfdatetime_time_elements.TimeElements(time_elements_tuple=time_elements_tuple)
            date_time.is_local_time = True
            date_time._precision = dfdatetime_definitions.PRECISION_1_MINUTE
        except ValueError:
            parser_mediator.ProduceExtractionWarning('invalid trigger start time: {0!s}'.format(time_elements_tuple))
    return date_time

Parses the start time from a trigger.

Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
trigger (job_trigger): a trigger.

Returns:
dfdatetime.DateTimeValues: last run date and time or None if not
available.


def expand_dims(self, axis):

        if axis == -1:
            axis = self.ndim
        array = np.expand_dims(self, axis)
        if axis == 0:

            return array
        else:
            new_labels = self.labels.insert(axis, None)
            return Timeseries(array, self.tspan, new_labels)

Insert a new axis, at a given position in the array shape
Args:
axis (int): Position (amongst axes) where new axis is to be inserted.


def write_data(self, output):

        if self.figure:
            canvas = FigureCanvas(self.figure)
            self.figure.savefig(output, format='png', bbox_inches='tight')
            output.seek(0)
            return output.getvalue()
        return None

Write the data out as base64 binary

Args:
output (file-like object): Output to write figure to.


def label_durations(self, label_list_ids=None):
    duration = collections.defaultdict(int)
    for utterance in self.utterances.values():
        for (label_value, utt_count) in utterance.label_total_duration(label_list_ids=label_list_ids).items():
            duration[label_value] += utt_count
    return duration

Return a dictionary containing the total duration, every label-value in this corpus is occurring.

Args:
label_list_ids (list): If not None, only labels from label-lists with an id contained in this list
are considered.

Returns:
dict: A dictionary containing the total duration with the label-value as key.


def call_flat(self, *args: core.Tensor) -> Sequence[core.Tensor]:
    expected_len = len(self.cached_definition.signature.input_arg)
    if len(args) != expected_len:
        raise ValueError(f'Signature specifies {expected_len} arguments, got: {len(args)}. Expected inputs: {self.cached_definition.signature.input_arg}. Received inputs: {args}. Function Type: {self.function_type!r}')
    with InterpolateRuntimeError(self):
        with ops.control_dependencies(self._call_options.control_captures):
            with record.stop_recording():
                if self._bound_context.executing_eagerly():
                    outputs = self._bound_context.call_function(self.name, list(args), len(self.function_type.flat_outputs))
                else:
                    outputs = make_call_op_in_graph(self, list(args), self._bound_context.function_call_options.as_attrs())
    for i, output_type in enumerate(self.function_type.flat_outputs):
        handle_data = output_type.dtype._handle_data
        if handle_data:
            handle_data_util.set_handle_data(outputs[i], handle_data.shape_inference)
    if not self._bound_context.executing_eagerly():
        for i, output_type in enumerate(self.function_type.flat_outputs):
            outputs[i].set_shape(output_type.shape)
    return outputs

Calls with flat tensor inputs and returns flat tensor outputs.

Args:
*args: arguments to call this function with.

Returns:
The outputs of the function call.

Raises:
ValueError: if the number of arguments is incorrect.
FunctionAlreadyGarbageCollectedError: if the function is no longer
available to be called because it has been garbage collected.


def scale(self, xfactor, yfactor=None):

        yfactor = xfactor if yfactor is None else yfactor
        x, y = self.centroid
        xshift = self.width * xfactor * 0.5
        yshift = self.height * yfactor * 0.5
        return Envelope(x - xshift, y - yshift, x + xshift, y + yshift)

Returns a new envelope rescaled from center by the given factor(s).

Arguments:
xfactor -- int or float X scaling factor
yfactor -- int or float Y scaling factor


def maybe_promote_tensors(*tensors, force_same_dtype=False):
    if ops.is_auto_dtype_conversion_enabled():
        return tensors
    if not tensors:
        return tensors
    if not ops.is_numpy_style_type_promotion():
        if not force_same_dtype:
            return tensors
        promoted_tensors = []
        promoted_tensors.append(tensors[0])
        dtype = tensors[0].dtype.base_dtype
        for tensor in tensors[1:]:
            promoted_tensors.append(ops.convert_to_tensor(tensor, dtype, name='x'))
        return promoted_tensors
    result_type = np_dtypes._result_type(*[_maybe_get_dtype(x) for x in nest.flatten(tensors)])

    def _promote_or_cast(x):
        if isinstance(x, tensor_lib.Tensor):
            x = gen_math_ops.cast(x, result_type)
        else:
            x = ops.convert_to_tensor(x, result_type)
        return x
    return [_promote_or_cast(x) for x in tensors]

Promotes tensors if numpy style promotion is enabled.

This function promotes `tensors` according to numpy promotion rules
if numpy style promotion is enabled.  Otherwise, if
`force_same_dtype` is `True`, it force-casts `tensors[1:]` to
`tensor[0]`'s dtype. Note that this force-cast can be problematic.
For example, when some `tensors[1:]` elements can be silently
downcasted.

Args:
*tensors: the list of tensors to promote.
force_same_dtype: bool (optional, default to `False`). When numpy
style promotion is disabled and `force_same_dtype` is `True`,
this function will force-casts `tensors[1:]` to `tensor[0]`'s
dtype (which could be problematic).

Returns:
The promoted list of tensors.


def activate_absence_with_period(self, endtime: datetime):

        data = {"endTime": endtime.strftime("%Y_%m_%d %H:%M")}
        return self._restCall(
            "home/heating/activateAbsenceWithPeriod", json.dumps(data)
        )

activates the absence mode until the given time

Args:
endtime(datetime): the time when the absence should automatically be disabled


def _query(cls, *args, **kwds):
    if ('distinct' in kwds):
        if ('group_by' in kwds):
            raise TypeError('cannot use distinct= and group_by= at the same time')
        projection = kwds.get('projection')
        if (not projection):
            raise TypeError('cannot use distinct= without projection=')
        if kwds.pop('distinct'):
            kwds['group_by'] = projection
    from .query import Query
    qry = Query(kind=cls._get_kind(), **kwds)
    qry = qry.filter(*cls._default_filters())
    qry = qry.filter(*args)
    return qry

Create a Query object for this class.

Args:
distinct: Optional bool, short hand for group_by = projection.
*args: Used to apply an initial filter
**kwds: are passed to the Query() constructor.

Returns:
A Query object.


def isemptyfile(filepath):
    exists = os.path.exists(safepath(filepath))
    if exists:
        filesize = os.path.getsize(safepath(filepath))
        return (filesize == 0)
    else:
        return False

Determine if the file both exists and isempty

Args:
filepath (str, path): file path

Returns:
bool


def uniprot_ec(uniprot_id):

    r = requests.post('http:
    ec = r.content.decode('utf-8').splitlines()[1]

    if len(ec) == 0:
        ec = None

    return ec

Retrieve the EC number annotation for a UniProt ID.

Args:
uniprot_id: Valid UniProt ID

Returns:


def has_soma_points(data_wrapper):
    db = data_wrapper.data_block
    return CheckResult((POINT_TYPE.SOMA in db[(:, COLS.TYPE)]), None)

Checks if the TYPE column of raw data block has an element of type soma

Returns:
CheckResult with result


def load_env(workdir, logfile=None, loglevel=logging.INFO):
    setup_sdk_logging(logfile, loglevel)
    workdir = os.path.abspath(workdir)
    loaded_workdir = lago_workdir.Workdir(path=workdir)
    prefix = loaded_workdir.get_prefix('current')
    return SDK(loaded_workdir, prefix)

Load an existing Lago environment

Args:
workdir(str): Path to the workdir directory, as created by
:func:`~lago.sdk.init` or created by the CLI.
logfile(str): A Path to setup a log file.
loglevel(int): :mod:`logging` log level.

Returns:
:class:`~lago.sdk.SDK`: Initialized Lago environment

Raises:
:exc:`~lago.utils.LagoException`: If loading the environment failed.


def canonicalize_without_job_and_task(d):
    canonicalized_device = canonicalize(d)
    spec = tf_device.DeviceSpec.from_string(canonicalized_device)
    spec = spec.replace(job=None, task=None, replica=0)
    return spec.to_string()

Partially canonicalize device string.

This returns device string from `d` without including job and task.
This is most useful for parameter server strategy where the device strings are
generated on the chief, but executed on workers.

For example:
If d = '/cpu:0', default='/job:worker/task:1', it returns
'/replica:0/device:CPU:0'.
If d = '/cpu:0', default='/job:worker', it returns
'/replica:0/device:CPU:0'.
If d = '/gpu:0', default=None, it returns
'/replica:0/device:GPU:0'.

Note: This uses "job:localhost" as the default if executing eagerly.

Args:
d: a device string or tf.config.LogicalDevice

Returns:
a partially canonicalized device string.


def remap_variables(fn):

    def custom_getter(getter, *args, **kwargs):
        v = getter(*args, **kwargs)
        return fn(v)
    return custom_getter_scope(custom_getter)

Use fn to map the output of any variable getter.

Args:
fn (tf.Variable -> tf.Tensor)

Returns:
The current variable scope with a custom_getter that maps
all the variables by fn.

Example:
.. code-block:: python

with varreplace.remap_variables(lambda var: quantize(var)):
x = FullyConnected('fc', x, 1000)   # fc/{W,b} will be quantized


def _GetSourceFileSystem(self, source_path_spec, resolver_context=None):
    if (not source_path_spec):
        raise RuntimeError('Missing source.')
    file_system = path_spec_resolver.Resolver.OpenFileSystem(source_path_spec, resolver_context=resolver_context)
    type_indicator = source_path_spec.type_indicator
    if path_spec_factory.Factory.IsSystemLevelTypeIndicator(type_indicator):
        mount_point = source_path_spec
    else:
        mount_point = source_path_spec.parent
    return (file_system, mount_point)

Retrieves the file system of the source.

Args:
source_path_spec (dfvfs.PathSpec): source path specification of the file
system.
resolver_context (dfvfs.Context): resolver context.

Returns:
tuple: containing:

dfvfs.FileSystem: file system.
dfvfs.PathSpec: mount point path specification that refers
to the base location of the file system.

Raises:
RuntimeError: if source path specification is not set.


def _activation_summary(x):
    tensor_name = re.sub(('%s_[0-9]*/' % TOWER_NAME), '', x.op.name)
    tf.summary.histogram((tensor_name + '/activations'), x)
    tf.summary.scalar((tensor_name + '/sparsity'), tf.nn.zero_fraction(x))

Helper to create summaries for activations.

Creates a summary that provides a histogram of activations.
Creates a summary that measures the sparsity of activations.

Args:
x: Tensor
Returns:
nothing


def matches_count(count, options):
    if (options.get('count') is not None):
        return (count == int(options['count']))
    if ((options.get('maximum') is not None) and (int(options['maximum']) < count)):
        return False
    if ((options.get('minimum') is not None) and (int(options['minimum']) > count)):
        return False
    if ((options.get('between') is not None) and (count not in options['between'])):
        return False
    return True

Returns whether the given count matches the given query options.

If no quantity options are specified, any count is considered acceptable.

Args:
count (int): The count to be validated.
options (Dict[str, int | Iterable[int]]): A dictionary of query options.

Returns:
bool: Whether the count matches the options.


def get_all(self, start=0, count=(- 1), sort=''):
    return self._helper.get_all(start, count, sort=sort)

Gets a list of logical interconnects based on optional sorting and filtering and is constrained by start
and count parameters.

Args:
start:
The first item to return, using 0-based indexing.
If not specified, the default is 0 - start with the first available item.
count:
The number of resources to return. A count of -1 requests all items.
The actual number of items in the response might differ from the requested
count if the sum of start and count exceeds the total number of items.
sort:
The sort order of the returned data set. By default, the sort order is based
on create time with the oldest entry first.

Returns:
list: A list of logical interconnects.


def append(self, value):

        if self._avm is not None and not self.terminated:
            path = self._last_path
            if path:
                path += '.'
            self[path + LIST_HEAD] = value
            self._last_path = path + LIST_TAIL
            self[self._last_path] = AVM()
        else:
            raise TdlError('Cannot append to a closed list.')

Append an item to the end of an open ConsList.

Args:
value (:class:`Conjunction`, :class:`Term`): item to add
Raises:
:class:`TdlError`: when appending to a closed list


def parse_metadata(lines):
    meta = defaultdict(list)
    for line in lines:
        line = line.rstrip()
        if line.startswith('!'):
            if (('_table_begin' in line) or ('_table_end' in line)):
                continue
            (key, value) = __parse_entry(line)
            meta[key].append(value)
    return dict(meta)

Parse list of lines with metadata information from SOFT file.

Args:
lines (:obj:`Iterable`): Iterator over the lines.

Returns:
:obj:`dict`: Metadata from SOFT file.


def __init__(self, debug_dump, config):
    self._debug_dump = debug_dump
    self._evaluator = evaluator.ExpressionEvaluator(self._debug_dump)
    self._tensor_filters = {}
    self._build_argument_parsers(config)
    config.set_callback('graph_recursion_depth', self._build_argument_parsers)

DebugAnalyzer constructor.

Args:
debug_dump: A DebugDumpDir object.
config: A `cli_config.CLIConfig` object that carries user-facing
configurations.


def __init__(self, script_hash=None, is_frozen=False, votes=None, balances=None):

        self.ScriptHash = script_hash
        self.IsFrozen = is_frozen
        if votes is None:
            self.Votes = []
        else:
            self.Votes = votes

        if balances is None:
            self.Balances = {}
        else:
            self.Balances = balances

Create an instance.

Args:
script_hash (UInt160):
is_frozen (bool):
votes (list): of EllipticCurve.ECPoint items.
balances (dict):
Key (UInt256): assetID.
Value (Fixed8): balance.


def read(self, numberOfBytes):
    if VERBOSE:
        _print_out('\nDummy_serial: Reading from port (max length {!r} bytes)'.format(numberOfBytes))
    if (numberOfBytes < 0):
        raise IOError('Dummy_serial: The numberOfBytes to read must not be negative. Given: {!r}'.format(numberOfBytes))
    if (not self._isOpen):
        raise IOError('Dummy_serial: Trying to read, but the port is not open.')
    if (self._waiting_data == DEFAULT_RESPONSE):
        returnstring = self._waiting_data
    elif (numberOfBytes == len(self._waiting_data)):
        returnstring = self._waiting_data
        self._waiting_data = NO_DATA_PRESENT
    elif (numberOfBytes < len(self._waiting_data)):
        if VERBOSE:
            _print_out(('Dummy_serial: The numberOfBytes to read is smaller than the available data. ' + 'Some bytes will be kept for later. Available data: {!r} (length = {}), numberOfBytes: {}'.format(self._waiting_data, len(self._waiting_data), numberOfBytes)))
        returnstring = self._waiting_data[:numberOfBytes]
        self._waiting_data = self._waiting_data[numberOfBytes:]
    else:
        if VERBOSE:
            _print_out(('Dummy_serial: The numberOfBytes to read is larger than the available data. ' + 'Will sleep until timeout. Available  data: {!r} (length = {}), numberOfBytes: {}'.format(self._waiting_data, len(self._waiting_data), numberOfBytes)))
        time.sleep(self.timeout)
        returnstring = self._waiting_data
        self._waiting_data = NO_DATA_PRESENT
    if VERBOSE:
        _print_out('Dummy_serial read return data: {!r} (has length {})\n'.format(returnstring, len(returnstring)))
    if (sys.version_info[0] > 2):
        return bytes(returnstring, encoding='latin1')
    else:
        return returnstring

Read from a port on dummy_serial.

The response is dependent on what was written last to the port on dummy_serial,
and what is defined in the :data:`RESPONSES` dictionary.

Args:
numberOfBytes (int): For compability with the real function.

Returns a **string** for Python2 and **bytes** for Python3.

If the response is shorter than numberOfBytes, it will sleep for timeout.
If the response is longer than numberOfBytes, it will return only numberOfBytes bytes.


def subtract_period_and_roll(self, date_tensor, period_tensor, roll_convention=constants.BusinessDayConvention.NONE):
    minus_period_tensor = periods.PeriodTensor(-period_tensor.quantity(), period_tensor.period_type())
    return self.add_period_and_roll(date_tensor, minus_period_tensor, roll_convention)

Subtracts given periods from given dates and rolls to business days.

The original dates are not rolled prior to subtraction.

Args:
date_tensor: DateTensor of dates to subtract from.
period_tensor: PeriodTensor broadcastable to `date_tensor`.
roll_convention: BusinessDayConvention. Determines how to roll a date that
falls on a holiday.

Returns:
The resulting DateTensor.


def __init__(self, model: PreTrainedModel, max_batch_size: int=1, max_cache_len: int=4096):
    super().__init__()
    self.model = model
    if not self.model.config.use_cache:
        raise AssertionError('Model must have caching enabled')
    self.cache = HybridCache(config=self.model.config, max_batch_size=max_batch_size, max_cache_len=max_cache_len, device=self.model.device, dtype=self.model.dtype)
    for i in range(len(self.cache.key_cache)):
        self.register_buffer(f'key_cache_{i}', self.cache.key_cache[i], persistent=False)
        self.register_buffer(f'value_cache_{i}', self.cache.value_cache[i], persistent=False)

Initializes the exportable module with `HybridCache`.

Args:
model (`PreTrainedModel`): The pretrained model to wrap.
max_batch_size (int): Maximum batch size for the cache.
max_cache_len (int): Maximum sequence length for the cache.

Raises:
AssertionError: If the model doesn't have the expected configuration for HybridCache.


def startstop(inst_id, cmdtodo):

    tar_inst = EC2R.Instance(inst_id)
    thecmd = getattr(tar_inst, cmdtodo)
    response = thecmd()
    return response

Start or Stop the Specified Instance.

Args:
inst_id (str): instance-id to perform command against
cmdtodo (str): command to perform (start or stop)
Returns:
response (dict): reponse returned from AWS after
performing specified action.


def _copy_and_clean_up_expectations_from_indexes(self, match_indexes, discard_result_format_kwargs=True, discard_include_configs_kwargs=True, discard_catch_exceptions_kwargs=True):
    rval = []
    for i in match_indexes:
        rval.append(self._copy_and_clean_up_expectation(self._expectations_config.expectations[i], discard_result_format_kwargs, discard_include_configs_kwargs, discard_catch_exceptions_kwargs))
    return rval

Copies and cleans all expectations provided by their index in DataAsset._expectations_config.expectations.

Applies the _copy_and_clean_up_expectation method to multiple expectations, provided by their index in \
`DataAsset,_expectations_config.expectations`. Returns a list of the copied and cleaned expectations.

Args:
match_indexes (List): \
Index numbers of the expectations from `expectation_config.expectations` to be copied and cleaned.
discard_result_format_kwargs (boolean): \
if True, will remove the kwarg `output_format` key-value pair from the copied expectation.
discard_include_configs_kwargs (boolean):
if True, will remove the kwarg `include_configs` key-value pair from the copied expectation.
discard_catch_exceptions_kwargs (boolean):
if True, will remove the kwarg `catch_exceptions` key-value pair from the copied expectation.

Returns:
A list of the copied expectations with `success_on_last_run` and other specified \
key-value pairs removed.

See also:
_copy_and_clean_expectation


def __init__(self, initializer, default_value, name=None, experimental_is_anonymous=False):
    self._initializer = initializer
    self._default_value = default_value
    self._is_anonymous = experimental_is_anonymous
    if not self._is_anonymous:
        self._shared_name = self._initializer._shared_name
        if not self._shared_name:
            self._shared_name = 'hash_table_%s' % (str(uuid.uuid4()),)
    self._name = name or 'hash_table'
    self._table_name = None
    super(StaticHashTable, self).__init__(default_value, initializer)
    self._value_shape = self._default_value.get_shape()

Creates a non-initialized `HashTable` object.

Creates a table, the type of its keys and values are specified by the
initializer.
Before using the table you will have to initialize it. After initialization
the table will be immutable.

Args:
initializer: The table initializer to use. See `HashTable` kernel for
supported key and value types.
default_value: The value to use if a key is missing in the table.
name: A name for the operation (optional).
experimental_is_anonymous: Whether to use anonymous mode for the
table (default is False). In anonymous mode, the table
resource can only be accessed via a resource handle. It can't
be looked up by a name. When all resource handles pointing to
that resource are gone, the resource will be deleted
automatically.

Returns:
A `HashTable` object.


def num_accumulated(self, name=None):
    if name is None:
        name = '%s_NumAccumulated' % self._name
    return gen_data_flow_ops.resource_accumulator_num_accumulated(self._accumulator_ref, name=name)

Number of gradients that have currently been aggregated in accumulator.

Args:
name: Optional name for the operation.

Returns:
Number of accumulated gradients currently in accumulator.


def put(self, json=None):

        return self._call('put', url=self.endpoint, json=json)

Send a PUT request and return the JSON decoded result.

Args:
json (dict, optional): Object to encode and send in request.

Returns:
mixed: JSON decoded response data.


def param_type(self, name):

        self._ensure_loaded()

        if name not in self.annotated_params:
            return None

        return self.annotated_params[name].type_name

Get the parameter type information by name.

Args:
name (str): The full name of a parameter.

Returns:
str: The type name or None if no type information is given.