def image(request, data):

    try:
        width = int(request.GET.get("w", PYDENTICON_WIDTH))
    except ValueError:
        raise SuspiciousOperation("Identicon width must be a positive integer.")
    try:
        height = int(request.GET.get("h", PYDENTICON_HEIGHT))
    except ValueError:
        raise SuspiciousOperation("Identicon height must be a positive integer.")
    output_format = request.GET.get("f", PYDENTICON_FORMAT)
    try:
        padding = [int(p) for p in request.GET["p"].split(",")]
    except KeyError:
        padding = PYDENTICON_PADDING
    except ValueError:
        raise SuspiciousOperation("Identicon padding must consist out of 4 positive integers separated with commas.")
    if "i" in request.GET:
        inverted = request.GET.get("i")
        if inverted.lower() == "true":
            inverted = True
        elif inverted.lower() == "false":
            inverted = False
        else:
            raise SuspiciousOperation("Inversion parameter must be a boolean (true/false).")
    else:
        inverted = PYDENTICON_INVERT

    if not isinstance(width, int) or width <= 0:
        raise SuspiciousOperation("Identicon width must be a positive integer.")
    if not isinstance(height, int) or height <= 0:
        raise SuspiciousOperation("Identicon height must be a positive integer.")
    if not all([isinstance(p, int) and p >= 0 for p in padding]) or len(padding) != 4:
        raise SuspiciousOperation("Padding must be a 4-element tuple consisting out of positive integers.")

    if output_format == "png":
        content_type = "image/png"
    elif output_format == "ascii":
        content_type = "text/plain"
    else:
        raise SuspiciousOperation("Unsupported identicon format requested - '%s' % output_format")

    generator = Generator(PYDENTICON_ROWS, PYDENTICON_COLUMNS,
                          foreground = PYDENTICON_FOREGROUND, background = PYDENTICON_BACKGROUND,
                          digest = PYDENTICON_DIGEST)

    content = generator.generate(data, width, height, padding=padding, output_format=output_format, inverted=inverted)

    response = HttpResponse(content, content_type=content_type)

    return response

Generates identicon image based on passed data.

Arguments:

data - Data which should be used for generating an identicon. This data
will be used in order to create a digest which is used for generating the
identicon. If the data passed is a hex digest already, the digest will be
used as-is.

Returns:

Identicon image in raw format.


def name(self):

        return ctypes.cast(self.sName, ctypes.c_char_p).value.decode()

Returns the name of the device.

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

Returns:
Device name.


def add_prop_descriptor_to_class(self, class_name, new_class_attrs, names_with_refs, container_names, dataspecs):
    from .bases import ContainerProperty
    from .dataspec import DataSpec
    name = self.name
    if (name in new_class_attrs):
        raise RuntimeError(('Two property generators both created %s.%s' % (class_name, name)))
    new_class_attrs[name] = self
    if self.has_ref:
        names_with_refs.add(name)
    if isinstance(self, BasicPropertyDescriptor):
        if isinstance(self.property, ContainerProperty):
            container_names.add(name)
        if isinstance(self.property, DataSpec):
            dataspecs[name] = self

``MetaHasProps`` calls this during class creation as it iterates
over properties to add, to update its registry of new properties.

The parameters passed in are mutable and this function is expected to
update them accordingly.

Args:
class_name (str) :
name of the class this descriptor is added to

new_class_attrs(dict[str, PropertyDescriptor]) :
mapping of attribute names to PropertyDescriptor that this
function will update

names_with_refs (set[str]) :
set of all property names for properties that also have
references, that this function will update

container_names (set[str]) :
set of all property names for properties that are
container props, that this function will update

dataspecs(dict[str, PropertyDescriptor]) :
mapping of attribute names to PropertyDescriptor for DataSpec
properties that this function will update

Return:
None


def get_named_tensor(self, name):
    if (name in self.named_tensors):
        return (True, self.named_tensors[name])
    else:
        return (False, None)

Returns a named tensor if available.

Returns:
valid: True if named tensor found, False otherwise
tensor: If valid, will be a tensor, otherwise None


def encode_all_features(dataset, vocabulary):

  def my_fn(features):
    ret = {}
    for k, v in features.items():
      v = vocabulary.encode_tf(v)
      v = tf.concat([tf.to_int64(v), [1]], 0)
      ret[k] = v
    return ret
  return dataset.map(my_fn, num_parallel_calls=tf.data.experimental.AUTOTUNE)

Encode all features.

Args:
dataset: a tf.data.Dataset
vocabulary: a vocabulary.Vocabulary
Returns:
a tf.data.Dataset


def _normalize_direction(heading: int) -> int:
    while (heading > 359):
        heading = int((heading - 359))
    while (heading < 0):
        heading = int((heading + 359))
    return heading

Make sure that 0 < heading < 360

Args:
heading: base heading

Returns: corrected heading


def _FindCodeObjectsReferents(module, start_objects, visit_recorder):

    def CheckIgnoreCodeObject(code_object):
        'Checks if the code object can be ignored.\n\n    Code objects that are not implemented in the module, or are from a lambda or\n    generator expression can be ignored.\n\n    If the module was precompiled, the code object may point to .py file, while\n    the module says that it originated from .pyc file. We just strip extension\n    altogether to work around it.\n\n    Args:\n      code_object: code object that we want to check against module.\n\n    Returns:\n      True if the code object can be ignored, False otherwise.\n    '
        if (code_object.co_name in ('<lambda>', '<genexpr>')):
            return True
        code_object_file = os.path.splitext(code_object.co_filename)[0]
        module_file = os.path.splitext(module.__file__)[0]
        if (code_object_file == module_file):
            return False
        return True

    def CheckIgnoreClass(cls):
        'Returns True if the class is definitely not coming from "module".'
        cls_module = sys.modules.get(cls.__module__)
        if (not cls_module):
            return False
        return ((cls_module is not module) and (getattr(cls_module, '__file__', None) != module.__file__))
    code_objects = set()
    current = start_objects
    for obj in current:
        visit_recorder.Record(current)
    depth = 0
    while (current and (depth < _MAX_REFERENTS_BFS_DEPTH)):
        new_current = []
        for current_obj in current:
            referents = gc.get_referents(current_obj)
            if ((current_obj is not module.__dict__) and (len(referents) > _MAX_OBJECT_REFERENTS)):
                continue
            for obj in referents:
                if (isinstance(obj, _BFS_IGNORE_TYPES) or (not visit_recorder.Record(obj))):
                    continue
                if (isinstance(obj, types.CodeType) and CheckIgnoreCodeObject(obj)):
                    continue
                if (isinstance(obj, six.class_types) and CheckIgnoreClass(obj)):
                    continue
                if isinstance(obj, types.CodeType):
                    code_objects.add(obj)
                else:
                    new_current.append(obj)
        current = new_current
        depth += 1
    return code_objects

Looks for all the code objects referenced by objects in start_objects.

The traversal implemented by this function is a shallow one. In other words
if the reference chain is a -> b -> co1 -> c -> co2, this function will
return [co1] only.

The traversal is implemented with BFS. The maximum depth is limited to avoid
touching all the objects in the process. Each object is only visited once
using visit_recorder.

Args:
module: module in which we are looking for code objects.
start_objects: initial set of objects for the BFS traversal.
visit_recorder: instance of _VisitRecorder class to ensure each object is
visited at most once.

Returns:
List of code objects.


def convert_bboxes_from_albumentations(bboxes, target_format, rows, cols, check_validity=False):
    return [convert_bbox_from_albumentations(bbox, target_format, rows, cols, check_validity) for bbox in bboxes]

Convert a list of bounding boxes from the format used by albumentations to a format, specified
in `target_format`.

Args:
bboxes (list): List of bounding box with coordinates in the format used by albumentations
target_format (str): required format of the output bounding box. Should be 'coco' or 'pascal_voc'.
rows (int): image height
cols (int): image width
check_validity (bool): check if all boxes are valid boxes


def MultiNotifyQueue(self, notifications, mutation_pool=None):
    extract_queue = (lambda notification: notification.session_id.Queue())
    for (queue, notifications) in iteritems(collection.Group(notifications, extract_queue)):
        self._MultiNotifyQueue(queue, notifications, mutation_pool=mutation_pool)

This is the same as NotifyQueue but for several session_ids at once.

Args:
notifications: A list of notifications.
mutation_pool: A MutationPool object to schedule Notifications on.

Raises:
RuntimeError: An invalid session_id was passed.


def automatic_control_dependencies(f):

    def wrapper(*args, **kwargs):
        with AutomaticControlDependencies() as a:
            result = f(*args, **kwargs)
            result_flat = [a.mark_as_return(t) for t in nest.flatten(result)]
            return nest.pack_sequence_as(result, result_flat)
    return tf_decorator.make_decorator(f, wrapper)

Wraps f to automatically insert control dependencies.

The inserted dependencies ensure that:
1. All stateful ops in f run when the result of f runs
2. Updates to the same resources happen in order.

Args:
f: the function to be wrapped.

Returns:
The wrapped function.


def argv(cls, name, short_name=None, type=None, help=None):

        cls.__hierarchy.append(argv.Argv(name, short_name, type, help))

Set command line arguments as a source

Parses the command line arguments described by the parameters.

Args:
name: the long name of the argument (foo)
short_name: the optional short name of the argument (f)
type: the optional type of the argument, defaults to bool
help: the optional help text for the argument


def _PromptUserForPartitionIdentifiers(
      self, volume_system, volume_identifiers):

    print_header = True
    while True:
      if print_header:
        self._PrintTSKPartitionIdentifiersOverview(
            volume_system, volume_identifiers)

        print_header = False

      lines = self._textwrapper.wrap(self._USER_PROMPT_TSK)
      self._output_writer.Write('\n'.join(lines))
      self._output_writer.Write('\n\nPartition identifiers: ')

      try:
        selected_volumes = self._ReadSelectedVolumes(volume_system, prefix='p')
        if (selected_volumes and
            not set(selected_volumes).difference(volume_identifiers)):
          break
      except ValueError:
        pass

      self._output_writer.Write('\n')

      lines = self._textwrapper.wrap(
          'Unsupported partition identifier(s), please try again or abort with '
          'Ctrl^C.')
      self._output_writer.Write('\n'.join(lines))
      self._output_writer.Write('\n\n')

    return selected_volumes

Prompts the user to provide partition identifiers.

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

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


def get_ethernet_settings(self):
    uri = '{}/ethernetSettings'.format(self.data['uri'])
    return self._helper.do_get(uri)

Gets the Ethernet interconnect settings for the Logical Interconnect.

Returns:
dict: Ethernet Interconnect Settings


def close(self):
    self._dll.JLINKARM_Close()
    if (self._lock is not None):
        del self._lock
        self._lock = None
    return None

Closes the open J-Link.

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

Returns:
``None``

Raises:
JLinkException: if there is no connected JLink.


def set_acl(self, role, users):

        acl_updates = [{"user": user, "role": role} for user in users]
        r = fapi.update_repository_method_acl(
            self.namespace, self.name, self.snapshot_id,
            acl_updates, self.api_url
        )
        fapi._check_response_code(r, 200)

Set permissions for this method.

Args:
role (str): Access level
one of {one of "OWNER", "READER", "WRITER", "NO ACCESS"}
users (list(str)): List of users to give role to


def combine(self, x):

    depth = tf.shape(x)[-1]
    x *= tf.expand_dims(self._nonpadding, -1)
    ret = tf.unsorted_segment_sum(
        x, self._flat_indices, num_segments=self._batch * self._length)
    ret = tf.reshape(ret, [self._batch, self._length, depth])
    return ret

Return the output from the experts.

When one example goes to multiple experts, the outputs are summed.

Args:
x: a Tensor with shape [batch, num_experts, expert_capacity, depth]

Returns:
a `Tensor` with shape `[batch, length, depth]


def are_equal(self, sp1, sp2):
    for s1 in sp1.keys():
        spin1 = getattr(s1, 'spin', 0)
        oxi1 = getattr(s1, 'oxi_state', 0)
        for s2 in sp2.keys():
            spin2 = getattr(s2, 'spin', 0)
            oxi2 = getattr(s2, 'oxi_state', 0)
            if ((s1.symbol == s2.symbol) and (oxi1 == oxi2) and (spin2 == (- spin1))):
                break
        else:
            return False
    return True

True if species are exactly the same, i.e., Fe2+ == Fe2+ but not
Fe3+. and the spins are reversed. i.e., spin up maps to spin down,
and vice versa.

Args:
sp1: First species. A dict of {specie/element: amt} as per the
definition in Site and PeriodicSite.
sp2: Second species. A dict of {specie/element: amt} as per the
definition in Site and PeriodicSite.

Returns:
Boolean indicating whether species are equal.


def is_subgroup(self, supergroup):

        warnings.warn("This is not fully functional. Only trivial subsets are tested right now. ")
        return set(self.symmetry_ops).issubset(supergroup.symmetry_ops)

True if this group is a subgroup of the supplied group.

Args:
supergroup (SymmetryGroup): Supergroup to test.

Returns:
True if this group is a subgroup of the supplied group.


def eval(self, session=None):
    return self._variable.eval(session=session)

In a session, computes and returns the value of this variable.

This is not a graph construction method, it does not add ops to the graph.

This convenience method requires a session where the graph
containing this variable has been launched. If no session is
passed, the default session is used.  See `tf.compat.v1.Session` for more
information on launching a graph and on sessions.

```python
v = tf.Variable([1, 2])
init = tf.compat.v1.global_variables_initializer()

with tf.compat.v1.Session() as sess:
sess.run(init)
# Usage passing the session explicitly.
print(v.eval(sess))
# Usage with the default session.  The 'with' block
# above makes 'sess' the default session.
print(v.eval())
```

Args:
session: The session to use to evaluate this variable. If none, the
default session is used.

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


def run(self, tag=None, output=None, **kwargs):
    start = datetime.datetime.now()
    count = 0
    if tag:
        tag = Uri(tag)
        xml_generator = etree.iterparse(self.source, tag=tag.etree)
    else:
        xml_generator = etree.iterparse(self.source)
    i = 0
    for (event, element) in xml_generator:
        type_tags = element.findall(_RDF_TYPE_TAG)
        rdf_types = [el.get(_RES_TAG) for el in type_tags if el.get(_RES_TAG)]
        if (str(self.filter_val) in rdf_types):
            pdb.set_trace()
            count += 1
        i += 1
        element.clear()
    print("Found '{}' items in {}".format(count, (datetime.datetime.now() - start)))

runs the extractor

Args:
-----
output: ['filepath', None]


def determine_git_ref(self, config):

        ref_config_keys = 0
        for i in ['commit', 'tag', 'branch']:
            if config.get(i):
                ref_config_keys += 1
        if ref_config_keys > 1:
            raise ImportError("Fetching remote git sources failed: "
                              "conflicting revisions (e.g. 'commit', 'tag', "
                              "'branch') specified for a package source")

        if config.get('commit'):
            ref = config['commit']
        elif config.get('tag'):
            ref = config['tag']
        else:

            ref = self.git_ls_remote(
                config['uri'],
                self.determine_git_ls_remote_ref(config)
            )
        if sys.version_info[0] > 2 and isinstance(ref, bytes):
            return ref.decode()
        return ref

Determine the ref to be used for 'git checkout'.

Args:
config (dict): git config dictionary

Returns:
str: A commit id or tag name


def parse(type: Type):

    def decorator(parser):
        EnvVar.parsers[type] = parser
        return parser
    return decorator

Register a parser for a attribute type.

Parsers will be used to parse `str` type objects from either
the commandline arguments or environment variables.

Args:
type: the type the decorated function will be responsible
for parsing a environment variable to.


def parse_column_path(column: str) -> list:
    nested_columns = []
    for col in column.split('.'):
        parts = PATTERN.match(col)
        if parts:
            column_name, key = (parts.groups()[0], parts.groups()[1])
        else:
            column_name, key = (col, None)
        if not column_name:
            raise ValueError(f'Invalid column path: {column}')
        nested_columns.append((column_name, key))
    return nested_columns

Parse the column string to extract nested fields and array indices.

Args:
column (str): The column string with potential nested fields and array
indices.

Returns:
list: A list of tuples, where each tuple contains the column name and the
key/index.


def __init__(self, input_dataset, target_device, source_device='/cpu:0'):
    self._input_dataset = input_dataset._apply_debug_options()
    self._target_device = target_device
    spec = framework_device.DeviceSpec().from_string(self._target_device)
    self._is_gpu_target = spec.device_type == 'GPU'
    self._source_device_string = source_device
    self._source_device = ops.convert_to_tensor(source_device)
    wrap_ds_variant = gen_dataset_ops.wrap_dataset_variant(self._input_dataset._variant_tensor)

    @def_function.function()
    def _init_func():

        ds_variant = gen_dataset_ops.unwrap_dataset_variant(wrap_ds_variant)
        resource = gen_dataset_ops.anonymous_iterator(**self._input_dataset._flat_structure)
        with ops.control_dependencies([gen_dataset_ops.make_iterator(ds_variant, resource)]):
            return gen_dataset_ops.iterator_to_string_handle(resource)
    init_func_concrete = _init_func.get_concrete_function()

    @def_function.function()
    def _remote_init_func():
        return functional_ops.remote_call(target=self._source_device, args=init_func_concrete.captured_inputs, Tout=[dtypes.string], f=init_func_concrete)
    self._init_func = _remote_init_func.get_concrete_function()
    self._init_captured_args = self._init_func.captured_inputs

    @def_function.function(input_signature=[tensor_spec.TensorSpec([], dtypes.string)])
    def _next_func(string_handle):

        with ops.device(self._source_device_string):
            iterator = iterator_ops.Iterator.from_string_handle(string_handle, dataset_ops.get_legacy_output_types(self), dataset_ops.get_legacy_output_shapes(self), dataset_ops.get_legacy_output_classes(self))
        return structure.to_tensor_list(self.element_spec, iterator.get_next())
    next_func_concrete = _next_func.get_concrete_function()

    @def_function.function(input_signature=[tensor_spec.TensorSpec([], dtypes.string)], experimental_attributes={'experimental_ints_on_device': True})
    def _remote_next_func(string_handle):
        return functional_ops.remote_call(target=self._source_device, args=[string_handle] + next_func_concrete.captured_inputs, Tout=self._input_dataset._flat_types, f=next_func_concrete)
    self._next_func = _remote_next_func.get_concrete_function()
    self._next_captured_args = self._next_func.captured_inputs

    @def_function.function(input_signature=[tensor_spec.TensorSpec([], dtypes.string)])
    def _finalize_func(string_handle):

        iterator_resource = gen_dataset_ops.iterator_from_string_handle_v2(string_handle, **self._input_dataset._flat_structure)
        with ops.control_dependencies([resource_variable_ops.destroy_resource_op(iterator_resource, ignore_lookup_error=True)]):
            return array_ops.constant(0, dtypes.int64)
    finalize_func_concrete = _finalize_func.get_concrete_function()

    @def_function.function(input_signature=[tensor_spec.TensorSpec([], dtypes.string)])
    def _remote_finalize_func(string_handle):
        return functional_ops.remote_call(target=self._source_device, args=[string_handle] + finalize_func_concrete.captured_inputs, Tout=[dtypes.int64], f=finalize_func_concrete)
    self._finalize_func = _remote_finalize_func.get_concrete_function()
    self._finalize_captured_args = self._finalize_func.captured_inputs
    g = ops.get_default_graph()
    self._init_func.add_to_graph(g)
    self._next_func.add_to_graph(g)
    self._finalize_func.add_to_graph(g)
    with ops.device(self._target_device):
        variant_tensor = gen_dataset_ops.generator_dataset(self._init_captured_args, self._next_captured_args, self._finalize_captured_args, init_func=self._init_func, next_func=self._next_func, finalize_func=self._finalize_func, **self._input_dataset._flat_structure)
    super(_CopyToDeviceDataset, self).__init__(input_dataset, variant_tensor)

Constructs a _CopyToDeviceDataset.

Args:
input_dataset: `Dataset` to be copied
target_device: The name of the device to which elements would be copied.
source_device: Device where input_dataset would be placed.


def dot(r1, r2):

    if r1.size != r2.size:
        raise ValueError("Both arguments must have the same input size.")
    if r1.deriv != r2.deriv:
        raise ValueError("Both arguments must have the same deriv.")
    return r1.x*r2.x + r1.y*r2.y + r1.z*r2.z

Compute the dot product

Arguments:
| ``r1``, ``r2``  -- two :class:`Vector3` objects

(Returns a Scalar)


def parse(self, values):

    type_map = {}
    for name, t in self._hparam_types.items():
      param_type, _ = t
      type_map[name] = param_type

    values_map = parse_values(values, type_map)
    return self.override_from_dict(values_map)

Override existing hyperparameter values, parsing new values from a string.

See parse_values for more detail on the allowed format for values.

Args:
values: String.  Comma separated list of `name=value` pairs where 'value'
must follow the syntax described above.

Returns:
The `HParams` instance.

Raises:
ValueError: If `values` cannot be parsed or a hyperparameter in `values`
doesn't exist.


def get_checkpoint_factories_and_keys(object_names, object_map=None):
    checkpoint_factory_map = object_identity.ObjectIdentityDictionary()
    unmapped_registered_savers = collections.defaultdict(dict)
    for trackable, object_name in object_names.items():
        object_to_save = util.get_mapped_trackable(trackable, object_map)
        saver_name = registration.get_registered_saver_name(object_to_save)
        if saver_name:
            unmapped_registered_savers[saver_name][object_name] = trackable
        else:
            checkpoint_factory_map[trackable] = []
            for name, saveable_factory in saveable_object_util.saveable_objects_from_trackable(object_to_save).items():
                key_suffix = saveable_compat.get_saveable_name(object_to_save) or name
                checkpoint_key = trackable_utils.checkpoint_key(object_name, key_suffix)
                if not saveable_compat.force_checkpoint_conversion_enabled():
                    name = key_suffix
                checkpoint_factory_map[trackable].append(_CheckpointFactoryData(factory=saveable_factory, name=name, checkpoint_key=checkpoint_key))
    return (checkpoint_factory_map, unmapped_registered_savers)

Gets a map of saveable factories and corresponding checkpoint keys.

Args:
object_names: a dictionary that maps `Trackable` objects to auto-generated
string names.
object_map: a dictionary mapping `Trackable` to copied `Trackable` objects.
The copied objects are generated from `Trackable.
_export_to_saved_model_graph()` which copies the object into another
graph. Generally only resource objects (e.g. Variables, Tables) will be
in this map.

Returns:
A tuple of (
Dictionary mapping trackable -> list of _CheckpointFactoryData,
Dictionary mapping registered saver name -> {object name -> trackable})


def create_function(self, vpc_config):

        zip_file = 'lambda-holder.zip'
        with zipfile.ZipFile(zip_file, mode='w') as zipped:
            zipped.writestr('index.py', 'print "Hello world"')

        contents = ''
        with open('lambda-holder.zip', 'rb') as openfile:
            contents = openfile.read()

        LOG.info('Creating lambda function: %s', self.app_name)

        try:
            self.lambda_client.create_function(
                Environment=self.lambda_environment,
                FunctionName=self.app_name,
                Runtime=self.runtime,
                Role=self.role_arn,
                Handler=self.handler,
                Code={'ZipFile': contents},
                Description=self.description,
                Timeout=int(self.timeout),
                MemorySize=int(self.memory),
                Publish=False,
                VpcConfig=vpc_config,
                Tags={'app_group': self.group,
                      'app_name': self.app_name})
        except boto3.exceptions.botocore.exceptions.ClientError as error:
            if 'CreateNetworkInterface' in error.response['Error']['Message']:
                message = '{0} is missing "ec2:CreateNetworkInterface"'.format(self.role_arn)
                LOG.critical(message)
                raise SystemExit(message)

            raise

        LOG.info("Successfully created Lambda function and alias")

Create lambda function, configures lambda parameters.

We need to upload non-zero zip when creating function. Uploading
hello_world python lambda function since AWS doesn't care which
executable is in ZIP.

Args:
vpc_config (dict): Dictionary of SubnetIds and SecurityGroupsIds for using
a VPC in lambda


def submit_files(self, halt_on_error=True):
    if (self.halt_on_file_error is not None):
        halt_on_error = self.halt_on_file_error
    upload_status = []
    for (xid, content_data) in self._files.items():
        del self._files[xid]
        status = True
        if (self.debug and (xid in self.saved_xids)):
            self.tcex.log.debug('skipping previously saved file {}.'.format(xid))
            continue
        content = content_data.get('fileContent')
        if callable(content):
            content = content_data.get('fileContent')(xid)
        if (content is None):
            upload_status.append({'uploaded': False, 'xid': xid})
            self.tcex.log.warning('File content was null for xid {}.'.format(xid))
            continue
        if (content_data.get('type') == 'Document'):
            api_branch = 'documents'
        elif (content_data.get('type') == 'Report'):
            api_branch = 'reports'
        url = '/v2/groups/{}/{}/upload'.format(api_branch, xid)
        headers = {'Content-Type': 'application/octet-stream'}
        params = {'owner': self._owner}
        r = self.submit_file_content('POST', url, content, headers, params, halt_on_error)
        if (r.status_code == 401):
            self.tcex.log.info('Received 401 status code using POST. Trying PUT to update.')
            r = self.submit_file_content('PUT', url, content, headers, params, halt_on_error)
        self.tcex.log.debug('{} Upload URL: {}.'.format(content_data.get('type'), r.url))
        if (not r.ok):
            status = False
            self.tcex.handle_error(585, [r.status_code, r.text], halt_on_error)
        elif self.debug:
            self.saved_xids.append(xid)
        self.tcex.log.info('Status {} for file upload with xid {}.'.format(r.status_code, xid))
        upload_status.append({'uploaded': status, 'xid': xid})
    return upload_status

Submit Files for Documents and Reports to ThreatConnect API.

Critical Errors

* There is insufficient document storage allocated to this account.

Args:
halt_on_error (bool, default:True): If True any exception will raise an error.

Returns:
dict: The upload status for each xid.


def search(cls, session, queries):
    return super(Conversations, cls).search(session, queries, SearchConversation)

Search for a conversation given a domain.

Args:
session (requests.sessions.Session): Authenticated session.
queries (helpscout.models.Domain or iter): The queries for the
domain. If a ``Domain`` object is provided, it will simply be
returned. Otherwise, a ``Domain`` object will be generated
from the complex queries. In this case, the queries should
conform to the interface in
:func:`helpscout.domain.Domain.from_tuple`.

Returns:
RequestPaginator(output_type=helpscout.models.SearchCustomer):
SearchCustomer iterator.


def __init__(self, identifier):

    super(Volume, self).__init__()
    self.identifier = identifier
    self._attributes = {}
    self._extents = []
    self._is_parsed = False

Initializes a volume.

Args:
identifier (str): identifier of the attribute within the volume.


def AddEventSource(self, event_source):

    self._RaiseIfNotWritable()

    self._AddAttributeContainer(
        self._CONTAINER_TYPE_EVENT_SOURCE, event_source)

Adds an event source.

Args:
event_source (EventSource): event source.

Raises:
IOError: when the storage file is closed or read-only.
OSError: when the storage file is closed or read-only.


def stacked_bi_rnn(units: tf.Tensor, n_hidden_list: List, cell_type='gru', seq_lengths=None, use_peepholes=False, name='RNN_layer'):
    for (n, n_hidden) in enumerate(n_hidden_list):
        with tf.variable_scope(((name + '_') + str(n))):
            if (cell_type == 'gru'):
                forward_cell = tf.nn.rnn_cell.GRUCell(n_hidden)
                backward_cell = tf.nn.rnn_cell.GRUCell(n_hidden)
            elif (cell_type == 'lstm'):
                forward_cell = tf.nn.rnn_cell.LSTMCell(n_hidden, use_peepholes=use_peepholes)
                backward_cell = tf.nn.rnn_cell.LSTMCell(n_hidden, use_peepholes=use_peepholes)
            else:
                raise RuntimeError('cell_type must be either gru or lstm')
            ((rnn_output_fw, rnn_output_bw), (fw, bw)) = tf.nn.bidirectional_dynamic_rnn(forward_cell, backward_cell, units, dtype=tf.float32, sequence_length=seq_lengths)
            units = tf.concat([rnn_output_fw, rnn_output_bw], axis=2)
            if (cell_type == 'gru'):
                last_units = tf.concat([fw, bw], axis=1)
            else:
                ((c_fw, h_fw), (c_bw, h_bw)) = (fw, bw)
                c = tf.concat([c_fw, c_bw], axis=1)
                h = tf.concat([h_fw, h_bw], axis=1)
                last_units = (h, c)
    return (units, last_units)

Stackted recurrent neural networks GRU or LSTM

Args:
units: a tensorflow tensor with dimensionality [None, n_tokens, n_features]
n_hidden_list: list with number of hidden units at the ouput of each layer
seq_lengths: length of sequences for different length sequences in batch
can be None for maximum length as a length for every sample in the batch
cell_type: 'lstm' or 'gru'
use_peepholes: whether to use peephole connections (only 'lstm' case affected)
name: what variable_scope to use for the network parameters
Returns:
units: tensor at the output of the last recurrent layer
with dimensionality [None, n_tokens, n_hidden_list[-1]]
last_units: tensor of last hidden states for GRU and tuple
of last hidden stated and last cell states for LSTM
dimensionality of cell states and hidden states are
similar and equal to [B x 2 * H], where B - batch
size and H is number of hidden units


def __init__(self, job_context, shard_state):

    self.job_context = job_context
    self.id = shard_state.shard_id
    self.number = shard_state.shard_number
    self.attempt = shard_state.retries + 1
    self._state = shard_state

Init.

The signature of __init__ is subject to change.

Read only properties:
job_context: JobContext object.
id: str. of format job_id-shard_number.
number: int. shard number. 0 indexed.
attempt: int. The current attempt at executing this shard.
Starting at 1.

Args:
job_context: map_job.JobConfig.
shard_state: model.ShardState.


def proxy_num(self, protocol=None):

        http_num = len(self.proxies['http'])
        https_num = len(self.proxies['https'])
        if protocol == 'http':
            return http_num
        elif protocol == 'https':
            return https_num
        else:
            return http_num + https_num

Get the number of proxies in the pool

Args:
protocol (str, optional): 'http' or 'https' or None. (default None)

Returns:
If protocol is None, return the total number of proxies, otherwise,
return the number of proxies of corresponding protocol.


def get_model_filepath(self, infodict):
    u = infodict['uniprot_ac']
    original_filename = '{}_{}_{}_{}'.format(infodict['from'], infodict['to'], infodict['template'], infodict['coordinate_id'])
    file_path = op.join(self.metadata_dir, u[:2], u[2:4], u[4:6], 'swissmodel', '{}.pdb'.format(original_filename))
    if op.exists(file_path):
        return file_path
    else:
        log.warning('{}: no file {} found for model'.format(u, file_path))
        return None

Get the path to the homology model using information from the index dictionary for a single model.

Example: use self.get_models(UNIPROT_ID) to get all the models, which returns a list of dictionaries.
Use one of those dictionaries as input to this function to get the filepath to the model itself.

Args:
infodict (dict): Information about a model from get_models

Returns:
str: Path to homology model


def is_array_str(x: Any) -> bool:
    if isinstance(x, (bytes, str)):
        return True
    elif is_array(x):
        return is_dtype_str(x.dtype)
    else:
        return False

Returns True if the given array is a `str` array.

Note: Also returns True for scalar `str`, `bytes` values. For compatibility
with `tensor.numpy()` which returns `bytes`

Args:
x: The array to test

Returns:
True or False


def set_authentication_profile(profile=None, deploy=False):

    if not profile:
        raise CommandExecutionError("Profile name option must not be none.")

    ret = {}

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

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

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

    return ret

Set the authentication profile of the Palo Alto proxy minion. A commit will be required before this is processed.

CLI Example:

Args:
profile (str): The name of the authentication profile to set.

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

.. code-block:: bash

salt '*' panos.set_authentication_profile foo
salt '*' panos.set_authentication_profile foo deploy=True


def _send_request(self, url, method="get", data=None, extra_headers=None):

        headers = {'Content-type': 'application/json'}
        if isinstance(extra_headers, dict):
            headers.update(extra_headers)

        if not data or "password" not in data:
            logger.debug("Sending {method} request to {url} with data {data}".format(
                method=method.upper(), url=url, data=data)
            )
        r = self.session.request(method, url, headers=headers, data=data)
        r.raise_for_status()
        return r.json()

Performs a given request and returns a json object

Args:
url (str): URL of the request
method (str): Any of "get", "post", "delete"
data (any): Possible extra data to send with the request
extra_headers (dict): Possible extra headers to send along in the request
Returns:
dict


def assert_almost_eq(arr_test, arr_target, thresh=1E-11):
    r
    if util_arg.NO_ASSERTS:
        return
    import utool as ut
    arr1 = np.array(arr_test)
    arr2 = np.array(arr_target)
    passed, error = ut.almost_eq(arr1, arr2, thresh, ret_error=True)
    if not np.all(passed):
        failed_xs = np.where(np.logical_not(passed))
        failed_error = error.take(failed_xs)
        failed_arr_test = arr1.take(failed_xs)
        failed_arr_target = arr2.take(failed_xs)

        msg_list = [
            'FAILED ASSERT ALMOST EQUAL',
            '  * failed_xs = %r' % (failed_xs,),
            '  * failed_error = %r' % (failed_error,),
            '  * failed_arr_test   = %r' % (failed_arr_test,),
            '  * failed_arr_target = %r' % (failed_arr_target,),
        ]
        msg = '\n'.join(msg_list)
        raise AssertionError(msg)
    return error

r"""
Args:
arr_test (ndarray or list):
arr_target (ndarray or list):
thresh (scalar or ndarray or list):


def make_anchor(file_path: pathlib.Path, offset: int, width: int, context_width: int, metadata, encoding: str='utf-8', handle=None):

    @contextmanager
    def get_handle():
        if (handle is None):
            with file_path.open(mode='rt', encoding=encoding) as fp:
                (yield fp)
        else:
            (yield handle)
    with get_handle() as fp:
        context = _make_context(fp, offset, width, context_width)
    return Anchor(file_path=file_path, encoding=encoding, context=context, metadata=metadata)

Construct a new `Anchor`.

Args:
file_path: The absolute path to the target file for the anchor.
offset: The offset of the anchored text in codepoints in `file_path`'s
contents.
width: The width in codepoints of the anchored text.
context_width: The width in codepoints of context on either side of the
anchor.
metadata: The metadata to attach to the anchor. Must be json-serializeable.
encoding: The encoding of the contents of `file_path`.
handle: If not `None`, this is a file-like object the contents of which
are used to calculate the context of the anchor. If `None`, then
the file indicated by `file_path` is opened instead.

Raises:
ValueError: `width` characters can't be read at `offset`.
ValueError: `file_path` is not absolute.


def secure_channel(target, credentials, options=None, *, loop=None, executor=None,
                   standalone_pool_for_streaming=False):

    return Channel(_grpc.secure_channel(target, credentials, options),
                   loop, executor, standalone_pool_for_streaming)

Creates a secure Channel to a server.

Args:
target: The server address.
credentials: A ChannelCredentials instance.
options: An optional list of key-value pairs (channel args in gRPC runtime)
to configure the channel.

Returns:
A Channel object.


def DeserializeExclusiveData(self, reader):

        self.Nonce = reader.ReadUInt32()
        self.Type = TransactionType.MinerTransaction

Deserialize full object.

Args:
reader (neo.IO.BinaryReader):


def AddBlob(self, blob_id, length):

    if self.finalized and length > 0:
      raise IOError("Can't add blobs to finalized BlobImage")

    self.content_dirty = True
    self.index.seek(0, 2)
    self.index.write(blob_id.AsBytes())
    self.size += length

    if length < self.chunksize:
      self.finalized = True

Add another blob to this image using its hash.

Once a blob is added that is smaller than the chunksize we finalize the
file, since handling adding more blobs makes the code much more complex.

Args:
blob_id: rdf_objects.BlobID object.
length: int length of blob

Raises:
IOError: if blob has been finalized.


def forward(self, encoder_hidden_states):
    hidden_states = encoder_hidden_states.transpose(1, -1)
    for layer in self.conv_layers:
        hidden_states = layer(hidden_states)
    hidden_states = self.linear(hidden_states.transpose(1, -1)).squeeze(-1)
    if not self.training:
        hidden_states = torch.clamp(torch.round(hidden_states.exp() - self.log_domain_offset), min=0).long()
    return hidden_states

Args:
hidden_states (`torch.Tensor` of shape `(batch_size, max_text_length, input_dim)`):
Batch of input sequences.
padding_masks (`torch.ByteTensor` of shape `(batch_size, max_text_length)`, *optional*):
Batch of masks indicating padded part.

Returns:
`torch.Tensor`: Batch of predicted durations in log domain `(batch_size, max_text_length)`.


def order_by(self, *args):

        clone = copy.deepcopy(self)
        clone.adapter.ordered = True
        if args:
            clone.adapter.order_by(*args)
        return clone

Applies query ordering.

Args:
**args: Order by fields names.
Defaults to ascending, prepend with hypen (-) for desecending ordering.

Returns:
Self. Queryset object.

Examples:
>>> Person.objects.order_by('-name', 'join_date')


def circuit_to_image(circ: Circuit,
                     qubits: Qubits = None) -> PIL.Image:

    latex = circuit_to_latex(circ, qubits)
    img = render_latex(latex)
    return img

Create an image of a quantum circuit.

A convenience function that calls circuit_to_latex() and render_latex().

Args:
circ:       A quantum Circuit
qubits:     Optional qubit list to specify qubit order

Returns:
Returns: A PIL Image (Use img.show() to display)

Raises:
NotImplementedError: For unsupported gates.
OSError: If an external dependency is not installed.


def update_labels(self, node_name: str, labels: dict):
    if (not self._manager):
        raise RuntimeError('Only the Swarm manager node can update node details.')
    node_spec = {'Availability': 'active', 'Name': node_name, 'Role': 'manager', 'Labels': labels}
    node = self._client.nodes.get(node_name)
    node.update(node_spec)

Update label of a node.

Args:
node_name (string): Name of the node.
labels (dict): Label to add to the node


def ParseFileObject(self, parser_mediator, file_object):

    display_name = parser_mediator.GetDisplayName()

    if not zipfile.is_zipfile(file_object):
      raise errors.UnableToParseFile(
          '[{0:s}] unable to parse file: {1:s} with error: {2:s}'.format(
              self.NAME, display_name, 'Not a Zip file.'))

    try:
      zip_file = zipfile.ZipFile(file_object, 'r', allowZip64=True)
      self._ProcessZipFileWithPlugins(parser_mediator, zip_file)
      zip_file.close()

    except (zipfile.BadZipfile, struct.error) as exception:
      raise errors.UnableToParseFile(
          '[{0:s}] unable to parse file: {1:s} with error: {2!s}'.format(
              self.NAME, display_name, exception))

Parses a compound ZIP file-like object.

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

Raises:
UnableToParseFile: when the file cannot be parsed.


def shakespeare(chunk_size):

  file_name = maybe_download('http:
                             'shakespear.txt')
  with open(file_name) as f:
    shakespeare_full = f.read()

  length = (len(shakespeare_full)
  if length < len(shakespeare_full):
    shakespeare_full = shakespeare_full[:length]
  arr = np.array([convert_to_int(c) for c in shakespeare_full])[
      0:len(shakespeare_full) / chunk_size * chunk_size]
  return arr.reshape((len(arr) / chunk_size, chunk_size))

Downloads Shakespeare, converts it into ASCII codes and chunks it.

Args:
chunk_size: The dataset is broken down so that it is shaped into batches x
chunk_size.
Returns:
A numpy array of ASCII codes shaped into batches x chunk_size.


def resize_file(fobj, diff, BUFFER_SIZE=2 ** 16):

    fobj.seek(0, 2)
    filesize = fobj.tell()

    if diff < 0:
        if filesize + diff < 0:
            raise ValueError

        fobj.truncate(filesize + diff)
    elif diff > 0:
        try:
            while diff:
                addsize = min(BUFFER_SIZE, diff)
                fobj.write(b"\x00" * addsize)
                diff -= addsize
            fobj.flush()
        except IOError as e:
            if e.errno == errno.ENOSPC:

                fobj.truncate(filesize)
            raise

Resize a file by `diff`.

New space will be filled with zeros.

Args:
fobj (fileobj)
diff (int): amount of size to change
Raises:
IOError


Test function

Args:
x: The input

Returns:
The output


def trace_region_count(self):
    cmd = enums.JLinkTraceCommand.GET_NUM_REGIONS
    data = ctypes.c_uint32(0)
    res = self._dll.JLINKARM_TRACE_Control(cmd, ctypes.byref(data))
    if (res == 1):
        raise errors.JLinkException('Failed to get trace region count.')
    return data.value

Retrieves a count of the number of available trace regions.

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

Returns:
Count of the number of available trace regions.


def clear(self, color: Tuple[(int, int, int)]) -> None:
    lib.TCOD_image_clear(self.image_c, color)

Fill this entire Image with color.

Args:
color (Union[Tuple[int, int, int], Sequence[int]]):
An (r, g, b) sequence or Color instance.


def VerifyServerPEM(self, http_object):
    try:
        server_pem = http_object.data
        server_url = http_object.url
        if (b'BEGIN CERTIFICATE' in server_pem):
            server_certificate = rdf_crypto.RDFX509Cert(server_pem)
            self.communicator.LoadServerCertificate(server_certificate=server_certificate, ca_certificate=self.ca_cert)
            logging.info('Server PEM re-keyed.')
            return True
    except Exception as e:
        logging.info('Unable to verify server certificate at %s: %s', server_url, e)
        return False

Check the server PEM for validity.

This is used to determine connectivity to the server. Sometimes captive
portals return a valid HTTP status, but the data is corrupted.

Args:
http_object: The response received from the server.

Returns:
True if the response contains a valid server certificate.


def from_maildir(self, codes: str) -> FrozenSet[Flag]:

        flags = set()
        for code in codes:
            if code == ',':
                break
            to_sys = self._to_sys.get(code)
            if to_sys is not None:
                flags.add(to_sys)
            else:
                to_kwd = self._to_kwd.get(code)
                if to_kwd is not None:
                    flags.add(to_kwd)
        return frozenset(flags)

Return the set of IMAP flags that correspond to the letter codes.

Args:
codes: The letter codes to map.


def problem(problem_name, **kwargs):

  spec = parse_problem_name(problem_name)
  try:
    return Registries.problems[spec.base_name](
        was_copy=spec.was_copy, was_reversed=spec.was_reversed)
  except KeyError:

    return env_problem(problem_name, **kwargs)

Get possibly copied/reversed problem in `base_registry` or `env_registry`.

Args:
problem_name: string problem name. See `parse_problem_name`.
**kwargs: forwarded to env problem's initialize method.

Returns:
possibly reversed/copied version of base problem registered in the given
registry.


def encode(self, s):
    return [(int(w) + self._num_reserved_ids) for w in s.split()]

Transform a human-readable string into a sequence of int ids.

The ids should be in the range [num_reserved_ids, vocab_size). Ids [0,
num_reserved_ids) are reserved.

EOS is not appended.

Args:
s: human-readable string to be converted.

Returns:
ids: list of integers


def napalm_cli(task: Task, commands: List[str]) -> Result:

    device = task.host.get_connection("napalm", task.nornir.config)
    result = device.cli(commands)
    return Result(host=task.host, result=result)

Run commands on remote devices using napalm

Arguments:
commands: commands to execute

Returns:
Result object with the following attributes set:
* result (``dict``): result of the commands execution


def increment_id(cls, _id: ObjectId, inc: int) -> ObjectId:
    id_number = _ObjectIdHelper.id_to_int(_id)
    new_number = id_number + inc
    if new_number < 0 or new_number >= 1 << 96:
        raise ValueError('invalid incremental, inc value must be within [%s, %s)' % (0 - id_number, 1 << 96 - id_number))
    return _ObjectIdHelper.int_to_id(new_number)

Increment object_id binary value by inc value and return new object id.

Args:
_id: The `_id` to change.
inc(int): The incremental int value to be added to `_id`.

Returns:
`_id` incremented by `inc` value


def infer(msg, mrar=False):
    df = common.df(msg)
    if common.allzeros(msg):
        return 'EMPTY'
    if (df == 17):
        tc = common.typecode(msg)
        if (1 <= tc <= 4):
            return 'BDS08'
        if (5 <= tc <= 8):
            return 'BDS06'
        if (9 <= tc <= 18):
            return 'BDS05'
        if (tc == 19):
            return 'BDS09'
        if (20 <= tc <= 22):
            return 'BDS05'
        if (tc == 28):
            return 'BDS61'
        if (tc == 29):
            return 'BDS62'
        if (tc == 31):
            return 'BDS65'
    IS10 = bds10.is10(msg)
    IS17 = bds17.is17(msg)
    IS20 = bds20.is20(msg)
    IS30 = bds30.is30(msg)
    IS40 = bds40.is40(msg)
    IS50 = bds50.is50(msg)
    IS60 = bds60.is60(msg)
    IS44 = bds44.is44(msg)
    IS45 = bds45.is45(msg)
    if mrar:
        allbds = np.array(['BDS10', 'BDS17', 'BDS20', 'BDS30', 'BDS40', 'BDS44', 'BDS45', 'BDS50', 'BDS60'])
        mask = [IS10, IS17, IS20, IS30, IS40, IS44, IS45, IS50, IS60]
    else:
        allbds = np.array(['BDS10', 'BDS17', 'BDS20', 'BDS30', 'BDS40', 'BDS50', 'BDS60'])
        mask = [IS10, IS17, IS20, IS30, IS40, IS50, IS60]
    bds = ','.join(sorted(allbds[mask]))
    if (len(bds) == 0):
        return None
    else:
        return bds

Estimate the most likely BDS code of an message.

Args:
msg (String): 28 bytes hexadecimal message string
mrar (bool): Also infer MRAR (BDS 44) and MHR (BDS 45). Defaults to False.

Returns:
String or None: BDS version, or possible versions, or None if nothing matches.


def wrap(access_pyxb, read_only=False):

    w = AccessPolicyWrapper(access_pyxb)
    yield w
    if not read_only:
        w.get_normalized_pyxb()

Work with the AccessPolicy in a SystemMetadata PyXB object.

Args:
access_pyxb : AccessPolicy PyXB object
The AccessPolicy to modify.

read_only: bool
Do not update the wrapped AccessPolicy.

When only a single AccessPolicy operation is needed, there's no need to use this
context manager. Instead, use the generated context manager wrappers.


def FileEntryExistsByPathSpec(self, path_spec):

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

    if (location is None or
        not location.startswith(self.LOCATION_ROOT)):
      return False

    if len(location) == 1:
      return True

    try:
      self._tar_file.getmember(location[1:])
      return True
    except KeyError:
      pass

    for name in iter(self._tar_file.getnames()):

      if name.startswith(location[1:]):
        return True

    return False

Determines if a file entry for a path specification exists.

Args:
path_spec (PathSpec): path specification.

Returns:
bool: True if the file entry exists.


def private_map(self):
    return self._private_map

A map from parents to symbols that should not be included at all.

This map can be edited, but it should not be edited once traversal has
begun.

Returns:
The map marking symbols to not include.


def __init__(self, match=None, qps=None, user_qps=None, daily=None,
               analytics_id=None):

    _CheckType(match, basestring, 'match')
    _CheckType(qps, int, 'qps')
    _CheckType(user_qps, int, 'user_qps')
    _CheckType(daily, int, 'daily')
    _CheckType(analytics_id, basestring, 'analytics_id')

    self.__match = match
    self.__qps = qps
    self.__user_qps = user_qps
    self.__daily = daily
    self.__analytics_id = analytics_id

Constructor for ApiFrontEndLimitRule.

Args:
match: string, the matching rule that defines this traffic segment.
qps: int, the aggregate QPS for this segment.
user_qps: int, the per-end-user QPS for this segment.
daily: int, the aggregate daily maximum for this segment.
analytics_id: string, the project ID under which traffic for this segment
will be logged.


def __init__(self, username, email, manager):

        super(User, self).__init__(manager)

        self.username = username
        self.email = email

Initialize a user.

Args:
username (str): The user's username.
email (str): The user's email.
manager (:class:`saltant.models.user.UserManager`):
The manager which spawned this user instance.


def do_usufy(self, query, **kwargs):

        try:
            self.wrapperAPI = TwitterAPIWrapper()

            results = self.wrapperAPI.get_user(query)

            for r in results:

                aux = {}
                aux["type"]="i3visio.uri"
                alias=r["value"].split(' - ')[1]
                aux["value"]= self.createURL(word=alias, mode="usufy")
                aux["attributes"]= []
                r["attributes"].append(aux)

        except Exception, e:
            return super(Twitter, self).do_usufy(query, **kwargs)

Verifying a usufy query in this platform.

This might be redefined in any class inheriting from Platform.

Args:
-----
query: The element to be searched.

Return:
-------
A list of elements to be appended.


def CreateDataTypeMapByType(cls, data_type_definition):

    data_type_map_class = cls._MAP_PER_DEFINITION.get(
        data_type_definition.TYPE_INDICATOR, None)
    if not data_type_map_class:
      return None

    return data_type_map_class(data_type_definition)

Creates a specific data type map by type indicator.

Args:
data_type_definition (DataTypeDefinition): data type definition.

Returns:
DataTypeMap: data type map or None if the date type definition
is not available.


def append_item(self, item):

        did_remove = self.remove_exit()
        item.menu = self
        self.items.append(item)
        if did_remove:
            self.add_exit()

Add an item to the end of the menu before the exit item.

Args:
item (MenuItem): The item to be added.


def persist_perf(run, session, svg_path):

    from benchbuild.utils import schema as s

    with open(svg_path, 'r') as svg_file:
        svg_data = svg_file.read()
        session.add(
            s.Metadata(name="perf.flamegraph", value=svg_data, run_id=run.id))

Persist the flamegraph in the database.

The flamegraph exists as a SVG image on disk until we persist it in the
database.

Args:
run: The run we attach these perf measurements to.
session: The db transaction we belong to.
svg_path: The path to the SVG file we want to store.


def merge_json_fhir_object_into_proto(json_value: Dict[str, Any], target: message.Message, *, validate: bool=True, default_timezone: str=_primitive_time_utils.SIMPLE_ZULU) -> None:
    parser = _json_parser.JsonParser.json_parser_with_default_timezone(_PRIMITIVE_HANDLER, default_timezone=default_timezone)
    parser.merge_value(json_value, target)
    if validate:
        resource_validation.validate_resource(target, _PRIMITIVE_HANDLER)

Merges the provided json_value object into a target Message.

Args:
json_value: The parsed JSON object to merge into target.
target: The Message instance to merge raw_json into.
validate: A Boolean value indicating if validation should be performed on
the resultant Message. Validation takes the form of ensuring that basic
checks such as cardinality guarantees, required field adherence, etc. are
met. Defaults to True.
default_timezone: A string specifying the timezone string to use for time-
like FHIR data during parsing. Defaults to 'Z' for UTC.

Raises:
fhir_errors.InvalidFhirError: In the event that validation fails after
parsing.


def __init__(self, action_meanings):

    self.action_meanings = action_meanings
    self._wait = True

    self.action_space = None
    self._last_step_tuples = None
    self.action_meanings = action_meanings
    self.name_to_action_num = {name: num for num, name in
                               enumerate(self.action_meanings)}

Constructor for PlayerEnv.

Args:
action_meanings: list of strings indicating action names. Can be obtain by
>>> env = gym.make("PongNoFrameskip-v4")  # insert your game name
>>> env.unwrapped.get_action_meanings()
See gym AtariEnv get_action_meanings() for more details.


def run(self, args):
    jlink = self.create_jlink(args)
    if args.downgrade:
        if (not jlink.firmware_newer()):
            print('DLL firmware is not older than J-Link firmware.')
        else:
            jlink.invalidate_firmware()
            try:
                jlink.update_firmware()
            except pylink.JLinkException as e:
                jlink = self.create_jlink(args)
            print(('Firmware Downgraded: %s' % jlink.firmware_version))
    elif args.upgrade:
        if (not jlink.firmware_outdated()):
            print('DLL firmware is not newer than J-Link firmware.')
        else:
            try:
                jlink.update_firmware()
            except pylink.JLinkException as e:
                jlink = self.create_jlink(args)
            print(('Firmware Updated: %s' % jlink.firmware_version))
    return None

Runs the firmware command.

Args:
self (FirmwareCommand): the ``FirmwareCommand`` instance
args (Namespace): arguments to parse

Returns:
``None``


def extract_all(self):
    (longmin, longmax, latmin, latmax) = self.Boundary()
    (sample_min, sample_max) = map(int, (self.SAMPLE_FIRST_PIXEL, self.SAMPLE_LAST_PIXEL))
    (line_min, line_max) = map(int, (self.LINE_FIRST_PIXEL, self.LINE_LAST_PIXEL))
    X = np.array(map(self.long_id, range(sample_min, (sample_max + 1), 1)))
    Y = np.array(map(self.lat_id, range(line_min, (line_max + 1), 1)))
    for (i, line) in enumerate(range(int(line_min), (int(line_max) + 1))):
        start = (((line - 1) * int(self.SAMPLE_LAST_PIXEL)) + sample_min)
        chunk_size = int((sample_max - sample_min))
        Za = self.array(chunk_size, start, self.bytesize)
        if (i == 0):
            Z = Za
        else:
            Z = np.vstack((Z, Za))
    (X, Y) = np.meshgrid(X, Y)
    return (X, Y, Z)

Extract all the image

Returns:
A tupple of three arrays ``(X,Y,Z)`` with ``X`` contains the
longitudes, ``Y`` contains the latitude and ``Z`` the values
extracted from the image.

Note:
All return arrays have the same size.

All coordinate are in degree.


def validate_json_schema(data, schema, name="task"):

    try:
        jsonschema.validate(data, schema)
    except jsonschema.exceptions.ValidationError as exc:
        raise ScriptWorkerTaskException(
            "Can't validate {} schema!\n{}".format(name, str(exc)),
            exit_code=STATUSES['malformed-payload']
        )

Given data and a jsonschema, let's validate it.

This happens for tasks and chain of trust artifacts.

Args:
data (dict): the json to validate.
schema (dict): the jsonschema to validate against.
name (str, optional): the name of the json, for exception messages.
Defaults to "task".

Raises:
ScriptWorkerTaskException: on failure


def loss_masks(self, masks_queries_logits: Tensor, mask_labels: List[Tensor], indices: Tuple[np.array], num_masks: int) -> Dict[str, Tensor]:
    src_idx = self._get_predictions_permutation_indices(indices)
    tgt_idx = self._get_targets_permutation_indices(indices)
    pred_masks = masks_queries_logits[src_idx]
    target_masks, _ = self._pad_images_to_max_in_batch(mask_labels)
    target_masks = target_masks[tgt_idx]
    pred_masks = pred_masks[:, None]
    target_masks = target_masks[:, None]
    with torch.no_grad():
        point_coords = self.sample_points_using_uncertainty(pred_masks, self.calculate_uncertainty, self.num_points, self.oversample_ratio, self.importance_sample_ratio)
        point_labels = sample_point(target_masks, point_coords, align_corners=False).squeeze(1)
    point_logits = sample_point(pred_masks, point_coords, align_corners=False).squeeze(1)
    losses = {'loss_mask': sigmoid_cross_entropy_loss(point_logits, point_labels, num_masks), 'loss_dice': dice_loss(point_logits, point_labels, num_masks)}
    del pred_masks
    del target_masks
    return losses

Compute the losses related to the masks using focal and dice loss.

Args:
masks_queries_logits (`torch.Tensor`):
A tensor of shape `batch_size, num_queries, height, width`
mask_labels (`torch.Tensor`):
List of mask labels of shape `(labels, height, width)`.
indices (`Tuple[np.array])`:
The indices computed by the Hungarian matcher.
num_masks (`int)`:
The number of masks, used for normalization.

Returns:
`Dict[str, Tensor]`: A dict of `torch.Tensor` containing two keys:
- **loss_mask** -- The loss computed using sigmoid ce loss on the predicted and ground truth masks.
- **loss_dice** -- The loss computed using dice loss on the predicted on the predicted and ground truth
masks.


def _get_configured_module(option_name, known_modules=None):

    from furious.job_utils import path_to_reference

    config = get_config()
    option_value = config[option_name]

    if not known_modules:
        known_modules = {}

    module_path = known_modules.get(option_value) or option_value
    return path_to_reference(module_path)

Get the module specified by the value of option_name. The value of the
configuration option will be used to load the module by name from the known
module list or treated as a path if not found in known_modules.
Args:
option_name: name of persistence module
known_modules: dictionary of module names and module paths,
ie: {'ndb':'furious.extras.appengine.ndb_persistence'}
Returns:
module of the module path matching the name in known_modules


def __init__(self, variant_type='snv'):

        super(VcfPlugin, self).__init__()

        self.individual_objs = []
        self.case_objs = []

        self.variant_type = variant_type
        logger.info("Setting variant type to {0}".format(variant_type))

        self.variant_columns = ['CHROM', 'POS', 'ID', 'REF', 'ALT', 'QUAL', 'FILTER']

        self.head = None
        self.vep_header = None
        self.snpeff_header = None

        self.filters.can_filter_gene = True
        self.filters.can_filter_frequency = True
        self.filters.can_filter_cadd = True
        self.filters.can_filter_consequence = True
        self.filters.can_filter_impact_severity = True
        self.filters.can_filter_sv = True
        self.filters.can_filter_sv_len = True
        self.filters.can_filter_inheritance = True

Initialize a vcf adapter.

When instansiating all cases are found.

Args:
variant_type(str) : 'snv' or 'sv'


def char_ngrams(s, n=3, token_fn=tokens.on_whitespace):
    tokens = token_fn(s)
    ngram_tuples = [__ngrams(t, n=min(len(t), n)) for t in tokens]

    def unpack(l):
        return sum(l, [])

    def untuple(l):
        return [''.join(t) for t in l]
    return untuple(unpack(ngram_tuples))

Character-level n-grams from within the words in a string.

By default, the word boundary is assumed to be whitespace.  n-grams are
not taken across word boundaries, only within words.

If a word's length is less than or equal to n, the n-grams are simply a
list with the word itself.

>>> ng.char_ngrams('This is not a test!')
['Thi', 'his', 'is', 'not', 'a', 'tes', 'est', 'st!']

Therefore some n-grams may have a length less than n, like 'is' and 'a'
in this example.

Args:
s: a string
n: an int for the n in n-gram
token_fn: a function that splits a string into a list of strings

Returns:
list: strings of char-level n-grams


def remove_waiter(self, waiter_handle):

        spec, waiter = waiter_handle
        self._remove_waiter(spec, waiter)

Remove a message callback.

This call will remove a callback previously registered using
every_match.

Args:
waiter_handle (object): The opaque handle returned by the
previous call to every_match().


def stop_dag(self, name=None):

        return self._client.send(
            Request(
                action='stop_dag',
                payload={'name': name if name is not None else self._dag_name}
            )
        ).success

Send a stop signal to the specified dag or the dag that hosts this task.

Args:
name str: The name of the dag that should be stopped. If no name is given the
dag that hosts this task is stopped.

Upon receiving the stop signal, the dag will not queue any new tasks and wait
for running tasks to terminate.

Returns:
bool: True if the signal was sent successfully.


def __init__(self, action_type=None, nw_addr=None):

        super().__init__(action_type, length=8)
        self.nw_addr = nw_addr

Create an ActionNWAddr with the optional parameters below.

Args:
action_type (:class:`~pyof.v0x01.common.action.ActionType`):
:attr:`~ActionType.OFPAT_SET_NW_SRC` or
:attr:`~ActionType.OFPAT_SET_NW_DST`.
nw_addr (int): IP Address.


def InsertData(self, table_id, fd, schema, job_id):
    configuration = {'schema': {'fields': schema}, 'destinationTable': {'projectId': self.project_id, 'tableId': table_id, 'datasetId': self.dataset_id}, 'sourceFormat': 'NEWLINE_DELIMITED_JSON'}
    body = {'configuration': {'load': configuration}, 'jobReference': {'projectId': self.project_id, 'jobId': job_id}}
    mediafile = http.MediaFileUpload(fd.name, mimetype='application/octet-stream')
    job = self.service.jobs().insert(projectId=self.project_id, body=body, media_body=mediafile)
    try:
        response = job.execute()
        return response
    except errors.HttpError as e:
        if self.GetDataset(self.dataset_id):
            logging.exception('Error with job: %s', job_id)
        else:
            logging.info('Attempting to create dataset: %s', self.dataset_id)
            self.CreateDataset()
        return self.RetryUpload(job, job_id, e)

Insert data into a bigquery table.

If the table specified doesn't exist, it will be created with the specified
schema.

Args:
table_id: string table id
fd: open file descriptor containing the newline separated JSON
schema: BigQuery schema dict
job_id: string job id

Returns:
API response object on success, None on failure


def __init__(self, fetches, contraction_fn):
    self._unique_fetches = []
    for fetch in fetches:
        try:
            self._unique_fetches.append(ops.get_default_graph().as_graph_element(fetch, allow_tensor=True, allow_operation=True))
        except TypeError as e:
            raise TypeError(f'Argument `fetch` = {fetch} has invalid type "{type(fetch).__name__}" must be a string or Tensor. ({str(e)})')
        except ValueError as e:
            raise ValueError(f'Argument `fetch` = {fetch} cannot be interpreted as a Tensor. ({str(e)})')
        except KeyError as e:
            raise ValueError(f'Argument `fetch` = {fetch} cannot be interpreted as a Tensor. ({str(e)})')
    self._contraction_fn = contraction_fn

Creates an _ElementFetchMapper.

This is the fetch mapper used for leaves in the fetch struct.  Because of
the expansions mechanism, a leaf can actually fetch more than one tensor.

Also note that the fetches here can be just strings (tensor or op names) or
any other object that the graph knows how to convert to a tensor, such as a
Variable.  So we have to run each fetch through `as_graph_element()` to get
the corresponding tensor or op.

Args:
fetches: List of objects, as returned by a fetch_fn defined in
_REGISTERED_EXPANSIONS.
contraction_fn: Callable as returned by a fetch_fn.


def view(value: Any, *, name: Optional[str]=None, root_path: Optional[utils.KeyPath]=None, view_id: str='html-tree-view', **kwargs) -> Content:
    if isinstance(value, Content):
        return value
    with view_options(**kwargs) as options:
        view_object = View.create(view_id)
        return view_object.render(value, name=name, root_path=root_path or utils.KeyPath(), **options)

Views an object through generating content based on a specific view.

Args:
value: The value to view.
name: The name of the value.
root_path: The root path of the value.
view_id: The ID of the view to use. See `pg.View.dir()` for all available
view IDs.
**kwargs: Additional keyword arguments passed to the view, wich
will be used as the preset arguments for the View and Extension methods.

Returns:
The rendered `Content` object.


def inner_join(df, other, **kwargs):
    (left_on, right_on, suffixes) = get_join_parameters(kwargs)
    joined = df.merge(other, how='inner', left_on=left_on, right_on=right_on, suffixes=suffixes)
    return joined

Joins on values present in both DataFrames.

Args:
df (pandas.DataFrame): Left DataFrame (passed in via pipe)
other (pandas.DataFrame): Right DataFrame

Kwargs:
by (str or list): Columns to join on. If a single string, will join
on that column. If a list of lists which contain strings or
integers, the right/left columns to join on.
suffixes (list): String suffixes to append to column names in left
and right DataFrames.

Example:
a >> inner_join(b, by='x1')

x1  x2     x3
0  A   1   True
1  B   2  False


def neighborhood_probability(self, threshold, radius, sigmas=None):
    if (sigmas is None):
        sigmas = [0]
    weights = disk(radius)
    filtered_prob = []
    for sigma in sigmas:
        filtered_prob.append(EnsembleConsensus(np.zeros(self.data.shape[1:], dtype=np.float32), 'neighbor_prob_r_{0:d}_s_{1:d}'.format(radius, sigma), self.ensemble_name, self.run_date, (self.variable + '_{0:0.2f}'.format(threshold)), self.start_date, self.end_date, ''))
    thresh_data = np.zeros(self.data.shape[2:], dtype=np.uint8)
    neighbor_prob = np.zeros(self.data.shape[2:], dtype=np.float32)
    for t in range(self.data.shape[1]):
        for m in range(self.data.shape[0]):
            thresh_data[(self.data[(m, t)] >= threshold)] = 1
            maximized = fftconvolve(thresh_data, weights, mode='same')
            maximized[(maximized > 1)] = 1
            maximized[(maximized < 1)] = 0
            neighbor_prob += fftconvolve(maximized, weights, mode='same')
            neighbor_prob[(neighbor_prob < 1)] = 0
            thresh_data[:] = 0
        neighbor_prob /= (self.data.shape[0] * float(weights.sum()))
        for (s, sigma) in enumerate(sigmas):
            if (sigma > 0):
                filtered_prob[s].data[t] = gaussian_filter(neighbor_prob, sigma=sigma)
            else:
                filtered_prob[s].data[t] = neighbor_prob
        neighbor_prob[:] = 0
    return filtered_prob

Hourly probability of exceeding a threshold based on model values within a specified radius of a point.

Args:
threshold (float): probability of exceeding this threshold
radius (int): distance from point in number of grid points to include in neighborhood calculation.
sigmas (array of ints): Radii for Gaussian filter used to smooth neighborhood probabilities.

Returns:
list of EnsembleConsensus objects containing neighborhood probabilities for each forecast hour.


def remove_codeblock_syntax_sentinals(code_text):
    flags = (re.MULTILINE | re.DOTALL)
    code_text_ = code_text
    code_text_ = re.sub('^ *
    code_text_ = re.sub('^ *
    code_text_ = re.sub('^ *
    code_text_ = code_text_.rstrip()
    return code_text_

r"""
Removes template comments and vim sentinals

Args:
code_text (str):

Returns:
str: code_text_


def restores(self):
    if (not self.__restores):
        self.__restores = Restores(self.__connection)
    return self.__restores

Gets the Restores API client.

Returns:
Restores:


def from_str(cls, label: str) -> int:
    label_norm = label.replace('1', 'one').upper()
    if (label_norm in cls.__members__):
        return DecayType[label_norm]
    else:
        raise NotImplementedError

Convert given string label of decay type to special index

Args:
label: name of decay type.
Set of values: `"linear"`, `"cosine"`, `"exponential"`,
`"onecycle"`, `"trapezoid"`, `["polynomial", K]`, where K is a polynomial power

Returns:
index of decay type


def patch_so(srcs_dir: str) -> None:
    to_patch = {'tensorflow/python/_pywrap_tensorflow_internal.so': '$ORIGIN/../../tensorflow/compiler/xla/tsl/python/lib/core', 'tensorflow/compiler/mlir/quantization/tensorflow/python/pywrap_function_lib.so': '$ORIGIN/../../../../../python', 'tensorflow/compiler/mlir/quantization/tensorflow/python/pywrap_quantize_model.so': '$ORIGIN/../../../../../python', 'tensorflow/compiler/mlir/tensorflow_to_stablehlo/python/pywrap_tensorflow_to_stablehlo.so': '$ORIGIN/../../../../python', 'tensorflow/compiler/mlir/lite/python/_pywrap_converter_api.so': '$ORIGIN/../../../../python'}
    for file, path in to_patch.items():
        rpath = subprocess.check_output(['patchelf', '--print-rpath', '{}/{}'.format(srcs_dir, file)]).decode().strip()
        new_rpath = rpath + ':' + path
        subprocess.run(['patchelf', '--set-rpath', new_rpath, '{}/{}'.format(srcs_dir, file)], check=True)
        subprocess.run(['patchelf', '--shrink-rpath', '{}/{}'.format(srcs_dir, file)], check=True)

Patch .so files.

We must patch some of .so files otherwise auditwheel will fail.

Args:
srcs_dir: target directory with .so files to patch.


def _DrawTrips(self, triplist, colpar=''):
    stations = []
    if ((not self._stations) and triplist):
        self._stations = self._CalculateYLines(self._TravelTimes(triplist))
        if (not self._stations):
            self._AddWarning('Failed to use traveltimes for graph')
            self._stations = self._CalculateYLines(self._Uniform(triplist))
            if (not self._stations):
                self._AddWarning('Failed to calculate station distances')
                return
    stations = self._stations
    tmpstrs = []
    servlist = []
    for t in triplist:
        if (not colpar):
            if (t.service_id not in servlist):
                servlist.append(t.service_id)
            shade = int(((servlist.index(t.service_id) * (200 / len(servlist))) + 55))
            color = ('
        else:
            color = colpar
        start_offsets = [0]
        first_stop = t.GetTimeStops()[0]
        for (j, freq_offset) in enumerate(start_offsets):
            if ((j > 0) and (not colpar)):
                color = 'purple'
            scriptcall = ('onmouseover="LineClick(\'%s\',\'Trip %s starting %s\')"' % (t.trip_id, t.trip_id, transitfeed.FormatSecondsSinceMidnight(t.GetStartTime())))
            tmpstrhead = ('<polyline class="T" id="%s" stroke="%s" %s points="' % (str(t.trip_id), color, scriptcall))
            tmpstrs.append(tmpstrhead)
            for (i, s) in enumerate(t.GetTimeStops()):
                arr_t = s[0]
                dep_t = s[1]
                if ((arr_t is None) or (dep_t is None)):
                    continue
                arr_x = (int(((arr_t / 3600.0) * self._hour_grid)) - (self._hour_grid * self._offset))
                dep_x = (int(((dep_t / 3600.0) * self._hour_grid)) - (self._hour_grid * self._offset))
                tmpstrs.append(('%s,%s ' % (int((arr_x + 20)), int((stations[i] + 20)))))
                tmpstrs.append(('%s,%s ' % (int((dep_x + 20)), int((stations[i] + 20)))))
            tmpstrs.append('" />')
    return ''.join(tmpstrs)

Generates svg polylines for each transit trip.

Args:
# Class Trip is defined in transitfeed.py
[Trip, Trip, ...]

Returns:
# A string containing a polyline tag for each trip
' <polyline class="T" stroke="#336633" points="433,0 ...'


def oauth2decorator_from_clientsecrets(filename, scope, message=None, cache=None):
    return OAuth2DecoratorFromClientSecrets(filename, scope, message=message, cache=cache)

Creates an OAuth2Decorator populated from a clientsecrets file.

Args:
filename: string, File name of client secrets.
scope: string or list of strings, scope(s) of the credentials being
requested.
message: string, A friendly string to display to the user if the
clientsecrets file is missing or invalid. The message may
contain HTML and will be presented on the web interface for
any method that uses the decorator.
cache: An optional cache service client that implements get() and set()
methods. See clientsecrets.loadfile() for details.

Returns: An OAuth2Decorator


def stop_loss_replace(self, accountID, orderID, **kwargs):

        return self.replace(
            accountID,
            orderID,
            order=StopLossOrderRequest(**kwargs)
        )

Shortcut to replace a pending Stop Loss Order in an Account

Args:
accountID : The ID of the Account
orderID : The ID of the Stop Loss Order to replace
kwargs : The arguments to create a StopLossOrderRequest

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


def create(window, root):

        notifications = {}
        _id = root.get_property("id")
        from foxpuppet.windows.browser.notifications import addons

        notifications.update(addons.NOTIFICATIONS)
        return notifications.get(_id, BaseNotification)(window, root)

Create a notification object.

Args:
window (:py:class:`BrowserWindow`): Window object this region
appears in.
root
(:py:class:`~selenium.webdriver.remote.webelement.WebElement`):
WebDriver element object that serves as the root for the
notification.

Returns:
:py:class:`BaseNotification`: Firefox notification.


def _load_data(self, resource, default=DEFAULT_VALUE_SAFEGUARD, **kwargs):
    default_val = (default if (default != self.DEFAULT_VALUE_SAFEGUARD) else {})
    try:
        return (get_edx_api_data(api_config=CatalogIntegration.current(), resource=resource, api=self.client, **kwargs) or default_val)
    except (SlumberBaseException, ConnectionError, Timeout) as exc:
        LOGGER.exception('Failed to load data from resource [%s] with kwargs [%s] due to: [%s]', resource, kwargs, str(exc))
        return default_val

Load data from API client.

Arguments:
resource(string): type of resource to load
default(any): value to return if API query returned empty result. Sensible values: [], {}, None etc.

Returns:
dict: Deserialized response from Course Catalog API


def attention_bias_proximal(length):
    r = tf.to_float(tf.range(length))
    diff = (tf.expand_dims(r, 0) - tf.expand_dims(r, 1))
    return tf.expand_dims(tf.expand_dims((- tf.log1p(tf.abs(diff))), 0), 0)

Bias for self-attention to encourage attention to close positions.

Args:
length: an integer scalar.

Returns:
a Tensor with shape [1, 1, length, length]


def list_asgs_all(access_token, subscription_id):

    endpoint = ''.join([get_rm_endpoint(),
                        '/subscriptions/', subscription_id,
                        '/providers/Microsoft.Network/virtualNetworks/',
                        '?api-version=', NETWORK_API])
    return do_get(endpoint, access_token)

Get details about the application security groups for a resource group.

Args:
access_token (str): A valid Azure authentication token.
subscription_id (str): Azure subscription id.

Returns:
HTTP response. ASG JSON body.


def text_colour_for_hex(hexx, percent=50, dark='
    return (light if hex_is_dark(hexx, percent=percent) else dark)

Function to decide what colour to use for a given hex colour.

Args:
hexx (str): A hexadecimal colour, starting with '#'.

Returns:
bool: The colour's brightness is less than the given percent.


def symlink(src, link):
    if (sys.getwindowsversion().major < 6):
        raise SaltInvocationError('Symlinks are only supported on Windows Vista or later.')
    if (not os.path.exists(src)):
        raise SaltInvocationError('The given source path does not exist.')
    if (not os.path.isabs(src)):
        raise SaltInvocationError('File path must be absolute.')
    src = os.path.normpath(src)
    link = os.path.normpath(link)
    is_dir = os.path.isdir(src)
    try:
        win32file.CreateSymbolicLink(link, src, int(is_dir))
        return True
    except pywinerror as exc:
        raise CommandExecutionError("Could not create '{0}' - [{1}] {2}".format(link, exc.winerror, exc.strerror))

Create a symbolic link to a file

This is only supported with Windows Vista or later and must be executed by
a user with the SeCreateSymbolicLink privilege.

The behavior of this function matches the Unix equivalent, with one
exception - invalid symlinks cannot be created. The source path must exist.
If it doesn't, an error will be raised.

Args:
src (str): The path to a file or directory
link (str): The path to the link

Returns:
bool: True if successful, otherwise False

CLI Example:

.. code-block:: bash

salt '*' file.symlink /path/to/file /path/to/link


def trace_set_buffer_capacity(self, size):

        cmd = enums.JLinkTraceCommand.SET_CAPACITY
        data = ctypes.c_uint32(size)
        res = self._dll.JLINKARM_TRACE_Control(cmd, ctypes.byref(data))
        if (res == 1):
            raise errors.JLinkException('Failed to set trace buffer size.')
        return None

Sets the capacity for the trace buffer.

Args:
self (JLink): the ``JLink`` instance.
size (int): the new capacity for the trace buffer.

Returns:
``None``


def supported_tifs(self):

        buf = ctypes.c_uint32()
        self._dll.JLINKARM_TIF_GetAvailable(ctypes.byref(buf))
        return buf.value

Returns a bitmask of the supported target interfaces.

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

Returns:
Bitfield specifying which target interfaces are supported.


def _ConvertAttributeContainerToDict(cls, attribute_container):
    if (not isinstance(attribute_container, containers_interface.AttributeContainer)):
        raise TypeError('{0:s} is not an attribute container type.'.format(type(attribute_container)))
    container_type = getattr(attribute_container, 'CONTAINER_TYPE', None)
    if (not container_type):
        raise ValueError('Unsupported attribute container type: {0:s}.'.format(type(attribute_container)))
    json_dict = {'__type__': 'AttributeContainer', '__container_type__': container_type}
    for (attribute_name, attribute_value) in attribute_container.GetAttributes():
        json_dict[attribute_name] = cls._ConvertAttributeValueToDict(attribute_value)
    return json_dict

Converts an attribute container object into a JSON dictionary.

The resulting dictionary of the JSON serialized objects consists of:
{
'__type__': 'AttributeContainer'
'__container_type__': ...
...
}

Here '__type__' indicates the object base type. In this case
'AttributeContainer'.

'__container_type__' indicates the container type and rest of the elements
of the dictionary make up the attributes of the container.

Args:
attribute_container (AttributeContainer): attribute container.

Returns:
dict[str, object]: JSON serialized objects.

Raises:
TypeError: if not an instance of AttributeContainer.
ValueError: if the attribute container type is not supported.


def parse_columns(lines):
    data = []
    index = []
    for line in lines:
        line = line.rstrip()
        if line.startswith('
            tmp = __parse_entry(line)
            data.append(tmp[1])
            index.append(tmp[0])
    return DataFrame(data, index=index, columns=['description'])

Parse list of lines with columns description from SOFT file.

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

Returns:
:obj:`pandas.DataFrame`: Columns description.


def GetEventTagByIdentifier(self, identifier):
    event_tag = self._GetAttributeContainerByIndex(self._CONTAINER_TYPE_EVENT_TAG, (identifier.row_identifier - 1))
    if event_tag:
        event_identifier = identifiers.SQLTableIdentifier(self._CONTAINER_TYPE_EVENT, event_tag.event_row_identifier)
        event_tag.SetEventIdentifier(event_identifier)
        del event_tag.event_row_identifier
    return event_tag

Retrieves a specific event tag.

Args:
identifier (SQLTableIdentifier): event tag identifier.

Returns:
EventTag: event tag or None if not available.


def kill_reporter(self, check_alive=True):

        if PY3:
            self._kill_process_type(
                ray_constants.PROCESS_TYPE_REPORTER, check_alive=check_alive)

Kill the reporter.

Args:
check_alive (bool): Raise an exception if the process was already
dead.


def csv_to_matrix(csv_file_path):

    mtx = []
    with open(csv_file_path) as csv_data_file:
        for row in csv_data_file:
            mtx.append(row.split(','))
    return mtx

Load a CSV file into a Python matrix of strings.

Args:
csv_file_path: Full path to a valid CSV file (e.g. c:/ladybug/test.csv)


def softplus(x, scale=1.0, name=None):

  if scale == 1:
    return tf.nn.softplus(x)
  else:
    with tf.name_scope(name, 'softplus', [x]):
      scale = tf.convert_to_tensor(scale, dtype=x.dtype.base_dtype)
      return tf.nn.softplus(x * scale) / scale

Computes softplus with a scale factor to sharpen of the hinge.

This is an alternate non-linearity to relu. It has a similar shape, but
it has a smooth transition from the linear part to 0.

Args:
x: A tensor.
scale: A float that sharpens the curve.
name: Optional name.
Returns:
y = log(1 + exp(scale * x)) / scale


def prep_parallel(self, binary_args, other_args):

        if self.length < 100:
            raise Exception("Run this across 1 processor by setting num_processors kwarg to None.")
        if self.num_processors == -1:
            self.num_processors = mp.cpu_count()

        split_val = int(np.ceil(self.length/self.num_splits))
        split_inds = [self.num_splits*i for i in np.arange(1, split_val)]

        inds_split_all = np.split(np.arange(self.length), split_inds)

        self.args = []
        for i, ind_split in enumerate(inds_split_all):
            trans_args = []
            for arg in binary_args:
                try:
                    trans_args.append(arg[ind_split])
                except TypeError:
                    trans_args.append(arg)

            self.args.append((i, tuple(trans_args)) + other_args)
        return

Prepare the parallel calculations

Prepares the arguments to be run in parallel.
It will divide up arrays according to num_splits.

Args:
binary_args (list): List of binary arguments for input into the SNR function.
other_args (tuple of obj): tuple of other args for input into parallel snr function.


def __init__(self, job_id, context):

    super(GCPJob, self).__init__(job_id)
    if context is None:
      context = google.datalab.Context.default()
    self._context = context
    self._api = self._create_api(context)

Initializes an instance of a Job.

Args:
job_id: the BigQuery job ID corresponding to this job.
context: a Context object providing project_id and credentials.


def preprocess(self, raw_inputs):
    image_arrays = []
    for raw_im in raw_inputs:
        im = raw_im.convert('L')
        im = im.resize(MNIST_DIM, Image.ANTIALIAS)
        arr = np.array(im)
        image_arrays.append(arr)
    inputs = np.array(image_arrays)
    return (inputs.reshape(len(inputs), MNIST_DIM[0], MNIST_DIM[1], 1).astype('float32') / 255)

Convert images into the format required by our model.

Our model requires that inputs be grayscale (mode 'L'), be resized to
`MNIST_DIM`, and be represented as float32 numpy arrays in range
[0, 1].

Args:
raw_inputs (list of Images): a list of PIL Image objects

Returns:
array (float32): num images * height * width * num channels


def _page_to_text(page):
    start_pos = page.find(u'<text')
    assert (start_pos != (- 1))
    end_tag_pos = page.find(u'>', start_pos)
    assert (end_tag_pos != (- 1))
    end_tag_pos += len(u'>')
    end_pos = page.find(u'</text>')
    if (end_pos == (- 1)):
        return u''
    return page[end_tag_pos:end_pos]

Extract the text from a page.

Args:
page: a unicode string
Returns:
a unicode string


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

Get a list of rated moview for a specific guest session id.

Args:
page: (optional) Minimum 1, maximum 1000.
sort_by: (optional) 'created_at.asc' | 'created_at.desc'
language: (optional) ISO 639-1 code.

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


def execute(self):
    for name_context, spec in zip(self._map_task.name_contexts, self._map_task.operations):
        op = create_operation(name_context, spec, self._counter_factory, None, self._state_sampler, test_shuffle_source=self._test_shuffle_source, test_shuffle_sink=self._test_shuffle_sink)
        self._ops.append(op)
        if hasattr(op.spec, 'input'):
            producer, output_index = op.spec.input
            self._ops[producer].add_receiver(op, output_index)
        if hasattr(op.spec, 'inputs'):
            for producer, output_index in op.spec.inputs:
                self._ops[producer].add_receiver(op, output_index)
    for ix, op in reversed(list(enumerate(self._ops))):
        _LOGGER.debug('Starting op %d %s', ix, op)
        op.start()
    for op in self._ops:
        op.finish()

Executes all the operation_specs.Worker* instructions in a map task.

We update the map_task with the execution status, expressed as counters.

Raises:
RuntimeError: if we find more than on read instruction in task spec.
TypeError: if the spec parameter is not an instance of the recognized
operation_specs.Worker* classes.


def _ragged_split(tensor, pieces):
    shape = tensor.shape
    if 1 != len(shape):
        raise ValueError('input tensor must be 1D')
    tensor_len = shape.dims[0].value
    chunk_size = tensor_len
    with ops.colocate_with(tensor):
        if tensor_len != pieces * chunk_size:
            assert pieces > 1
            last_chunk_size = tensor_len - (pieces - 1) * chunk_size
            assert last_chunk_size > 0
            piece_lens = [chunk_size for _ in range(pieces - 1)] + [last_chunk_size]
            return array_ops.split(tensor, piece_lens)
        else:
            return array_ops.split(tensor, pieces)

Like split for 1D tensors but allows case where len % pieces != 0.

Args:
tensor: `tf.Tensor` that must be 1D.
pieces: a positive integer specifying the number of pieces into which
tensor should be split.

Returns:
list of `tf.Tensor` of length pieces, which hold the values of
the input tensor, in order. The final tensor may be shorter
than the others, which will all be of equal length.

Raises:
ValueError: input tensor must be 1D.


class PatchTSMixerForRegressionOutput(ModelOutput):
    loss: Optional[torch.FloatTensor] = None
    regression_outputs: Optional[torch.FloatTensor] = None
    last_hidden_state: Optional[torch.FloatTensor] = None
    hidden_states: Optional[Tuple[torch.FloatTensor]] = None

Output type of [`PatchTSMixerForRegressionOutput`].

Args:
regression_outputs (`torch.FloatTensor` of shape `(batch_size, num_targets)`):
Prediction output from the regression head.
last_hidden_state (`torch.FloatTensor` of shape `(batch_size, num_input_channels, num_patches, d_model)`):
Backbone embeddings before passing through the head.
hidden_states (`tuple(torch.FloatTensor)`, *optional*):
Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.
loss (*optional*, returned when `y` is provided, `torch.FloatTensor` of shape `()`):
Total loss.


def GetContainingWhileContext(ctxt, stop_ctxt=None):
    while ctxt:
        if ctxt.IsWhileContext() or ctxt == stop_ctxt:
            return ctxt
        ctxt = ctxt.outer_context
    return None

Returns the first ancestor WhileContext of `ctxt`.

Returns `ctxt` if `ctxt` is a WhileContext, or None if `ctxt` is not in a
while loop.

Args:
ctxt: ControlFlowContext
stop_ctxt: ControlFlowContext, optional. If provided, the search will end
if it sees stop_ctxt.

Returns:
`ctxt` if `ctxt` is a WhileContext, the most nested WhileContext containing
`ctxt`, or None if `ctxt` is not in a while loop.  If `stop_ctxt` is not
`None`, this returns `ctxt` if it matches `stop_ctxt` in its traversal.


def Create(conf, map_name, automount_mountpoint=None):
    global _cache_implementations
    if not _cache_implementations:
        raise RuntimeError('no cache implementations exist')
    cache_name = conf['name']
    if cache_name not in _cache_implementations:
        raise RuntimeError('cache not implemented: %r' % (cache_name,))
    if map_name not in _cache_implementations[cache_name]:
        raise RuntimeError('map %r not supported by cache %r' % (map_name, cache_name))
    return _cache_implementations[cache_name][map_name](conf, map_name, automount_mountpoint=automount_mountpoint)

Cache creation factory method.

Args:
conf: a dictionary of configuration key/value pairs, including one
required attribute 'name'
map_name: a string identifying the map name to handle
automount_mountpoint: A string containing the automount mountpoint, used only
by automount maps.

Returns:
an instance of a Cache

Raises:
RuntimeError: problem instantiating the requested cache


def structure_2_lmpdata(structure, ff_elements=None, atom_style="charge"):

    s = structure.get_sorted_structure()

    a, b, c = s.lattice.abc
    m = s.lattice.matrix
    xhi = a
    xy = np.dot(m[1], m[0] / xhi)
    yhi = np.sqrt(b ** 2 - xy ** 2)
    xz = np.dot(m[2], m[0] / xhi)
    yz = (np.dot(m[1], m[2]) - xy * xz) / yhi
    zhi = np.sqrt(c ** 2 - xz ** 2 - yz ** 2)
    box_bounds = [[0.0, xhi], [0.0, yhi], [0.0, zhi]]
    box_tilt = [xy, xz, yz]
    box_tilt = None if not any(box_tilt) else box_tilt
    box = LammpsBox(box_bounds, box_tilt)
    new_latt = Lattice([[xhi, 0, 0], [xy, yhi, 0], [xz, yz, zhi]])
    s.lattice = new_latt

    symbols = list(s.symbol_set)
    if ff_elements:
        symbols.extend(ff_elements)
    elements = sorted(Element(el) for el in set(symbols))
    mass_info = [tuple([i.symbol] * 2) for i in elements]
    ff = ForceField(mass_info)
    topo = Topology(s)
    return LammpsData.from_ff_and_topologies(box=box, ff=ff, topologies=[topo],
                                             atom_style=atom_style)

Converts a structure to a LammpsData object with no force field
parameters and topologies.

Args:
structure (Structure): Input structure.
ff_elements ([str]): List of strings of elements that must be
present due to force field settings but not necessarily in
the structure. Default to None.
atom_style (str): Choose between "atomic" (neutral) and
"charge" (charged). Default to "charge".

Returns:
LammpsData


def lookup(self, keys, name=None):
    with ops.name_scope(name, '%s_lookup_table_find' % self.name, [self.resource_handle, keys]):
        keys = ops.convert_to_tensor(keys, dtype=self._key_dtype, name='keys')
        with ops.colocate_with(self.resource_handle):
            values = gen_lookup_ops.lookup_table_find_v2(self.resource_handle, keys, self._default_value)
    return values

Looks up `keys` in a table, outputs the corresponding values.

The `default_value` is used for keys not present in the table.

Args:
keys: Keys to look up. Can be a tensor of any shape. Must match the
table's key_dtype.
name: A name for the operation (optional).

Returns:
A tensor containing the values in the same shape as `keys` using the
table's value type.

Raises:
TypeError: when `keys` do not match the table data types.


def __init__(self, ball_radius=10, n_chains=4, chain_length=10, monomer=None):

        super(Tnp, self).__init__()

        if not monomer:
            monomer = Bead(particle_kind='t')

        n = 129
        self.add(Sphere(n=n, radius=ball_radius, port_distance_from_surface=0.7), label="np")

        pattern = mb.SpherePattern(n_chains)

        pattern.scale(ball_radius)

        chain_proto = mb.Polymer(monomer, n=chain_length)

        chain_protos, empty_backfill = pattern.apply_to_compound(chain_proto,
                guest_port_name="down", host=self['np'])
        self.add(chain_protos)

        self.generate_bonds('np', 'np', sqrt(4 * ball_radius ** 2 * pi / n) - 0.5,
                            sqrt(4 * ball_radius**2 * pi / n) + 0.5)
        self.generate_bonds('np', 't', 0.1, 0.3)
        self.generate_bonds('t', 'np', 0.1, 0.3)

Initialize a tethered nanoparticle.

Args:
ball_radius (float): Radius of the nanoparticle.
n_chains (int): Number of chains to attach to the nanoparticle.
chain_length (int): Length of the chains being attached.
monomer (Compound, optional): Type of chain being attached.


def save_plot(self, filename, img_format="eps", ylim=None, units="thz"):

        plt = self.get_plot(ylim=ylim, units=units)
        plt.savefig(filename, format=img_format)
        plt.close()

Save matplotlib plot to a file.

Args:
filename: Filename to write to.
img_format: Image format to use. Defaults to EPS.
ylim: Specifies the y-axis limits.
units: units for the frequencies. Accepted values thz, ev, mev, ha, cm-1, cm^-1.


def upload_dict(s3_conn, s3_prefix, data_to_sync):
    (bucket_name, prefix) = split_s3_path(s3_prefix)
    bucket = s3_conn.get_bucket(bucket_name)
    for (key, value) in data_to_sync.items():
        full_name = '{}/{}.json'.format(prefix, key)
        s3_key = boto.s3.key.Key(bucket=bucket, name=full_name)
        logging.info('uploading key %s', full_name)
        s3_key.set_contents_from_string(json.dumps(value))

Syncs a dictionary to an S3 bucket, serializing each value in the
dictionary as a JSON file with the key as its name.

Args:
s3_conn: (boto.s3.connection) an s3 connection
s3_prefix: (str) the destination prefix
data_to_sync: (dict)


def initial_sql(self, value):

        self._initial_sql = value

        if value is None:
            try:
                del self._connectionXML.attrib['one-time-sql']
            except KeyError:
                pass
        else:
            self._connectionXML.set('one-time-sql', value)

Set the connection's initial_sql property.

Args:
value:  New initial_sql value. String.

Returns:
Nothing.


def get_unbound_arg_names(arg_names, arg_binding_keys):

    bound_arg_names = [abk._arg_name for abk in arg_binding_keys]
    return [arg_name for arg_name in arg_names
            if arg_name not in bound_arg_names]

Determines which args have no arg binding keys.

Args:
arg_names: a sequence of the names of possibly bound args
arg_binding_keys: a sequence of ArgBindingKey each of whose arg names is
in arg_names
Returns:
a sequence of arg names that is a (possibly empty, possibly non-proper)
subset of arg_names


def add_file_to_tree(tree, file_path, file_contents, is_executable=False):

    record = {
        "path": file_path,
        "mode": "100755" if is_executable else "100644",
        "type": "blob",
        "content": file_contents,
        }
    tree.append(record)
    return tree

Add a file to a tree.

Args:

tree
A list of dicts containing info about each blob in a tree.

file_path
The path of the new file in the tree.

file_contents
The (UTF-8 encoded) contents of the new file.

is_executable
If ``True``, the new file will get executable permissions (0755).
Otherwise, it will get 0644 permissions.

Returns:
The provided tree, but with the new file added.