def cube(width, height, depth, center=(0.0, 0.0, 0.0), normals=True, uvs=True) -> VAO:

    width, height, depth = width / 2.0, height / 2.0, depth / 2.0

    pos = numpy.array([
        center[0] + width, center[1] - height, center[2] + depth,
        center[0] + width, center[1] + height, center[2] + depth,
        center[0] - width, center[1] - height, center[2] + depth,
        center[0] + width, center[1] + height, center[2] + depth,
        center[0] - width, center[1] + height, center[2] + depth,
        center[0] - width, center[1] - height, center[2] + depth,
        center[0] + width, center[1] - height, center[2] - depth,
        center[0] + width, center[1] + height, center[2] - depth,
        center[0] + width, center[1] - height, center[2] + depth,
        center[0] + width, center[1] + height, center[2] - depth,
        center[0] + width, center[1] + height, center[2] + depth,
        center[0] + width, center[1] - height, center[2] + depth,
        center[0] + width, center[1] - height, center[2] - depth,
        center[0] + width, center[1] - height, center[2] + depth,
        center[0] - width, center[1] - height, center[2] + depth,
        center[0] + width, center[1] - height, center[2] - depth,
        center[0] - width, center[1] - height, center[2] + depth,
        center[0] - width, center[1] - height, center[2] - depth,
        center[0] - width, center[1] - height, center[2] + depth,
        center[0] - width, center[1] + height, center[2] + depth,
        center[0] - width, center[1] + height, center[2] - depth,
        center[0] - width, center[1] - height, center[2] + depth,
        center[0] - width, center[1] + height, center[2] - depth,
        center[0] - width, center[1] - height, center[2] - depth,
        center[0] + width, center[1] + height, center[2] - depth,
        center[0] + width, center[1] - height, center[2] - depth,
        center[0] - width, center[1] - height, center[2] - depth,
        center[0] + width, center[1] + height, center[2] - depth,
        center[0] - width, center[1] - height, center[2] - depth,
        center[0] - width, center[1] + height, center[2] - depth,
        center[0] + width, center[1] + height, center[2] - depth,
        center[0] - width, center[1] + height, center[2] - depth,
        center[0] + width, center[1] + height, center[2] + depth,
        center[0] - width, center[1] + height, center[2] - depth,
        center[0] - width, center[1] + height, center[2] + depth,
        center[0] + width, center[1] + height, center[2] + depth,
    ], dtype=numpy.float32)

    if normals:
        normal_data = numpy.array([
            -0, 0, 1,
            -0, 0, 1,
            -0, 0, 1,
            0, 0, 1,
            0, 0, 1,
            0, 0, 1,
            1, 0, 0,
            1, 0, 0,
            1, 0, 0,
            1, 0, 0,
            1, 0, 0,
            1, 0, 0,
            0, -1, 0,
            0, -1, 0,
            0, -1, 0,
            0, -1, 0,
            0, -1, 0,
            0, -1, 0,
            -1, -0, 0,
            -1, -0, 0,
            -1, -0, 0,
            -1, -0, 0,
            -1, -0, 0,
            -1, -0, 0,
            0, 0, -1,
            0, 0, -1,
            0, 0, -1,
            0, 0, -1,
            0, 0, -1,
            0, 0, -1,
            0, 1, 0,
            0, 1, 0,
            0, 1, 0,
            0, 1, 0,
            0, 1, 0,
            0, 1, 0,
        ], dtype=numpy.float32)

    if uvs:
        uvs_data = numpy.array([
            1, 0,
            1, 1,
            0, 0,
            1, 1,
            0, 1,
            0, 0,
            1, 0,
            1, 1,
            0, 0,
            1, 1,
            0, 1,
            0, 0,
            1, 1,
            0, 1,
            0, 0,
            1, 1,
            0, 0,
            1, 0,
            0, 1,
            0, 0,
            1, 0,
            0, 1,
            1, 0,
            1, 1,
            1, 0,
            1, 1,
            0, 1,
            1, 0,
            0, 1,
            0, 0,
            1, 1,
            0, 1,
            1, 0,
            0, 1,
            0, 0,
            1, 0
        ], dtype=numpy.float32)

    vao = VAO("geometry:cube")

    vao.buffer(pos, '3f', ['in_position'])
    if normals:
        vao.buffer(normal_data, '3f', ['in_normal'])
    if uvs:
        vao.buffer(uvs_data, '2f', ['in_uv'])

    return vao

Creates a cube VAO with normals and texture coordinates

Args:
width (float): Width of the cube
height (float): Height of the cube
depth (float): Depth of the cube

Keyword Args:
center: center of the cube as a 3-component tuple
normals: (bool) Include normals
uvs: (bool) include uv coordinates

Returns:
A :py:class:`demosys.opengl.vao.VAO` instance


def list_dir(root, prefix=False):
    root = os.path.expanduser(root)
    directories = list(filter((lambda p: os.path.isdir(os.path.join(root, p))), os.listdir(root)))
    if (prefix is True):
        directories = [os.path.join(root, d) for d in directories]
    return directories

List all directories at a given root

Args:
root (str): Path to directory whose folders need to be listed
prefix (bool, optional): If true, prepends the path to each result, otherwise
only returns the name of the directories found


def create_assembly_instance(self, assembly_uri, part_uri, configuration):

        payload = {
          "documentId": part_uri["did"],
          "elementId": part_uri["eid"],

          "versionId": part_uri["wvm"],

          "isAssembly": False,
          "isWholePartStudio": True,
          "configuration": self.encode_configuration(part_uri["did"], part_uri["eid"], configuration)
        }
        return self._api.request('post', '/api/assemblies/d/' + assembly_uri["did"] + '/' + assembly_uri["wvm_type"] +
                                 '/' + assembly_uri["wvm"] + '/e/' + assembly_uri["eid"] + '/instances', body=payload)

Insert a configurable part into an assembly.

Args:
- assembly (dict): eid, wid, and did of the assembly into which will be inserted
- part (dict): eid and did of the configurable part
- configuration (dict): the configuration

Returns:
- requests.Response: Onshape response data


def save_wav_file(filename, wav_data, sample_rate):
    with tf.compat.v1.Session(graph=tf.Graph()) as sess:
        wav_filename_placeholder = tf.compat.v1.placeholder(tf.string, [])
        sample_rate_placeholder = tf.compat.v1.placeholder(tf.int32, [])
        wav_data_placeholder = tf.compat.v1.placeholder(tf.float32, [None, 1])
        wav_encoder = tf.audio.encode_wav(wav_data_placeholder, sample_rate_placeholder)
        wav_saver = io_ops.write_file(wav_filename_placeholder, wav_encoder)
        sess.run(wav_saver, feed_dict={wav_filename_placeholder: filename, sample_rate_placeholder: sample_rate, wav_data_placeholder: np.reshape(wav_data, (-1, 1))})

Saves audio sample data to a .wav audio file.

Args:
filename: Path to save the file to.
wav_data: 2D array of float PCM-encoded audio data.
sample_rate: Samples per second to encode in the file.


def autodiff_tree(func, wrt, motion, mode, preserve_result, check_dims, verbose):
    import tangent
    namespace = {'tangent': tangent, 'numpy': numpy}
    done = set()
    final = gast.Module(body=[])
    namespace.update(six.get_function_globals(func))
    (node, required) = autodiff_ast(func, wrt, motion, mode, preserve_result, check_dims, verbose)
    final.body.extend(node.body)
    to_do = set(required)
    if ((motion == 'split') and (mode == 'reverse')):
        done.add((func, wrt))
        to_do -= done
    while to_do:
        (func, wrt) = to_do.pop()
        namespace.update(six.get_function_globals(func))
        (node, required) = autodiff_ast(func=func, wrt=wrt, motion='split', mode=mode, preserve_result=True, check_dims=False, verbose=verbose)
        final.body.extend(node.body)
        done.add((func, wrt))
        to_do.update(required)
        to_do -= done
    return (final, namespace)

Perform AD on all functions in a call tree.

This function walks the call tree and differentiates each function in it. It
also ensures that the global namespaces that each function in the call tree
was in are merged.

The `tangent` and `numpy` packages are added to the namespace here, so that
the gradient templates can assume that they are present.

Args:
See `grad`.

Returns:
final: A single module which contains the primals and adjoints of all the
functions in the call tree.
namespace: A merged dictionary with all the variables in the global
namespaces of each function. The primals and adjoints need access to
these in order to execute.


def _translate(pattern, case_sensitive=True):
    if (not case_sensitive):
        pattern = pattern.lower()
    (i, n) = (0, len(pattern))
    res = ''
    while (i < n):
        c = pattern[i]
        i = (i + 1)
        if (c == '*'):
            res = (res + '[^/]*')
        elif (c == '?'):
            res = (res + '.')
        elif (c == '['):
            j = i
            if ((j < n) and (pattern[j] == '!')):
                j = (j + 1)
            if ((j < n) and (pattern[j] == ']')):
                j = (j + 1)
            while ((j < n) and (pattern[j] != ']')):
                j = (j + 1)
            if (j >= n):
                res = (res + '\\[')
            else:
                stuff = pattern[i:j].replace('\\', '\\\\')
                i = (j + 1)
                if (stuff[0] == '!'):
                    stuff = ('^' + stuff[1:])
                elif (stuff[0] == '^'):
                    stuff = ('\\' + stuff)
                res = ('%s[%s]' % (res, stuff))
        else:
            res = (res + re.escape(c))
    return res

Translate a wildcard pattern to a regular expression.

There is no way to quote meta-characters.

Arguments:
pattern (str): A wildcard pattern.
case_sensitive (bool): Set to `False` to use a case
insensitive regex (default `True`).

Returns:
str: A regex equivalent to the given pattern.


def snapshot(self, wiki=False, streamed=False, action=None, chunk_size=1024, **kwargs):
    path = ('/projects/%s/snapshot' % self.get_id())
    result = self.manager.gitlab.http_get(path, streamed=streamed, raw=True, **kwargs)
    return utils.response_content(result, streamed, action, chunk_size)

Return a snapshot of the repository.

Args:
wiki (bool): If True return the wiki repository
streamed (bool): If True the data will be processed by chunks of
`chunk_size` and each chunk is passed to `action` for
treatment.
action (callable): Callable responsible of dealing with chunk of
data
chunk_size (int): Size of each chunk
**kwargs: Extra options to send to the server (e.g. sudo)

Raises:
GitlabAuthenticationError: If authentication is not correct
GitlabGetError: If the content could not be retrieved

Returns:
str: The uncompressed tar archive of the repository


class DPTPreActResidualLayer(nn.Module):

    def __init__(self, config):
        super().__init__()
        self.use_batch_norm = config.use_batch_norm_in_fusion_residual
        use_bias_in_fusion_residual = config.use_bias_in_fusion_residual if config.use_bias_in_fusion_residual is not None else not self.use_batch_norm
        self.activation1 = nn.ReLU()
        self.convolution1 = nn.Conv2d(config.fusion_hidden_size, config.fusion_hidden_size, kernel_size=3, stride=1, padding=1, bias=use_bias_in_fusion_residual)
        self.activation2 = nn.ReLU()
        self.convolution2 = nn.Conv2d(config.fusion_hidden_size, config.fusion_hidden_size, kernel_size=3, stride=1, padding=1, bias=use_bias_in_fusion_residual)
        if self.use_batch_norm:
            self.batch_norm1 = nn.BatchNorm2d(config.fusion_hidden_size)
            self.batch_norm2 = nn.BatchNorm2d(config.fusion_hidden_size)

    def forward(self, hidden_state: torch.Tensor) -> torch.Tensor:
        residual = hidden_state
        hidden_state = self.activation1(hidden_state)
        hidden_state = self.convolution1(hidden_state)
        if self.use_batch_norm:
            hidden_state = self.batch_norm1(hidden_state)
        hidden_state = self.activation2(hidden_state)
        hidden_state = self.convolution2(hidden_state)
        if self.use_batch_norm:
            hidden_state = self.batch_norm2(hidden_state)
        return hidden_state + residual

ResidualConvUnit, pre-activate residual unit.

Args:
config (`[DPTConfig]`):
Model configuration class defining the model architecture.


def _FormatPropertyName(self, property_name):
    fix_key = re.sub('(.)([A-Z][a-z]+)', '\\1_\\2', property_name)
    return re.sub('([a-z0-9])([A-Z])', '\\1_\\2', fix_key).lower()

Formats a camel case property name as snake case.

Args:
property_name (str): property name in camel case.

Returns:
str: property name in snake case.


def wait_for_js(function):

    @functools.wraps(function)
    def wrapper(*args, **kwargs):

        if len(args) < 1:
            return function(*args, **kwargs)

        else:
            self = args[0]

            if hasattr(self, 'wait_for_js'):
                self.wait_for_js()

            return function(*args, **kwargs)

    return wrapper

Method decorator that waits for JavaScript dependencies before executing `function`.
If the function is not a method, the decorator has no effect.

Args:
function (callable): Method to decorate.

Returns:
Decorated method


def AddKeywordsForName(self, name, keywords):

    data_store.DB.IndexAddKeywordsForName(self.urn, name, keywords)

Associates keywords with name.

Records that keywords are associated with name.

Args:
name: A name which should be associated with some keywords.
keywords: A collection of keywords to associate with name.


def IsErrorSuppressedByNolint(category, linenum):

  return (linenum in _error_suppressions.get(category, set()) or
          linenum in _error_suppressions.get(None, set()))

Returns true if the specified error category is suppressed on this line.

Consults the global error_suppressions map populated by
ParseNolintSuppressions/ResetNolintSuppressions.

Args:
category: str, the category of the error.
linenum: int, the current line number.
Returns:
bool, True iff the error should be suppressed due to a NOLINT comment.


def load_ini(self, ini_file):
    if (ini_file and (not os.path.exists(ini_file))):
        self.log.critical(f'Settings file specified but not found. {ini_file}')
        sys.exit(1)
    if (not ini_file):
        ini_file = f'{self.cwd}/settings.ini'
    if os.path.exists(ini_file):
        config = configparser.RawConfigParser(allow_no_value=True)
        config.read(ini_file)
        for (key, value) in self.spec.items():
            entry = None
            if (value['type'] == str):
                entry = config.get('settings', option=key.lower(), fallback=None)
            elif (value['type'] == bool):
                entry = config.getboolean('settings', option=key.lower(), fallback=None)
            elif (value['type'] == int):
                entry = config.getint('settings', option=key.lower(), fallback=None)
            elif (value['type'] == float):
                entry = config.getfloat('settings', option=key.lower(), fallback=None)
            elif (value['type'] in [list, dict]):
                entries = config.get('settings', option=key.lower(), fallback=None)
                if entries:
                    try:
                        entry = json.loads(entries)
                    except json.decoder.JSONDecodeError as _err:
                        self.log.critical(f'Error parsing json from ini file. {entries}')
                        sys.exit(1)
            if (entry is not None):
                setattr(self, key.upper(), entry)

Load the contents from the ini file

Args:
ini_file (str): The file from which the settings should be loaded


def ProduceEventWithEventData(self, event, event_data):

    if event.timestamp is None:
      raise errors.InvalidEvent('Event timestamp value not set.')

    if event.timestamp < self._INT64_MIN or event.timestamp > self._INT64_MAX:
      raise errors.InvalidEvent('Event timestamp value out of bounds.')

    event_data_hash = event_data.GetAttributeValuesHash()
    if event_data_hash != self._last_event_data_hash:

      event_data = copy.deepcopy(event_data)

      self.ProcessEvent(
          event_data, parser_chain=self.GetParserChain(),
          file_entry=self._file_entry)

      self._storage_writer.AddEventData(event_data)

      self._last_event_data_hash = event_data_hash
      self._last_event_data_identifier = event_data.GetIdentifier()

    if self._last_event_data_identifier:
      event.SetEventDataIdentifier(self._last_event_data_identifier)

    event.parser = self.GetParserChain()

    self._storage_writer.AddEvent(event)
    self._number_of_events += 1

    self.last_activity_timestamp = time.time()

Produces an event.

Args:
event (EventObject): event.
event_data (EventData): event data.

Raises:
InvalidEvent: if the event timestamp value is not set or out of bounds.


def _create_slots(self, var_list):
    pass

Create all slots needed by the variables.

Args:
var_list: A list of `Variable` objects.


def decode(image, symbols=None):

    pixels, width, height = _pixel_data(image)

    results = []
    with _image_scanner() as scanner:
        if symbols:

            disable = set(ZBarSymbol).difference(symbols)
            for symbol in disable:
                zbar_image_scanner_set_config(
                    scanner, symbol, ZBarConfig.CFG_ENABLE, 0
                )

            for symbol in symbols:
                zbar_image_scanner_set_config(
                    scanner, symbol, ZBarConfig.CFG_ENABLE, 1
                )
        with _image() as img:
            zbar_image_set_format(img, _FOURCC['L800'])
            zbar_image_set_size(img, width, height)
            zbar_image_set_data(img, cast(pixels, c_void_p), len(pixels), None)
            decoded = zbar_scan_image(scanner, img)
            if decoded < 0:
                raise PyZbarError('Unsupported image format')
            else:
                results.extend(_decode_symbols(_symbols_for_image(img)))

    return results

Decodes datamatrix barcodes in `image`.

Args:
image: `numpy.ndarray`, `PIL.Image` or tuple (pixels, width, height)
symbols: iter(ZBarSymbol) the symbol types to decode; if `None`, uses
`zbar`'s default behaviour, which is to decode all symbol types.

Returns:
:obj:`list` of :obj:`Decoded`: The values decoded from barcodes.


def is_tracking_shield_displayed(self):
    with self.selenium.context(self.selenium.CONTEXT_CHROME):
        if (self.window.firefox_version >= 63):
            el = self.root.find_element(*self._tracking_protection_shield_locator)
            return (el.get_attribute('active') is not None)
        el = self.root.find_element(By.ID, 'tracking-protection-icon')
        return bool(el.get_attribute('state'))

Tracking Protection shield.

Returns:
bool: True or False if the Tracking Shield is displayed.


def stack50(op, delay):
    n = 50
    delays = delay + tf.range(0, n, dtype=float) / 10000.0
    start_t = time.time()
    func = tf.function(lambda: tf.stack([op(delays[i]) for i in range(n)]))
    r_numpy = func().numpy()
    end_t = time.time()
    print('')
    print('Total time = %5.3f seconds using %s' % (end_t - start_t, str(op)))
    print('Returned values from the ops:')
    np.set_printoptions(precision=4, suppress=True)
    print(r_numpy)
    sys.stdout.flush()

Create a tf.stack of 50 sleep ops.

Args:
op: The sleep op, either sleep_op.SyncSleep or sleep_op.AsyncSleep.
delay: Each op should finish at least float `delay` seconds after it starts.


def generate(self, past_values: torch.Tensor) -> SamplePatchTSMixerRegressionOutput:
    num_parallel_samples = self.num_parallel_samples
    outputs = self(past_values=past_values, target_values=None, output_hidden_states=False)
    distribution = self.distribution_output.distribution(outputs.regression_outputs)
    samples = [distribution.sample() for _ in range(num_parallel_samples)]
    samples = torch.stack(samples, dim=1).view(-1, num_parallel_samples, self.config.num_targets)
    return SamplePatchTSMixerRegressionOutput(sequences=samples)

Generate sequences of sample predictions from a model with a probability distribution head.

Args:
past_values (`torch.FloatTensor` of shape `(batch_size, sequence_length, num_input_channels)`):
Past values of the time series that serves as context in order to predict the target values.

Return:
[`SamplePatchTSMixerRegressionOutput`] where the outputs `sequences` tensor will have shape `(batch_size,
number of samples, num_targets)`.


def is_subtype_of(self, other: trace.TraceType) -> bool:
    if type(self) is not type(other):
        return False
    is_subtype = True

    def check_attribute(attribute_self, attribute_other):
        nonlocal is_subtype
        if not is_subtype:
            return
        if isinstance(attribute_self, trace.TraceType):
            if not attribute_self.is_subtype_of(attribute_other):
                is_subtype = False
                return
        elif attribute_self != attribute_other:
            is_subtype = False
    try:
        nest.map_structure(check_attribute, self._serialize(), other._serialize())
    except (ValueError, TypeError):
        return False
    return is_subtype

Returns True if `self` is a subtype of `other`.

Implements the tf.types.experimental.func.TraceType interface.

If not overridden by a subclass, the default behavior is to assume the
TypeSpec is covariant upon attributes that implement TraceType and
invariant upon rest of the attributes as well as the structure and type
of the TypeSpec.

Args:
other: A TraceType object.


def inquire_property(name, doc=None):

    def inquire_property(self):
        if (not self._started):
            msg = 'Cannot read {0} from a security context whose establishment has not yet been started.'
            raise AttributeError(msg)
        return getattr(self._inquire(**{name: True}), name)
    return property(inquire_property, doc=doc)

Creates a property based on an inquire result

This method creates a property that calls the
:python:`_inquire` method, and return the value of the
requested information.

Args:
name (str): the name of the 'inquire' result information

Returns:
property: the created property


def fit2dArrayToFn(arr, fn, mask=None, down_scale_factor=None, output_shape=None, guess=None, outgrid=None):
    if (mask is None):
        mask = np.ones(shape=arr.shape, dtype=bool)
    if (down_scale_factor is None):
        if (mask.sum() > 1000):
            down_scale_factor = 0.3
        else:
            down_scale_factor = 1
    if (down_scale_factor != 1):
        arr2 = zoom(arr, down_scale_factor)
        mask = zoom(mask, down_scale_factor, output=bool)
    else:
        arr2 = arr
    (x, y) = np.where(mask)
    z = arr2[mask]
    (parameters, cov_matrix) = curve_fit(fn, (x, y), z, p0=guess)
    perr = np.sqrt(np.diag(cov_matrix))
    if (outgrid is not None):
        (yy, xx) = outgrid
        rebuilt = fn((yy, xx), *parameters)
    else:
        if (output_shape is None):
            output_shape = arr.shape
        fx = (arr2.shape[0] / output_shape[0])
        fy = (arr2.shape[1] / output_shape[1])
        rebuilt = np.fromfunction((lambda x, y: fn(((x * fx), (y * fy)), *parameters)), output_shape)
    return (rebuilt, parameters, perr)

Fit a 2d array to a 2d function

USE ONLY MASKED VALUES

* [down_scale_factor] map to speed up fitting procedure, set value smaller than 1
* [output_shape] shape of the output array
* [guess] must be scaled using [scale_factor]

Returns:
Fitted map, fitting params (scaled), error


def annotations_from_file(filename):
    import edflib
    e = edflib.EdfReader(filename, annotations_mode='all')
    return e.read_annotations()

Get a list of event annotations from an EDF (European Data Format file
or EDF+ file, using edflib.

Args:
filename: EDF+ file

Returns:
list: annotation events, each in the form [start_time, duration, text]


def get_missing_services(self, services):
    required_services = set(services)
    provided_services = set(self._services.keys())
    missing_services = required_services.difference(provided_services)
    return sorted(missing_services)

Check if all required services are provided

Args:
services: List with the service names which are required
Returns:
List with missing services


def new(cls, access_token, environment='prod'):

        api_client = ApiClient.new(access_token, environment)
        return cls(api_client)

Create new storage service client.

Arguments:
environment(str): The service environment to be used for the client.
'prod' or 'dev'.
access_token(str): The access token used to authenticate with the
service

Returns:
A storage_service.Client instance


def from_tokenizer(cls, tokenizer: GPT2Tokenizer, *args, **kwargs):
    merges = [' '.join(m) for m in tokenizer.bpe_ranks.keys()]
    vocab = tokenizer.get_vocab()
    return cls(vocab, merges, *args, **kwargs)

Creates TFGPT2Tokenizer from GPT2Tokenizer

Args:
tokenizer (GPT2Tokenizer)

Examples:

```python
from transformers import AutoTokenizer, TFGPT2Tokenizer

tokenizer = AutoTokenizer.from_pretrained("openai-community/gpt2")
tf_tokenizer = TFGPT2Tokenizer.from_tokenizer(tokenizer)
```


def notify(self, cuuid, event_data):
    euuid = str(uuid.uuid1())
    if ('encryption' in self.registry[cuuid]):
        client_key = self.registry[cuuid]['encryption']
    else:
        client_key = None
    logger.debug(('<%s> <%s> Sending NOTIFY event to client with event data: %s' % (str(cuuid), str(euuid), pformat(event_data))))
    try:
        ip_address = self.registry[cuuid]['host']
    except KeyError:
        logger.warning(('<%s> <%s> Host not found in registry! Transmit Canceled' % (str(cuuid), str(euuid))))
        return False
    try:
        port = self.registry[cuuid]['port']
    except KeyError:
        logger.warning(('<%s> <%s> Port not found! Transmit Canceled' % (str(cuuid), str(euuid))))
        return False
    packet = serialize_data({'method': 'NOTIFY', 'event_data': event_data, 'euuid': euuid}, self.compression, self.encryption, client_key)
    address = (ip_address, port)
    self.event_uuids[euuid] = 0
    logger.debug(('<%s> Currently processing events: %s' % (cuuid, pformat(self.event_uuids))))
    logger.debug(('<%s> New NOTIFY event being processed:' % cuuid))
    logger.debug(('<%s> EUUID: %s' % (cuuid, euuid)))
    logger.debug(('<%s> Event Data: %s' % (cuuid, pformat(event_data))))
    self.listener.send_datagram(packet, address)
    self.listener.call_later(self.timeout, self.retransmit, {'euuid': euuid, 'response': packet, 'cuuid': cuuid})

This function will send a NOTIFY event to a registered client.

NOTIFY messages are nearly identical to EVENT messages, except that
NOTIFY messages are always sent from server -> client. EVENT messages
are always sent from client -> server. In addition to this difference,
NOTIFY messages are not processed by a middleware to determine if
they are legal or not, since all messages from the server should be
considered LEGAL.

Args:
cuuid (string): The client uuid to send the event data to.
event_data (any): The event data that we will be sending to the
client.

Returns:
None


def _parse_trunk_groups(self, config):
    values = re.findall('switchport trunk group ([^\\s]+)', config, re.M)
    return dict(trunk_groups=values)

Scans the specified config and parses the trunk group values

Args:
config (str): The interface configuraiton blcok

Returns:
A dict object with the trunk group values that can be merged
into the resource dict


def PauliX(local_space, states=None):
    (local_space, states) = _get_pauli_args(local_space, states)
    (g, e) = states
    return (LocalSigma.create(g, e, hs=local_space) + LocalSigma.create(e, g, hs=local_space))

r"""Pauli-type X-operator

.. math::

\hat{\sigma}_x = \begin{pmatrix}
0 & 1 \\
1 & 0
\end{pmatrix}

on an arbitrary two-level system.

Args:
local_space (str or int or .LocalSpace): Associated Hilbert space.
If :class:`str` or :class:`int`, a :class:`LocalSpace` with a
matching label will be created.
states (None or tuple[int or str]): The labels for the basis states
for the two levels on which the operator acts. If None, the two
lowest levels are used.

Returns:
Operator: Local X-operator as a linear combination of
:class:`LocalSigma`


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

    if file_object is not None and compression_method is None:
      raise ValueError(
          'File-like object provided without corresponding compression '
          'method.')

    super(CompressedStream, self).__init__(resolver_context)
    self._compression_method = compression_method
    self._file_object = file_object
    self._file_object_set_in_init = bool(file_object)
    self._compressed_data = b''
    self._current_offset = 0
    self._decompressor = None
    self._realign_offset = True
    self._uncompressed_data = b''
    self._uncompressed_data_offset = 0
    self._uncompressed_data_size = 0
    self._uncompressed_stream_size = None

Initializes a file-like object.

If the file-like object is chained do not separately use the parent
file-like object.

Args:
resolver_context (Context): resolver context.
compression_method (Optional[str]): method used to the compress the data.
file_object (Optional[file]): parent file-like object.

Raises:
ValueError: if file_object provided but compression_method is not.


def register_test_preprocessor(cls, test_names: Union[str, List]):
    if isinstance(test_names, str):
        test_names = [test_names]

    def apply(preprocessor):
        for test_name in test_names:
            if test_name not in cls._test_preprocessor:
                cls._test_preprocessor[test_name] = []
            cls._test_preprocessor[test_name].append(preprocessor)
        return preprocessor
    return apply

Decorator to register a preprocessor function for specific tests.

This decorator is used to associate a preprocessor function with one or
more test names. The preprocessor function will be called before the
corresponding test is executed, allowing for modification of the test
specification or environment setup.

Args:
test_names: A string or a list of strings representing the names of the
tests for which the preprocessor should be registered. The test names
should match the names generated by `parse_test_methods`.

Returns:
A decorator function that takes the preprocessor function as an argument
and registers it.


def __init__(self, num_classes=1000):

        super(Xception, self).__init__()
        self.num_classes = num_classes

        self.conv1 = nn.Conv2d(3, 32, 3,2, 0, bias=False)
        self.bn1 = nn.BatchNorm2d(32)
        self.relu1 = nn.ReLU(inplace=True)

        self.conv2 = nn.Conv2d(32,64,3,bias=False)
        self.bn2 = nn.BatchNorm2d(64)
        self.relu2 = nn.ReLU(inplace=True)

        self.block1=Block(64,128,2,2,start_with_relu=False,grow_first=True)
        self.block2=Block(128,256,2,2,start_with_relu=True,grow_first=True)
        self.block3=Block(256,728,2,2,start_with_relu=True,grow_first=True)

        self.block4=Block(728,728,3,1,start_with_relu=True,grow_first=True)
        self.block5=Block(728,728,3,1,start_with_relu=True,grow_first=True)
        self.block6=Block(728,728,3,1,start_with_relu=True,grow_first=True)
        self.block7=Block(728,728,3,1,start_with_relu=True,grow_first=True)

        self.block8=Block(728,728,3,1,start_with_relu=True,grow_first=True)
        self.block9=Block(728,728,3,1,start_with_relu=True,grow_first=True)
        self.block10=Block(728,728,3,1,start_with_relu=True,grow_first=True)
        self.block11=Block(728,728,3,1,start_with_relu=True,grow_first=True)

        self.block12=Block(728,1024,2,2,start_with_relu=True,grow_first=False)

        self.conv3 = SeparableConv2d(1024,1536,3,1,1)
        self.bn3 = nn.BatchNorm2d(1536)
        self.relu3 = nn.ReLU(inplace=True)

        self.conv4 = SeparableConv2d(1536,2048,3,1,1)
        self.bn4 = nn.BatchNorm2d(2048)

        self.fc = nn.Linear(2048, num_classes)

Constructor
Args:
num_classes: number of classes


def __setitem__(self, predicates, new_value):

        if self.df is not None and self.column_name is not None:
            self.df[self.column_name] = self.mask(predicates, new_value)

Summary

Args:
predicates (TYPE): Description
new_value (TYPE): Description

Returns:
TYPE: Description


def put(self, filename, encoding=None):

        from . import LocalFile

        if os.path.isdir(filename) and self.source is None:
            raise ValueError("Cannot write this object to "
                             "directory %s without an explicit filename." % filename)

        target = get_target_path(filename, self.source)

        if (encoding is not None) and (encoding != self.encoded_with):
            raise ValueError('%s is already encoded as "%s"' % self, self.encoded_with)

        with self.open('rb') as infile, open(target, 'wb') as outfile:
            for line in infile:
                outfile.write(line)
        return LocalFile(target)

Write the file to the given path

Args:
filename(str): path to write this file to

Returns:
LocalFile: reference to the copy of the file stored at ``filename``


def __init__(self, min_interval_sec=10, max_interval_sec=600, multiplier=2):

    self.min_interval_sec = min_interval_sec
    self.max_interval_sec = max_interval_sec
    self.multiplier = multiplier
    self.Succeeded()

Class constructor.

Args:
min_interval_sec: initial small delay.
max_interval_sec: maximum delay between retries.
multiplier: factor for exponential increase.


def read_from_hdx(identifier, configuration=None):
    resourceview = ResourceView(configuration=configuration)
    result = resourceview._load_from_hdx('resource view', identifier)
    if result:
        return resourceview
    return None

Reads the resource view given by identifier from HDX and returns ResourceView object

Args:
identifier (str): Identifier of resource view
configuration (Optional[Configuration]): HDX configuration. Defaults to global configuration.

Returns:
Optional[ResourceView]: ResourceView object if successful read, None if not


def _RetryLoop(self, func, timeout=None):

    timeout = timeout or self.DEFAULT_TIMEOUT
    deadline = time.time() + timeout
    sleep = 1
    while True:
      try:
        return func(timeout)
      except grpc.RpcError:
        if time.time() + sleep > deadline:
          raise
        time.sleep(sleep)
        sleep *= 2
        timeout = deadline - time.time()

Retries an operation until success or deadline.

Args:

func: The function to run. Must take a timeout, in seconds, as a single
parameter. If it raises grpc.RpcError and deadline has not be reached,
it will be run again.

timeout: Retries will continue until timeout seconds have passed.


async def _on_event(self, event_):
    conv_id = event_.conversation_id.id
    try:
        conv = (await self._get_or_fetch_conversation(conv_id))
    except exceptions.NetworkError:
        logger.warning('Failed to fetch conversation for event notification: %s', conv_id)
    else:
        self._sync_timestamp = parsers.from_timestamp(event_.timestamp)
        conv_event = conv.add_event(event_)
        if (conv_event is not None):
            (await self.on_event.fire(conv_event))
            (await conv.on_event.fire(conv_event))

Receive a hangouts_pb2.Event and fan out to Conversations.

Args:
event_: hangouts_pb2.Event instance


def clone(self, data=None, shared_data=True, new_type=None, *args, **overrides):

        if 'datatype' not in overrides:
            datatypes = [self.interface.datatype] + self.datatype
            overrides['datatype'] = list(util.unique_iterator(datatypes))
        return super(Dataset, self).clone(data, shared_data, new_type, *args, **overrides)

Clones the object, overriding data and parameters.

Args:
data: New data replacing the existing data
shared_data (bool, optional): Whether to use existing data
new_type (optional): Type to cast object to
*args: Additional arguments to pass to constructor
**overrides: New keyword arguments to pass to constructor

Returns:
Cloned object


def get_electron_number(self, charge=0):
    atomic_number = constants.elements['atomic_number'].to_dict()
    return (sum([atomic_number[atom] for atom in self['atom']]) - charge)

Return the number of electrons.

Args:
charge (int): Charge of the molecule.

Returns:
int:


def __init__(self, file_entry):

    super(VShadowVolume, self).__init__(file_entry.name)
    self._file_entry = file_entry

Initializes a volume.

Args:
file_entry (VShadowFileEntry): a VSS file entry.


def check_status(status, expected, path, headers=None, resp_headers=None, body=None, extras=None):
    if (status in expected):
        return
    msg = ('Expect status %r from Google Storage. But got status %d.\nPath: %r.\nRequest headers: %r.\nResponse headers: %r.\nBody: %r.\nExtra info: %r.\n' % (expected, status, path, headers, resp_headers, body, extras))
    if (status == httplib.UNAUTHORIZED):
        raise AuthorizationError(msg)
    elif (status == httplib.FORBIDDEN):
        raise ForbiddenError(msg)
    elif (status == httplib.NOT_FOUND):
        raise NotFoundError(msg)
    elif (status == httplib.REQUEST_TIMEOUT):
        raise TimeoutError(msg)
    elif (status == httplib.REQUESTED_RANGE_NOT_SATISFIABLE):
        raise InvalidRange(msg)
    elif ((status == httplib.OK) and (308 in expected) and (httplib.OK not in expected)):
        raise FileClosedError(msg)
    elif (status >= 500):
        raise ServerError(msg)
    else:
        raise FatalError(msg)

Check HTTP response status is expected.

Args:
status: HTTP response status. int.
expected: a list of expected statuses. A list of ints.
path: filename or a path prefix.
headers: HTTP request headers.
resp_headers: HTTP response headers.
body: HTTP response body.
extras: extra info to be logged verbatim if error occurs.

Raises:
AuthorizationError: if authorization failed.
NotFoundError: if an object that's expected to exist doesn't.
TimeoutError: if HTTP request timed out.
ServerError: if server experienced some errors.
FatalError: if any other unexpected errors occurred.


def get_paths(self, key):
    final_paths = []
    if (key in self.__cli):
        paths = (self.__cli[key] or [])
        from_conf = False
    else:
        paths = (self.__config.get(key) or [])
        from_conf = True
    for path in flatten_list(paths):
        final_path = self.__abspath(path, from_conf)
        if final_path:
            final_paths.append(final_path)
    return final_paths

Same as `ConfigParser.get_path` for a list of paths.

Args:
key: str, the key to lookup the paths with

Returns:
list: The paths.


def candidates(self, word):

        if self.known([word]):
            return {word}

        res = [x for x in self.edit_distance_1(word)]
        tmp = self.known(res)
        if tmp:
            return tmp

        if self._distance == 2:
            tmp = self.known([x for x in self.__edit_distance_alt(res)])
            if tmp:
                return tmp
        return {word}

Generate possible spelling corrections for the provided word up to
an edit distance of two, if and only when needed

Args:
word (str): The word for which to calculate candidate spellings
Returns:
set: The set of words that are possible candidates


def throw(self, exception_class, should_throw):

        return self.__copy_and_set('throws', self._throws + [(exception_class, should_throw)])

Defines if the an exception should be thrown after the request is sent

Args:
exception_class (class): The class of the exception to instantiate
should_throw (function): The predicate that should indicate if the exception
should be thrown. This function will be called with the response as a parameter

Returns:
The request builder instance in order to chain calls


def gcs(line, cell=None):

  parser = google.datalab.utils.commands.CommandParser(prog='%gcs', description=)

  copy_parser = parser.subcommand('copy', 'Copy one or more Google Cloud Storage objects to a '
                                          'different location.')
  copy_parser.add_argument('-s', '--source', help='The name of the object(s) to copy', nargs='+')
  copy_parser.add_argument('-d', '--destination', required=True,
                           help='The copy destination. For multiple source objects this must be a '
                                'bucket.')
  copy_parser.set_defaults(func=_gcs_copy)

  create_parser = parser.subcommand('create', 'Create one or more Google Cloud Storage buckets.')
  create_parser.add_argument('-p', '--project', help='The project associated with the objects')
  create_parser.add_argument('-b', '--bucket', help='The name of the bucket(s) to create',
                             nargs='+')
  create_parser.set_defaults(func=_gcs_create)

  delete_parser = parser.subcommand('delete', 'Delete one or more Google Cloud Storage buckets or '
                                              'objects.')
  delete_parser.add_argument('-b', '--bucket', nargs='*',
                             help='The name of the bucket(s) to remove')
  delete_parser.add_argument('-o', '--object', nargs='*',
                             help='The name of the object(s) to remove')
  delete_parser.set_defaults(func=_gcs_delete)

  list_parser = parser.subcommand('list', 'List buckets in a project, or contents of a bucket.')
  list_parser.add_argument('-p', '--project', help='The project associated with the objects')
  list_parser.add_argument('-o', '--objects',
                           help='List objects under the given Google Cloud Storage path',
                           nargs='?')
  list_parser.set_defaults(func=_gcs_list)

  read_parser = parser.subcommand('read', 'Read the contents of a Google Cloud Storage object into '
                                          'a Python variable.')
  read_parser.add_argument('-o', '--object', help='The name of the object to read',
                           required=True)
  read_parser.add_argument('-v', '--variable', required=True,
                           help='The name of the Python variable to set')
  read_parser.set_defaults(func=_gcs_read)

  view_parser = parser.subcommand('view', 'View the contents of a Google Cloud Storage object.')
  view_parser.add_argument('-n', '--head', type=int, default=20,
                           help='The number of initial lines to view')
  view_parser.add_argument('-t', '--tail', type=int, default=20,
                           help='The number of lines from end to view')
  view_parser.add_argument('-o', '--object', help='The name of the object to view',
                           required=True)
  view_parser.set_defaults(func=_gcs_view)

  write_parser = parser.subcommand('write', 'Write the value of a Python variable to a Google '
                                            'Cloud Storage object.')
  write_parser.add_argument('-v', '--variable', help='The name of the source Python variable',
                            required=True)
  write_parser.add_argument('-o', '--object', required=True,
                            help='The name of the destination Google Cloud Storage object to write')
  write_parser.add_argument('-c', '--content_type', help='MIME type', default='text/plain')
  write_parser.set_defaults(func=_gcs_write)

  return google.datalab.utils.commands.handle_magic_line(line, cell, parser)

Implements the gcs cell magic for ipython notebooks.

Args:
line: the contents of the gcs line.
Returns:
The results of executing the cell.


def ParseVideoRow(self, parser_mediator, query, row, **unused_kwargs):

    query_hash = hash(query)

    event_data = KodiVideoEventData()
    event_data.filename = self._GetRowValue(query_hash, row, 'strFilename')
    event_data.play_count = self._GetRowValue(query_hash, row, 'playCount')
    event_data.query = query

    timestamp = self._GetRowValue(query_hash, row, 'lastPlayed')
    date_time = dfdatetime_time_elements.TimeElements()
    date_time.CopyFromDateTimeString(timestamp)
    event = time_events.DateTimeValuesEvent(
        date_time, definitions.TIME_DESCRIPTION_LAST_VISITED)
    parser_mediator.ProduceEventWithEventData(event, event_data)

Parses a Video row.

Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
query (str): query that created the row.
row (sqlite3.Row): row.


def _GetArgDefault(flag, spec):
    num_defaults = len(spec.defaults)
    args_with_defaults = spec.args[-num_defaults:]
    for arg, default in zip(args_with_defaults, spec.defaults):
        if arg == flag:
            return repr(default)
    if flag in spec.kwonlydefaults:
        return repr(spec.kwonlydefaults[flag])
    return ''

Returns a string describing a flag's default value.

Args:
flag: The name of the flag.
spec: An instance of fire.inspectutils.FullArgSpec, containing type and
default information about the arguments to a callable.
Returns:
A string to be used in constructing the help screen for the function, the
empty string if the flag does not have a default or the default is not
available.


def GlobForPaths(self, paths, pathtype='OS', root_path=None, process_non_regular_files=False, collect_ext_attrs=False):
    patterns = []
    if (not paths):
        return
    self.state.pathtype = pathtype
    self.state.root_path = root_path
    self.state.process_non_regular_files = process_non_regular_files
    self.state.collect_ext_attrs = collect_ext_attrs
    for path in paths:
        patterns.extend(path.Interpolate(knowledge_base=self.client_knowledge_base))
    patterns.sort(key=len, reverse=True)
    for pattern in patterns:
        curr_node = self.state.component_tree
        components = self.ConvertGlobIntoPathComponents(pattern)
        for (i, curr_component) in enumerate(components):
            is_last_component = (i == (len(components) - 1))
            next_node = curr_node.get(curr_component.SerializeToString(), {})
            if (is_last_component and next_node):
                curr_node[curr_component.SerializeToString()] = {}
            else:
                curr_node = curr_node.setdefault(curr_component.SerializeToString(), {})
    root_path = next(iterkeys(self.state.component_tree))
    self.CallStateInline(messages=[None], next_state='ProcessEntry', request_data=dict(component_path=[root_path]))

Starts the Glob.

This is the main entry point for this flow mixin.

First we convert the pattern into regex components, and then we
interpolate each component. Finally, we generate a cartesian product of all
combinations.

Args:
paths: A list of GlobExpression instances.
pathtype: The pathtype to use for creating pathspecs.
root_path: A pathspec where to start searching from.
process_non_regular_files: Work with all kinds of files - not only with
regular ones.
collect_ext_attrs: Whether to gather information about file extended
attributes.


def NgramScorer(frequency_map):

    length = len(next(iter(frequency_map)))

    floor = math.log10(0.01 / sum(frequency_map.values()))
    ngrams = frequency.frequency_to_probability(frequency_map, decorator=math.log10)

    def inner(text):

        text = ''.join(text)
        text = remove(text.upper(), string.whitespace + string.punctuation)
        return sum(ngrams.get(ngram, floor) for ngram in iterate_ngrams(text, length))

    return inner

Compute the score of a text by using the frequencies of ngrams.

Example:
>>> fitness = NgramScorer(english.unigrams)
>>> fitness("ABC")
-4.3622319742618245

Args:
frequency_map (dict): ngram to frequency mapping


def is_torch_support_available(self) -> bool:
    if is_torch_available():
        from transformers.utils import get_torch_version
        return version.parse(get_torch_version()) >= self.torch_onnx_minimum_version
    else:
        return False

The minimum PyTorch version required to export the model.

Returns:
`bool`: Whether the installed version of PyTorch is compatible with the model.


def precheck_ami_id(context):

  key = "{}/{}".format(context.env, context.service_name)
  print_if_verbose("precheck_ami_id with key: {}".format(key))
  current_ami = context.versionresolver.lookup("ami-id,{}".format(key))
  print_if_verbose("ami found: {}".format(current_ami))

  if current_ami is None:
    print_if_verbose("precheck passed without check because current AMI is None")
    return True

  instances_running_ami = context.aws_client("ec2").describe_instances(
      Filters=[{
          'Name': 'image-id',
          'Values': [current_ami]
      }]
  )["Reservations"]
  if instances_running_ami:
    instances_running_ami = [resv["Instances"][0]["InstanceId"] for resv in instances_running_ami]
  print_if_verbose("instances running ami {}:\n{}".format(current_ami, repr(instances_running_ami)))

  env_service = "{}-{}".format(context.env, context.service_name)
  instances_running_as_env_service = context.aws_client("ec2").describe_instances(
      Filters=[{
          'Name': 'iam-instance-profile.arn',
          'Values': ["arn:aws:iam::*:instance-profile/{}-{}".format(context.env, context.service_name)]
      }]
  )["Reservations"]
  if instances_running_as_env_service:
    instances_running_as_env_service = \
        [resv["Instances"][0]["InstanceId"] for resv in instances_running_as_env_service]
  print_if_verbose("instances running as {}".format(env_service))
  print_if_verbose(repr(instances_running_as_env_service))

  for instance_id in instances_running_as_env_service:
    if instance_id not in instances_running_ami:
      raise RuntimeError("Instance: {} not running expected ami: {}".format(instance_id, current_ami))

  return True

Is the AMI in service the same as the AMI marked current in the version records?
This tool won't update records unless the world state is coherent.
Args:
context: a populated EFVersionContext object
Returns:
True if ok to proceed
Raises:
RuntimeError if not ok to proceed


def is_action(task):
    result = False
    if _extract_from_env_in_payload(task, 'ACTION_CALLBACK'):
        result = True
    if (task.get('extra', {}).get('action') is not None):
        result = True
    return result

Determine if a task is an action task.

Trusted decision and action tasks are important in that they can generate
other valid tasks. The verification of decision and action tasks is slightly
different, so we need to be able to tell them apart.

This checks for the following things::

* ``task.payload.env.ACTION_CALLBACK`` exists
* ``task.extra.action`` exists

Args:
task (dict): the task definition to check

Returns:
bool: True if it's an action


def list_installed():
    cmd = 'Get-WindowsFeature -ErrorAction SilentlyContinue -WarningAction SilentlyContinue | Select DisplayName,Name,Installed'
    features = _pshell_json(cmd)
    ret = {}
    for entry in features:
        if entry['Installed']:
            ret[entry['Name']] = entry['DisplayName']
    return ret

List installed features. Supported on Windows Server 2008 and Windows 8 and
newer.

Returns:
dict: A dictionary of installed features

CLI Example:

.. code-block:: bash

salt '*' win_servermanager.list_installed


def _parse_dataset(file_path, tmp_dir, train):
    input_path = file_path
    file_name = ('train' if train else 'dev')
    gen_output_path = os.path.join(tmp_dir, (file_name + '.txt'))
    example_output_path = os.path.join(tmp_dir, _EXAMPLES_FILE)
    print(('input path: ' + input_path))
    print(('gen_output_path: ' + gen_output_path))
    print(('example_output_path: ' + example_output_path))
    input_file = tf.gfile.Open(input_path, mode='r')
    examples = []
    for (counter, line) in enumerate(input_file):
        if (counter == 0):
            continue
        line_split = line.split('\t')
        parse1 = line_split[_PARSE1_INDEX]
        parse2 = line_split[_PARSE2_INDEX]
        consensus_label = line_split[_LABEL_INDEX]
        tokens1 = _get_tokens_and_tags(parse1)
        tokens2 = _get_tokens_and_tags(parse2)
        tokens1_str = ' '.join(tokens1)
        tokens2_str = ' '.join(tokens2)
        if (consensus_label != '-'):
            examples.append([tokens1_str, tokens2_str, consensus_label])
    input_file.close()
    with tf.gfile.GFile(gen_output_path, 'w') as f:
        for (tokens1_str, tokens2_str, consensus_label) in examples:
            f.write(('%s\t%s\t%s\n' % (tokens1_str, tokens2_str, consensus_label)))
    if train:
        with tf.gfile.GFile(example_output_path, 'w') as f:
            for (tokens1_str, tokens2_str, consensus_label) in examples:
                f.write(('%s %s\n' % (tokens1_str, tokens2_str)))

Convert the dataset in to a simpler format.

This function creates two files. One for being processed to produce a vocab
and another to generate the data.

Args:
file_path: string, path to the file to parse.
tmp_dir: string, path to the directory to output the files.
train: bool, indicating if we are parsing the training set.


def diff_compute(self, text1, text2, checklines, deadline):

    if not text1:

      return [(self.DIFF_INSERT, text2)]

    if not text2:

      return [(self.DIFF_DELETE, text1)]

    if len(text1) > len(text2):
      (longtext, shorttext) = (text1, text2)
    else:
      (shorttext, longtext) = (text1, text2)
    i = longtext.find(shorttext)
    if i != -1:

      diffs = [(self.DIFF_INSERT, longtext[:i]), (self.DIFF_EQUAL, shorttext),
               (self.DIFF_INSERT, longtext[i + len(shorttext):])]

      if len(text1) > len(text2):
        diffs[0] = (self.DIFF_DELETE, diffs[0][1])
        diffs[2] = (self.DIFF_DELETE, diffs[2][1])
      return diffs

    if len(shorttext) == 1:

      return [(self.DIFF_DELETE, text1), (self.DIFF_INSERT, text2)]

    hm = self.diff_halfMatch(text1, text2)
    if hm:

      (text1_a, text1_b, text2_a, text2_b, mid_common) = hm

      diffs_a = self.diff_main(text1_a, text2_a, checklines, deadline)
      diffs_b = self.diff_main(text1_b, text2_b, checklines, deadline)

      return diffs_a + [(self.DIFF_EQUAL, mid_common)] + diffs_b

    if checklines and len(text1) > 100 and len(text2) > 100:
      return self.diff_lineMode(text1, text2, deadline)

    return self.diff_bisect(text1, text2, deadline)

Find the differences between two texts.  Assumes that the texts do not
have any common prefix or suffix.

Args:
text1: Old string to be diffed.
text2: New string to be diffed.
checklines: Speedup flag.  If false, then don't run a line-level diff
first to identify the changed areas.
If true, then run a faster, slightly less optimal diff.
deadline: Time when the diff should be complete by.

Returns:
Array of changes.


def reformat_css(input_file, output_file):

    line_count = get_line_count(input_file)

    f = open(input_file, 'r+')
    output = open(output_file, 'w')

    for line in range(line_count):

        string = f.readline().strip()

        string = re.sub('\{', '{\n', string)

        string = re.sub('; ', ';', string)
        string = re.sub(';', ';\n', string)

        string = re.sub('} ', '*/\n', string)

        output.write(string)

    output.close()
    f.close()

    indent_css(output_file, output_file)

    add_whitespace_before("{", output_file, output_file)

Reformats poorly written css. This function does not validate or fix errors in the code.
It only gives code the proper indentation.

Args:
input_file: string, path to the input file.

output_file: string, path to where the reformatted css should be saved. If the target file
doesn't exist, a new file is created.

Returns:
None.


def marcxml2record(marcxml):

    marcjson = create_record(marcxml, keep_singletons=False)
    collections = _get_collections(marcjson)

    if 'conferences' in collections:
        return conferences.do(marcjson)
    elif 'data' in collections:
        return data.do(marcjson)
    elif 'experiment' in collections:
        return experiments.do(marcjson)
    elif 'hepnames' in collections:
        return hepnames.do(marcjson)
    elif 'institution' in collections:
        return institutions.do(marcjson)
    elif 'job' in collections or 'jobhidden' in collections:
        return jobs.do(marcjson)
    elif 'journals' in collections or 'journalsnew' in collections:
        return journals.do(marcjson)
    return hep.do(marcjson)

Convert a MARCXML string to a JSON record.

Tries to guess which set of rules to use by inspecting the contents
of the ``980__a`` MARC field, but falls back to HEP in case nothing
matches, because records belonging to special collections logically
belong to the Literature collection but don't have ``980__a:HEP``.

Args:
marcxml(str): a string containing MARCXML.

Returns:
dict: a JSON record converted from the string.


def check_column(df: DataFrame, row: int, name: str, fn: Callable[[float], bool]) -> bool:
    is_ok = True
    if df(row, 'trt_model'):
        if not fn(df(row, name)):
            logging.error('Unsatisfied %s found at: %s', name, df(row))
            is_ok = False
    return is_ok

Checks the values of a column using a custom function and logs abnormals.

The check is only performed on TensorRT models, not native CPU/GPU models.

Args:
df: The DataFrame to be checked.
row: The row in the DataFrame
name: The name of the column to be checked.
fn: The function that takes a value of at the specified column and returns
if the value satisfies the check.

Returns:
Whether all the values of the specified column satisfies the provided check.


def change_tz(cal, new_timezone, default, utc_only=False, utc_tz=icalendar.utc):
    for vevent in getattr(cal, 'vevent_list', []):
        start = getattr(vevent, 'dtstart', None)
        end = getattr(vevent, 'dtend', None)
        for node in (start, end):
            if node:
                dt = node.value
                if (isinstance(dt, datetime) and ((not utc_only) or (dt.tzinfo == utc_tz))):
                    if (dt.tzinfo is None):
                        dt = dt.replace(tzinfo=default)
                    node.value = dt.astimezone(new_timezone)

Change the timezone of the specified component.

Args:
cal (Component): the component to change
new_timezone (tzinfo): the timezone to change to
default (tzinfo): a timezone to assume if the dtstart or dtend in cal
doesn't have an existing timezone
utc_only (bool): only convert dates that are in utc
utc_tz (tzinfo): the tzinfo to compare to for UTC when processing
utc_only=True


def fetch_friends(self, user, paginate=False):
    if USING_ALLAUTH:
        social_app = SocialApp.objects.get_current('facebook')
        oauth_token = SocialToken.objects.get(account=user, app=social_app).token
    else:
        social_auth_backend = FacebookBackend()
        tokens = social_auth_backend.tokens(user)
        oauth_token = tokens['access_token']
    graph = facebook.GraphAPI(oauth_token)
    friends = graph.get_connections('me', 'friends')
    if paginate:
        total_friends = friends.copy()
        total_friends.pop('paging')
        while (('paging' in friends) and ('next' in friends['paging']) and friends['paging']['next']):
            next_url = friends['paging']['next']
            next_url_parsed = urlparse.urlparse(next_url)
            query_data = urlparse.parse_qs(next_url_parsed.query)
            query_data.pop('access_token')
            for (k, v) in query_data.items():
                query_data[k] = v[0]
            friends = graph.get_connections('me', 'friends', **query_data)
            total_friends['data'] = sum([total_friends['data'], friends['data']], [])
    else:
        total_friends = friends
    return total_friends

fethces friends from facebook using the oauth_token
fethched by django-social-auth.

Note - user isn't a user - it's a UserSocialAuth if using social auth, or a SocialAccount if using allauth

Returns:
collection of friend objects fetched from facebook


def duration_distance(item_a, item_b, max_value):

    duration_a = item_a.times.size
    duration_b = item_b.times.size
    return np.minimum(np.abs(duration_a - duration_b), max_value) / float(max_value)

Absolute difference in the duration of two items

Args:
item_a: STObject from the first set in TrackMatcher
item_b: STObject from the second set in TrackMatcher
max_value: Maximum distance value used as scaling value and upper constraint.

Returns:
Distance value between 0 and 1.


def __init__(self, ascii_codepage='cp1252', key_path_prefix=''):

    super(REGFWinRegistryFile, self).__init__(
        ascii_codepage=ascii_codepage, key_path_prefix=key_path_prefix)
    self._file_object = None
    self._regf_file = pyregf.file()
    self._regf_file.set_ascii_codepage(ascii_codepage)

Initializes the Windows Registry file.

Args:
ascii_codepage (Optional[str]): ASCII string codepage.
key_path_prefix (Optional[str]): Windows Registry key path prefix.


def mkdirs(self, path):
    try:
        os.makedirs(path)
    except OSError as err:
        raise IOError(err)

Recursively create directories for the provided path.

Args:
path: string path of the directory structure that should be created

Raises:
IOError: if leaf directory already exists.


def is_compatible(self, other: 'Schema') -> bool:
    if not isinstance(other, Schema):
        raise TypeError(f"Argument 'other' should be a Schema object. Encountered {other}.")
    for key_spec in other.keys():
        if key_spec not in self:
            return False
    for key_spec, field in self.items():
        if key_spec not in other:
            return False
        if not field.value.is_compatible(other[key_spec].value):
            return False
    return True

Returns whether current schema is compatible with the other schema.

NOTE(daiyip): schema A is compatible with schema B when:
schema A and schema B have the same keys, with compatible values specs.

Args:
other: Other schema.

Returns:
True if values that is acceptable to the other schema is acceptable to
current schema.
Raises:
TypeError: If `other` is not a schema object.


def describe(self):
    response = {'TransformJobStatus': self.state, 'ModelName': self.model_name, 'TransformJobName': self.name, 'TransformJobArn': _UNUSED_ARN, 'TransformEndTime': self.end_time, 'CreationTime': self.start_time, 'TransformStartTime': self.start_time, 'Environment': {}, 'BatchStrategy': self.batch_strategy}
    if self.transform_resources:
        response['TransformResources'] = self.transform_resources
    if self.output_data:
        response['TransformOutput'] = self.output_data
    if self.input_data:
        response['TransformInput'] = self.input_data
    return response

Describe this _LocalTransformJob

The response is a JSON-like dictionary that follows the response of the
boto describe_transform_job() API.

Returns:
dict: description of this _LocalTransformJob


def with_rank_at_most(self, rank):
    if ((self.ndims is not None) and (self.ndims > rank)):
        raise ValueError(('Shape %s must have rank at most %d' % (self, rank)))
    else:
        return self

Returns a shape based on `self` with at most the given rank.

Args:
rank: An integer.

Returns:
A shape that is at least as specific as `self` with at most the given
rank.

Raises:
ValueError: If `self` does not represent a shape with at most the given
`rank`.


def to_dict(self):
    output = super().to_dict()
    if isinstance(self.esmfold_config, EsmFoldConfig):
        output['esmfold_config'] = self.esmfold_config.to_dict()
    return output

Serializes this instance to a Python dictionary. Override the default [`~PretrainedConfig.to_dict`].

Returns:
`Dict[str, any]`: Dictionary of all the attributes that make up this configuration instance,


def heightmap_lerp_hm(
    hm1: np.ndarray, hm2: np.ndarray, hm3: np.ndarray, coef: float
) -> None:

    lib.TCOD_heightmap_lerp_hm(
        _heightmap_cdata(hm1),
        _heightmap_cdata(hm2),
        _heightmap_cdata(hm3),
        coef,
    )

Perform linear interpolation between two heightmaps storing the result
in ``hm3``.

This is the same as doing ``hm3[:] = hm1[:] + (hm2[:] - hm1[:]) * coef``

Args:
hm1 (numpy.ndarray): The first heightmap.
hm2 (numpy.ndarray): The second heightmap to add to the first.
hm3 (numpy.ndarray): A destination heightmap to store the result.
coef (float): The linear interpolation coefficient.


def replace_punctuation(self, text, excluded=None, replacement=''):
    if (excluded is None):
        excluded = set()
    elif (not isinstance(excluded, set)):
        excluded = set(excluded)
    punct = ''.join(self.__punctuation.difference(excluded))
    return self.replace_characters(text, characters=punct, replacement=replacement)

Replace punctuation symbols in text.

Removes punctuation from input text or replaces them with a
string if specified. Characters replaced will be those
in string.punctuation.

Args:
text: The text to be processed.
excluded: Set of characters to exclude.
replacement: New text that will replace punctuation.

Returns:
The text without punctuation.


def __init__(self, type_, value):

        self.type_ = type_
        self.value = value
        super(CastError, self).__init__(
            'Unable to cast "{}" to {}.'.format(value, type_.__name__))

Instantiate the exception with a descriptive message.

Args:
type_: The type to which the cast was attempting to convert the
value.
value: The value that was attempted to be cast.


def add_dspam_headers(self, results):
    for header in self.headers:
        hname = (self.header_prefix + header)
        if (header.lower() in results):
            hvalue = results[header.lower()]
            logger.debug('<{}> Adding header {}: {}'.format(self.id, hname, hvalue))
            self.addheader(hname, hvalue)
        elif (header == 'Processed'):
            hvalue = datetime.datetime.now().strftime('%a %b %d %H:%M:%S %Y')
            logger.debug('<{}> Adding header {}: {}'.format(self.id, hname, hvalue))
            self.addheader(hname, hvalue)
        else:
            logger.warning('<{}> Not adding header {}, no data available in DSPAM results'.format(self.id, hname))

Format DSPAM headers with passed results, and add them to the message.

Args:
results -- A results dictionary from DspamClient.


def __init__(self, trainer_id):
    if not trainer_id:
        raise ValueError('tf.data service cross-trainer cache requires a non-empty trainer ID.')
    self.trainer_id = trainer_id

Constructs a CrossTrainerCache.

Args:
trainer_id: Each training job has a unique ID. Once a job has consumed
data, the data remains in the cache and is re-used by jobs with different
`trainer_id`s. Requests with the same `trainer_id` do not re-use data.

Raises:
ValueError if `trainer_id` is empty.


def __init__(self, add_tag_methods=None):

        super(PacketTags, self).__init__()

        self.tag_methods = [PacketTags._tag_net_direction, PacketTags._tag_nxdomain]
        if add_tag_methods:
            self.tag_methods += add_tag_methods

        self.output_stream = self.tag_stuff()

Initialize PacketTags Class

Args:
add_tag_methods: a list of additional tag methods (optional, defaults to None))
Note: all methods must take the data dictionary as an argmument (e.g. tag_method(data))


def _shadow_model_variables(shadow_vars):
    G = tf.get_default_graph()
    curr_shadow_vars = set([v.name for v in shadow_vars])
    model_vars = tf.model_variables()
    shadow_model_vars = []
    for v in model_vars:
        assert v.name.startswith('tower'), 'Found some MODEL_VARIABLES created outside of the tower function!'
        (stripped_op_name, stripped_var_name) = get_op_tensor_name(re.sub('^tower[0-9]+/', '', v.name))
        if (stripped_op_name in curr_shadow_vars):
            continue
        try:
            G.get_tensor_by_name(stripped_var_name)
            logger.warn('Model Variable {} also appears in other collections.'.format(stripped_var_name))
            continue
        except KeyError:
            pass
        new_v = tf.get_variable(stripped_op_name, dtype=v.dtype.base_dtype, initializer=v.initial_value, trainable=False)
        curr_shadow_vars.add(stripped_op_name)
        shadow_vars.append(new_v)
        shadow_model_vars.append((new_v, v))
    return shadow_model_vars

Create shadow vars for model_variables as well, and add to the list of ``shadow_vars``.

Returns:
list of (shadow_model_var, local_model_var) used for syncing.


def to_view(self, view_name):
    from . import _view
    return _view.View(view_name, self._context).create(self._sql)

Create a View from this Query.

Args:
view_name: the name of the View either as a string or a 3-part tuple
(projectid, datasetid, name).

Returns:
A View for the Query.


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 get_attribute_from_config(config, section, attribute):
    section = config.get(section)
    if section:
        option = section.get(attribute)
        if option:
            return option
    raise ConfigurationError("Config file badly formed!\nFailed to get attribute '{}' from section '{}'!".format(attribute, section))

Try to parse an attribute of the config file.

Args:
config (defaultdict): A defaultdict.
section (str): The section of the config file to get information from.
attribute (str): The attribute of the section to fetch.
Returns:
str: The string corresponding to the section and attribute.
Raises:
ConfigurationError


def Verify(self, mempool):

        logger.info("Verifying transaction: %s " % self.Hash.ToBytes())

        return Helper.VerifyScripts(self)

Verify the transaction.

Args:
mempool:

Returns:
bool: True if verified. False otherwise.


def record_factory(app, fields=None):

    record = Record(app, {
        '$type': Record._type,
        'isNew': True,
        'applicationId': app.id,
        'comments': {
            '$type': 'System.Collections.Generic.Dictionary`2[[System.String, mscorlib],[System.Collections.Generic.List`1[[Core.Models.Record.Comments, Core]], mscorlib]], mscorlib'
        },
        'values': {
            '$type': 'System.Collections.Generic.Dictionary`2[[System.String, mscorlib],[System.Object, mscorlib]], mscorlib'
        }
    })

    fields = fields or {}

    for name, value in six.iteritems(fields):
        record[name] = value

    copy_raw = copy.copy(record._raw)
    values_dict = {}
    for key, value in six.iteritems(copy_raw['values']):
        if value is not None:
            values_dict[key] = value
    record._raw['values'] = values_dict

    return record

Return a temporary Record instance to be used for field validation and value parsing

Args:
app (App): Target App to create a transient Record instance for
fields (dict): Optional dict of fields and values to set on new Record instance before returning

Returns:
Record: Unsaved Record instance to be used for validation, creation, etc.


def parse_binary_descriptor(bindata):
    func_names = {0: 'copy_latest_a', 1: 'average_a', 2: 'copy_all_a', 3: 'sum_a', 4: 'copy_count_a', 5: 'trigger_streamer', 6: 'call_rpc', 7: 'subtract_afromb'}
    if (len(bindata) != 20):
        raise ArgumentError('Invalid binary node descriptor with incorrect size', size=len(bindata), expected=20, bindata=bindata)
    (a_trig, b_trig, stream_id, a_id, b_id, proc, a_cond, b_cond, trig_combiner) = struct.unpack('<LLHHHBBBB2x', bindata)
    node_stream = DataStream.FromEncoded(stream_id)
    if (a_id == 65535):
        raise ArgumentError('Invalid binary node descriptor with invalid first input', input_selector=a_id)
    a_selector = DataStreamSelector.FromEncoded(a_id)
    a_trigger = _process_binary_trigger(a_trig, a_cond)
    b_selector = None
    b_trigger = None
    if (b_id != 65535):
        b_selector = DataStreamSelector.FromEncoded(b_id)
        b_trigger = _process_binary_trigger(b_trig, b_cond)
    if (trig_combiner == SGNode.AndTriggerCombiner):
        comb = '&&'
    elif (trig_combiner == SGNode.OrTriggerCombiner):
        comb = '||'
    else:
        raise ArgumentError('Invalid trigger combiner in binary node descriptor', combiner=trig_combiner)
    if (proc not in func_names):
        raise ArgumentError('Unknown processing function', function_id=proc, known_functions=func_names)
    func_name = func_names[proc]
    if (b_selector is None):
        return '({} {}) => {} using {}'.format(a_selector, a_trigger, node_stream, func_name)
    return '({} {} {} {} {}) => {} using {}'.format(a_selector, a_trigger, comb, b_selector, b_trigger, node_stream, func_name)

Convert a binary node descriptor into a string descriptor.

Binary node descriptor are 20-byte binary structures that encode all
information needed to create a graph node.  They are used to communicate
that information to an embedded device in an efficent format.  This
function exists to turn such a compressed node description back into
an understandable string.

Args:
bindata (bytes): The raw binary structure that contains the node
description.

Returns:
str: The corresponding string description of the same sensor_graph node


def server_hardware_types(self):
    if (not self.__server_hardware_types):
        self.__server_hardware_types = ServerHardwareTypes(self.__connection)
    return self.__server_hardware_types

Gets the ServerHardwareTypes API client.

Returns:
ServerHardwareTypes:


def parse_int(value: Any) -> Numeric:
    return int(value)

Attempts to parse a valid integer value from the provided value.

Args:
* value: of Any type

Returns:
* int value: if valid

Raises:
* ValueError: if parsing failed


def _get_context_name(self, app=None):
    elements = [self.__class__.__name__, 'context', text_type(id(self))]
    if app:
        elements.append(text_type(id(app)))
    else:
        try:
            elements.append(text_type(id(self.app)))
        except RuntimeError:
            pass
    return '_'.join(elements)

Generate the name of the context variable for this component & app.

Because we store the ``context`` in a Local so the component
can be used across multiple apps, we cannot store the context on the
instance itself. This function will generate a unique and predictable
key in which to store the context.

Returns:
str: The name of the context variable to set and get the context
from.


def match_rules_context(tree, rules, parent_context={}):

    for template, match_rules in rules.items():
        context = parent_context.copy()
        if match_template(tree, template, context):
            for key, child_rules in match_rules.items():
                child_context = match_rules_context(context[key], child_rules, context)
                if child_context:
                    for k, v in child_context.items():
                        context[k] = v
                else:
                    return None
            return context
    return None

Recursively matches a Tree structure with rules and returns context

Args:
tree (Tree): Parsed tree structure
rules (dict): See match_rules
parent_context (dict): Context of parent call
Returns:
dict: Context matched dictionary of matched rules or
None if no match


def _get_members(self, class_obj, member_type, include_in_public=None):
    try:
        app = self.state.document.settings.env.app
    except AttributeError:
        app = None
    if (not include_in_public):
        include_in_public = []
    all_members = []
    for member_name in dir(class_obj):
        try:
            documenter = get_documenter(app, safe_getattr(class_obj, member_name), class_obj)
        except AttributeError:
            continue
        if (documenter.objtype == member_type):
            all_members.append(member_name)
    public_members = [x for x in all_members if ((x in include_in_public) or (not x.startswith('_')))]
    return (public_members, all_members)

Return class members of the specified type.

class_obj: Class object.

member_type: Member type ('method' or 'attribute').

include_in_public: set/list/tuple with member names that should be
included in public members in addition to the public names (those
starting without underscore).

Returns:
tuple(public_members, all_members): Names of the class members of
the specified member type (public / all).


def group_protos(cls, proto_list: List[types.ProtobufBaseType], **kwargs) -> Dict[str, List[types.ProtobufBaseType]]:
    del proto_list, kwargs
    return []

Creates a dict of batchable protos.

For a list of protos, generates a dictionary `{key: grouped_protos}` such
that the `grouped_protos` can be batched together.

Args:
proto_list: A list of `Instrument` protos.
**kwargs: Any extra arguments. E.g., pricing configuration.

Returns:
A dictionary of grouped protos.


def unzip(input_layer, split_dim=0, num_splits=2):

  shape = input_layer.shape
  _check_split_dims(num_splits, split_dim, shape)
  splits = functions.unzip(input_layer, split_dim, shape[split_dim], num_splits)
  return input_layer.with_sequence(splits)

Unzips this Tensor along the split_dim into num_splits Equal chunks.

Examples:

* `[1, 2, 3, 4] -> [1, 3], [2, 4]`
* `[[1, 1], [2, 2], [3, 3], [4, 4]] -> [[1, 1], [3, 3]], [[2, 2], [4, 4]]`

Args:
input_layer: The chainable object, supplied.
split_dim: The dimension to split along. Defaults to batch.
num_splits: The number of splits.
Returns:
A list of PrettyTensors.
Raises:
ValueError: If split_dim is out of range or isn't divided evenly by
num_splits.


def determine_action(self, issue):
    resource_type = self.resource_types[issue.resource.resource_type_id]
    issue_alert_schedule = (self.alert_schedule[resource_type] if (resource_type in self.alert_schedule) else self.alert_schedule['*'])
    action_item = {'action': None, 'action_description': None, 'last_alert': issue.last_alert, 'issue': issue, 'resource': self.resource_classes[self.resource_types[issue.resource.resource_type_id]](issue.resource), 'owners': [], 'stop_after': issue_alert_schedule['stop'], 'remove_after': issue_alert_schedule['remove'], 'notes': issue.notes, 'missing_tags': issue.missing_tags}
    time_elapsed = (time.time() - issue.created)
    stop_schedule = pytimeparse.parse(issue_alert_schedule['stop'])
    remove_schedule = pytimeparse.parse(issue_alert_schedule['remove'])
    if self.collect_only:
        action_item['action'] = AuditActions.IGNORE
    elif (remove_schedule and (time_elapsed >= remove_schedule)):
        action_item['action'] = AuditActions.REMOVE
        action_item['action_description'] = 'Resource removed'
        action_item['last_alert'] = remove_schedule
        if issue.update({'last_alert': remove_schedule}):
            db.session.add(issue.issue)
    elif (stop_schedule and (time_elapsed >= stop_schedule)):
        action_item['action'] = AuditActions.STOP
        action_item['action_description'] = 'Resource stopped'
        action_item['last_alert'] = stop_schedule
        if issue.update({'last_alert': stop_schedule}):
            db.session.add(issue.issue)
    else:
        alert_selection = self.determine_alert(issue_alert_schedule['alert'], issue.get_property('created').value, issue.get_property('last_alert').value)
        if alert_selection:
            action_item['action'] = AuditActions.ALERT
            action_item['action_description'] = '{} alert'.format(alert_selection)
            action_item['last_alert'] = alert_selection
            if issue.update({'last_alert': alert_selection}):
                db.session.add(issue.issue)
        else:
            action_item['action'] = AuditActions.IGNORE
    db.session.commit()
    return action_item

Determine the action we should take for the issue

Args:
issue: Issue to determine action for

Returns:
`dict`


def __init__(self, *timeslots: List[Timeslot]):

        self._table = defaultdict(list)

        for slot in timeslots:
            for interval in self._table[slot.channel]:
                if slot.interval.has_overlap(interval):
                    raise PulseError("Cannot create TimeslotCollection from overlapped timeslots")
            self._table[slot.channel].append(slot.interval)

        self._timeslots = tuple(timeslots)

Create a new time-slot collection.

Args:
*timeslots: list of time slots
Raises:
PulseError: when overlapped time slots are specified


def wait_for_bq_job(self, job_reference, sleep_duration_sec=5, max_retries=0):
    retry = 0
    while True:
        retry += 1
        job = self.get_job(job_reference.projectId, job_reference.jobId, job_reference.location)
        _LOGGER.info('Job %s status: %s', job.id, job.status.state)
        if job.status.state == 'DONE' and job.status.errorResult:
            raise RuntimeError('BigQuery job {} failed. Error Result: {}'.format(job_reference.jobId, job.status.errorResult))
        elif job.status.state == 'DONE':
            return True
        else:
            time.sleep(sleep_duration_sec)
            if max_retries != 0 and retry >= max_retries:
                raise RuntimeError('The maximum number of retries has been reached')

Poll job until it is DONE.

Args:
job_reference: bigquery.JobReference instance.
sleep_duration_sec: Specifies the delay in seconds between retries.
max_retries: The total number of times to retry. If equals to 0,
the function waits forever.

Raises:
`RuntimeError`: If the job is FAILED or the number of retries has been
reached.


def _create_state_graph(self, name):
    import_collections = [tf_v1.GraphKeys.GLOBAL_VARIABLES, tf_v1.GraphKeys.MODEL_VARIABLES, tf_v1.GraphKeys.TABLE_INITIALIZERS, tf_v1.GraphKeys.ASSET_FILEPATHS, tf_v1.GraphKeys.COND_CONTEXT, tf_v1.GraphKeys.WHILE_CONTEXT]
    if self._trainable:
        import_collections.extend([tf_v1.GraphKeys.TRAINABLE_VARIABLES, tf_v1.GraphKeys.REGULARIZATION_LOSSES])
    absolute_scope_name = tf_v1.get_default_graph().unique_name(name, mark_as_used=False)
    relative_scope_name = absolute_scope_name.split('/')[(- 1)]
    assert (relative_scope_name == name)
    meta_graph = meta_graph_pb2.MetaGraphDef()
    meta_graph.CopyFrom(self._meta_graph)
    meta_graph_lib.filter_collections(meta_graph, import_collections)
    meta_graph_lib.prefix_shared_name_attributes(meta_graph, absolute_scope_name)
    tf_v1.train.import_meta_graph(meta_graph, input_map={}, import_scope=relative_scope_name)
    variables_tensor_map = {}
    for var in tf_v1.global_variables():
        if var.op.name.startswith((absolute_scope_name + '/')):
            variables_tensor_map[var.name[(len(absolute_scope_name) + 1):]] = var

    def _get_tensor(tensor_name):
        return tf_v1.get_default_graph().get_tensor_by_name(meta_graph_lib.prepend_name_scope(tensor_name, import_scope=absolute_scope_name))
    state_op_names = list_registered_stateful_ops_without_inputs()
    state_map = get_state_map(meta_graph, state_op_names, set(), _get_tensor)
    return (variables_tensor_map, state_map)

Creates the graph nodes that hold the state of the Module.

Args:
name: name scope to create the state graph in.

Returns:
A tuple consisting of:
variables_tensor_map: a map from tensor names in the original graph def
to the created Variables objects.
state_map: a map from tensors names in the original graph def to the
instantiated tensors to be used as a state_map.


def _order_pases(self, passes):
    passes = set(passes)
    pass_deps = {}
    for opt in passes:
        (_, before, after) = self._known_passes[opt]
        if (opt not in pass_deps):
            pass_deps[opt] = set()
        for after_pass in after:
            pass_deps[opt].add(after_pass)
        for other in before:
            if (other not in passes):
                continue
            if (other not in pass_deps):
                pass_deps[other] = set()
            pass_deps[other].add(opt)
    return toposort_flatten(pass_deps)

Topologically sort optimization passes.

This ensures that the resulting passes are run in order
respecting before/after constraints.

Args:
passes (iterable): An iterable of pass names that should
be included in the optimization passes run.


def listdir(self, target_directory):

        target_directory = self.resolve_path(target_directory, allow_fd=True)
        directory = self.confirmdir(target_directory)
        directory_contents = directory.contents
        return list(directory_contents.keys())

Return a list of file names in target_directory.

Args:
target_directory: Path to the target directory within the
fake filesystem.

Returns:
A list of file names within the target directory in arbitrary
order.

Raises:
OSError: if the target is not a directory.


def AddSubkey(self, registry_key):

    name = registry_key.name.upper()
    if name in self._subkeys:
      raise KeyError(
          'Subkey: {0:s} already exists.'.format(registry_key.name))

    self._subkeys[name] = registry_key

    key_path = self._JoinKeyPath([self._key_path, registry_key.name])
    registry_key._key_path = key_path

Adds a subkey.

Args:
registry_key (WinRegistryKey): Windows Registry subkey.

Raises:
KeyError: if the subkey already exists.


def init_op(self):
    return self._init_op

Return the Init Op used by the supervisor.

Returns:
An Op or `None`.


def match_criterion(self, tag):

        return tag.name == self.reference_tag_name and \
            tag.attrs.get('kind', '') == self.reference_tag_kind

Override. Determine if a tag has the desired name and kind attribute
value.

Args:
tag: A BeautifulSoup Tag.

Returns:
True if tag has the desired name and kind, otherwise False.


def _pad_modernbert_output(inputs: torch.Tensor, indices: torch.Tensor, batch: int, seqlen: int) -> torch.Tensor:
    if inputs.dim() == 1:
        output = torch.zeros(batch * seqlen, dtype=inputs.dtype, device=inputs.device)
        output[indices] = inputs
        padded_inputs = output.view(batch, seqlen)
    else:
        _, *rest = inputs.shape
        output = torch.zeros(batch * seqlen, *rest, dtype=inputs.dtype, device=inputs.device)
        output[indices] = inputs
        padded_inputs = output.view(batch, seqlen, *rest)
    return padded_inputs

Add padding to sequences.

Args:
inputs: (total_nnz, ...) or (total_nnz,), where total_nnz = number of tokens selected in attention_mask.
indices: (total_nnz)
batch: int, batch size
seqlen: int, max sequence length

Returns:
padded_inputs: (batch, seqlen, ...) or (batch, seqlen)


def is_generic_union(type_: Type) -> bool:

    if hasattr(typing, '_GenericAlias'):

        return (isinstance(type_, typing._GenericAlias) and
                type_.__origin__ is Union)
    else:
        if hasattr(typing, '_Union'):

            return isinstance(type_, typing._Union)
        else:

            return isinstance(type_, typing.UnionMeta)
    raise RuntimeError('Could not determine whether type is a Union. Is this'
                       ' a YAtiML-supported Python version?')

Determines whether a type is a Union[...].

How to do this varies for different Python versions, due to the
typing library not having a stable API. This functions smooths
over the differences.

Args:
type_: The type to check.

Returns:
True iff it's a Union[...something...].


def FromEncoded(cls, bindata):
    if (len(bindata) != 8):
        raise ArgumentError('Invalid binary slot descriptor with invalid length', length=len(bindata), expected=8, data=bindata)
    (slot, match_op) = struct.unpack('<B6xB', bindata)
    match_name = cls.KNOWN_MATCH_CODES.get(match_op)
    if (match_name is None):
        raise ArgumentError('Unknown match operation specified in binary slot descriptor', operation=match_op, known_match_ops=cls.KNOWN_MATCH_CODES)
    if (match_name == 'match_controller'):
        return SlotIdentifier(controller=True)
    if (match_name == 'match_slot'):
        return SlotIdentifier(slot=slot)
    raise ArgumentError('Unsupported match operation in binary slot descriptor', match_op=match_name)

Create a slot identifier from an encoded binary descriptor.

These binary descriptors are used to communicate slot targeting
to an embedded device.  They are exactly 8 bytes in length.

Args:
bindata (bytes): The 8-byte binary descriptor.

Returns:
SlotIdentifier


def _push_frontier(self, early_frontier: Dict[(ops.Qid, int)], late_frontier: Dict[(ops.Qid, int)], update_qubits: Iterable[ops.Qid]=None) -> Tuple[(int, int)]:
    if (update_qubits is None):
        update_qubits = set(early_frontier).difference(late_frontier)
    n_new_moments = (max(((early_frontier.get(q, 0) - late_frontier[q]) for q in late_frontier)) if late_frontier else 0)
    if (n_new_moments > 0):
        insert_index = min(late_frontier.values())
        self._moments[insert_index:insert_index] = ([ops.Moment()] * n_new_moments)
        for q in update_qubits:
            if (early_frontier.get(q, 0) > insert_index):
                early_frontier[q] += n_new_moments
        return (insert_index, n_new_moments)
    return (0, 0)

Inserts moments to separate two frontiers.

After insertion n_new moments, the following holds:
for q in late_frontier:
early_frontier[q] <= late_frontier[q] + n_new
for q in update_qubits:
early_frontier[q] the identifies the same moment as before
(but whose index may have changed if this moment is after
those inserted).

Args:
early_frontier: The earlier frontier. For qubits not in the later
frontier, this is updated to account for the newly inserted
moments.
late_frontier: The later frontier. This is not modified.
update_qubits: The qubits for which to update early_frontier to
account for the newly inserted moments.

Returns:
(index at which new moments were inserted, how many new moments
were inserted) if new moments were indeed inserted. (0, 0)
otherwise.


def run(self, resources):

        hwman = resources['connection']
        con = hwman.hwman.controller()
        test_interface = con.test_interface()
        try:
            test_interface.synchronize_clock()
            print('Time currently set at %s' % test_interface.current_time_str())
        except:
            raise ArgumentError('Error setting RTC time, check if controller actually has RTC or if iotile-support-lib-controller-3 is updated')

Sets the RTC timestamp to UTC.

Args:
resources (dict): A dictionary containing the required resources that
we needed access to in order to perform this step.


def _get_data_buffer_time_limit_ms(experiments):
    for experiment in experiments:
        if re.match('data_buffer_time_limit_ms=', experiment):
            return int(re.match('data_buffer_time_limit_ms=(?P<data_buffer_time_limit_ms>.*)', experiment).group('data_buffer_time_limit_ms'))
    return 0

Defines the time limt of the outbound data buffering.

Note: data_buffer_time_limit_ms is an experimental flag and might
not be available in future releases.

Returns:
an int indicating the time limit in milliseconds of the outbound
data buffering. Default is 0 (disabled)


def sample_with_temperature(x, dim, temperature=1.0, dtype=tf.int32, name=None):

  dim = convert_to_dimension(dim)
  with tf.name_scope(name, default_name="sample_with_temperature"):
    if temperature != 0.0:

      tiny_val = 1e-9
      g = -log(-log(
          random_uniform(
              x.mesh,
              x.shape,
              minval=tiny_val,
              maxval=1.,
              dtype=x.dtype)))
      x += g * temperature
    return argmax(x, dim, dtype, name)

Either argmax or random sampling.

Args:
x: a Tensor.
dim: a Dimension in x.shape.dims
temperature: a float  0.0=argmax 1.0=random
dtype: a tf.dtype (for the output)
name: an optional string

Returns:
a Tensor with type dtype.


def _process_celeba_config_file(self, file_path):

    with tf.io.gfile.GFile(file_path) as f:
      data_raw = f.read()
    lines = data_raw.split("\n")

    keys = lines[1].strip().split()
    values = {}

    for line in lines[2:-1]:
      row_values = line.strip().split()

      values[row_values[0]] = [int(v) for v in row_values[1:]]
    return keys, values

Unpack the celeba config file.

The file starts with the number of lines, and a header.
Afterwards, there is a configuration for each file: one per line.

Args:
file_path: Path to the file with the configuration.

Returns:
keys: names of the attributes
values: map from the file name to the list of attribute values for
this file.


def _align_monomer(self, monomer, mon_vector, move_direction):

        axis = np.cross(mon_vector, move_direction)
        origin = monomer[self.start].coords
        angle = get_angle(mon_vector, move_direction)
        op = SymmOp.from_origin_axis_angle(origin, axis, angle)
        monomer.apply_operation(op)

rotate the monomer so that it is aligned along the move direction

Args:
monomer (Molecule)
mon_vector (numpy.array): molecule vector that starts from the
start atom index to the end atom index
move_direction (numpy.array): the direction of the polymer chain
extension


def Matches(self, file_entry):

    if not self._file_scanner or not file_entry.IsFile():
      return None

    file_object = file_entry.GetFileObject()
    if not file_object:
      return False

    try:
      scan_state = pysigscan.scan_state()
      self._file_scanner.scan_file_object(scan_state, file_object)

    except IOError as exception:

      location = getattr(file_entry.path_spec, 'location', '')
      logging.error((
          '[skipping] unable to scan file: {0:s} for signatures '
          'with error: {1!s}').format(location, exception))
      return False

    finally:
      file_object.close()

    return scan_state.number_of_scan_results > 0

Compares the file entry against the filter.

Args:
file_entry (dfvfs.FileEntry): file entry to compare.

Returns:
bool: True if the file entry matches the filter, False if not or
None if the filter does not apply.


def _to_backend_layout(tensor_layout):
    if tensor_layout.device_mesh is None:
        raise ValueError('Cannot create sharding when device mesh is not set for TensorLayout.')
    sharding_specs = [axis if axis else dtensor.UNSHARDED for axis in tensor_layout.axes]
    dtensor_mesh = tensor_layout.device_mesh.backend_mesh
    return dtensor.Layout(sharding_specs=sharding_specs, mesh=dtensor_mesh)

Convert the TensorLayout to Tensorflow backend specific Sharding.

Args:
tensor_layout: TensorLayout instance to convert.

Returns:
A `tf.dtensor.Layout` instance.


def rtt_get_num_down_buffers(self):

        cmd = enums.JLinkRTTCommand.GETNUMBUF
        dir = ctypes.c_int(enums.JLinkRTTDirection.DOWN)
        return self.rtt_control(cmd, dir)

After starting RTT, get the current number of down buffers.
Args:
self (JLink): the ``JLink`` instance

Returns:
The number of configured down buffers on the target.

Raises:
JLinkRTTException if the underlying JLINK_RTTERMINAL_Control call fails.


def _check_lambda_alias(self):
    aliases = self.lambda_client.list_aliases(FunctionName=self.app_name)
    matched_alias = False
    for alias in aliases['Aliases']:
        if (alias['Name'] == self.env):
            LOG.info('Found alias %s for function %s', self.env, self.app_name)
            matched_alias = True
            break
    else:
        LOG.info('No alias %s found for function %s', self.env, self.app_name)
    return matched_alias

Check if lambda alias exists.

Returns:
True if alias exists
False if alias does not exist


def _build_projection_expression(clean_table_keys):

    projection_expression = ''
    for key in clean_table_keys[:-1]:
        projection_expression += ('{},').format(key)
    projection_expression += clean_table_keys[-1]
    return projection_expression

Given cleaned up keys, this will return a projection expression for
the dynamodb lookup.

Args:
clean_table_keys (dict): keys without the data types attached

Returns:
str: A projection expression for the dynamodb lookup.


def xsrf_secret_key():
    secret = memcache.get(XSRF_MEMCACHE_ID, namespace=OAUTH2CLIENT_NAMESPACE)
    if (not secret):
        model = SiteXsrfSecretKey.get_or_insert(key_name='site')
        if (not model.secret):
            model.secret = _generate_new_xsrf_secret_key()
            model.put()
        secret = model.secret
        memcache.add(XSRF_MEMCACHE_ID, secret, namespace=OAUTH2CLIENT_NAMESPACE)
    return str(secret)

Return the secret key for use for XSRF protection.

If the Site entity does not have a secret key, this method will also create
one and persist it.

Returns:
The secret key.


def derive_temporary_python2_environment(
        destination_directory: str,
        python3_environment: PreparedEnv,
        verbose: bool,
        env_name: str = '.test_virtualenv_py2',
        python_path: str = "/usr/bin/python2.7") -> PreparedEnv:

    shutil.rmtree(destination_directory)
    input_directory = cast(str, python3_environment.destination_directory)
    os.chdir(input_directory)
    conversion_script_path = os.path.join(
        input_directory,
        'dev_tools',
        'python2.7-generate.sh')
    shell_tools.run_cmd('bash',
                        conversion_script_path,
                        destination_directory,
                        input_directory,
                        python3_environment.virtual_env_path,
                        out=sys.stderr)
    os.chdir(destination_directory)

    env_path = os.path.join(destination_directory, env_name)

    req_path = os.path.join(destination_directory, 'requirements.txt')
    dev_req_path = os.path.join(destination_directory,
                                'pip-list-test-tools.txt')
    contrib_req_path = os.path.join(destination_directory,
                                    'cirq',
                                    'contrib',
                                    'contrib-requirements.txt')
    req_paths = [req_path, dev_req_path, contrib_req_path]
    create_virtual_env(venv_path=env_path,
                       python_path=python_path,
                       requirements_paths=req_paths,
                       verbose=verbose)

    return PreparedEnv(github_repo=python3_environment.repository,
                       actual_commit_id=python3_environment.actual_commit_id,
                       compare_commit_id=python3_environment.compare_commit_id,
                       destination_directory=destination_directory,
                       virtual_env_path=env_path)

Creates a python 2.7 environment starting from a prepared python 3 one.

Args:
destination_directory: Where to put the python 2 environment.
python3_environment: The prepared environment to start from.
verbose: When set, more progress output is produced.
env_name: The name to use for the virtualenv directory.
python_path: The python binary to use.

Returns:
A description of the environment that was prepared.