def _process_update(self, item, feed_item):
    if feed_item.get(FieldMap.CAMPAIGN_ID, '') == '':
        feed_item[FieldMap.CAMPAIGN_ID] = item['campaignId']
    campaign = self.campaign_dao.get(feed_item, required=True)
    placement_group = self.placement_group_dao.get(feed_item, required=True)
    feed_item[FieldMap.CAMPAIGN_ID] = campaign['id']
    feed_item[FieldMap.CAMPAIGN_NAME] = campaign['name']
    if placement_group:
        feed_item[FieldMap.PLACEMENT_GROUP_ID] = placement_group['id']
        feed_item[FieldMap.PLACEMENT_GROUP_NAME] = placement_group['name']
        item['placementGroupId'] = placement_group['id']
    else:
        item['placementGroupId'] = None
    self._process_skipability(feed_item, item)
    item['pricingSchedule']['startDate'] = StringExtensions.convertDateTimeStrToDateStr(feed_item.get(FieldMap.PLACEMENT_START_DATE, None)) if feed_item.get(FieldMap.PLACEMENT_START_DATE, '') else item['pricingSchedule']['startDate']
    item['pricingSchedule']['endDate'] = StringExtensions.convertDateTimeStrToDateStr(feed_item.get(FieldMap.PLACEMENT_END_DATE, None)) if feed_item.get(FieldMap.PLACEMENT_END_DATE, '') else item['pricingSchedule']['endDate']
    item['pricingSchedule']['pricingType'] = feed_item.get(FieldMap.PLACEMENT_PRICING_SCHEDULE_COST_STRUCTURE, None) if feed_item.get(FieldMap.PLACEMENT_PRICING_SCHEDULE_COST_STRUCTURE, '') else item['pricingSchedule']['pricingType']
    if feed_item.get(FieldMap.PLACEMENT_PRICING_TESTING_START, None):
        item['pricingSchedule']['testingStartDate'] = feed_item.get(FieldMap.PLACEMENT_PRICING_TESTING_START, None)
    item['name'] = feed_item.get(FieldMap.PLACEMENT_NAME, None) if feed_item.get(FieldMap.PLACEMENT_NAME, '') else item['name']
    item['archived'] = feed_item.get(FieldMap.PLACEMENT_ARCHIVED, None) if feed_item.get(FieldMap.PLACEMENT_ARCHIVED, '') else item['archived']
    item['adBlockingOptOut'] = feed_item.get(FieldMap.PLACEMENT_AD_BLOCKING, False)
    self._process_transcode(item, feed_item)
    self._process_active_view_and_verification(item, feed_item)
    self._process_pricing_schedule(item, feed_item)
    key_values = feed_item.get(FieldMap.PLACEMENT_ADDITIONAL_KEY_VALUES, None)
    if key_values == '':
        if item.get('tagSetting', {}).get('additionalKeyValues'):
            del item['tagSetting']['additionalKeyValues']
    elif key_values != None:
        if not 'tagSetting' in item:
            item['tagSetting'] = {}
        item['tagSetting']['additionalKeyValues'] = key_values

Updates an placement based on the values from the feed.

Args:
item: Object representing the placement to be updated, this object is
updated directly.
feed_item: Feed item representing placement values from the Bulkdozer
feed.


def get_column(self, X, column):

        if isinstance(X, pd.DataFrame):
            return X[column].values

        return X[:, column]

Return a column of the given matrix.

Args:
X: `numpy.ndarray` or `pandas.DataFrame`.
column: `int` or `str`.

Returns:
np.ndarray: Selected column.


def __init__(self, validate_args=False, name="reciprocal"):

    self._name = name
    super(Reciprocal, self).__init__(
        forward_min_event_ndims=0,
        validate_args=validate_args,
        name=name)

Instantiates the `Reciprocal`.

Args:
validate_args: Python `bool` indicating whether arguments should be
checked for correctness.
name: Python `str` name given to ops managed by this object.


def _convert_to_json(self, response):

        try:
            return response.json()
        except ValueError:
            logging.warning('Expected response in JSON format from {0} but the actual response text is: {1}'.format(
                response.request.url, response.text,
            ))
        return None

Converts response to JSON.
If the response cannot be converted to JSON then `None` is returned.

Args:
response - An object of type `requests.models.Response`
Returns:
Response in JSON format if the response can be converted to JSON. `None` otherwise.


def run(self, dag):

        new_dag = DAGCircuit()

        if self.initial_layout is None:
            if self.property_set["layout"]:
                self.initial_layout = self.property_set["layout"]
            else:
                self.initial_layout = Layout.generate_trivial_layout(*dag.qregs.values())

        if len(dag.qubits()) != len(self.initial_layout):
            raise TranspilerError('The layout does not match the amount of qubits in the DAG')

        if len(self.coupling_map.physical_qubits) != len(self.initial_layout):
            raise TranspilerError(
                "Mappers require to have the layout to be the same size as the coupling map")

        current_layout = self.initial_layout.copy()

        for layer in dag.serial_layers():
            subdag = layer['graph']

            for gate in subdag.twoQ_gates():
                physical_q0 = current_layout[gate.qargs[0]]
                physical_q1 = current_layout[gate.qargs[1]]
                if self.coupling_map.distance(physical_q0, physical_q1) != 1:

                    swap_layer = DAGCircuit()

                    path = self.coupling_map.shortest_undirected_path(physical_q0, physical_q1)
                    for swap in range(len(path) - 2):
                        connected_wire_1 = path[swap]
                        connected_wire_2 = path[swap + 1]

                        qubit_1 = current_layout[connected_wire_1]
                        qubit_2 = current_layout[connected_wire_2]

                        for qreg in current_layout.get_registers():
                            if qreg not in swap_layer.qregs.values():
                                swap_layer.add_qreg(qreg)

                        swap_layer.apply_operation_back(SwapGate(),
                                                        qargs=[qubit_1, qubit_2],
                                                        cargs=[])

                    edge_map = current_layout.combine_into_edge_map(self.initial_layout)
                    new_dag.compose_back(swap_layer, edge_map)

                    for swap in range(len(path) - 2):
                        current_layout.swap(path[swap], path[swap + 1])

            edge_map = current_layout.combine_into_edge_map(self.initial_layout)
            new_dag.extend_back(subdag, edge_map)

        return new_dag

Runs the BasicSwap pass on `dag`.
Args:
dag (DAGCircuit): DAG to map.

Returns:
DAGCircuit: A mapped DAG.

Raises:
TranspilerError: if the coupling map or the layout are not
compatible with the DAG


async def get(self, request):
    ticket = (await self.get_ticket(request))
    if (ticket is None):
        return None
    try:
        now = time.time()
        fields = self._ticket.validate(ticket, self._get_ip(request), now)
        if ((self._reissue_time is not None) and (now >= (fields.valid_until - self._reissue_time))):
            request[_REISSUE_KEY] = self._new_ticket(request, fields.user_id)
        return fields.user_id
    except TicketError as e:
        return None

Gets the user_id for the request.

Gets the ticket for the request using the get_ticket() function, and
authenticates the ticket.

Args:
request: aiohttp Request object.

Returns:
The userid for the request, or None if the ticket is not
authenticated.


def _AttemptAutoDetectTagFile(self, analysis_mediator):

    self._autodetect_tag_file_attempt = True
    if not analysis_mediator.data_location:
      return False

    operating_system = analysis_mediator.operating_system.lower()
    filename = self._OS_TAG_FILES.get(operating_system, None)
    if not filename:
      return False

    logger.info('Using auto detected tag file: {0:s}'.format(filename))
    tag_file_path = os.path.join(analysis_mediator.data_location, filename)
    self.SetAndLoadTagFile(tag_file_path)
    return True

Detects which tag file is most appropriate.

Args:
analysis_mediator (AnalysisMediator): analysis mediator.

Returns:
bool: True if a tag file is autodetected.


def target_encode(self, answer: str, add_special_tokens: bool=True, padding: Union[bool, str, PaddingStrategy]=False, truncation: Union[bool, str, TruncationStrategy, TapexTruncationStrategy]=None, max_length: Optional[int]=None, return_tensors: Optional[Union[str, TensorType]]=None, **kwargs) -> List[int]:
    encoded_outputs = self.target_encode_plus(answer=answer, add_special_tokens=add_special_tokens, padding=padding, truncation=truncation, max_length=max_length, return_tensors=return_tensors, **kwargs)
    return encoded_outputs['input_ids']

Prepare the answer string for the model. This method does not return token type IDs, attention masks, etc.
which are necessary for the model to work correctly. Use this method if you want to build your processing on
your own, otherwise refer to `__call__`.

Args:
answer `str`:
Corresponding answer supervision to the queries for training the model


def preload_check():
    if os.name == 'nt':
        if MSVCP_DLL_NAMES in build_info.build_info:
            missing = []
            for dll_name in build_info.build_info[MSVCP_DLL_NAMES].split(','):
                try:
                    ctypes.WinDLL(dll_name)
                except OSError:
                    missing.append(dll_name)
            if missing:
                raise ImportError('Could not find the DLL(s) %r. TensorFlow requires that these DLLs be installed in a directory that is named in your %%PATH%% environment variable. You may install these DLLs by downloading "Microsoft C++ Redistributable for Visual Studio 2015, 2017 and 2019" for your platform from this URL: https:
    else:
        from tensorflow.python.platform import _pywrap_cpu_feature_guard
        _pywrap_cpu_feature_guard.InfoAboutUnusedCPUFeatures()

Raises an exception if the environment is not correctly configured.

Raises:
ImportError: If the check detects that the environment is not correctly
configured, and attempting to load the TensorFlow runtime will fail.


def annotated(func, name=None):
    if hasattr(func, 'metadata'):
        if (name is not None):
            func.metadata = AnnotatedMetadata(func, name)
        return func
    func.metadata = AnnotatedMetadata(func, name)
    func.finalizer = False
    func.takes_cmdline = False
    func.decorated = False
    func.context = False
    return func

Mark a function as callable from the command line.

This function is meant to be called as decorator.  This function
also initializes metadata about the function's arguments that is
built up by the param decorator.

Args:
func (callable): The function that we wish to mark as callable
from the command line.
name (str): Optional string that will override the function's
built-in name.


def xeval(source, optimize=True):
    native = xcompile(source, optimize=optimize)
    return native()

Compiles to native Python bytecode and runs program, returning the
topmost value on the stack.

Args:
optimize: Whether to optimize the code after parsing it.

Returns:
None: If the stack is empty
obj: If the stack contains a single value
[obj, obj, ...]: If the stack contains many values


def zero_state(self, sample_batch_shape=()):
    h0 = tf.zeros([1, self.hidden_size])
    c0 = tf.zeros([1, self.hidden_size])
    combined_shape = tf.concat((tf.convert_to_tensor(value=sample_batch_shape, dtype=tf.int32), [self.dimensions]), axis=(- 1))
    previous_output = tf.zeros(combined_shape)
    return (previous_output, (h0, c0))

Returns an initial state for the LSTM cell.

Args:
sample_batch_shape: A 0D or 1D tensor of the combined sample and
batch shape.

Returns:
A tuple of the initial previous output at timestep 0 of shape
[sample_batch_shape, dimensions], and the cell state.


def GetNotificationsForAllShards(self, queue):
    notifications_by_session_id = {}
    for queue_shard in self.GetAllNotificationShards(queue):
        self._GetUnsortedNotifications(queue_shard, notifications_by_session_id=notifications_by_session_id)
    return notifications_by_session_id.values()

Returns notifications for all shards of a queue at once.

Used by worker_test_lib.MockWorker to cover all shards with a single worker.

Args:
queue: usually rdfvalue.RDFURN("aff4:/W")

Returns:
List of rdf_flows.GrrNotification objects


def decode_iter_request(data: dict) -> Optional[Union[str, int]]:

    if "response_metadata" in data:
        return data["response_metadata"].get("next_cursor")
    elif "paging" in data:
        current_page = int(data["paging"].get("page", 1))
        max_page = int(data["paging"].get("pages", 1))

        if current_page < max_page:
            return current_page + 1
    elif "has_more" in data and data["has_more"] and "latest" in data:
        return data["messages"][-1]["ts"]

    return None

Decode incoming response from an iteration request

Args:
data: Response data

Returns:
Next itervalue


def stack_call(self, *args):
    self.pipelined_args.append(args)
    self.number_of_stacked_calls = (self.number_of_stacked_calls + 1)

Stacks a redis command inside the object.

The syntax is the same than the call() method a Client class.

Args:
*args: full redis command as variable length argument list.

Examples:
>>> pipeline = Pipeline()
>>> pipeline.stack_call("HSET", "key", "field", "value")
>>> pipeline.stack_call("PING")
>>> pipeline.stack_call("INCR", "key2")


def GetEntries(self, parser_mediator, data=None, **unused_kwargs):
    seeding_time = data.get('seeding-time-seconds', None)
    event_data = TransmissionEventData()
    event_data.destination = data.get('destination', None)
    (event_data.seedtime, _) = divmod(seeding_time, 60)
    timestamp = data.get('added-date', None)
    if timestamp:
        date_time = dfdatetime_posix_time.PosixTime(timestamp=timestamp)
        event = time_events.DateTimeValuesEvent(date_time, definitions.TIME_DESCRIPTION_ADDED)
        parser_mediator.ProduceEventWithEventData(event, event_data)
    timestamp = data.get('done-date', None)
    if timestamp:
        date_time = dfdatetime_posix_time.PosixTime(timestamp=timestamp)
        event = time_events.DateTimeValuesEvent(date_time, definitions.TIME_DESCRIPTION_FILE_DOWNLOADED)
        parser_mediator.ProduceEventWithEventData(event, event_data)
    timestamp = data.get('activity-date', None)
    if timestamp:
        date_time = dfdatetime_posix_time.PosixTime(timestamp=timestamp)
        event = time_events.DateTimeValuesEvent(date_time, definitions.TIME_DESCRIPTION_LAST_ACCESS)
        parser_mediator.ProduceEventWithEventData(event, event_data)

Extract data from Transmission's resume folder files.

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

Transmission stores an individual Bencoded file for each active download
in a folder named resume under the user's application data folder.

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 begin_disconnection(self, conn_or_internal_id, callback, timeout):

        data = {
            'id': conn_or_internal_id,
            'callback': callback
        }

        action = ConnectionAction('begin_disconnection', data, timeout=timeout, sync=False)
        self._actions.put(action)

Begin a disconnection attempt

Args:
conn_or_internal_id (string, int): Either an integer connection id or a string
internal_id
callback (callable): Callback to call when this disconnection attempt either
succeeds or fails
timeout (float): How long to allow this connection attempt to proceed
without timing it out (in seconds)


def inputs(eval_data, data_dir, batch_size):
    if (not eval_data):
        filenames = [os.path.join(data_dir, ('data_batch_%d.bin' % i)) for i in xrange(1, 6)]
        num_examples_per_epoch = NUM_EXAMPLES_PER_EPOCH_FOR_TRAIN
    else:
        filenames = [os.path.join(data_dir, 'test_batch.bin')]
        num_examples_per_epoch = NUM_EXAMPLES_PER_EPOCH_FOR_EVAL
    for f in filenames:
        if (not tf.gfile.Exists(f)):
            raise ValueError(('Failed to find file: ' + f))
    filename_queue = tf.train.string_input_producer(filenames)
    read_input = read_cifar10(filename_queue)
    reshaped_image = tf.cast(read_input.uint8image, tf.float32)
    height = IMAGE_SIZE
    width = IMAGE_SIZE
    resized_image = tf.image.resize_image_with_crop_or_pad(reshaped_image, height, width)
    float_image = tf.image.per_image_standardization(resized_image)
    float_image.set_shape([height, width, 3])
    read_input.label.set_shape([1])
    min_fraction_of_examples_in_queue = 0.4
    min_queue_examples = int((num_examples_per_epoch * min_fraction_of_examples_in_queue))
    return _generate_image_and_label_batch(float_image, read_input.label, min_queue_examples, batch_size, shuffle=False)

Construct input for CIFAR evaluation using the Reader ops.

Args:
eval_data: bool, indicating if one should use the train or eval data set.
data_dir: Path to the CIFAR-10 data directory.
batch_size: Number of images per batch.

Returns:
images: Images. 4D tensor of [batch_size, IMAGE_SIZE, IMAGE_SIZE, 3] size.
labels: Labels. 1D tensor of [batch_size] size.


def __init__(self, app):

        super(SMTPEmailAdapter, self).__init__(app)

        try:
            from flask_mail import Mail
        except ImportError:
            raise ConfigError(
                "The Flask-Mail package is missing. Install Flask-Mail with 'pip install Flask-Mail'.")
        self.mail = Mail(app)

Check config settings and setup Flask-Mail.

Args:
app(Flask): The Flask application instance.


def get_checkpoint_mtimes(checkpoint_prefixes):
    mtimes = []

    def match_maybe_append(pathname):
        fnames = file_io.get_matching_files(pathname)
        if fnames:
            mtimes.append(file_io.stat(fnames[0]).mtime_nsec / 1000000000.0)
            return True
        return False
    for checkpoint_prefix in checkpoint_prefixes:
        pathname = _prefix_to_checkpoint_path(checkpoint_prefix, saver_pb2.SaverDef.V2)
        if match_maybe_append(pathname):
            continue
        match_maybe_append(checkpoint_prefix)
    return mtimes

Returns the mtimes (modification timestamps) of the checkpoints.

Globs for the checkpoints pointed to by `checkpoint_prefixes`.  If the files
exist, collect their mtime.  Both V2 and V1 checkpoints are considered, in
that priority.

This is the recommended way to get the mtimes, since it takes into account
the naming difference between V1 and V2 formats.

Note: If not all checkpoints exist, the length of the returned mtimes list
will be smaller than the length of `checkpoint_prefixes` list, so mapping
checkpoints to corresponding mtimes will not be possible.

Args:
checkpoint_prefixes: a list of checkpoint paths, typically the results of
`Saver.save()` or those of `tf.train.latest_checkpoint()`, regardless of
sharded/non-sharded or V1/V2.
Returns:
A list of mtimes (in microseconds) of the found checkpoints.


def hexagonal(a: float, c: float):

        return Lattice.from_parameters(a, a, c, 90, 90, 120)

Convenience constructor for a hexagonal lattice.

Args:
a (float): *a* lattice parameter of the hexagonal cell.
c (float): *c* lattice parameter of the hexagonal cell.

Returns:
Hexagonal lattice of dimensions a x a x c.


def __init__(self, obj, saveables):
    self._obj = obj
    self._saveables = saveables

Constructor.

Args:
obj: A Trackable object.
saveables: A list of saveables for `obj`.


def rescale(self, image: np.ndarray, rescale_factor: float, data_format: Optional[Union[str, ChannelDimension]]=None, input_data_format: Optional[Union[str, ChannelDimension]]=None) -> np.ndarray:
    return rescale(image, rescale_factor, data_format=data_format, input_data_format=input_data_format)

Rescale the image by the given factor. image = image * rescale_factor.

Args:
image (`np.ndarray`):
Image to rescale.
rescale_factor (`float`):
The value to use for rescaling.
data_format (`str` or `ChannelDimension`, *optional*):
The channel dimension format for the output image. If unset, the channel dimension format of the input
image is used. Can be one of:
- `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
- `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
input_data_format (`str` or `ChannelDimension`, *optional*):
The channel dimension format for the input image. If unset, is inferred from the input image. Can be
one of:
- `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
- `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.


def save(self, internal=False, meta=None, index_fields=None):
    for f in self.on_save:
        f(self)
    if (not (internal or self._pre_save_hook_called)):
        self._pre_save_hook_called = True
        self.pre_save()
    if (not self.deleted):
        self._handle_uniqueness()
    if (not self.exist):
        self.pre_creation()
    old_data = self._data.copy()
    if (self.just_created is None):
        self.setattrs(just_created=(not self.exist))
    if (self._just_created is None):
        self.setattrs(_just_created=self.just_created)
    self.objects.save_model(self, meta_data=meta, index_fields=index_fields)
    self._handle_changed_fields(old_data)
    self._process_relations(internal)
    if (not (internal or self._post_save_hook_called)):
        self._post_save_hook_called = True
        self.post_save()
        if self._just_created:
            self.setattrs(just_created=self._just_created, _just_created=False)
            self.post_creation()
    self._pre_save_hook_called = False
    self._post_save_hook_called = False
    if (not internal):
        self._initial_data = self.clean_value()
    return self

Save's object to DB.

Do not override this method, use pre_save and post_save methods.

Args:
internal (bool): True if called within model.
Used to prevent unneccessary calls to pre_save and
post_save methods.
meta (dict): JSON serializable meta data for logging of save operation.
{'lorem': 'ipsum', 'dolar': 5}
index_fields (list): Tuple list for indexing keys in riak (with 'bin' or 'int').
bin is used for string fields, int is used for integer fields.
[('lorem','bin'),('dolar','int')]

Returns:
Saved model instance.


def apply(self, data, path=None):

        if path is None:
            path = []

        if not isinstance(data, dict):
            return data

        def _enumerate(value):
            if isinstance(value, list):
                for k, v in enumerate(value):
                    yield k, v
            elif isinstance(value, dict):
                for k, v in value.items():
                    yield k, v

        def _set(container, key, value):
            if isinstance(container, list):
                container.append(value)
            else:
                container[key] = value

        def _apply(ramap, value, status=False, wc=False, path=[]):

            if not isinstance(value, dict) and not isinstance(value, list):
                if status:
                    return value
                else:
                    return None

            if not wc:
                status = ramap.get("__", status)

            handler = None
            key_handler = None
            if path and self.handlers:
                namespace = Namespace(path)
                for _handler in self.handlers.values():
                    if namespace.match(_handler.get("namespace").keys, partial=False):
                        handler = _handler
                        key_handler = handler.get("key")
                        break

            if isinstance(value, list):
                if not key_handler:
                    key_handler = list_key_handler
                rv = []
            else:
                rv = {}

            for k, v in _enumerate(value):
                if key_handler:
                    k = key_handler(v, k)
                k = str(k)
                if isinstance(v, dict) or isinstance(v, list):
                    if k in ramap:
                        r = _apply(ramap[k], v, status=status, path=path+[k])
                        if r:
                            _set(rv, k, r)
                    elif "*" in ramap:
                        r = _apply(ramap["*"], v, status=status, wc=True, path=path+[k])
                        if r:
                            _set(rv, k, r)
                    elif status:
                        _set(rv, k, v)
                else:
                    if k in ramap:
                        if ramap[k].get("__", True):
                            _set(rv, k, v)
                    elif "*" in ramap and ramap["*"].get("__", True):
                        _set(rv, k, v)
                    elif status:
                        _set(rv, k, v)

            return rv

        tmpns = {}
        for ns, handler in self.handlers.items():
            if handler.get("explicit"):
                p = self.pset.get_permissions(ns)
                if p & const.PERM_READ:
                    exists = False
                    for _ns in self.pset.namespaces:
                        if Namespace(_ns).match(Namespace(ns).keys, partial=False):
                            exists = True
                            break
                    if exists:
                        continue
                    tmpns[ns] = p
                    self.pset[ns] = const.PERM_DENY

        rv = _apply(self.pset.read_access_map, data)

        for ns, p in tmpns.items():
            if p is None:
                del self.pset[ns]
            else:
                self.pset[ns] = p

        return rv

Apply permissions in this set to the provided data, effectively
removing all keys from it are not permissioned to be viewed

Arguments:

data -- dict of data

Returns:

Cleaned data


def print_versions(file: typing.TextIO=None) -> None:
    print('** QuantumFlow dependencies (> python -m quantumflow.meta) **')
    print('quantumflow \t', qf.__version__, file=file)
    print('python      \t', sys.version[0:5], file=file)
    print('numpy       \t', np.__version__, file=file)
    print('networkx    \t', nx.__version__, file=file)
    print('cvxpy      \t', cvx.__version__, file=file)
    print('pyquil      \t', pyquil.__version__, file=file)
    print(bk.name, '   \t', bk.version, '(BACKEND)', file=file)

Print version strings of currently installed dependencies

``> python -m quantumflow.meta``

Args:
file: Output stream. Defaults to stdout.


def post_process_semantic_segmentation(self, outputs, target_sizes: Optional[List[Tuple]]=None):
    logits = outputs.logits
    if target_sizes is not None:
        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 is_torch_tensor(target_sizes):
            target_sizes = target_sizes.numpy()
        semantic_segmentation = []
        for idx in range(len(logits)):
            resized_logits = torch.nn.functional.interpolate(logits[idx].unsqueeze(dim=0), size=target_sizes[idx], mode='bilinear', align_corners=False)
            semantic_map = resized_logits[0].argmax(dim=0)
            semantic_segmentation.append(semantic_map)
    else:
        semantic_segmentation = logits.argmax(dim=1)
        semantic_segmentation = [semantic_segmentation[i] for i in range(semantic_segmentation.shape[0])]
    return semantic_segmentation

Converts the output of [`MobileViTForSemanticSegmentation`] into semantic segmentation maps. Only supports PyTorch.

Args:
outputs ([`MobileViTForSemanticSegmentation`]):
Raw outputs of the model.
target_sizes (`List[Tuple]` of length `batch_size`, *optional*):
List of tuples corresponding to the requested final size (height, width) of each prediction. If unset,
predictions will not be resized.

Returns:
semantic_segmentation: `List[torch.Tensor]` of length `batch_size`, where each item is a semantic
segmentation map of shape (height, width) corresponding to the target_sizes entry (if `target_sizes` is
specified). Each entry of each `torch.Tensor` correspond to a semantic class id.


async def apply_async(processor: Processor | PartProcessor, content: Iterable[ProcessorPart]) -> list[ProcessorPart]:
    async with context():
        content_processor = processor.to_processor()
        as_async = stream_content(content)
        return await gather_stream(content_processor(as_async))

Applies a Processor asynchronously.

When a part processor is given as input, this method will first turn it into
a processor and then will process the content asynchronously.

Args:
processor: the Processor to apply to the content.
content: a collection of ProcessorParts on which to apply the Processor.

Returns:
the content, with the Processor applied to each content part.


def join(self, timeout: Optional[float]=None):
    if self._generation_thread is not None:
        self._generation_thread.join(timeout=timeout)
        if self._generation_thread.is_alive():
            logger.warning('Generation thread did not exit after join timeout.')
        else:
            logger.info('Continuous Batching Manager stopped.')
            self._generation_thread = None

Wait for the background thread to finish.

Args:
timeout: Maximum time to wait for the thread to stop


def _pack_fn(self):
    if (not self.packed_length):
        return None

    def my_fn(records):
        'Function from list of TFRecords to list of TFRecords.'
        examples = []
        for record in records:
            x = tf.train.Example()
            x.ParseFromString(record)
            example_dict = {}
            if self.has_inputs:
                example_dict['inputs'] = [int(i) for i in x.features.feature['inputs'].int64_list.value]
            example_dict['targets'] = [int(i) for i in x.features.feature['targets'].int64_list.value]
            examples.append(example_dict)
        examples = list(self._maybe_pack_examples(examples))
        return [generator_utils.to_example(x).SerializeToString() for x in examples]
    return my_fn

For packed datasets, returns a function to pack examples.

Returns:
None or a function from list of TFRecords to list of TFRecords


def merge_context(self, tag, metadata):
    self.entities.append(tag)
    for k in metadata.keys():
        if (k not in self.metadata):
            self.metadata[k] = k

merge into contextManagerFrame new entity and metadata.

Appends tag as new entity and adds keys in metadata to keys in
self.metadata.

Args:
tag(str): entity to be added to self.entities
metadata(object): metadata containes keys to be added to self.metadata


def fit_freq_min_max(self, training_signal):

        window_length = len(self.window)
        window_weight = sum(self.window)
        max_mask = np.zeros(int(window_length / 2) + 1)
        min_mask = np.zeros(int(window_length / 2) + 1)

        for i in range(0, len(training_signal) - window_length - 1):
            rfft = np.fft.rfft(training_signal[i:i + window_length] * self.window)
            temp = np.abs(rfft) / window_weight
            max_mask = np.maximum(max_mask, temp)
            min_mask = np.minimum(min_mask, temp)

        self.mask_top = self.gain * max_mask
        self.mask_bottom = min_mask / self.gain

Defines a spectral mask based on training data using min and max values of each
frequency component

Args:
training_signal: Training data


def flatten_output_collection_property(cls, name: str, field: Iterable[Any]) -> Dict[str, Any]:
    from itertools import chain
    return {f'{name}.{idx}': item for idx, item in enumerate(chain.from_iterable(field))}

Flatten any potential nested structure expanding the name of the field with the index of the element within the
structure.

Args:
name: The name of the nested structure
field: The structure to, potentially, be flattened

Returns:
(Dict[str, Any]): Outputs with flattened structure and key mapping this new structure.


def plugin_method(*plugin_names):

    def wrapper(callable_obj):
        for plugin_name in plugin_names:
            if (not hasattr(callable_obj, plugin_name)):
                setattr(callable_obj, plugin_name, True)
        return callable_obj
    return wrapper

Plugin Method decorator.
Signs a web handler function with the plugins to be applied as attributes.

Args:
plugin_names (list): A list of plugin callable names

Returns:
A wrapped handler callable.

Examples:
>>> @plugin_method('json', 'bill')
... def method():
...     return "Hello!"
...
>>> print method.json
True
>>> print method.bill
True


def get_train_hooks(name_list, **kwargs):

  if not name_list:
    return []

  train_hooks = []
  for name in name_list:
    hook_name = HOOKS.get(name.strip().lower())
    if hook_name is None:
      raise ValueError('Unrecognized training hook requested: {}'.format(name))
    else:
      train_hooks.append(hook_name(**kwargs))

  return train_hooks

Factory for getting a list of TensorFlow hooks for training by name.

Args:
name_list: a list of strings to name desired hook classes. Allowed:
LoggingTensorHook, ProfilerHook, ExamplesPerSecondHook, which are defined
as keys in HOOKS
**kwargs: a dictionary of arguments to the hooks.

Returns:
list of instantiated hooks, ready to be used in a classifier.train call.

Raises:
ValueError: if an unrecognized name is passed.


def _ReadDefinition(self, definitions_registry, definition_values):

    if not definition_values:
      error_message = 'missing definition values'
      raise errors.DefinitionReaderError(None, error_message)

    name = definition_values.get('name', None)
    if not name:
      error_message = 'missing name'
      raise errors.DefinitionReaderError(None, error_message)

    type_indicator = definition_values.get('type', None)
    if not type_indicator:
      error_message = 'invalid definition missing type'
      raise errors.DefinitionReaderError(name, error_message)

    data_type_callback = self._DATA_TYPE_CALLBACKS.get(type_indicator, None)
    if data_type_callback:
      data_type_callback = getattr(self, data_type_callback, None)
    if not data_type_callback:
      error_message = 'unuspported data type definition: {0:s}.'.format(
          type_indicator)
      raise errors.DefinitionReaderError(name, error_message)

    return data_type_callback(definitions_registry, definition_values, name)

Reads a data type definition.

Args:
definitions_registry (DataTypeDefinitionsRegistry): data type definitions
registry.
definition_values (dict[str, object]): definition values.

Returns:
DataTypeDefinition: data type definition or None.

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


def GetEntries(
      self, parser_mediator, cookie_data=None, url=None, **kwargs):

    fields = cookie_data.split('.')
    number_of_fields = len(fields)

    if number_of_fields not in (1, 6):
      parser_mediator.ProduceExtractionWarning(
          'unsupported number of fields: {0:d} in cookie: {1:s}'.format(
              number_of_fields, self.COOKIE_NAME))
      return

    if number_of_fields == 1:
      domain_hash = None
      visitor_identifier = None
      first_visit_posix_time = None
      previous_visit_posix_time = None

      try:

        last_visit_posix_time = int(fields[0], 10) / 10000000
      except ValueError:
        last_visit_posix_time = None

      number_of_sessions = None

    elif number_of_fields == 6:
      domain_hash = fields[0]
      visitor_identifier = fields[1]

      try:
        first_visit_posix_time = int(fields[2], 10)
      except ValueError:
        first_visit_posix_time = None

      try:
        previous_visit_posix_time = int(fields[3], 10)
      except ValueError:
        previous_visit_posix_time = None

      try:
        last_visit_posix_time = int(fields[4], 10)
      except ValueError:
        last_visit_posix_time = None

      try:
        number_of_sessions = int(fields[5], 10)
      except ValueError:
        number_of_sessions = None

    event_data = GoogleAnalyticsEventData('utma')
    event_data.cookie_name = self.COOKIE_NAME
    event_data.domain_hash = domain_hash
    event_data.sessions = number_of_sessions
    event_data.url = url
    event_data.visitor_id = visitor_identifier

    if first_visit_posix_time is not None:
      date_time = dfdatetime_posix_time.PosixTime(
          timestamp=first_visit_posix_time)
      event = time_events.DateTimeValuesEvent(
          date_time, 'Analytics Creation Time')
      parser_mediator.ProduceEventWithEventData(event, event_data)

    if previous_visit_posix_time is not None:
      date_time = dfdatetime_posix_time.PosixTime(
          timestamp=previous_visit_posix_time)
      event = time_events.DateTimeValuesEvent(
          date_time, 'Analytics Previous Time')
      parser_mediator.ProduceEventWithEventData(event, event_data)

    date_time = None
    if last_visit_posix_time is not None:
      date_time = dfdatetime_posix_time.PosixTime(
          timestamp=last_visit_posix_time)
      timestamp_description = definitions.TIME_DESCRIPTION_LAST_VISITED
    elif first_visit_posix_time is None and previous_visit_posix_time is None:

      date_time = dfdatetime_semantic_time.SemanticTime('Not set')
      timestamp_description = definitions.TIME_DESCRIPTION_NOT_A_TIME

    if date_time is not None:
      event = time_events.DateTimeValuesEvent(date_time, timestamp_description)
      parser_mediator.ProduceEventWithEventData(event, event_data)

Extracts event objects from the cookie.

Args:
parser_mediator (ParserMediator): parser mediator.
cookie_data (str): cookie data.
url (str): URL or path where the cookie got set.


def Prob(self, x):

        if x < self.xs[0]: return 0.0
        index = bisect.bisect(self.xs, x)
        p = self.ps[index - 1]
        return p

Returns CDF(x), the probability that corresponds to value x.

Args:
x: number

Returns:
float probability


def get_unsharded_shape(self, shapes):
    self._fill_default_values()
    if len(shapes) != self.number_of_shards:
        raise ValueError(f'Shapes {shapes} is length {len(shapes)} but must be a list of length number_of_shards={self.number_of_shards}')
    unsharded_shapes = [self._unshard_shape(s) for s in shapes]
    for i in range(self.number_of_shards - 1):
        if not unsharded_shapes[i].is_compatible_with(unsharded_shapes[self.number_of_shards - 1]):
            raise ValueError(f'Sharded shapes {shapes} are not consistent shards of a full shape sharded {self.number_of_shards} ways along dimension {self.shard_dimension}.')
    return unsharded_shapes[0]

Returns the shape of an unsharded Tensor given a list of shards.

When given a list of shapes of shards, returns the shape of the
unsharded Tensor that would generate the shards. Sets defaults for the
policy if number_of_shards or shard_dimension is None.

Args:
shapes: The shapes of the Tensor shards to be combined.

Returns:
The shape of the unsharded version of the Tensor.

Raises:
ValueError: if shapes is not a list of length
self.number_of_shards; or any element of shapes is not a valid
shape consistent with the sharding policy; or the list of
shapes is not a valid sharding of a full shape.
TypeError: if an element of shapes is not convertible to a
TensorShape


def _get_linear_trajectory(x0, velocity, t):

  x0 = tf.convert_to_tensor(x0)
  velocity = tf.convert_to_tensor(velocity)
  t = tf.convert_to_tensor(t)
  if x0.shape.ndims != 1:
    raise ValueError("x0 must be a rank 1 tensor")
  if velocity.shape.ndims != 1:
    raise ValueError("velocity must be a rank 1 tensor")
  if t.shape.ndims != 1:
    raise ValueError("t must be a rank 1 tensor")
  x0 = tf.expand_dims(x0, axis=0)
  velocity = tf.expand_dims(velocity, axis=0)
  dx = velocity * tf.expand_dims(t, axis=-1)
  linear_trajectories = x0 + dx
  assert linear_trajectories.shape.ndims == 2, \
    "linear_trajectories should be a rank 2 tensor"
  return linear_trajectories

Construct a linear trajectory from x0.

Args:
x0: N-D float tensor.
velocity: N-D float tensor
t: [sequence_length]-length float tensor

Returns:
x: [sequence_length, ndims] float tensor.


def __init__(self, affine_transformation_matrix, tol=0.01):

        affine_transformation_matrix = np.array(affine_transformation_matrix)
        if affine_transformation_matrix.shape != (4, 4):
            raise ValueError("Affine Matrix must be a 4x4 numpy array!")
        self.affine_matrix = affine_transformation_matrix
        self.tol = tol

Initializes the SymmOp from a 4x4 affine transformation matrix.
In general, this constructor should not be used unless you are
transferring rotations.  Use the static constructors instead to
generate a SymmOp from proper rotations and translation.

Args:
affine_transformation_matrix (4x4 array): Representing an
affine transformation.
tol (float): Tolerance for determining if matrices are equal.


def get_dataset_date(self, date_format=None):

        dataset_date = self.get_dataset_date_as_datetime()
        return self._get_formatted_date(dataset_date, date_format)

Get dataset date as string in specified format. For range returns start date.
If no format is supplied, an ISO 8601 string is returned.

Args:
date_format (Optional[str]): Date format. None is taken to be ISO 8601. Defaults to None.

Returns:
Optional[str]: Dataset date string or None if no date is set


def angle_to_name(angle, segments=8, abbr=False):

    if segments == 4:
        string = COMPASS_NAMES[int((angle + 45) / 90) % 4 * 2]
    elif segments == 8:
        string = COMPASS_NAMES[int((angle + 22.5) / 45) % 8 * 2]
    elif segments == 16:
        string = COMPASS_NAMES[int((angle + 11.25) / 22.5) % 16]
    else:
        raise ValueError('Segments parameter must be 4, 8 or 16 not %r'
                         % segments)
    if abbr:
        return ''.join(i[0].capitalize() for i in string.split('-'))
    else:
        return string

Convert angle in to direction name.

Args:
angle (float): Angle in degrees to convert to direction name
segments (int): Number of segments to split compass in to
abbr (bool): Whether to return abbreviated direction string

Returns:
str: Direction name for ``angle``


def register(
        self,
        pattern: str,
        handler: Any,
        flags: int = 0,
        channel: str = "*",
        subtype: Optional[str] = None,
    ) -> None:

        LOG.debug('Registering message endpoint "%s: %s"', pattern, handler)
        match = re.compile(pattern, flags)

        if subtype not in self._routes[channel]:
            self._routes[channel][subtype] = dict()

        if match in self._routes[channel][subtype]:
            self._routes[channel][subtype][match].append(handler)
        else:
            self._routes[channel][subtype][match] = [handler]

Register a new handler for a specific :class:`slack.events.Message`.

The routing is based on regex pattern matching the message text and the incoming slack channel.

Args:
pattern: Regex pattern matching the message text.
handler: Callback
flags: Regex flags.
channel: Slack channel ID. Use * for any.
subtype: Message subtype


def to_grayscale(img, num_output_channels=1):

    if not _is_pil_image(img):
        raise TypeError('img should be PIL Image. Got {}'.format(type(img)))

    if num_output_channels == 1:
        img = img.convert('L')
    elif num_output_channels == 3:
        img = img.convert('L')
        np_img = np.array(img, dtype=np.uint8)
        np_img = np.dstack([np_img, np_img, np_img])
        img = Image.fromarray(np_img, 'RGB')
    else:
        raise ValueError('num_output_channels should be either 1 or 3')

    return img

Convert image to grayscale version of image.

Args:
img (PIL Image): Image to be converted to grayscale.

Returns:
PIL Image: Grayscale version of the image.
if num_output_channels = 1 : returned image is single channel

if num_output_channels = 3 : returned image is 3 channel with r = g = b


def get_examples_from_dataset(self, dataset, evaluate=False):
    if evaluate:
        dataset = dataset['validation']
    else:
        dataset = dataset['train']
    examples = []
    for tensor_dict in tqdm(dataset):
        examples.append(self._get_example_from_tensor_dict(tensor_dict, evaluate=evaluate))
    return examples

Creates a list of [`~data.processors.squad.SquadExample`] using a TFDS dataset.

Args:
dataset: The tfds dataset loaded from *tensorflow_datasets.load("squad")*
evaluate: Boolean specifying if in evaluation mode or in training mode

Returns:
List of SquadExample

Examples:

```python
>>> import tensorflow_datasets as tfds

>>> dataset = tfds.load("squad")

>>> training_examples = get_examples_from_dataset(dataset, evaluate=False)
>>> evaluation_examples = get_examples_from_dataset(dataset, evaluate=True)
```


def zoomlevel(self):
    resources = self.get_resource()
    zoomlevel = namedtuple('zoomlevel', 'zoomLevel')
    try:
        return [zoomlevel(resource['zoomLevel']) for resource in resources]
    except TypeError:
        try:
            if isinstance(resources['ElevationData'], dict):
                return zoomlevel(resources['ElevationData']['ZoomLevel'])
        except KeyError:
            try:
                if isinstance(resources['SeaLevelData'], dict):
                    zoom = resources['SeaLevelData']['ZoomLevel']
                    return zoomlevel(zoom)
            except KeyError:
                print(KeyError)

Retrieves zoomlevel from the output response

Returns:
zoomlevel (namedtuple): A namedtuple of zoomlevel from the output
response


async def send_heartbeat(self, short_name):
    if (short_name not in self.services):
        raise ArgumentError('Unknown service name', short_name=short_name)
    self.services[short_name]['state'].heartbeat()
    (await self._notify_update(short_name, 'heartbeat'))

Post a heartbeat for a service.

Args:
short_name (string): The short name of the service to query


def get_ax_fig_plt(ax=None, **kwargs):
    import matplotlib.pyplot as plt
    if (ax is None):
        fig = plt.figure(**kwargs)
        ax = fig.add_subplot(1, 1, 1)
    else:
        fig = plt.gcf()
    return (ax, fig, plt)

Helper function used in plot functions supporting an optional Axes argument.
If ax is None, we build the `matplotlib` figure and create the Axes else
we return the current active figure.

Args:
kwargs: keyword arguments are passed to plt.figure if ax is not None.

Returns:
ax: :class:`Axes` object
figure: matplotlib figure
plt: matplotlib pyplot module.


def list_worker_processes(apppool):

    ps_cmd = ['Get-ChildItem',
              r"'IIS:\AppPools\{0}\WorkerProcesses'".format(apppool)]

    cmd_ret = _srvmgr(cmd=ps_cmd, return_json=True)

    try:
        items = salt.utils.json.loads(cmd_ret['stdout'], strict=False)
    except ValueError:
        raise CommandExecutionError('Unable to parse return data as Json.')

    ret = dict()
    for item in items:
        ret[item['processId']] = item['appPoolName']

    if not ret:
        log.warning('No backups found in output: %s', cmd_ret)

    return ret

Returns a list of worker processes that correspond to the passed
application pool.

.. versionadded:: 2017.7.0

Args:
apppool (str): The application pool to query

Returns:
dict: A dictionary of worker processes with their process IDs

CLI Example:

.. code-block:: bash

salt '*' win_iis.list_worker_processes 'My App Pool'


def end_block(self, request_end_block):
    self.abort_if_abci_chain_is_not_synced()
    chain_shift = (0 if (self.chain is None) else self.chain['height'])
    height = (request_end_block.height + chain_shift)
    self.new_height = height
    logger.debug(f'Updating pre-commit state: {self.new_height}')
    pre_commit_state = dict(height=self.new_height, transactions=self.block_txn_ids)
    self.bigchaindb.store_pre_commit_state(pre_commit_state)
    block_txn_hash = calculate_hash(self.block_txn_ids)
    block = self.bigchaindb.get_latest_block()
    if self.block_txn_ids:
        self.block_txn_hash = calculate_hash([block['app_hash'], block_txn_hash])
    else:
        self.block_txn_hash = block['app_hash']
    validator_update = Election.process_block(self.bigchaindb, self.new_height, self.block_transactions)
    return ResponseEndBlock(validator_updates=validator_update)

Calculate block hash using transaction ids and previous block
hash to be stored in the next block.

Args:
height (int): new height of the chain.


def incomplete_size(self, name=None):
    if name is None:
        name = '%s_incomplete_size' % self._name
    return self._incomplete_size_fn(shared_name=self._name, name=name, dtypes=self._dtypes, capacity=self._capacity, memory_limit=self._memory_limit)

Returns the number of incomplete elements in the staging area.

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

Returns:
The created op


def import_module(module_or_filename):
    if os.path.exists(module_or_filename):
        if not module_or_filename.endswith('.py'):
            try:
                return import_from_module_name(module_or_filename)
            except ImportError:
                raise ValueError('Fire can only be called on .py files.')
        return import_from_file_path(module_or_filename)
    if os.path.sep in module_or_filename:
        raise OSError('Fire was passed a filename which could not be found.')
    return import_from_module_name(module_or_filename)

Imports a given module or filename.

If the module_or_filename exists in the file system and ends with .py, we
attempt to import it. If that import fails, try to import it as a module.

Args:
module_or_filename (str): string name of path or module.

Raises:
ValueError: if the given file is invalid.
IOError: if the file or module can not be found or imported.

Returns:
Tuple[ModuleType, str]: returns the imported module and the module name,
usually extracted from the path itself.


def amend_commit(
            self,
            append_to_msg: typing.Optional[str] = None,
            new_message: typing.Optional[str] = None,
            files_to_add: typing.Optional[typing.Union[typing.List[str], str]] = None,
    ):

Amends last commit

Args:
append_to_msg: string to append to previous message
new_message: new commit message
files_to_add: optional list of files to commit


def generate_output_header(self, query_type='RDAP'):

        output = '\n{0}{1}{2} query for {3}:{4}\n\n'.format(
            ANSI['ul'],
            ANSI['b'],
            query_type,
            self.obj.address_str,
            ANSI['end']
        )

        return output

The function for generating the CLI output header.

Args:
query_type (:obj:`str`): The IPWhois query type. Defaults to
'RDAP'.

Returns:
str: The generated output.


def get_database_info(db_uri):

  if not db_uri:
    return None, None
  scheme = urlparse.urlparse(db_uri).scheme
  if scheme == 'sqlite':
    return sqlite3, create_sqlite_connection_provider(db_uri)
  else:
    raise ValueError('Only sqlite DB URIs are supported now: ' + db_uri)

Returns TBContext fields relating to SQL database.

Args:
db_uri: A string URI expressing the DB file, e.g. "sqlite:~/tb.db".

Returns:
A tuple with the db_module and db_connection_provider TBContext fields. If
db_uri was empty, then (None, None) is returned.

Raises:
ValueError: If db_uri scheme is not supported.


def get_urls_from_onetab(onetab):
    html = requests.get(onetab).text
    soup = BeautifulSoup(html, 'lxml')
    divs = soup.findAll('div', {'style': 'padding-left: 24px; padding-top: 8px; position: relative; font-size: 13px;'})
    return [div.find('a').attrs['href'] for div in divs]

Get video urls from a link to the onetab shared page.

Args:
onetab (str): Link to a onetab shared page.

Returns:
list: List of links to the videos.


def forward(self, inputs: torch.Tensor):
    inputs = self.dropout1(nn.functional.gelu(self.fc1(inputs)))
    inputs = self.fc2(inputs)
    inputs = self.dropout2(inputs)
    return inputs

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


def restore(self, request):
    self._connection.connection.rpush(self._request_key, pickle.dumps(request))

Push the request back onto the queue.

Args:
request (Request): Reference to a request object that should be pushed back
onto the request queue.


def create_binary_array(self, key, value):
    data = None
    if ((key is not None) and (value is not None)):
        value_encoded = []
        for v in value:
            try:
                value_encoded.append(base64.b64encode(bytes(v)).decode('utf-8'))
            except TypeError:
                value_encoded.append(base64.b64encode(bytes(v, 'utf-8')).decode('utf-8'))
        data = self.db.create(key.strip(), json.dumps(value_encoded))
    else:
        self.tcex.log.warning(u'The key or value field was None.')
    return data

Create method of CRUD operation for binary array data.

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

Returns:
(string): Result of DB write.


def move(self, queue_item, status):

        items = self.__get_var("items_" + queue_item.status)

        del items[queue_item.get_hash()]
        self.count_total -= 1

        queue_item.status = status
        self.add(queue_item)

Move a request/response pair to another status.

Args:
queue_item (:class:`nyawc.QueueItem`): The queue item to move
status (str): The new status of the queue item.


def _infer_binary_broadcast_shape(shape1, shape2, given_output_shape=None):

  shape1 = convert_to_shape(shape1)
  shape2 = convert_to_shape(shape2)
  given_output_shape = convert_to_shape(given_output_shape)
  if given_output_shape is not None:
    return given_output_shape
  if is_subsequence(shape1.dims, shape2.dims):
    return shape2
  if is_subsequence(shape2.dims, shape1.dims):
    return shape1
  return Shape(
      shape1.dims + [d for d in shape2.dims if d not in shape1.dims])

Infer shape of the output of a binary op with broadcasting.

If the output shape is not given with given_output_shape, then we check
to see if one of the shapes is a subsequence of the other one, and we
return the one that is the supersequence.  Otherwise, we list the dimensions
of shape1, followed by all new dimensions in shape2.

Args:
shape1: a Shape
shape2: a Shape
given_output_shape: an optional Shape
Returns:
a Shape


def _new(self, name, **kwargs):
    super(Package, self)._new(name, **kwargs)
    ElementTree.SubElement(self, 'filename').text = name

Create a new Package from scratch.

Args:
name: String filename of the package to use for the
Package object's Display Name (here, "name").
Will also be used as the "filename" value. Casper will
let you specify different values, but it is not
recommended.
kwargs:
Accepted keyword args include all top-level keys.
Values will be cast to string. (Int 10, bool False
become string values "10" and "false").


def new(self, name, *args, **kwargs):

        if name in self._instance_map:
            raise ValueError('Instance {0} is already initialized'
                             .format(name))

        instance = self._class_map[name](*args, **kwargs)
        self._instance_map[name] = instance
        return instance

Create an instance.

Args:
name (str): The name of the class
args: The arguments to pass to the class.
kwargs: The keyword arguments to pass to the class.

Returns:
instance


def gini(y, p):
    assert (y.shape == p.shape)
    n_samples = y.shape[0]
    arr = np.array([y, p]).transpose()
    true_order = arr[arr[(:, 0)].argsort()][(::(- 1), 0)]
    pred_order = arr[arr[(:, 1)].argsort()][(::(- 1), 0)]
    l_true = (np.cumsum(true_order) / np.sum(true_order))
    l_pred = (np.cumsum(pred_order) / np.sum(pred_order))
    l_ones = np.linspace((1 / n_samples), 1, n_samples)
    g_true = np.sum((l_ones - l_true))
    g_pred = np.sum((l_ones - l_pred))
    return (g_pred / g_true)

Normalized Gini Coefficient.

Args:
y (numpy.array): target
p (numpy.array): prediction

Returns:
e (numpy.float64): normalized Gini coefficient


def to_file(self, path):

        with open(os.path.expanduser(path), "w") as ofile:
            ofile.write(self.__repr__())

Write object XML to path.

Args:
path: String file path to the file you wish to (over)write.
Path will have ~ expanded prior to opening.


def content_metadata_uploads(self, mirror=False):
    excludes_str = ''
    includes_cmds = []
    cmd_base = self._get_upload_cmd(mirror=mirror)
    for content in self.s3props.get('content_metadata'):
        full_path = os.path.join(self.artifact_path, content['path'])
        if (not os.listdir(full_path)):
            raise S3ArtifactNotFound
        excludes_str += '--exclude "{}/*" '.format(content['path'])
        include_cmd = '{} --exclude "*", --include "{}/*"'.format(cmd_base, content['path'])
        include_cmd += ' --content-encoding {} --metadata-directive REPLACE'.format(content['content-encoding'])
        includes_cmds.append(include_cmd)
    exclude_cmd = '{} {}'.format(cmd_base, excludes_str)
    result = subprocess.run(exclude_cmd, check=True, shell=True, stdout=subprocess.PIPE)
    LOG.info('Uploaded files without metadata with command: %s', exclude_cmd)
    LOG.debug('Upload Command Output: %s', result.stdout)
    for include_cmd in includes_cmds:
        result = subprocess.run(include_cmd, check=True, shell=True, stdout=subprocess.PIPE)
        LOG.info('Uploaded files with metadata with command: %s', include_cmd)
        LOG.debug('Upload Command Output: %s', result.stdout)
    return True

Finds all specified encoded directories and uploads in multiple parts,
setting metadata for objects.

Args:
mirror (bool): If true, uses a flat directory structure instead of nesting under a version.

Returns:
bool: True if uploaded


def get_parameter(self, name):
    i = self.get_parameter_names(include_frozen=True).index(name)
    return self.get_parameter_vector(include_frozen=True)[i]

Get a parameter value by name

Args:
name: The name of the parameter


def user_func(func, arg_types=None, return_type=None):

    class UserFunction(std_core.TypedFunction):
        name = func.__name__

        def __call__(self, *args, **kwargs):
            return func(*args, **kwargs)

        @classmethod
        def reflect_static_args(cls):
            return arg_types

        @classmethod
        def reflect_static_return(cls):
            return return_type
    return UserFunction()

Create an EFILTER-callable version of function 'func'.

As a security precaution, EFILTER will not execute Python callables
unless they implement the IApplicative protocol. There is a perfectly good
implementation of this protocol in the standard library and user functions
can inherit from it.

This will declare a subclass of the standard library TypedFunction and
return an instance of it that EFILTER will happily call.

Arguments:
func: A Python callable that will serve as the implementation.
arg_types (optional): A tuple of argument types. If the function takes
keyword arguments, they must still have a defined order.
return_type (optional): The type the function returns.

Returns:
An instance of a custom subclass of efilter.stdlib.core.TypedFunction.

Examples:
def my_callback(tag):
print("I got %r" % tag)

api.apply("if True then my_callback('Hello World!')",
vars={
"my_callback": api.user_func(my_callback)
})

# This should print "I got 'Hello World!'".


def HandleClockSync(self, response):

    self.logger.info('Clock drift token has changed: %s.', response)
    self.distro_utils.HandleClockSync(self.logger)

Called when clock drift token changes.

Args:
response: string, the metadata response with the new drift token value.


def nr_cases(self, snv_cases=None, sv_cases=None):
    query = {}
    if snv_cases:
        query = {'vcf_path': {'$exists': True}}
    if sv_cases:
        query = {'vcf_sv_path': {'$exists': True}}
    if (snv_cases and sv_cases):
        query = None
    return self.db.case.count_documents(query)

Return the number of cases in the database

Args:
snv_cases(bool): If only snv cases should be searched
sv_cases(bool): If only snv cases should be searched

Returns:
cases (Iterable(Case)): A iterable with mongo cases


def __getitem__(self, key):

		if key in self._nodes:	return self._nodes[key]
		else:					raise KeyError(key)

Get Item (__getitem__)

Returns a specific key from the parent

Arguments:
key {str} -- The key to get

Raises:
KeyError

Returns:
mixed


def calculate_keys_by_mapreduce_state(cls, mapreduce_state):

    if mapreduce_state is None:
      return []

    keys = []
    for i in range(mapreduce_state.mapreduce_spec.mapper.shard_count):
      shard_id = cls.shard_id_from_number(mapreduce_state.key().name(), i)
      keys.append(cls.get_key_by_shard_id(shard_id))
    return keys

Calculate all shard states keys for given mapreduce.

Args:
mapreduce_state: MapreduceState instance

Returns:
A list of keys for shard states, sorted by shard id.
The corresponding shard states may not exist.


def is_struct(declaration):
    if (not is_class(declaration)):
        return False
    decl = class_traits.get_declaration(declaration)
    return (decl.class_type == class_declaration.CLASS_TYPES.STRUCT)

Returns True if declaration represents a C++ struct

Args:
declaration (declaration_t): the declaration to be checked.

Returns:
bool: True if declaration represents a C++ struct


def adopt_module_key_flags(module, flag_values=_flagvalues.FLAGS):

  if not isinstance(module, types.ModuleType):
    raise _exceptions.Error('Expected a module object, not %r.' % (module,))
  _internal_declare_key_flags(
      [f.name for f in flag_values.get_key_flags_for_module(module.__name__)],
      flag_values=flag_values)

  if module == _helpers.FLAGS_MODULE:
    _internal_declare_key_flags(

        [_helpers.SPECIAL_FLAGS[name].name for name in _helpers.SPECIAL_FLAGS],
        flag_values=_helpers.SPECIAL_FLAGS,
        key_flag_values=flag_values)

Declares that all flags key to a module are key to the current module.

Args:
module: module, the module object from which all key flags will be declared
as key flags to the current module.
flag_values: FlagValues, the FlagValues instance in which the flags will
be declared as key flags. This should almost never need to be
overridden.

Raises:
Error: Raised when given an argument that is a module name (a string),
instead of a module object.


def __init__(self, learning_rate, initial_accumulator_value=0.1, l1_regularization_strength=0.0, l2_regularization_strength=0.0, use_locking=False, name='ProximalAdagrad'):
    if initial_accumulator_value <= 0.0:
        raise ValueError('initial_accumulator_value must be positive: %s' % initial_accumulator_value)
    super(ProximalAdagradOptimizer, self).__init__(use_locking, name)
    self._learning_rate = learning_rate
    self._initial_accumulator_value = initial_accumulator_value
    self._l1_regularization_strength = l1_regularization_strength
    self._l2_regularization_strength = l2_regularization_strength
    self._l1_regularization_strength_tensor = None
    self._l2_regularization_strength_tensor = None
    self._learning_rate_tensor = None

Construct a new ProximalAdagrad optimizer.

Args:
learning_rate: A `Tensor` or a floating point value.  The learning rate.
initial_accumulator_value: A floating point value.
Starting value for the accumulators, must be positive.
l1_regularization_strength: A float value, must be greater than or
equal to zero.
l2_regularization_strength: A float value, must be greater than or
equal to zero.
use_locking: If `True` use locks for update operations.
name: Optional name prefix for the operations created when applying
gradients.  Defaults to "Adagrad".

Raises:
ValueError: If the `initial_accumulator_value` is invalid.


def populate_development(version):

    with open(DEVELOPMENT_TEMPLATE, "r") as file_obj:
        template = file_obj.read()
    contents = template.format(revision=version, rtd_version=version)
    with open(DEVELOPMENT_FILE, "w") as file_obj:
        file_obj.write(contents)

Populates ``DEVELOPMENT.rst`` with release-specific data.

This is because ``DEVELOPMENT.rst`` is used in the Sphinx documentation.

Args:
version (str): The current version.


def is_unknown(input, model_file=None, model_proto=None, name=None):
    return _gen_sentencepiece_processor_op.sentencepiece_get_piece_type(input, model_file=model_file, model_proto=model_proto, name=name, piece_type=0)

Returns true if input id is unknown piece.

Args:
input: An arbitrary tensor of int32.
model_file: The sentencepiece model file path.
model_proto: The sentencepiece model serialized proto.
Either `model_file` or `model_proto` must be set.
name: The name argument that is passed to the op function.
Returns:
A tensor of bool with the same shape as input.


async def get_match(self, m_id, force_update=False) -> Match:

        found_m = self._find_match(m_id)
        if force_update or found_m is None:
            await self.get_matches()
            found_m = self._find_match(m_id)
        return found_m

get a single match by id

|methcoro|

Args:
m_id: match id
force_update (default=False): True to force an update to the Challonge API

Returns:
Match

Raises:
APIException


def Start(self, hostname, port):

    if not self._Open(hostname, port):
      return False

    self._rpc_thread = threading.Thread(
        name=self._THREAD_NAME, target=self._xmlrpc_server.serve_forever)
    self._rpc_thread.start()
    return True

Starts the process status RPC server.

Args:
hostname (str): hostname or IP address to connect to for requests.
port (int): port to connect to for requests.

Returns:
bool: True if the RPC server was successfully started.


def _rpc(self, rpc_func_name, *args, **kwargs):
    try:
        self.check_server_proc_running()
    except Exception:
        self.log.error('Server process running check failed, skip sending RPC method(%s).', rpc_func_name)
        raise
    with self._lock:
        rpc_id = next(self._counter)
        request = self._gen_rpc_request(rpc_id, rpc_func_name, *args, **kwargs)
        self.log.debug('Sending RPC request %s.', request)
        response = self.send_rpc_request(request)
        self.log.debug('RPC request sent.')
        if self.verbose_logging or _MAX_RPC_RESP_LOGGING_LENGTH >= len(response):
            self.log.debug('Snippet received: %s', response)
        else:
            self.log.debug('Snippet received: %s... %d chars are truncated', response[:_MAX_RPC_RESP_LOGGING_LENGTH], len(response) - _MAX_RPC_RESP_LOGGING_LENGTH)
    response_decoded = self._decode_response_string_and_validate_format(rpc_id, response)
    return self._handle_rpc_response(rpc_func_name, response_decoded)

Sends an RPC to the server.

Args:
rpc_func_name: str, the name of the snippet function to execute on the
server.
*args: any, the positional arguments of the RPC request.
**kwargs: any, the keyword arguments of the RPC request.

Returns:
The result of the RPC.

Raises:
errors.ProtocolError: something went wrong when exchanging data with the
server.
errors.ApiError: the RPC went through, however executed with errors.


def lstm_with_recurrent_dropout(hidden_size, keep_prob=0.5, **kwargs):

  lstm = LSTM(hidden_size, **kwargs)
  return RecurrentDropoutWrapper(lstm, LSTMState(keep_prob, None)), lstm

LSTM with recurrent dropout.

Args:
hidden_size: the LSTM hidden size.
keep_prob: the probability to keep an entry when applying dropout.
**kwargs: Extra keyword arguments to pass to the LSTM.

Returns:
A tuple (train_lstm, test_lstm) where train_lstm is an LSTM with
recurrent dropout enabled to be used for training and test_lstm
is the same LSTM without recurrent dropout.


def _write_to_file(self, fileinfo, filename):

        txt = to_text_string(fileinfo.editor.get_text_with_eol())
        fileinfo.encoding = encoding.write(txt, filename, fileinfo.encoding)

Low-level function for writing text of editor to file.

Args:
fileinfo: FileInfo object associated to editor to be saved
filename: str with filename to save to

This is a low-level function that only saves the text to file in the
correct encoding without doing any error handling.


def get_pending_domain_join():
    base_key = 'SYSTEM\\CurrentControlSet\\Services\\Netlogon'
    avoid_key = '{0}\\AvoidSpnSet'.format(base_key)
    join_key = '{0}\\JoinDomain'.format(base_key)
    if __utils__['reg.key_exists']('HKLM', avoid_key):
        log.debug('Key exists: %s', avoid_key)
        return True
    else:
        log.debug('Key does not exist: %s', avoid_key)
    if __utils__['reg.key_exists']('HKLM', join_key):
        log.debug('Key exists: %s', join_key)
        return True
    else:
        log.debug('Key does not exist: %s', join_key)
    return False

Determine whether there is a pending domain join action that requires a
reboot.

.. versionadded:: 2016.11.0

Returns:
bool: ``True`` if there is a pending domain join action, otherwise
``False``

CLI Example:

.. code-block:: bash

salt '*' system.get_pending_domain_join


def loss_scale(self):
    return self._loss_scale

Returns the loss scale of this Policy.

Returns:
A `tf.compat.v1.mixed_precision.experimental.LossScale`, or None.


def _prep_crypto_msg(message):
    signature = message['signature']
    certificate = message['certificate']
    (sliced_signature, sliced_certificate) = ([], [])
    for x in range(0, len(signature), 76):
        sliced_signature.append(signature[x:(x + 76)])
    for x in range(0, len(certificate), 76):
        sliced_certificate.append(certificate[x:(x + 76)])
    message['signature'] = (u'\n'.join(sliced_signature) + u'\n')
    message['certificate'] = (u'\n'.join(sliced_certificate) + u'\n')
    return message

Split the signature and certificate in the same way M2Crypto does.

M2Crypto is dropping newlines into its signature and certificate. This
exists purely to maintain backwards compatibility.

Args:
message (dict): A message with the ``signature`` and ``certificate`` keywords.
The values of these two keys must be byte strings.

Returns:
dict: The same message, but with the values of ``signature`` and ``certificate``
split every 76 characters with a newline and a final newline at the end.


def trainable_initial_state(batch_size, state_size, dtype, initializers=None, regularizers=None, name=None):
    flat_state_size = nest.flatten(state_size)
    if (not initializers):
        flat_initializer = tuple((tf.zeros_initializer() for _ in flat_state_size))
    else:
        nest.assert_same_structure(initializers, state_size)
        flat_initializer = nest.flatten(initializers)
        if (not all([callable(init) for init in flat_initializer])):
            raise ValueError('Not all the passed initializers are callable objects.')
    if (not regularizers):
        flat_regularizer = tuple(({} for _ in flat_state_size))
    else:
        nest.assert_same_structure(regularizers, state_size)
        flat_regularizer = nest.flatten(regularizers)
        if (not all([callable(regularizer) for regularizer in flat_regularizer])):
            raise ValueError('Not all the passed regularizers are callable objects.')
    name_prefix = (name or 'initial_state')
    try:
        name_suffixes = [state_size._fields[i] for i in xrange(len(flat_state_size))]
    except (AttributeError, IndexError):
        name_suffixes = range(len(flat_state_size))
    flat_initial_state = []
    for (name_suffix, size, init, regularizer) in zip(name_suffixes, flat_state_size, flat_initializer, flat_regularizer):
        shape_with_batch_dim = ([1] + tf.TensorShape(size).as_list())
        variable_name = '{}_{}'.format(name_prefix, name_suffix)
        initial_state_module = basic.TrainableVariable(shape_with_batch_dim, dtype=dtype, initializers={'w': init}, regularizers={'w': regularizer}, name=variable_name)
        initial_state_variable = initial_state_module()
        tiled_name = 'state_{}_tiled'.format(name_suffix)
        initial_state_variable_dims = initial_state_variable.get_shape().ndims
        tile_dims = ([batch_size] + ([1] * (initial_state_variable_dims - 1)))
        flat_initial_state.append(tf.tile(initial_state_variable, tile_dims, name=tiled_name))
    return nest.pack_sequence_as(structure=state_size, flat_sequence=flat_initial_state)

Creates an initial state consisting of trainable variables.

The trainable variables are created with the same shapes as the elements of
`state_size` and are tiled to produce an initial state.

Args:
batch_size: An int, or scalar int32 Tensor representing the batch size.
state_size: A `TensorShape` or nested tuple of `TensorShape`s to use for the
shape of the trainable variables.
dtype: The data type used to create the variables and thus initial state.
initializers: An optional container of the same structure as `state_size`
containing initializers for the variables.
regularizers: An optional container of the same structure as `state_size`
containing regularizers for the variables.
name: optional string used to prefix the initial state variable names.

Returns:
A `Tensor` or nested tuple of `Tensor`s with the same size and structure
as `state_size`, where each `Tensor` is a tiled trainable `Variable`.

Raises:
ValueError: if the user passes initializers that are not functions.
ValueError: if the user passes regularizers that are not functions.


def memoise(cls, func):

        @functools.wraps(func)
        def f(*a):

            for arg in a:
                if isinstance(arg, User):
                    user = arg
                    break
            else:
                raise ValueError("One position argument must be a User")

            func_key = (func, tuple(a))
            cache = cls.get_cache(user)

            if func_key not in cache:
                cache[func_key] = func(*a)

            return cache[func_key]

        return f

Decorator that stores the result of the stored function in the
user's results cache until the batch completes. Keyword arguments are
not yet supported.

Arguments:
func (callable(*a)): The function whose results we want
to store. The positional arguments, ``a``, are used as cache
keys.

Returns:
callable(*a): The memosing version of ``func``.


def indexed_slices_union_indices_and_values(x1, x2_indices, x2_values=None):
    dim_0 = x1.dense_shape[0]
    x1_indices_expanded = tf.expand_dims(x1.indices, axis=1)
    x2_indices_expanded = tf.expand_dims(x2_indices, axis=1)
    x1_indices_count = tf.shape(x1_indices_expanded)[0]
    x2_indices_count = tf.shape(x2_indices_expanded)[0]
    x1_indices_one_hot = tf.scatter_nd(x1_indices_expanded, ones_bool((x1_indices_count,)), (dim_0,))
    x2_indices_one_hot = tf.scatter_nd(x2_indices_expanded, ones_bool((x2_indices_count,)), (dim_0,))
    union_indices = tf.squeeze(tf.where(tf.math.logical_or(x1_indices_one_hot, x2_indices_one_hot)), axis=-1)
    union_indices_count = tf.shape(union_indices)[0]

    def values_for_union(indices_expanded, indices_count, values):
        indices_indices = tf.scatter_nd(indices_expanded, tf.range(1, indices_count + 1), (dim_0,))
        to_union_indices = tf.gather(indices_indices, union_indices)
        values_with_leading_zeros = tf.concat([tf.zeros_like(values[0:1]), values], axis=0)
        return tf.gather(values_with_leading_zeros, to_union_indices)
    x1_values_for_union_indices = tf.cond(tf.equal(x1_indices_count, union_indices_count), lambda: x1.values, lambda: values_for_union(x1_indices_expanded, x1_indices_count, x1.values))
    if x2_values is not None:
        x2_values_for_union_indices = tf.cond(tf.equal(x2_indices_count, union_indices_count), lambda: x2_values, lambda: values_for_union(x2_indices_expanded, x2_indices_count, x2_values))
    else:
        x2_values_for_union_indices = None
    return (union_indices, x1_values_for_union_indices, x2_values_for_union_indices)

Compute the indices for the union of two `tf.IndexedSlices` and modify
the values for these indices.

Args:
x1: the first `tf.IndexedSlices`.
x2_indices: the indices for the second `tf.IndexedSlices`.
x2_value: (optional) the values for the second `tf.IndexedSlices`.
Returns: A tuple containing:
- the indices for the union
- `x1` values for the union indices (some zeros were added)
- `x2` values for the union indices (some zeros were added) or `None` if
`x2_values` was `None`.


def fulfill(self):
    (is_fulfilled, result) = self._check_fulfilled()
    if is_fulfilled:
        return result
    else:
        raise BrokenPromise(self)

Evaluate the promise and return the result.

Returns:
The result of the `Promise` (second return value from the `check_func`)

Raises:
BrokenPromise: the `Promise` was not satisfied within the time or attempt limits.


def connected_site_pairs( self ):

        site_connections = {}
        for initial_site in self.sites:
            if not initial_site.label in site_connections:
                site_connections[ initial_site.label ] = []
            for final_site in initial_site.p_neighbours:
                if final_site.label not in site_connections[ initial_site.label ]:
                    site_connections[ initial_site.label ].append( final_site.label )
        return site_connections

Returns a dictionary of all connections between pair of sites (by site label).
e.g. for a linear lattice A-B-C will return::

{ 'A' : [ 'B' ], 'B' : [ 'A', 'C' ], 'C' : [ 'B' ] }

Args:
None

Returns:
site_connections (Dict{Str List[Str]}): A dictionary of neighbouring site types in the lattice.


def create_media_service_rg(access_token, subscription_id, rgname, location, stoname, msname):

    endpoint = ''.join([get_rm_endpoint(),
                        '/subscriptions/', subscription_id,
                        '/resourceGroups/', rgname,
                        '/providers/microsoft.media/mediaservices/', msname,
                        '?api-version=', MEDIA_API])
    ms_body = {'name': msname}
    ms_body['location'] = location
    sub_id_str = '/subscriptions/' + subscription_id + '/resourceGroups/' + rgname + \
        '/providers/Microsoft.Storage/storageAccounts/' + stoname
    storage_account = {'id': sub_id_str}
    storage_account['isPrimary'] = True
    properties = {'storageAccounts': [storage_account]}
    ms_body['properties'] = properties
    body = json.dumps(ms_body)
    return do_put(endpoint, body, access_token)

Create a media service in a resource group.

Args:
access_token (str): A valid Azure authentication token.
subscription_id (str): Azure subscription id.
rgname (str): Azure resource group name.
location (str): Azure data center location. E.g. westus.
stoname (str): Azure storage account name.
msname (str): Media service name.

Returns:
HTTP response. JSON body.


def select_by_key(self, key):
    self._selected_key = None
    self._selected_item = None
    for item in self.children.values():
        item.attributes['selected'] = False
    if (key in self.children):
        self.children[key].attributes['selected'] = True
        self._selected_key = key
        self._selected_item = self.children[key]

Selects an item by its key.

Args:
key (str): The unique string identifier of the item that have to be selected.


def build_kw_dict(kw_list):

    kw_dict = OrderedDict()
    sorted_list = sorted(
        kw_list,
        key=lambda x: x.get("zahlavi").encode("utf-8")
    )

    for keyword_data in sorted_list:
        if "zahlavi" not in keyword_data:
            continue

        zahlavi = keyword_data["zahlavi"].encode("utf-8")
        old_record = kw_dict.get(zahlavi)

        if not old_record:
            kw_dict[zahlavi] = keyword_data
            continue

        key = "angl_ekvivalent"
        if not old_record.get(key) and keyword_data.get(key):
            kw_dict[zahlavi] = keyword_data
            continue

        key = "zdroj_angl_ekvivalentu"
        if not old_record.get(key) and keyword_data.get(key):
            kw_dict[zahlavi] = keyword_data
            continue

        if len(str(keyword_data)) > len(str(old_record)):
            kw_dict[zahlavi] = keyword_data
            continue

    return kw_dict

Build keyword dictionary from raw keyword data. Ignore invalid or
invalidated records.

Args:
kw_list (list): List of dicts from :func:`read_kw_file`.

Returns:
OrderedDict: dictionary with keyword data.


def insert_or_assign(self, keys, values, name=None):
    with ops.name_scope(name, '%s_lookup_table_insert' % self.name, [self.resource_handle, keys, values]):
        keys = ops.convert_to_tensor(keys, dtype=self._key_dtype, name='keys')
        values = ops.convert_to_tensor(values, dtype=self._value_dtype, name='values')
        with ops.colocate_with(self.resource_handle):
            op = gen_lookup_ops.lookup_table_insert_v2(self.resource_handle, keys, values)
        return op

Associates `keys` with `values`.

Args:
keys: Keys to insert. Can be a tensor of any shape. Must match the table's
key type.
values: Values to be associated with keys. Must be a tensor of the same
shape as `keys` and match the table's value type.
name: A name for the operation (optional).

Returns:
The created Operation.

Raises:
TypeError: when `keys` or `values` doesn't match the table data
types.


def FileEntryExistsByPathSpec(self, path_spec):

    location = getattr(path_spec, 'location', None)

    if location is None:
      return False

    is_device = False
    if platform.system() == 'Windows':

      try:
        is_device = pysmdev.check_device(location)
      except IOError as exception:

        exception_string = str(exception)
        if not isinstance(exception_string, py2to3.UNICODE_TYPE):
          exception_string = py2to3.UNICODE_TYPE(
              exception_string, errors='replace')

        if ' access denied ' in exception_string:
          is_device = True

    return is_device or os.path.exists(location) or os.path.islink(location)

Determines if a file entry for a path specification exists.

Args:
path_spec (PathSpec): a path specification.

Returns:
bool: True if the file entry exists, false otherwise.


def get_per_replica_batch_size(self, global_batch_size):
    if global_batch_size % self._num_replicas_in_sync != 0:
        raise ValueError('The `global_batch_size` %r is not divisible by `num_replicas_in_sync` %r ' % (global_batch_size, self._num_replicas_in_sync))
    return global_batch_size

Returns the per-replica batch size.

Args:
global_batch_size: the global batch size which should be divisible by
`num_replicas_in_sync`.

Returns:
the per-replica batch size.

Raises:
ValueError: if `global_batch_size` not divisible by
`num_replicas_in_sync`.


def from_dict_(cls, conf_dict):

        return cls(**{name: Section(**opts)
                      for name, opts in conf_dict.items()})

Use a dictionary to create a :class:`ConfigurationManager`.

Args:
conf_dict (dict of dict of :class:`ConfOpt`): the first level of
keys should be the section names. The second level should be
the option names. The values are the options metadata.

Returns:
:class:`ConfigurationManager`: a configuration manager with the
requested sections and options.


def __init__(self, file_path):

        self._file_path = os.path.normpath(file_path) if file_path is not None else None
        self._is_header_loaded = False
        self._is_data_loaded = False
        self._is_ip = False

        self._data = []
        self._metadata = {}
        self._heating_dict = {}
        self._cooling_dict = {}
        self._extremes_dict = {}
        self._extreme_hot_weeks = {}
        self._extreme_cold_weeks = {}
        self._typical_weeks = {}
        self._monthly_ground_temps = {}
        self._is_leap_year = False
        self.daylight_savings_start = '0'
        self.daylight_savings_end = '0'
        self.comments_1 = ''
        self.comments_2 = ''

        self._num_of_fields = 35

Initalize an EPW object from from a local .epw file.

Args:
file_path: Local file address to an .epw file.


def apply_fixup_array(bin_view, fx_offset, fx_count, entry_size):
    fx_array = bin_view[fx_offset:(fx_offset + (2 * fx_count))]
    fx_len = (fx_count - 1)
    sector_size = int((entry_size / fx_len))
    index = 1
    position = ((sector_size * index) - 2)
    while (position <= entry_size):
        if (bin_view[position:(position + 2)].tobytes() == fx_array[:2].tobytes()):
            bin_view[position:(position + 2)] = fx_array[(index * 2):((index * 2) + 2)]
        else:
            _MOD_LOGGER.error('Error applying the fixup array')
            raise FixUpError(f'Signature {fx_array[:2].tobytes()} does not match {bin_view[position:(position + 2)].tobytes()} at offset {position}.')
        index += 1
        position = ((sector_size * index) - 2)
    _MOD_LOGGER.info('Fix up array applied successfully.')

This function reads the fixup array and apply the correct values
to the underlying binary stream. This function changes the bin_view
in memory.

Args:
bin_view (memoryview of bytearray) - The binary stream
fx_offset (int) - Offset to the fixup array
fx_count (int) - Number of elements in the fixup array
entry_size (int) - Size of the MFT entry


def get_player(first_name, last_name=None, season=constants.CURRENT_SEASON, only_current=0, just_id=True):
    if (last_name is None):
        name = first_name.lower()
    else:
        name = '{}, {}'.format(last_name, first_name).lower()
    pl = PlayerList(season=season, only_current=only_current).info()
    hdr = 'DISPLAY_LAST_COMMA_FIRST'
    if HAS_PANDAS:
        item = pl[(pl.DISPLAY_LAST_COMMA_FIRST.str.lower() == name)]
    else:
        item = next((plyr for plyr in pl if (str(plyr[hdr]).lower() == name)))
    if (len(item) == 0):
        raise PlayerNotFoundException
    elif just_id:
        return item['PERSON_ID']
    else:
        return item

Calls our PlayerList class to get a full list of players and then returns
just an id if specified or the full row of player information

Args:
:first_name: First name of the player
:last_name: Last name of the player
(this is None if the player only has first name [Nene])
:only_current: Only wants the current list of players
:just_id: Only wants the id of the player

Returns:
Either the ID or full row of information of the player inputted

Raises:
:PlayerNotFoundException::


def retrieve_collected_errors():
    serialized_message_list = wrap_converter.wrapped_retrieve_collected_errors()
    return list(map(converter_error_data_pb2.ConverterErrorData.FromString, serialized_message_list))

Returns and clears the list of collected errors in ErrorCollector.

The RetrieveCollectedErrors function in C++ returns a list of serialized proto
messages. This function will convert them to ConverterErrorData instances.

Returns:
A list of ConverterErrorData.


def stream(self, report, callback=None):
    if (self._push_channel is None):
        return
    self._push_channel.stream(report, callback=callback)

Stream a report asynchronously.

If no one is listening for the report, the report may be dropped,
otherwise it will be queued for sending

Args:
report (IOTileReport): The report that should be streamed
callback (callable): Optional callback to get notified when
this report is actually sent.


def check_config(config):
    for (section, expected_section_keys) in SECTION_KEYS.items():
        section_content = config.get(section)
        if (not section_content):
            raise ConfigurationError('Config file badly formed! Section {} is missing.'.format(section))
        elif (not _section_is_healthy(section_content, expected_section_keys)):
            raise ConfigurationError('The {} section of the configuration file is badly formed!'.format(section))

Check that all sections of the config contain the keys that they should.

Args:
config (defaultdict): A defaultdict.
Raises:
ConfigurationError


def sensor(self, name, config=None, inactive_sensor_expiration_time_seconds=sys.maxsize, parents=None):
    sensor = self.get_sensor(name)
    if sensor:
        return sensor
    with self._lock:
        sensor = self.get_sensor(name)
        if (not sensor):
            sensor = Sensor(self, name, parents, (config or self.config), inactive_sensor_expiration_time_seconds)
            self._sensors[name] = sensor
            if parents:
                for parent in parents:
                    children = self._children_sensors.get(parent)
                    if (not children):
                        children = []
                        self._children_sensors[parent] = children
                    children.append(sensor)
            logger.debug('Added sensor with name %s', name)
        return sensor

Get or create a sensor with the given unique name and zero or
more parent sensors. All parent sensors will receive every value
recorded with this sensor.

Arguments:
name (str): The name of the sensor
config (MetricConfig, optional): A default configuration to use
for this sensor for metrics that don't have their own config
inactive_sensor_expiration_time_seconds (int, optional):
If no value if recorded on the Sensor for this duration of
time, it is eligible for removal
parents (list of Sensor): The parent sensors

Returns:
Sensor: The sensor that is created


def get_oauth_access_token(url, client_id, client_secret, token_type='jwt', grant_type='client_credentials', refresh_token=None):
    now = datetime.datetime.utcnow()
    data = {'grant_type': grant_type, 'client_id': client_id, 'client_secret': client_secret, 'token_type': token_type}
    if refresh_token:
        data['refresh_token'] = refresh_token
    else:
        assert (grant_type != 'refresh_token'), 'refresh_token parameter required'
    response = requests.post(url, data=data, headers={'User-Agent': USER_AGENT})
    data = response.json()
    try:
        access_token = data['access_token']
        expires_in = data['expires_in']
    except KeyError:
        raise requests.RequestException(response=response)
    expires_at = (now + datetime.timedelta(seconds=expires_in))
    return (access_token, expires_at)

Retrieves OAuth 2.0 access token using the given grant type.

Args:
url (str): Oauth2 access token endpoint
client_id (str): client ID
client_secret (str): client secret
Kwargs:
token_type (str): Type of token to return. Options include bearer and jwt.
grant_type (str): One of 'client_credentials' or 'refresh_token'
refresh_token (str): The previous access token (for grant_type=refresh_token)

Returns:
tuple: Tuple containing access token string and expiration datetime.


def from_string(string_data, file_format='xyz'):
    mols = pb.readstring(str(file_format), str(string_data))
    return BabelMolAdaptor(mols.OBMol)

Uses OpenBabel to read a molecule from a string in all supported
formats.

Args:
string_data: String containing molecule data.
file_format: String specifying any OpenBabel supported formats.

Returns:
BabelMolAdaptor object


def stat(self, entry_path, follow_symlinks=True):

        try:
            file_object = self.resolve(
                entry_path, follow_symlinks, allow_fd=True)
            self.raise_for_filepath_ending_with_separator(
                entry_path, file_object, follow_symlinks)

            return file_object.stat_result.copy()
        except IOError as io_error:
            winerror = (io_error.winerror if hasattr(io_error, 'winerror')
                        else io_error.errno)
            self.raise_os_error(io_error.errno, entry_path, winerror=winerror)

Return the os.stat-like tuple for the FakeFile object of entry_path.

Args:
entry_path:  Path to filesystem object to retrieve.
follow_symlinks: If False and entry_path points to a symlink,
the link itself is inspected instead of the linked object.

Returns:
The FakeStatResult object corresponding to entry_path.

Raises:
OSError: if the filesystem object doesn't exist.


def read_stream(self, file: IO, data_stream: DataStream) -> Reply:

        yield from data_stream.read_file(file=file)

        reply = yield from self._control_stream.read_reply()

        self.raise_if_not_match(
            'End stream',
            ReplyCodes.closing_data_connection,
            reply
        )

        data_stream.close()

        return reply

Read from the data stream.

Args:
file: A destination file object or a stream writer.
data_stream: The stream of which to read from.

Coroutine.

Returns:
Reply: The final reply.


def scatter_max(self, sparse_delta, use_locking=False, name=None):
    if not isinstance(sparse_delta, indexed_slices.IndexedSlices):
        raise TypeError(f'Argument `sparse_delta` must be a `tf.IndexedSlices`. Received arg: {sparse_delta}')
    return self._lazy_read(gen_resource_variable_ops.resource_scatter_max(self.handle, sparse_delta.indices, ops.convert_to_tensor(sparse_delta.values, self.dtype), name=name))

Updates this variable with the max of `tf.IndexedSlices` and itself.

Args:
sparse_delta: `tf.IndexedSlices` to use as an argument of max with this
variable.
use_locking: If `True`, use locking during the operation.
name: the name of the operation.

Returns:
The updated variable.

Raises:
TypeError: if `sparse_delta` is not an `IndexedSlices`.


def send_message(self, message):
    try:
        if (_message_test_port is not None):
            _message_test_port.sent.append(message)
        (yield message.send(self))
    except (WebSocketClosedError, StreamClosedError):
        log.warning('Failed sending message as connection was closed')
    raise gen.Return(None)

Send a Bokeh Server protocol message to the connected client.

Args:
message (Message) : a message to send


def get_own_new(self, node: cfg.CFGNode, value: cfg.Binding) -> tuple[cfg.CFGNode, cfg.Variable | None]:
    node, new = self.ctx.attribute_handler.get_attribute(node, value.data, '__new__')
    if new is None:
        return (node, None)
    if len(new.bindings) == 1:
        f = new.bindings[0].data
        if isinstance(f, _abstract.AMBIGUOUS_OR_EMPTY) or self.ctx.convert.object_type.is_object_new(f):
            return (node, None)
    return (node, new)

Get this value's __new__ method, if it isn't object.__new__.

Args:
node: The current node.
value: A cfg.Binding containing this value.

Returns:
A tuple of (1) a node and (2) either a cfg.Variable of the special
__new__ method, or None.


def __normalized_name(self, message_type):

    name = message_type.definition_name()

    split_name = re.split(r'[^0-9a-zA-Z]', name)
    normalized = ''.join(
        part[0].upper() + part[1:] for part in split_name if part)

    previous = self.__normalized_names.get(normalized)
    if previous:
      if previous != name:
        raise KeyError('Both %s and %s normalize to the same schema name: %s' %
                       (name, previous, normalized))
    else:
      self.__normalized_names[normalized] = name

    return normalized

Normalized schema name.

Generate a normalized schema name, taking the class name and stripping out
everything but alphanumerics, and camel casing the remaining words.
A normalized schema name is a name that matches [a-zA-Z][a-zA-Z0-9]*

Args:
message_type: protorpc.message.Message class being parsed.

Returns:
A string, the normalized schema name.

Raises:
KeyError: A collision was found between normalized names.


def ContainsAddressStr(self, address):
    for (key, contract) in self._contracts.items():
        if (contract.Address == address):
            return True
    return False

Determine if the wallet contains the address.

Args:
address (str): a string representing the public key.

Returns:
bool: True, if the address is present in the wallet. False otherwise.


def bbox_scaling(bboxes, scale, clip_shape=None):
    if (float(scale) == 1.0):
        scaled_bboxes = bboxes.copy()
    else:
        w = ((bboxes[(..., 2)] - bboxes[(..., 0)]) + 1)
        h = ((bboxes[(..., 3)] - bboxes[(..., 1)]) + 1)
        dw = ((w * (scale - 1)) * 0.5)
        dh = ((h * (scale - 1)) * 0.5)
        scaled_bboxes = (bboxes + np.stack(((- dw), (- dh), dw, dh), axis=(- 1)))
    if (clip_shape is not None):
        return bbox_clip(scaled_bboxes, clip_shape)
    else:
        return scaled_bboxes

Scaling bboxes w.r.t the box center.

Args:
bboxes (ndarray): Shape(..., 4).
scale (float): Scaling factor.
clip_shape (tuple, optional): If specified, bboxes that exceed the
boundary will be clipped according to the given shape (h, w).

Returns:
ndarray: Scaled bboxes.


def add_object(self, object_path, weights):
    if not isinstance(weights, dict):
        raise ValueError(f"Argument `weights` should be a dict where keys are weight names (usually '0', '1', etc.) and values are NumPy arrays. Received: type(weights)={type(weights)}")
    if '/' in object_path:
        elements = object_path.split('/')
        partial_path = '/'.join(elements[:-1])
        weights_dict = self.weights_dict
        for e in elements[:-1]:
            if e not in weights_dict:
                raise ValueError(f"Path '{partial_path}' not found in model.")
            weights_dict = weights_dict[e]
        weights_dict[elements[-1]] = weights
    else:
        self.weights_dict[object_path] = weights

Add a new object to the file (e.g. a layer).

Args:
object_path: String, full path of the
object to add (e.g. `"layers/dense_2"`).
weights: Dict mapping weight names to weight
values (arrays),
e.g. `{"0": kernel_value, "1": bias_value}`.


def _get_authorization_headers(self) -> dict:
    auth = base64.encodestring(((self.client_id + ':') + self.client_secret).encode('latin-1')).decode('latin-1')
    auth = auth.replace('\n', '').replace(' ', '')
    auth = 'Basic {}'.format(auth)
    headers = {'Authorization': auth}
    return headers

Constructs and returns the Authorization header for the client app.

Args:
None

Returns:
header dict for communicating with the authorization endpoints


class TFTopKLogitsWarper(TFLogitsWarper):

    def __init__(self, top_k: int, filter_value: float=-float('Inf'), min_tokens_to_keep: int=1):
        if not isinstance(top_k, int) or top_k <= 0:
            raise ValueError(f'`top_k` has to be a strictly positive integer, but is {top_k}')
        self.top_k = max(top_k, min_tokens_to_keep)
        self.filter_value = filter_value

    def __call__(self, input_ids: tf.Tensor, scores: tf.Tensor, cur_len: int) -> tf.Tensor:
        top_k = min(self.top_k, scores.shape[-1])
        indices_to_remove = scores < tf.math.top_k(scores, k=top_k)[0][..., -1:]
        next_scores = tf.where(indices_to_remove, self.filter_value, scores)
        return next_scores

[`TFLogitsWarper`] that performs top-k, i.e. restricting to the k highest probability elements.

Args:
top_k (`int`):
The number of highest probability vocabulary tokens to keep for top-k-filtering.
filter_value (`float`, *optional*, defaults to -inf):
All filtered values will be set to this float value.
min_tokens_to_keep (`int`, *optional*, defaults to 1):
Minimum number of tokens that cannot be filtered.