def resolve_json_id(self, json_id, allow_no_match=False):

        if not json_id:
            return None

        if json_id.startswith('~'):
            # keep caches of all the pseudo-ids to avoid doing 1000s of lookups during import
            if json_id not in self.pseudo_id_cache:
                spec = get_pseudo_id(json_id)
                spec = self.limit_spec(spec)

                if isinstance(spec, Q):
                    objects = self.model_class.objects.filter(spec)
                else:
                    objects = self.model_class.objects.filter(**spec)
                ids = {each.id for each in objects}
                if len(ids) == 1:
                    self.pseudo_id_cache[json_id] = ids.pop()
                    errmsg = None
                elif not ids:
                    errmsg = 'cannot resolve pseudo id to {}: {}'.format(
                        self.model_class.__name__, json_id)
                else:
                    errmsg = 'multiple objects returned for {} pseudo id {}: {}'.format(
                        self.model_class.__name__, json_id, ids)

                # either raise or log error
                if errmsg:
                    if not allow_no_match:
                        raise UnresolvedIdError(errmsg)
                    else:
                        self.error(errmsg)
                        self.pseudo_id_cache[json_id] = None

            # return the cached object
            return self.pseudo_id_cache[json_id]

        # get the id that the duplicate points to, or use self
        json_id = self.duplicates.get(json_id, json_id)

        try:
            return self.json_to_db_id[json_id]
        except KeyError:
            raise UnresolvedIdError('cannot resolve id: {}'.format(json_id))

Given an id found in scraped JSON, return a DB id for the object.

    params:
        json_id:        id from json
        allow_no_match: just return None if id can't be resolved

Returns:
        database id

Raises:
        ValueError if id couldn't be resolved


def ColorWithHue(self, hue):

    h, s, l = self.__hsl
    return Color((hue, s, l), 'hsl', self.__a, self.__wref)

Create a new instance based on this one with a new hue.

    Parameters:
        :hue:
        The hue of the new color [0...360].

Returns:
        A grapefruit.Color instance.

    >>> Color.NewFromHsl(30, 1, 0.5).ColorWithHue(60)
    (1.0, 1.0, 0.0, 1.0)
    >>> Color.NewFromHsl(30, 1, 0.5).ColorWithHue(60).hsl
    (60, 1, 0.5)


def connect(self, component):

        if not isinstance(component, ThreadPool):
            raise TypeError('"component" must be a ThreadPool object')
        component.in_queue = self.out_queue
        return component

Connect two ThreadPools.

    The ``in_queue`` of the second pool will be set as the ``out_queue`` of
    the current pool, thus all the output will be input to the second pool.

Args:
        component (ThreadPool): the ThreadPool to be connected.

Returns:
        ThreadPool: the modified second ThreadPool.


def lighten(self, color, diff, *args):

        if color and diff:
            return self._ophsl(color, diff, 1, operator.add)
        raise ValueError('Illegal color values')

Lighten a color

Args:
        color (str): color
        diff (str): percentage

Returns:
        str


def load_ipython_extension(shell):

  # Inject our user agent on all requests by monkey-patching a wrapper around httplib2.Http.request.

  def _request(self, uri, method="GET", body=None, headers=None,
               redirections=_httplib2.DEFAULT_MAX_REDIRECTS, connection_type=None):
    if headers is None:
      headers = {}
    headers['user-agent'] = 'GoogleCloudDataLab/1.0'
    return _orig_request(self, uri, method=method, body=body, headers=headers,
                         redirections=redirections, connection_type=connection_type)

  _httplib2.Http.request = _request

  # Similarly for the requests library.

  def _init_session(self):
    _orig_init(self)
    self.headers['User-Agent'] = 'GoogleCloudDataLab/1.0'

  _requests.Session.__init__ = _init_session

  # Be more tolerant with magics. If the user specified a cell magic that doesn't
  # exist and an empty cell body but a line magic with that name exists, run that
  # instead. Conversely, if the user specified a line magic that doesn't exist but
  # a cell magic exists with that name, run the cell magic with an empty body.

  def _run_line_magic(self, magic_name, line):
    fn = self.find_line_magic(magic_name)
    if fn is None:
      cm = self.find_cell_magic(magic_name)
      if cm:
        return _run_cell_magic(self, magic_name, line, None)
    return _orig_run_line_magic(self, magic_name, line)

  def _run_cell_magic(self, magic_name, line, cell):
    if cell is None or len(cell) == 0 or cell.isspace():
      fn = self.find_line_magic(magic_name)
      if fn:
        return _orig_run_line_magic(self, magic_name, line)
      # IPython will complain if cell is empty string but not if it is None
      cell = None
    return _orig_run_cell_magic(self, magic_name, line, cell)

  _shell.InteractiveShell.run_cell_magic = _run_cell_magic
  _shell.InteractiveShell.run_line_magic = _run_line_magic

  # Define global 'project_id' and 'set_project_id' functions to manage the default project ID. We
  # do this conditionally in a try/catch # to avoid the call to Context.default() when running tests
  # which mock IPython.get_ipython().

  def _get_project_id():
    try:
      return google.datalab.Context.default().project_id
    except Exception:
      return None

  def _set_project_id(project_id):
    context = google.datalab.Context.default()
    context.set_project_id(project_id)
    try:
      from datalab.context import Context as _old_context
      _old_context.default().set_project_id(project_id)
    except ImportError:
      # If the old library is not loaded, then we don't have to do anything
      pass

  try:
    if 'datalab_project_id' not in _IPython.get_ipython().user_ns:
      _IPython.get_ipython().user_ns['datalab_project_id'] = _get_project_id
      _IPython.get_ipython().user_ns['set_datalab_project_id'] = _set_project_id
  except TypeError:
    pass

Called when the extension is loaded.

Args:
        shell - (NotebookWebApplication): handle to the Notebook interactive shell instance.


def bold(self, action):

        if action =='on':
            action = 'E'
        elif action == 'off':
            action = 'F'
        else:
            raise RuntimeError('Invalid action for function bold. Options are on and off')
        self.send(chr(27)+action)

Enable/cancel bold printing

Args:
        action: Enable or disable bold printing. Options are 'on' and 'off'

Returns:
        None

Raises:
        RuntimeError: Invalid action.


def __init__(self, channel):

        self.BatchWriteSpans = channel.unary_unary(
            "/google.devtools.cloudtrace.v2.TraceService/BatchWriteSpans",
            request_serializer=google_dot_devtools_dot_cloudtrace__v2_dot_proto_dot_tracing__pb2.BatchWriteSpansRequest.SerializeToString,
            response_deserializer=google_dot_protobuf_dot_empty__pb2.Empty.FromString,
        )
        self.CreateSpan = channel.unary_unary(
            "/google.devtools.cloudtrace.v2.TraceService/CreateSpan",
            request_serializer=google_dot_devtools_dot_cloudtrace__v2_dot_proto_dot_trace__pb2.Span.SerializeToString,
            response_deserializer=google_dot_devtools_dot_cloudtrace__v2_dot_proto_dot_trace__pb2.Span.FromString,
        )

Constructor.

Args:
        channel: A grpc.Channel.


def _check_consistent_returns(self, node):

        # explicit return statements are those with a not None value
        explicit_returns = [
            _node for _node in self._return_nodes[node.name] if _node.value is not None
        ]
        if not explicit_returns:
            return
        if len(explicit_returns) == len(
            self._return_nodes[node.name]
        ) and self._is_node_return_ended(node):
            return
        self.add_message("inconsistent-return-statements", node=node)

Check that all return statements inside a function are consistent.

    Return statements are consistent if:
        - all returns are explicit and if there is no implicit return;
        - all returns are empty and if there is, possibly, an implicit return.

Args:
        node (astroid.FunctionDef): the function holding the return statements.


def __init__(self, rr, table='services'):

        self.rr = rr
        self.table = table
        self._ensure_table()

Initialize the service registry.

    Creates the database table if it does not exist.

Args:
        rr (doublethink.Rethinker): a doublethink.Rethinker, which must
            have `dbname` set


def _is_propertyable(
    names,  # type: List[str]
    attrs,  # type: Dict[str, Any]
    annotations,  # type: Dict[str, type]
    attr,  # Dict[str, Any]
):
    # type: (...) -> bool

    return (
        attr in annotations
        and not attr.startswith("_")
        and not attr.isupper()
        and "__{}".format(attr) not in names
        and not isinstance(getattr(attrs, attr, None), types.MethodType)
    )

Determine if an attribute can be replaced with a property.

Args:
        names: The complete list of all attribute names for the class.
        attrs: The attribute dict returned by __prepare__.
        annotations: A mapping of all defined annotations for the class.
        attr: The attribute to test.

Returns:
        True if the attribute can be replaced with a property; else False.


def ping(token_or_hostname=None):

    if not token_or_hostname:
        return "Pong!"
    node = nago.core.get_node(token_or_hostname)
    if not node and token_or_hostname in ('master', 'server'):
        token_or_hostname = nago.settings.get_option('server')
        node = nago.core.get_node(token_or_hostname)
    if not node:
        try:
            address = socket.gethostbyname(token_or_hostname)
            node = nago.core.Node()
            node['host_name'] = token_or_hostname
            node['address'] = address
            node['access'] = 'node'
            if token_or_hostname == nago.settings.get_option('server'):
                node['access'] = 'master'
            node.save()
        except Exception:
            raise Exception("'%s' was not found in list of known hosts, and does not resolve to a valid address" % token_or_hostname)
    return node.send_command('nodes', 'ping')

Send an echo request to a nago host.

Args:
        token_or_host_name  -- The remote node to ping
                            If node is not provided, simply return pong
                            You can use the special nodenames "server" or "master"


def uniprot_sites(uniprot_id):

    r = requests.post('http://www.uniprot.org/uniprot/%s.gff' % uniprot_id)
    gff = StringIO(r.content.decode('utf-8'))

    feats = list(GFF.parse(gff))
    if len(feats) > 1:
        log.warning('Too many sequences in GFF')
    else:
        return feats[0].features

Retrieve a list of UniProt sites parsed from the feature file

    Sites are defined here: http://www.uniprot.org/help/site and here: http://www.uniprot.org/help/function_section

Args:
        uniprot_id: Valid UniProt ID

    Returns:


def Analyze(self, hashes):

    hash_analyses = []
    for digest in hashes:
      json_response = self._QueryHash(digest)
      hash_analysis = interface.HashAnalysis(digest, json_response)
      hash_analyses.append(hash_analysis)

    return hash_analyses

Looks up hashes in Viper using the Viper HTTP API.

Args:
        hashes (list[str]): hashes to look up.

Returns:
        list[HashAnalysis]: hash analysis.

Raises:
        RuntimeError: If no host has been set for Viper.


def _Open(self, path_spec=None, mode='rb'):

    if not path_spec:
      raise ValueError('Missing path specification.')

    if not path_spec.HasParent():
      raise errors.PathSpecError(
          'Unsupported path specification without parent.')

    self._gzip_file_object = resolver.Resolver.OpenFileObject(
        path_spec.parent, resolver_context=self._resolver_context)
    file_size = self._gzip_file_object.get_size()

    self._gzip_file_object.seek(0, os.SEEK_SET)

    uncompressed_data_offset = 0
    next_member_offset = 0

    while next_member_offset < file_size:
      member = gzipfile.GzipMember(
          self._gzip_file_object, next_member_offset, uncompressed_data_offset)
      uncompressed_data_offset = (
          uncompressed_data_offset + member.uncompressed_data_size)
      self._members_by_end_offset[uncompressed_data_offset] = member
      self.uncompressed_data_size += member.uncompressed_data_size
      next_member_offset = member.member_end_offset

Opens the file-like object defined by path specification.

Args:
        path_spec (Optional[PathSpec]): path specification.
        mode (Optional[str]): file access mode.

Raises:
        AccessError: if the access to open the file was denied.
        IOError: if the file-like object could not be opened.
        OSError: if the file-like object could not be opened.
        PathSpecError: if the path specification is incorrect.
        ValueError: if the path specification is invalid.


def compute_classification_results(self, adv_batches, dataset_batches,
                                     dataset_meta, defense_work=None):

    class_batch_to_work = {}
    if defense_work:
      for v in itervalues(defense_work.work):
        class_batch_to_work[v['output_classification_batch_id']] = v

    # accuracy_matrix[defense_id, attack_id] = num correctly classified
    accuracy_matrix = ResultMatrix()
    # error_matrix[defense_id, attack_id] = num misclassfied
    error_matrix = ResultMatrix()
    # hit_target_class_matrix[defense_id, attack_id] = num hit target class
    hit_target_class_matrix = ResultMatrix()
    # processed_images_count[defense_id] = num processed images by defense
    processed_images_count = {}

    total_count = len(self.data)
    processed_count = 0
    logging.info('Processing %d files with classification results',
                 len(self.data))
    for k, v in iteritems(self.data):
      if processed_count % 100 == 0:
        logging.info('Processed %d out of %d classification results',
                     processed_count, total_count)
      processed_count += 1
      defense_id = v['submission_id']
      adv_batch = adv_batches.data[v['adversarial_batch_id']]
      attack_id = adv_batch['submission_id']

      work_item = class_batch_to_work.get(k)
      required_work_stats = ['stat_correct', 'stat_error', 'stat_target_class',
                             'stat_num_images']
      if work_item and work_item['error']:
        # ignore batches with error
        continue
      if work_item and all(work_item.get(i) is not None
                           for i in required_work_stats):
        count_correctly_classified = work_item['stat_correct']
        count_errors = work_item['stat_error']
        count_hit_target_class = work_item['stat_target_class']
        num_images = work_item['stat_num_images']
      else:
        logging.warning('Recomputing accuracy for classification batch %s', k)
        (count_correctly_classified, count_errors, count_hit_target_class,
         num_images) = analyze_one_classification_result(
             self._storage_client, v['result_path'], adv_batch, dataset_batches,
             dataset_meta)

      # update accuracy and hit target class
      accuracy_matrix[defense_id, attack_id] += count_correctly_classified
      error_matrix[defense_id, attack_id] += count_errors
      hit_target_class_matrix[defense_id, attack_id] += count_hit_target_class
      # update number of processed images
      processed_images_count[defense_id] = (
          processed_images_count.get(defense_id, 0) + num_images)
    return (accuracy_matrix, error_matrix, hit_target_class_matrix,
            processed_images_count)

Computes classification results.

Args:
        adv_batches: instance of AversarialBatches
        dataset_batches: instance of DatasetBatches
        dataset_meta: instance of DatasetMetadata
        defense_work: instance of DefenseWorkPieces

Returns:
        accuracy_matrix, error_matrix, hit_target_class_matrix,
        processed_images_count


def replaceFA(self, faDataType: int, xml: str):

        self.client.replaceFA(faDataType, xml)

Replaces Financial Advisor's settings.

Args:
        faDataType: See :meth:`.requestFA`.
        xml: The XML-formatted configuration string.


def substitute(dict_, source):

    d_esc = (re.escape(k) for k in dict_.keys())
    pattern = re.compile('|'.join(d_esc))
    return pattern.sub(lambda x: dict_[x.group()], source)

Perform re.sub with the patterns in the given dict

Args:
        dict_: {pattern: repl}
        source: str


def is_unknown(input, model_file=None, model_proto=None, name=None):

  return _gen_sentencepiece_processor_op.sentencepiece_get_piece_type(
      input, model_file=model_file, model_proto=model_proto, name=name,
      piece_type=0)

Returns true if input id is unknown piece.

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

Returns:
        A tensor of bool with the same shape as input.


def _create_test(self, testcase, function_name, sdkobject, attribute=None):

        func = getattr(testcase, function_name)
        object_name = sdkobject.rest_name

        # Name that will be displayed
        test_name = ""
        rep = dict()
        rep["object"] = object_name

        if attribute:
            rep["attribute"] = attribute.local_name

        rep = dict((re.escape(k), v) for k, v in rep.items())
        pattern = re.compile("|".join(list(rep.keys())))

        if function_name.startswith("_"):
            function_name = function_name[1:]

        test_name = pattern.sub(lambda m: rep[re.escape(m.group(0))], function_name)

        # Prepare and add test method to test suite
        test_func = None

        if attribute:
            test_func = lambda self, attribute=attribute: func(self, attribute)
        else:
            test_func = lambda self: func(self)

        test_func.__name__ = str(test_name)

        return (test_name, test_func)

Create a test method for the sdkoject

Args:
        testcase: the testcase to that should manage the method
        function_name: the name of the method in the testcase
        sdkobject: the object that should be tested
        attribute: the attribute information if necessary

Returns:
        It returns a tuple (name, method) that represents the test method


def pil_image(self, fill_value=None, compute=True):

        channels, mode = self.finalize(fill_value)
        res = channels.transpose('y', 'x', 'bands')
        img = dask.delayed(PILImage.fromarray)(np.squeeze(res.data), mode)
        if compute:
            img = img.compute()
        return img

Return a PIL image from the current image.

Args:
        fill_value (int or float): Value to use for NaN null values.
            See :meth:`~trollimage.xrimage.XRImage.finalize` for more
            info.
        compute (bool): Whether to return a fully computed PIL.Image
            object (True) or return a dask Delayed object representing
            the Image (False). This is True by default.


def filter_by_dates(files_or_folders: list, date_fmt=DATE_FMT) -> list:

    r = re.compile(f'.*{date_fmt}.*')
    return list(filter(
        lambda vv: r.match(vv.replace('\\', '/').split('/')[-1]) is not None,
        files_or_folders,
    ))

Filter files or dates by date patterns

Args:
        files_or_folders: list of files or folders
        date_fmt: date format

Returns:
        list


def __init__(self, optimizer, scope=None, summary_labels=(), **kwargs):

        self.tf_optimizer_type = optimizer
        self.tf_optimizer = TFOptimizer.tf_optimizers[optimizer](**kwargs)

        super(TFOptimizer, self).__init__(scope=(scope or optimizer), summary_labels=summary_labels)

Creates a new optimizer instance of a TensorFlow optimizer.

Args:
        optimizer: The name of the optimizer. Must be one of the keys of the tf_optimizers dict.
        **kwargs: Arguments passed on to the TensorFlow optimizer constructor as **kwargs.


def send_data(data):

    datalength = len(data)
    csm1 = checksum1(data, datalength)
    csm2 = checksum2(csm1)
    data.insert(0, 0xFF)
    data.insert(1, 0xFF)
    data.insert(5, csm1)
    data.insert(6, csm2)
    stringtosend = ""
    for i in range(len(data)):
        byteformat = '%02X' % data[i]
        stringtosend = stringtosend + "\\x" + byteformat

    try:

        SERPORT.write(stringtosend.decode('string-escape'))
        #print stringtosend

    except:
        raise HerkulexError("could not communicate with motors")

Send data to herkulex

    Paketize & write the packet to serial port

Args:
        data (list): the data to be sent

Raises:
        SerialException: Error occured while opening serial port


def draw_pl_vote(m, gamma):

    localgamma = np.copy(gamma) # work on a copy of gamma
    localalts = np.arange(m) # enumeration of the candidates
    vote = []
    for j in range(m): # generate position in vote for every alternative

        # transform local gamma into intervals up to 1.0
        localgammaintervals = np.copy(localgamma)
        prev = 0.0
        for k in range(len(localgammaintervals)):
            localgammaintervals[k] += prev
            prev = localgammaintervals[k]

        selection = np.random.random() # pick random number

        # selection will fall into a gamma interval
        for l in range(len(localgammaintervals)): # determine position
            if selection <= localgammaintervals[l]:
                vote.append(localalts[l])
                localgamma = np.delete(localgamma, l) # remove that gamma
                localalts = np.delete(localalts, l) # remove the alternative
                localgamma /= np.sum(localgamma) # renormalize
                break
    return vote

Description:
    Generate a Plackett-Luce vote given the model parameters.
    Parameters:
    m:     number of alternatives
    gamma: parameters of the Plackett-Luce model


def write(data, file_name, worksheet_names=None):

    if re.search(XML_EXT_REGEX, file_name):
        return write_xml(data, file_name, worksheet_names=worksheet_names)
    elif re.search(XLSX_EXT_REGEX, file_name):
        return write_xlsx(data, file_name, worksheet_names=worksheet_names)
    elif re.search(XLS_EXT_REGEX, file_name):
        return write_xls(data, file_name, worksheet_names=worksheet_names)
    elif re.search(CSV_EXT_REGEX, file_name):
        return write_csv(data, file_name)
    else:
        return write_csv(data, file_name)

Writes 2D tables to file.

Args:
        data: 2D list of tables/worksheets.
        file_name: Name of the output file (determines type).
        worksheet_names: A list of worksheet names (optional).


def adversary_assets(self, main_type, sub_type, unique_id, params=None):

        params = params or {}

        url = '/v2/{}/{}/{}/adversaryAssets'.format(main_type, sub_type, unique_id)
        for aa in self._iterate(url, params, 'adversaryAsset'):
            yield aa

Args:
    main_type:
    sub_type:
    unique_id:
    params:

    Return:


def load_b26_file(file_name):

    # file_name = "Z:\Lab\Cantilever\Measurements\\tmp_\\a"

    assert os.path.exists(file_name)

    with open(file_name, 'r') as infile:
        data = yaml.safe_load(infile)
    return data

loads a .b26 file into a dictionary

Args:
        file_name:

    Returns: dictionary with keys instrument, scripts, probes


def submit_files(self, halt_on_error=True):

        # check global setting for override
        if self.halt_on_file_error is not None:
            halt_on_error = self.halt_on_file_error

        upload_status = []
        for xid, content_data in self._files.items():
            del self._files[xid]  # win or loose remove the entry
            status = True

            # used for debug/testing to prevent upload of previously uploaded file
            if self.debug and xid in self.saved_xids:
                self.tcex.log.debug('skipping previously saved file {}.'.format(xid))
                continue

            # process the file content
            content = content_data.get('fileContent')
            if callable(content):
                content = content_data.get('fileContent')(xid)
            if content is None:
                upload_status.append({'uploaded': False, 'xid': xid})
                self.tcex.log.warning('File content was null for xid {}.'.format(xid))
                continue
            if content_data.get('type') == 'Document':
                api_branch = 'documents'
            elif content_data.get('type') == 'Report':
                api_branch = 'reports'

            # Post File
            url = '/v2/groups/{}/{}/upload'.format(api_branch, xid)
            headers = {'Content-Type': 'application/octet-stream'}
            params = {'owner': self._owner}
            r = self.submit_file_content('POST', url, content, headers, params, halt_on_error)
            if r.status_code == 401:
                # use PUT method if file already exists
                self.tcex.log.info('Received 401 status code using POST. Trying PUT to update.')
                r = self.submit_file_content('PUT', url, content, headers, params, halt_on_error)
            self.tcex.log.debug('{} Upload URL: {}.'.format(content_data.get('type'), r.url))
            if not r.ok:
                status = False
                self.tcex.handle_error(585, [r.status_code, r.text], halt_on_error)
            elif self.debug:
                self.saved_xids.append(xid)
            self.tcex.log.info('Status {} for file upload with xid {}.'.format(r.status_code, xid))
            upload_status.append({'uploaded': status, 'xid': xid})
        return upload_status

Submit Files for Documents and Reports to ThreatConnect API.

    Critical Errors

    * There is insufficient document storage allocated to this account.

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

Returns:
        dict: The upload status for each xid.


def decrypt(key, ciphertext):

    index = 0
    decrypted = ""
    for char in ciphertext:
        if char in string.punctuation + string.whitespace + string.digits:
            decrypted += char
            continue  # Not part of the decryption

        # Rotate character by the alphabet position of the letter in the key
        alphabet = string.ascii_uppercase if key[index].isupper() else string.ascii_lowercase
        decrypted += ''.join(shift.decrypt(int(alphabet.index(key[index])), char))
        index = (index + 1) % len(key)

    return decrypted

Decrypt Vigenere encrypted ``ciphertext`` using ``key``.

Example:
        >>> decrypt("KEY", "RIJVS")
        HELLO

Args:
        key (iterable): The key to use
        ciphertext (str): The text to decrypt

Returns:
        Decrypted ciphertext


def set_config_variables(repo, variables):

    with repo.config_writer() as writer:
        for k, value in variables.items():
            section, option = k.split('.')
            writer.set_value(section, option, value)
        writer.release()

Set config variables

Args:
        repo (git.Repo): repo
        variables (dict): entries of the form 'user.email': 'you@example.com'


def showAddColumnDialog(self, triggered):

        if triggered:
            dialog = AddAttributesDialog(self)
            dialog.accepted.connect(self.addColumn)
            dialog.rejected.connect(self.uncheckButton)
            dialog.show()

Display the dialog to add a column to the model.

    This method is also a slot.

Args:
        triggered (bool): If the corresponding button was
            activated, the dialog will be created and shown.


def deserialize_subject_info(subject_info_xml):

    try:
        return d1_common.xml.deserialize(subject_info_xml)
    except ValueError as e:
        raise d1_common.types.exceptions.InvalidToken(
            0,
            'Could not deserialize SubjectInfo. subject_info="{}", error="{}"'.format(
                subject_info_xml, str(e)
            ),
        )

Deserialize SubjectInfo XML doc to native object.

Args:
        subject_info_xml: str
            SubjectInfo XML doc

Returns:
        SubjectInfo PyXB object


def update_ledger(self, ledger_id, description=None):

        arguments = {'description': description}
        return self.do_req('PUT',
                           self.merchant_api_base_url + '/ledger/' +
                           ledger_id + '/', arguments)

Update ledger info

Args:
        ledger_id:
            Ledger id assigned by mCASH
        description:
            Description of the Ledger and it's usage


def ValidateDependencies(rdf_artifact):

  for dependency in GetArtifactDependencies(rdf_artifact):
    try:
      dependency_obj = REGISTRY.GetArtifact(dependency)
    except rdf_artifacts.ArtifactNotRegisteredError as e:
      raise rdf_artifacts.ArtifactDependencyError(
          rdf_artifact, "missing dependency", cause=e)

    message = dependency_obj.error_message
    if message:
      raise rdf_artifacts.ArtifactDependencyError(
          rdf_artifact, "dependency error", cause=message)

Validates artifact dependencies.

    This method checks whether all dependencies of the artifact are present
    and contain no errors.

    This method can be called only after all other artifacts have been loaded.

Args:
        rdf_artifact: RDF object artifact.

Raises:
        ArtifactDependencyError: If a dependency is missing or contains errors.


def snapshot(self, filename="tmp.png"):

        if not filename:
            filename = "tmp.png"
        if self.handle:
            try:
                screenshot(filename, self.handle)
            except win32gui.error:
                self.handle = None
                screenshot(filename)
        else:
            screenshot(filename)

        img = aircv.imread(filename)
        os.remove(filename)

        return img

Take a screenshot and save it to `tmp.png` filename by default

Args:
        filename: name of file where to store the screenshot

Returns:
        display the screenshot


def MakeCdfFromItems(items, name=''):

    runsum = 0
    xs = []
    cs = []

    for value, count in sorted(items):
        runsum += count
        xs.append(value)
        cs.append(runsum)

    total = float(runsum)
    ps = [c / total for c in cs]

    cdf = Cdf(xs, ps, name)
    return cdf

Makes a cdf from an unsorted sequence of (value, frequency) pairs.

Args:
        items: unsorted sequence of (value, frequency) pairs
        name: string name for this CDF

Returns:
        cdf: list of (value, fraction) pairs


def __init__(self, resolver_context):

    super(VShadowFileSystem, self).__init__(resolver_context)
    self._file_object = None
    self._vshadow_volume = None

Initializes a file system.

Args:
        resolver_context (Context): resolver context.


def filter_by_pattern(self, pattern):

        _filt_values, _filt_datetimes = self._filter_by_pattern(pattern)
        if self._enumeration is None:
            self._get_mutable_enumeration()
        col_obj = self._enumeration['mutable'][self._collection_type]
        collection = col_obj(self.header.duplicate(), _filt_values, _filt_datetimes)
        collection._validated_a_period = self._validated_a_period
        return collection

Filter the Data Collection based on a list of booleans.

Args:
        pattern: A list of True/False values.  Typically, this is a list
            with a length matching the length of the Data Collections values
            but it can also be a pattern to be repeated over the Data Collection.

Returns:
        A new Data Collection with filtered data


def __init__(self, filename,f_start=None, f_stop=None,t_start=None, t_stop=None, load_data=True, max_load=1.):

        super(FilReader, self).__init__()

        self.header_keywords_types = sigproc.header_keyword_types

        if filename and os.path.isfile(filename):
            self.filename = filename
            self.load_data = load_data
            self.header = self.read_header()
            self.file_size_bytes = os.path.getsize(self.filename)
            self.idx_data = sigproc.len_header(self.filename)
            self.n_channels_in_file  = self.header[b'nchans']
            self.n_beams_in_file = self.header[b'nifs'] #Placeholder for future development.
            self.n_pols_in_file = 1 #Placeholder for future development.
            self._n_bytes = int(self.header[b'nbits'] / 8)  #number of bytes per digit.
            self._d_type = self._setup_dtype()
            self._setup_n_ints_in_file()
            self.file_shape = (self.n_ints_in_file,self.n_beams_in_file,self.n_channels_in_file)

            if self.header[b'foff'] < 0:
                self.f_end  = self.header[b'fch1']
                self.f_begin  = self.f_end + self.n_channels_in_file*self.header[b'foff']
            else:
                self.f_begin  = self.header[b'fch1']
                self.f_end  = self.f_begin + self.n_channels_in_file*self.header[b'foff']

            self.t_begin = 0
            self.t_end = self.n_ints_in_file

            #Taking care all the frequencies are assigned correctly.
            self._setup_selection_range(f_start=f_start, f_stop=f_stop, t_start=t_start, t_stop=t_stop, init=True)
            #Convert input frequencies into what their corresponding channel number would be.
            self._setup_chans()
            #Update frequencies ranges from channel number.
            self._setup_freqs()

            self.freq_axis = 2
            self.time_axis = 0
            self.beam_axis = 1  # Place holder

#EE ie.
#           spec = np.squeeze(fil_file.data)
            # set start of data, at real length of header  (future development.)
#            self.datastart=self.hdrraw.find('HEADER_END')+len('HEADER_END')+self.startsample*self.channels

            #Applying data size limit to load.
            if max_load is not None:
                if max_load > 1.0:
                    logger.warning('Setting data limit != 1GB, please handle with care!')
                self.MAX_DATA_ARRAY_SIZE = max_load * MAX_DATA_ARRAY_SIZE_UNIT
            else:
                self.MAX_DATA_ARRAY_SIZE = MAX_DATA_ARRAY_SIZE_UNIT

            if self.file_size_bytes > self.MAX_DATA_ARRAY_SIZE:
                self.large_file = True
            else:
                self.large_file = False

            if self.load_data:
                if self.large_file:
                    if self.f_start or self.f_stop or self.t_start or self.t_stop:
                        if self.isheavy():
                            logger.warning("Selection size of %.2f GB, exceeding our size limit %.2f GB. Instance created, header loaded, but data not loaded, please try another (t,v) selection." % (self._calc_selection_size() / (1024. ** 3), self.MAX_DATA_ARRAY_SIZE / (1024. ** 3)))
                            self._init_empty_selection()
                        else:
                            self.read_data()
                    else:
                        logger.warning("The file is of size %.2f GB, exceeding our size limit %.2f GB. Instance created, header loaded, but data not loaded. You could try another (t,v) selection."%(self.file_size_bytes/(1024.**3), self.MAX_DATA_ARRAY_SIZE/(1024.**3)))
                        self._init_empty_selection()
                else:
                    self.read_data()
            else:
                logger.info("Skipping loading data ...")
                self._init_empty_selection()
        else:
            raise IOError("Need a file to open, please give me one!")

Constructor.

Args:
        filename (str): filename of blimpy file.
        f_start (float): start frequency, in MHz
        f_stop (float): stop frequency, in MHz
        t_start (int): start time bin
        t_stop (int): stop time bin


def sign(self, byts):

        chosen_hash = c_hashes.SHA256()
        hasher = c_hashes.Hash(chosen_hash, default_backend())
        hasher.update(byts)
        digest = hasher.finalize()
        return self.priv.sign(digest,
                              c_ec.ECDSA(c_utils.Prehashed(chosen_hash))
                              )

Compute the ECC signature for the given bytestream.

Args:
        byts (bytes): The bytes to sign.

Returns:
        bytes: The RSA Signature bytes.


def _parse_udf_file_entry(self, abs_file_entry_extent, icb, parent):
        # type: (int, udfmod.UDFLongAD, Optional[udfmod.UDFFileEntry]) -> Optional[udfmod.UDFFileEntry]

        self._seek_to_extent(abs_file_entry_extent)
        icbdata = self._cdfp.read(icb.extent_length)

        if all(v == 0 for v in bytearray(icbdata)):
            # We have seen ISOs in the wild (Windows 2008 Datacenter Enterprise
            # Standard SP2 x86 DVD) where the UDF File Identifier points to a
            # UDF File Entry of all zeros.  In those cases, we just keep the
            # File Identifier, and keep the UDF File Entry blank.
            return None

        desc_tag = udfmod.UDFTag()
        desc_tag.parse(icbdata, icb.log_block_num)
        if desc_tag.tag_ident != 261:
            raise pycdlibexception.PyCdlibInvalidISO('UDF File Entry Tag identifier not 261')

        file_entry = udfmod.UDFFileEntry()
        file_entry.parse(icbdata, abs_file_entry_extent, parent, desc_tag)

        return file_entry

An internal method to parse a single UDF File Entry and return the
    corresponding object.

    Parameters:
    part_start - The extent number the partition starts at.
    icb - The ICB object for the data.
    parent - The parent of the UDF File Entry.

Returns:
    A UDF File Entry object corresponding to the on-disk File Entry.


def load(self, languages=[]):

        duckling_load = self.clojure.var("duckling.core", "load!")
        clojure_hashmap = self.clojure.var("clojure.core", "hash-map")
        clojure_list = self.clojure.var("clojure.core", "list")

        if languages:
            # Duckling's load function expects ISO 639-1 Language Codes (e.g. "en")
            iso_languages = [Language.convert_to_iso(lang) for lang in languages]

            duckling_load.invoke(
                clojure_hashmap.invoke(
                    self.clojure.read(':languages'),
                    clojure_list.invoke(*iso_languages)
                )
            )
        else:
            duckling_load.invoke()

        self._is_loaded = True

Loads the Duckling corpus.

    Languages can be specified, defaults to all.

Args:
        languages: Optional parameter to specify languages,
            e.g. [Duckling.ENGLISH, Duckling.FRENCH] or supported ISO 639-1 Codes (e.g. ["en", "fr"])


def __init__(self, unit_def):

        if isinstance(unit_def, str):
            unit = collections.defaultdict(int)
            import re
            for m in re.finditer(r"([A-Za-z]+)\s*\^*\s*([\-0-9]*)", unit_def):
                p = m.group(2)
                p = 1 if not p else int(p)
                k = m.group(1)
                unit[k] += p
        else:
            unit = {k: v for k, v in dict(unit_def).items() if v != 0}
        self._unit = check_mappings(unit)

Constructs a unit.

Args:
        unit_def: A definition for the unit. Either a mapping of unit to
            powers, e.g., {"m": 2, "s": -1} represents "m^2 s^-1",
            or simply as a string "kg m^2 s^-1". Note that the supported
            format uses "^" as the power operator and all units must be
            space-separated.


def create(self, callback_url):

        resource = self.resource.create({'subscribed_to': 'address',
                                         'callback_url': callback_url})
        subscription = self.wrap(resource)
        self.add(subscription)
        return subscription

Register a new Subscription on this collection's parent object.

Args:
        callback_url (str): URI of an active endpoint which can receive
        notifications.

Returns:
        A round.Subscription object if successful.


def new(self):
        # type: () -> None

        if self._initialized:
            raise pycdlibexception.PyCdlibInternalError('UDF File Set Descriptor already initialized')

        self.desc_tag = UDFTag()
        self.desc_tag.new(256)  # FIXME: we should let the user set serial_number

        self.recording_date = UDFTimestamp()
        self.recording_date.new()

        self.domain_ident = UDFEntityID()
        self.domain_ident.new(0, b'*OSTA UDF Compliant', b'\x02\x01\x03')

        self.root_dir_icb = UDFLongAD()
        self.root_dir_icb.new(2048, 2)

        self.file_set_num = 0
        self.log_vol_char_set = _unicodecharset()
        self.log_vol_ident = _ostaunicode_zero_pad('CDROM', 128)
        self.file_set_char_set = _unicodecharset()
        self.file_set_ident = _ostaunicode_zero_pad('CDROM', 32)
        self.copyright_file_ident = b'\x00' * 32  # FIXME: let the user set this
        self.abstract_file_ident = b'\x00' * 32  # FIXME: let the user set this

        self._initialized = True

A method to create a new UDF File Set Descriptor.

    Parameters:
    None.

Returns:
    Nothing.


def get_pourbaix_plot(self, limits=None, title="",
                          label_domains=True, plt=None):

        if limits is None:
            limits = [[-2, 16], [-3, 3]]

        plt = plt or pretty_plot(16)

        xlim = limits[0]
        ylim = limits[1]

        h_line = np.transpose([[xlim[0], -xlim[0] * PREFAC],
                               [xlim[1], -xlim[1] * PREFAC]])
        o_line = np.transpose([[xlim[0], -xlim[0] * PREFAC + 1.23],
                               [xlim[1], -xlim[1] * PREFAC + 1.23]])
        neutral_line = np.transpose([[7, ylim[0]], [7, ylim[1]]])
        V0_line = np.transpose([[xlim[0], 0], [xlim[1], 0]])

        ax = plt.gca()
        ax.set_xlim(xlim)
        ax.set_ylim(ylim)
        lw = 3
        plt.plot(h_line[0], h_line[1], "r--", linewidth=lw)
        plt.plot(o_line[0], o_line[1], "r--", linewidth=lw)
        plt.plot(neutral_line[0], neutral_line[1], "k-.", linewidth=lw)
        plt.plot(V0_line[0], V0_line[1], "k-.", linewidth=lw)

        for entry, vertices in self._pd._stable_domain_vertices.items():
            center = np.average(vertices, axis=0)
            x, y = np.transpose(np.vstack([vertices, vertices[0]]))
            plt.plot(x, y, 'k-', linewidth=lw)
            if label_domains:
                plt.annotate(generate_entry_label(entry), center, ha='center',
                             va='center', fontsize=20, color="b")

        plt.xlabel("pH")
        plt.ylabel("E (V)")
        plt.title(title, fontsize=20, fontweight='bold')
        return plt

Plot Pourbaix diagram.

Args:
        limits: 2D list containing limits of the Pourbaix diagram
            of the form [[xlo, xhi], [ylo, yhi]]
        title (str): Title to display on plot
        label_domains (bool): whether to label pourbaix domains
        plt (pyplot): Pyplot instance for plotting

Returns:
        plt (pyplot) - matplotlib plot object with pourbaix diagram


def __init__(self, path, script, optimized=True):

        # Save member variables
        self.path = path
        self.script = script

        if optimized:
            # For old ns-3 installations, the library is in build, while for
            # recent ns-3 installations it's in build/lib. Both paths are
            # thus required to support all versions of ns-3.
            library_path = "%s:%s" % (
                os.path.join(path, 'build/optimized'),
                os.path.join(path, 'build/optimized/lib'))

            # We use both LD_ and DYLD_ to support Linux and Mac OS.
            self.environment = {
                'LD_LIBRARY_PATH': library_path,
                'DYLD_LIBRARY_PATH': library_path}
        else:
            library_path = "%s:%s" % (os.path.join(path, 'build'),
                                      os.path.join(path, 'build/lib'))
            self.environment = {
                'LD_LIBRARY_PATH': os.path.join(path, 'build'),
                'DYLD_LIBRARY_PATH': os.path.join(path, 'build')}

        # Configure and build ns-3
        self.configure_and_build(path, optimized=optimized)

        # ns-3's build status output is used to get the executable path for the
        # specified script.
        if optimized:
            build_status_path = os.path.join(path,
                                             'build/optimized/build-status.py')
        else:
            build_status_path = os.path.join(path,
                                             'build/build-status.py')

        # By importing the file, we can naturally get the dictionary
        try:  # This only works on Python >= 3.5
            spec = importlib.util.spec_from_file_location('build_status',
                                                          build_status_path)
            build_status = importlib.util.module_from_spec(spec)
            spec.loader.exec_module(build_status)
        except (AttributeError):  # This happens in Python <= 3.4
            import imp
            build_status = imp.load_source('build_status', build_status_path)

        # Search is simple: we look for the script name in the program field.
        # Note that this could yield multiple matches, in case the script name
        # string is contained in another script's name.
        # matches contains [program, path] for each program matching the script
        matches = [{'name': program,
                    'path': os.path.abspath(os.path.join(path, program))} for
                   program in build_status.ns3_runnable_programs if self.script
                   in program]

        if not matches:
            raise ValueError("Cannot find %s script" % self.script)

        # To handle multiple matches, we take the 'better matching' option,
        # i.e., the one with length closest to the original script name.
        match_percentages = map(lambda x: {'name': x['name'],
                                           'path': x['path'],
                                           'percentage':
                                           len(self.script)/len(x['name'])},
                                matches)

        self.script_executable = max(match_percentages,
                                     key=lambda x: x['percentage'])['path']

        if optimized and "scratch" in self.script_executable:
            self.script_executable = os.path.abspath(
                os.path.join(path, "build/optimized/scratch", self.script))

Initialization function.

Args:
        path (str): absolute path to the ns-3 installation this Runner
            should lock on.
        script (str): ns-3 script that will be used by this Runner.
        optimized (bool): whether this Runner should build ns-3 with the
            optimized profile.


def get_shape_str(tensors):

    if isinstance(tensors, (list, tuple)):
        for v in tensors:
            assert isinstance(v, (tf.Tensor, tf.Variable)), "Not a tensor: {}".format(type(v))
        shape_str = ",".join(
            map(lambda x: str(x.get_shape().as_list()), tensors))
    else:
        assert isinstance(tensors, (tf.Tensor, tf.Variable)), "Not a tensor: {}".format(type(tensors))
        shape_str = str(tensors.get_shape().as_list())
    return shape_str

Internally used by layer registry, to print shapes of inputs/outputs of layers.

Args:
        tensors (list or tf.Tensor): a tensor or a list of tensors

Returns:
        str: a string to describe the shape


def save_link(self, path_info):

        assert path_info["scheme"] == "local"
        path = path_info["path"]

        if not os.path.exists(path):
            return

        mtime, _ = get_mtime_and_size(path)
        inode = get_inode(path)
        relpath = os.path.relpath(path, self.root_dir)

        cmd = (
            "REPLACE INTO {}(path, inode, mtime) "
            'VALUES ("{}", {}, "{}")'.format(
                self.LINK_STATE_TABLE, relpath, self._to_sqlite(inode), mtime
            )
        )
        self._execute(cmd)

Adds the specified path to the list of links created by dvc. This
    list is later used on `dvc checkout` to cleanup old links.

Args:
        path_info (dict): path info to add to the list of links.


def scheduled_sample_prob(ground_truth_x,
                          generated_x,
                          batch_size,
                          scheduled_sample_var):

  probability_threshold = scheduled_sample_var
  probability_of_generated = tf.random_uniform([batch_size])
  return tf.where(probability_of_generated > probability_threshold,
                  generated_x, ground_truth_x)

Probability based scheduled sampling.

Args:
        ground_truth_x: tensor of ground-truth data points.
        generated_x: tensor of generated data points.
        batch_size: batch size
        scheduled_sample_var: probability of choosing from ground_truth.

Returns:
        New batch with randomly selected data points.


def _process_counter_example(self, mma, w_string):

        diff = len(w_string)
        same = 0
        membership_answer = self._membership_query(w_string)
        while True:
            i = (same + diff) / 2
            access_string = self._run_in_hypothesis(mma, w_string, i)
            if membership_answer != self._membership_query(access_string + w_string[i:]):
                diff = i
            else:
                same = i
            if diff - same == 1:
                break
        exp = w_string[diff:]
        self.observation_table.em_vector.append(exp)
        for row in self.observation_table.sm_vector + self.observation_table.smi_vector:
            self._fill_table_entry(row, exp)
        return 0

Process a counterexample in the Rivest-Schapire way.

Args:
        mma (DFA): The hypothesis automaton
        w_string (str): The examined string to be consumed

Returns:
        None


def _generate_entry(self, vm):

        return \
            '{name} ' \
            'ansible_host={ip} ' \
            'ansible_ssh_private_key_file={key}'.format(
                name=vm.name(),
                ip=vm.ip(),
                key=self.prefix.paths.ssh_id_rsa()
            )

Generate host entry for the given VM

Args:
        vm (lago.plugins.vm.VMPlugin): The VM for which the entry
            should be created for.

Returns:
        str: An entry for vm


def get_inputs_outputs(namespace, method, snapshot_id):

    body = {
        "methodNamespace" : namespace,
        "methodName"      : method,
        "methodVersion"   : snapshot_id
    }
    return __post("inputsOutputs", json=body)

Get a description of the inputs and outputs for a method.

    The method should exist in the methods repository.

Args:
        namespace (str): Methods namespace
        method (str): method name
        snapshot_id (int): snapshot_id of the method

    Swagger:
        https://api.firecloud.org/#!/Method_Repository/getMethodIO


def get_compute_usage(access_token, subscription_id, location):

    endpoint = ''.join([get_rm_endpoint(),
                        '/subscriptions/', subscription_id,
                        '/providers/Microsoft.compute/locations/', location,
                        '/usages?api-version=', COMP_API])
    return do_get(endpoint, access_token)

List compute usage and limits for a location.

Args:
        access_token (str): A valid Azure authentication token.
        subscription_id (str): Azure subscription id.
        location (str): Azure data center location. E.g. westus.

Returns:
        HTTP response. JSON body of Compute usage and limits data.


def AddBudget(self, client_customer_id, micro_amount):

    self.client.SetClientCustomerId(client_customer_id)

    budget_service = self.client.GetService('BudgetService')

    operations = [{
        'operator': 'ADD',
        'operand': {
            'name': 'Budget #%s' % time.time(),
            'amount': {
                'microAmount': micro_amount
            },
            'deliveryMethod': 'STANDARD'
        }
    }]

    return budget_service.mutate(operations)['value'][0]['budgetId']

Create a new Budget with the given microAmount.

Args:
        client_customer_id: str Client Customer Id used to create Budget.
        micro_amount: str The budget represented in micros.

Returns:
        str BudgetId of the newly created Budget.


def _gsa_force(grav, mass_i, mass_j, position_i, position_j):

    position_diff = numpy.subtract(position_j, position_i)
    distance = numpy.linalg.norm(position_diff)

    # The first 3 terms give the magnitude of the force
    # The last term is a vector that provides the direction
    # Epsilon prevents divide by zero errors
    return grav * (mass_i * mass_j) / (distance + EPSILON) * position_diff

Gives the force of solution j on solution i.

    Variable name in GSA paper given in ()

Args:
        grav: The gravitational constant. (G)
        mass_i: The mass of solution i (derived from fitness). (M_i)
        mass_j: The mass of solution j (derived from fitness). (M_j)
        position_i: The position of solution i. (x_i)
        position_j: The position of solution j. (x_j)

Returns:
        numpy.array; The force vector of solution j on solution i.


def __call__(self, text, toLang, fromLang=None):

        return self.skype.conn("GET", "{0}/skype/translate".format(SkypeConnection.API_TRANSLATE),
                               params={"from": fromLang or "", "to": toLang, "text": text},
                               auth=SkypeConnection.Auth.SkypeToken).json()

Attempt translation of a string.  Supports automatic language detection if ``fromLang`` is not specified.

Args:
        text (str): input text to be translated
        toLang (str): country code of output language
        fromLang (str): country code of input language


def imresize_like(img, dst_img, return_scale=False, interpolation='bilinear'):

    h, w = dst_img.shape[:2]
    return imresize(img, (w, h), return_scale, interpolation)

Resize image to the same size of a given image.

Args:
        img (ndarray): The input image.
        dst_img (ndarray): The target image.
        return_scale (bool): Whether to return `w_scale` and `h_scale`.
        interpolation (str): Same as :func:`resize`.

Returns:
        tuple or ndarray: (`resized_img`, `w_scale`, `h_scale`) or
            `resized_img`.


def simple_layer_stack(include_encdec_attention,
                       num_layers=6,
                       d_ff=2048,
                       num_heads=8,
                       d_kv=128,
                       dropout_rate=0.1):

  ret = []
  for _ in xrange(num_layers):
    ret.append(
        transformer_layers.SelfAttention(
            num_heads=num_heads,
            key_value_size=d_kv,
            attention_kwargs={"dropout_rate": dropout_rate}))
    if include_encdec_attention:
      ret.append(
          transformer_layers.EncDecAttention(
              num_heads=num_heads,
              key_value_size=d_kv,
              attention_kwargs={"dropout_rate": dropout_rate}))
    ret.append(
        transformer_layers.DenseReluDense(
            hidden_size=d_ff,
            dropout_rate=dropout_rate))
  return transformer.LayerStack(ret)

Create a layer stack.

Args:
        include_encdec_attention: a boolean
        num_layers: an integer
        d_ff: an integer
        num_heads: an integer
        d_kv: an integer
        dropout_rate: a float

Returns:
        a LayerStack


def relative_humidity(self, value=999):

        if value is not None:
            try:
                value = int(value)
            except ValueError:
                raise ValueError('value {} need to be of type int '
                                 'for field `relative_humidity`'.format(value))
            if value < 0:
                raise ValueError('value need to be greater or equal 0 '
                                 'for field `relative_humidity`')
            if value > 110:
                raise ValueError('value need to be smaller 110 '
                                 'for field `relative_humidity`')

        self._relative_humidity = value

Corresponds to IDD Field `relative_humidity`

Args:
        value (int): value for IDD Field `relative_humidity`
            value >= 0
            value <= 110
            Missing value: 999
            if `value` is None it will not be checked against the
            specification and is assumed to be a missing value

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


def consume_input(self, mystr, stack=[], state=1, curchar=0, depth=0):

        mystrsplit = mystr.split(' ')
        if self.s[state].type == 1:
            stack.append(self.s[state].sym)
            if len(self.s[state].trans) > 0:
                state = self.s[state].trans[0]
                if self.parse(
                        mystr,
                        stack=stack,
                        state=state,
                        curchar=curchar,
                        depth=depth + 1) == 1:
                    return True
            return False
        if self.s[state].type == 2:
            if len(stack) == 0:
                return False
            sym = stack.pop()
            for key in self.s[state].trans:
                if sym in self.s[state].trans[key]:
                    if self.parse(
                            mystr,
                            stack=stack,
                            state=key,
                            curchar=curchar,
                            depth=depth + 1) == 1:
                        return True
            return False
        if self.s[state].type == 3:
            for key in self.s[state].trans:
                if mystrsplit[curchar] in self.s[state].trans[key]:
                    # print 'found '
                    if curchar + 1 == len(mystrsplit) \
                            and 'closing' in self.s[key].trans:
                        return True
                    elif curchar + 1 == len(mystrsplit):
                        return False

                    # print 'lets try as next state the state ' + repr(key)
                    if self.parse(
                            mystr,
                            stack=stack,
                            state=key,
                            curchar=curchar + 1,
                            depth=depth + 1) == 1:
                        return True
            return False

Consumes an input and validates if it is accepted

Args:
        mystr (str): the input string to be consumes
        stack (list): the stack of symbols
        state (int): the current state of the PDA
        curchar (int): the index of the consumed character
        depth (int): the depth of the function call in the stack

Returns:
        bool: A value indicating the correct or erroneous execution


def preprocess(self, style):

        if self.property == 'font':
            style = [
                ''.join(u.expression()) if hasattr(u, 'expression') else u
                for u in style
            ]
        else:
            style = [(u, ' ') if hasattr(u, 'expression') else u
                     for u in style]
        return style

Hackish preprocessing from font shorthand tags.
    Skips expression parse on certain tags.

Args:
        style (list): .

Returns:
        list


def sample_many(self, num_samples = 2000):

        x = []
        y = []
        fix = []
        sample = []

        # XXX: Delete ProgressBar
        pbar = ProgressBar(widgets=[Percentage(),Bar()], maxval=num_samples).start()

        for s in range(0, num_samples):
            for i, (xs, ys) in enumerate(self.sample()):
                x.append(xs)
                y.append(ys)
                fix.append(i+1)
                sample.append(s)
            pbar.update(s+1)

        fields = {'fix':np.array(fix), 'y':np.array(y), 'x':np.array(x)}
        param = {'pixels_per_degree':self.fm.pixels_per_degree}
        out =  fixmat.VectorFixmatFactory(fields, param)
        return out

Generates a given number of trajectories, using the method sample().
    Returns a fixmat with the generated data.

    Parameters:
        num_samples : int, optional
            The number of trajectories that shall be generated.


def proc_val(key, val):

        list_keys = ("LDAUU", "LDAUL", "LDAUJ", "MAGMOM", "DIPOL",
                     "LANGEVIN_GAMMA", "QUAD_EFG", "EINT")
        bool_keys = ("LDAU", "LWAVE", "LSCALU", "LCHARG", "LPLANE", "LUSE_VDW",
                     "LHFCALC", "ADDGRID", "LSORBIT", "LNONCOLLINEAR")
        float_keys = ("EDIFF", "SIGMA", "TIME", "ENCUTFOCK", "HFSCREEN",
                      "POTIM", "EDIFFG", "AGGAC", "PARAM1", "PARAM2")
        int_keys = ("NSW", "NBANDS", "NELMIN", "ISIF", "IBRION", "ISPIN",
                    "ICHARG", "NELM", "ISMEAR", "NPAR", "LDAUPRINT", "LMAXMIX",
                    "ENCUT", "NSIM", "NKRED", "NUPDOWN", "ISPIND", "LDAUTYPE",
                    "IVDW")

        def smart_int_or_float(numstr):
            if numstr.find(".") != -1 or numstr.lower().find("e") != -1:
                return float(numstr)
            else:
                return int(numstr)

        try:
            if key in list_keys:
                output = []
                toks = re.findall(
                    r"(-?\d+\.?\d*)\*?(-?\d+\.?\d*)?\*?(-?\d+\.?\d*)?", val)
                for tok in toks:
                    if tok[2] and "3" in tok[0]:
                        output.extend(
                            [smart_int_or_float(tok[2])] * int(tok[0])
                            * int(tok[1]))
                    elif tok[1]:
                        output.extend([smart_int_or_float(tok[1])] *
                                      int(tok[0]))
                    else:
                        output.append(smart_int_or_float(tok[0]))
                return output
            if key in bool_keys:
                m = re.match(r"^\.?([T|F|t|f])[A-Za-z]*\.?", val)
                if m:
                    if m.group(1) == "T" or m.group(1) == "t":
                        return True
                    else:
                        return False
                raise ValueError(key + " should be a boolean type!")

            if key in float_keys:
                return float(re.search(r"^-?\d*\.?\d*[e|E]?-?\d*", val).group(0))

            if key in int_keys:
                return int(re.match(r"^-?[0-9]+", val).group(0))

        except ValueError:
            pass

        # Not in standard keys. We will try a hierarchy of conversions.
        try:
            val = int(val)
            return val
        except ValueError:
            pass

        try:
            val = float(val)
            return val
        except ValueError:
            pass

        if "true" in val.lower():
            return True

        if "false" in val.lower():
            return False

        return val.strip().capitalize()

Static helper method to convert INCAR parameters to proper types, e.g.,
    integers, floats, lists, etc.

Args:
        key: INCAR parameter key
        val: Actual value of INCAR parameter.


def get_generated_cols(X_original, X_transformed, to_transform):

    original_cols = list(X_original.columns)

    if len(to_transform) > 0:
        [original_cols.remove(c) for c in to_transform]

    current_cols = list(X_transformed.columns)
    if len(original_cols) > 0:
        [current_cols.remove(c) for c in original_cols]

    return current_cols

Returns a list of the generated/transformed columns.

Args:
        X_original: df
            the original (input) DataFrame.
        X_transformed: df
            the transformed (current) DataFrame.
        to_transform: [str]
            a list of columns that were transformed (as in the original DataFrame), commonly self.cols.

    Output:
        a list of columns that were transformed (as in the current DataFrame).


def askstring(title, prompt, **kw):

    return psidialogs.ask_string(title=title, message=prompt)

Original doc: get a string from the user

Args:
        title -- the dialog title
        prompt -- the label text
        **kw -- see SimpleDialog class

    Return value is a string


def add_parents(self, parents):

        self._parents += [p for p in parents if p not in self._parents]

Adds new parent nodes after filtering for duplicates

Args:
        parents (list): list of OmniTree nodes to add as parents


def _expression_to_sql(expression, node, context):

    _expression_transformers = {
        expressions.LocalField: _transform_local_field_to_expression,
        expressions.Variable: _transform_variable_to_expression,
        expressions.Literal: _transform_literal_to_expression,
        expressions.BinaryComposition: _transform_binary_composition_to_expression,
    }
    expression_type = type(expression)
    if expression_type not in _expression_transformers:
        raise NotImplementedError(
            u'Unsupported compiler expression "{}" of type "{}" cannot be converted to SQL '
            u'expression.'.format(expression, type(expression)))
    return _expression_transformers[expression_type](expression, node, context)

Recursively transform a Filter block predicate to its SQLAlchemy expression representation.

Args:
        expression: expression, the compiler expression to transform.
        node: SqlNode, the SqlNode the expression applies to.
        context: CompilationContext, global compilation state and metadata.

Returns:
        Expression, SQLAlchemy Expression equivalent to the passed compiler expression.


def get_structure_from_name(self, structure_name):

        return next((st for st in self.structures if st.name == structure_name), None)

Return a structure from a name

Args:
        structure_name (str): name of the structure

Returns:
        Structure


def parse_isoformat(timestamp):

        if len(timestamp) == 20:
            zone = TzOffset('+00:00')
            timestamp = timestamp[:-1]
        elif len(timestamp) == 24:
            zone = TzOffset('%s:%s' % (timestamp[-5:-2], timestamp[-2:]))
            timestamp = timestamp[:-5]
        elif len(timestamp) == 25:
            zone = TzOffset(timestamp[-6:])
            timestamp = timestamp[:-6]
        timestamp = Timestamp.strptime(timestamp, '%Y-%m-%dT%H:%M:%S')
        timestamp = timestamp.replace(tzinfo=zone)
        return timestamp

Parse an ISO 8601 formatted time stamp.

Args:
        timestamp (str): Timestamp to parse

Returns:
        Timestamp: Parsed timestamp


def load(nifti_filename):

    # Expand filename to be absolute
    nifti_filename = os.path.expanduser(nifti_filename)

    try:
        data = nib.load(nifti_filename)
        img = data.get_data()

    except Exception as e:
        raise ValueError("Could not load file {0} for conversion."
                         .format(nifti_filename))
        raise

    return img

Import a nifti file into a numpy array. TODO:  Currently only
    transfers raw data for compatibility with annotation and ND formats

Args:
        nifti_filename (str):  A string filename of a nifti datafile

Returns:
        A numpy array with data from the nifti file


def options(self, options=None):

		# If opts aren't set, this is a getter
		if options is None:
			return self._options

		# If the options are not a list
		if not isinstance(options, (list, tuple)):
			raise ValueError('__options__')

		# If the type is not one that can have options
		if self._type not in ['base64', 'date', 'datetime', 'decimal', 'float', \
								'int', 'ip', 'md5', 'price', 'string', 'time', \
								'timestamp', 'uint', 'uuid']:
			raise TypeError('can not set __options__ for ' + self._type)

		# Init the list of options to be saved
		lOpts = []

		# Go through each item and make sure it's unique and valid
		for i in range(len(options)):

			# Convert the value based on the type
			# If the type is a string one that we can validate
			if self._type in ['base64', 'date', 'datetime', 'ip', 'md5', 'time', 'uuid']:

				# If the value is not a string or doesn't match its regex, raise
				# 	an error
				if not isinstance(options[i], basestring) \
					or not _typeToRegex[self._type].match(options[i]):
					raise ValueError('__options__[%d]' % i)

			# Else if it's decimal
			elif self._type == 'decimal':

				# If it's a Decimal
				if isinstance(options[i], Decimal):
					pass

				# Else if we can't conver it
				else:
					try: options[i] = Decimal(options[i])
					except ValueError:
						raise ValueError('__options__[%d]' % i)

			# Else if it's a float
			elif self._type == 'float':

				try:
					options[i] = float(options[i])
				except ValueError:
					raise ValueError('__options__[%d]' % i)

			# Else if it's an integer
			elif self._type in ['int', 'timestamp', 'uint']:

				# If we don't already have an int
				if not isinstance(options[i], (int, long)):

					# And we don't have a string
					if not isinstance(options[i], basestring):
						raise ValueError('__options__[%d]' % i)

					try:
						options[i] = int(options[i], 0)
					except ValueError:
						raise ValueError('__options__[%d]' % i)

				# If the type is unsigned and negative, raise an error
				if self._type in ['timestamp', 'uint'] and options[i] < 0:
					raise ValueError('__options__[' + str(i) + ']')

			# Else if it's a price
			elif self._type == 'price':

				# If it's a Decimal
				if isinstance(options[i], Decimal):
					pass

				# Else if it's not a valid price representation
				elif not isinstance(options[i], basestring) or not _typeToRegex['price'].match(options[i]):
					raise ValueError('__options__[%d]' % i)

				# Store it as a Decimal
				options[i] = Decimal(options[i])

			# Else if the type is a string
			elif self._type == 'string':

				# If the value is not a string
				if not isinstance(options[i], basestring):

					# If the value can't be turned into a string
					try:
						options[i] = str(options[i])
					except ValueError:
						raise ValueError('__options__[%d]' % i)

			# Else we have no validation for the type
			else:
				raise TypeError('can not set __options__ for ' + self._type)

			# If it's already in the list, raise an error
			if options[i] in lOpts:
				sys.stderr.write('__options__[' + str(i) + '] is a duplicate')

			# Store the option
			else:
				lOpts.append(options[i])

		# Store the list of options
		self._options = lOpts

Options

    Sets or gets the list of acceptable values for the Node

Args:
    options {list} -- A list of valid values

Raises:
    TypeError, ValueError

Returns:
    None | list


def __init__(self, name):

        self.name = name
        self.edges_in = set()
        self.edges_out = set()

Initialization method.

Args:
        name (str): name of the vertex.


def AddArguments(cls, argument_group):

    argument_group.add_argument(
        '--analysis', metavar='PLUGIN_LIST', dest='analysis_plugins',
        default='', action='store', type=str, help=(
            'A comma separated list of analysis plugin names to be loaded '
            'or "--analysis list" to see a list of available plugins.'))

    arguments = sys.argv[1:]
    argument_index = 0

    if '--analysis' in arguments:
      argument_index = arguments.index('--analysis') + 1

    if 0 < argument_index < len(arguments):
      names = [name.strip() for name in arguments[argument_index].split(',')]
    else:
      names = None

    if names and names != ['list']:
      manager.ArgumentHelperManager.AddCommandLineArguments(
          argument_group, category='analysis', names=names)

Adds command line arguments to an argument group.

    This function takes an argument parser or an argument group object and adds
    to it all the command line arguments this helper supports.

Args:
        argument_group (argparse._ArgumentGroup|argparse.ArgumentParser):
        argparse group.


def set(self, status_item, status):

        lg = logging.getLogger("%s.%s" % (self.ln, inspect.stack()[0][3]))
        lg.setLevel(self.log_level)
        sparql =
        return self.conn.query(sparql=sparql.format(self.group,
                                                     status_item,
                                                     str(status).lower()),
                                mode='update')

sets the status item to the passed in paramaters

Args:
        status_item: the name if the item to set
        status: boolean value to set the item


def _publish_internal(self, push_messages):

        # Delayed import because this file is immediately read on install, and
        # the requests library may not be installed yet.
        import requests

        response = requests.post(
            self.host + self.api_url + '/push/send',
            data=json.dumps([pm.get_payload() for pm in push_messages]),
            headers={
                'accept': 'application/json',
                'accept-encoding': 'gzip, deflate',
                'content-type': 'application/json',
            }
        )

        # Let's validate the response format first.
        try:
            response_data = response.json()
        except ValueError:
            # The response isn't json. First, let's attempt to raise a normal
            # http error. If it's a 200, then we'll raise our own error.
            response.raise_for_status()

            raise PushServerError('Invalid server response', response)

        # If there are errors with the entire request, raise an error now.
        if 'errors' in response_data:
            raise PushServerError(
                'Request failed',
                response,
                response_data=response_data,
                errors=response_data['errors'])

        # We expect the response to have a 'data' field with the responses.
        if 'data' not in response_data:
            raise PushServerError(
                'Invalid server response',
                response,
                response_data=response_data)

        # Use the requests library's built-in exceptions for any remaining 4xx
        # and 5xx errors.
        response.raise_for_status()

        # Sanity check the response
        if len(push_messages) != len(response_data['data']):
            raise PushServerError(
                ('Mismatched response length. Expected %d %s but only '
                 'received %d' % (
                     len(push_messages),
                     'receipt' if len(push_messages) == 1 else 'receipts',
                     len(response_data['data']))),
                response,
                response_data=response_data)

        # At this point, we know it's a 200 and the response format is correct.
        # Now let's parse the responses per push notification.
        receipts = []
        for i, receipt in enumerate(response_data['data']):
            receipts.append(PushResponse(
                push_message=push_messages[i],
                # If there is no status, assume error.
                status=receipt.get('status', PushResponse.ERROR_STATUS),
                message=receipt.get('message', ''),
                details=receipt.get('details', None)))

        return receipts

Send push notifications

    The server will validate any type of syntax errors and the client will
    raise the proper exceptions for the user to handle.

    Each notification is of the form:
    {
        'to': 'ExponentPushToken[xxx]',
        'body': 'This text gets display in the notification',
        'badge': 1,
        'data': {'any': 'json object'},
    }

Args:
        push_messages: An array of PushMessage objects.


def _marginalize_factor(self, nodes, factor):

        marginalizing_nodes = list(set(factor.scope()).difference(nodes))
        return factor.marginalize(marginalizing_nodes, inplace=False)

Marginalizing the factor selectively for a set of variables.

    Parameters:
    ----------
    nodes: list, array-like
        A container of nodes (list, dict, set, etc.).

    factor: factor
        factor which is to be marginalized.


def fit_arrhenius(temps, diffusivities):

    t_1 = 1 / np.array(temps)
    logd = np.log(diffusivities)
    # Do a least squares regression of log(D) vs 1/T
    a = np.array([t_1, np.ones(len(temps))]).T
    w, res, _, _ = np.linalg.lstsq(a, logd, rcond=None)
    w = np.array(w)
    n = len(temps)
    if n > 2:
        std_Ea = (res[0] / (n - 2) / (
        n * np.var(t_1))) ** 0.5 * const.k / const.e
    else:
        std_Ea = None
    return -w[0] * const.k / const.e, np.exp(w[1]), std_Ea

Returns Ea, c, standard error of Ea from the Arrhenius fit:
    D = c * exp(-Ea/kT)

Args:
    temps ([float]): A sequence of temperatures. units: K
    diffusivities ([float]): A sequence of diffusivities (e.g.,
        from DiffusionAnalyzer.diffusivity). units: cm^2/s


def unexpected_disconnect(self, conn_or_internal_id):

        data = {
            'id': conn_or_internal_id
        }

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

Notify that there was an unexpected disconnection of the device.

    Any in progress operations are canceled cleanly and the device is transitioned
    to a disconnected state.

Args:
        conn_or_internal_id (string, int): Either an integer connection id or a string
            internal_id


def load_model(itos_filename, classifier_filename, num_classes):

    # load the int to string mapping file
    itos = pickle.load(Path(itos_filename).open('rb'))
    # turn it into a string to int mapping (which is what we need)
    stoi = collections.defaultdict(lambda:0, {str(v):int(k) for k,v in enumerate(itos)})

    # these parameters aren't used, but this is the easiest way to get a model
    bptt,em_sz,nh,nl = 70,400,1150,3
    dps = np.array([0.4,0.5,0.05,0.3,0.4])*0.5
    vs = len(itos)

    model = get_rnn_classifer(bptt, 20*70, num_classes, vs, emb_sz=em_sz, n_hid=nh, n_layers=nl, pad_token=1,
            layers=[em_sz*3, 50, num_classes], drops=[dps[4], 0.1],
            dropouti=dps[0], wdrop=dps[1], dropoute=dps[2], dropouth=dps[3])

    # load the trained classifier
    model.load_state_dict(torch.load(classifier_filename, map_location=lambda storage, loc: storage))

    # put the classifier into evaluation mode
    model.reset()
    model.eval()

    return stoi, model

Load the classifier and int to string mapping

Args:
        itos_filename (str): The filename of the int to string mapping file (usually called itos.pkl)
        classifier_filename (str): The filename of the trained classifier

Returns:
        string to int mapping, trained classifer model


def clone_rtcpath_update_rt_as(path, new_rt_as):

    assert path and new_rt_as
    if not path or path.route_family != RF_RTC_UC:
        raise ValueError('Expected RT_NLRI path')
    old_nlri = path.nlri
    new_rt_nlri = RouteTargetMembershipNLRI(new_rt_as, old_nlri.route_target)
    return RtcPath(path.source, new_rt_nlri, path.source_version_num,
                   pattrs=path.pathattr_map, nexthop=path.nexthop,
                   is_withdraw=path.is_withdraw)

Clones given RT NLRI `path`, and updates it with new RT_NLRI AS.

    Parameters:
        - `path`: (Path) RT_NLRI path
        - `new_rt_as`: AS value of cloned paths' RT_NLRI


def build_profile_variant(variant):

    chrom = variant.CHROM
    if chrom.startswith(('chr', 'CHR', 'Chr')):
        chrom = chrom[3:]

    pos = int(variant.POS)

    variant_id = get_variant_id(variant)

    ref = variant.REF
    alt = variant.ALT[0]

    maf = get_maf(variant)

    profile_variant = ProfileVariant(
        variant_id=variant_id,
        chrom=chrom,
        pos=pos,
        ref=ref,
        alt=alt,
        maf=maf,
        id_column = variant.ID
    )

    return profile_variant

Returns a ProfileVariant object

Args:
        variant (cyvcf2.Variant)

Returns:
        variant (models.ProfileVariant)


def assignSchedule(self, schedule, period, hour, minute, tariff):

        if ((schedule not in range(Extents.Schedules)) or
                (period not in range(Extents.Tariffs)) or
                (hour < 0) or (hour > 23) or (minute < 0) or
                (minute > 59) or (tariff < 0)):
            ekm_log("Out of bounds in Schedule_" + str(schedule + 1))
            return False

        period += 1
        idx_min = "Min_" + str(period)
        idx_hour = "Hour_" + str(period)
        idx_rate = "Tariff_" + str(period)
        if idx_min not in self.m_schedule_params:
            ekm_log("Incorrect index: " + idx_min)
            return False
        if idx_hour not in self.m_schedule_params:
            ekm_log("Incorrect index: " + idx_hour)
            return False
        if idx_rate not in self.m_schedule_params:
            ekm_log("Incorrect index: " + idx_rate)
            return False

        self.m_schedule_params[idx_rate] = tariff
        self.m_schedule_params[idx_hour] = hour
        self.m_schedule_params[idx_min] = minute
        self.m_schedule_params['Schedule'] = schedule
        return True

Assign one schedule tariff period to meter bufffer.

Args:
        schedule (int): A :class:`~ekmmeters.Schedules` value or in range(Extents.Schedules).
        tariff (int): :class:`~ekmmeters.Tariffs` value or in range(Extents.Tariffs).
        hour (int): Hour from 0-23.
        minute (int): Minute from 0-59.
        tariff (int): Rate value.

Returns:
        bool: True on completed assignment.


def assert_shape_match(shape1, shape2):

  shape1 = tf.TensorShape(shape1)
  shape2 = tf.TensorShape(shape2)
  if shape1.ndims is None or shape2.ndims is None:
    raise ValueError('Shapes must have known rank. Got %s and %s.' %
                     (shape1.ndims, shape2.ndims))
  shape1.assert_same_rank(shape2)
  shape1.assert_is_compatible_with(shape2)

Ensure the shape1 match the pattern given by shape2.

    Ex:
        assert_shape_match((64, 64, 3), (None, None, 3))

Args:
        shape1 (tuple): Static shape
        shape2 (tuple): Dynamic shape (can contain None)


def get_group_by_id(self, group_id: str) -> typing.Optional['Group']:

        VALID_POSITIVE_INT.validate(group_id, 'get_group_by_id', exc=ValueError)
        for group in self.groups:

            if group.group_id == group_id:
                return group
        return None

Gets a group by id

Args:
        group_id: group id

    Returns: Group


def run_local(self, commands):

        process = subprocess.Popen(
            commands.get('cli_command'),
            shell=self.shell,
            stdin=subprocess.PIPE,
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
        )

        out, err = process.communicate()

        # display app output
        self.run_display_app_output(out)
        self.run_display_app_errors(err)

        # Exit Code
        return self.run_exit_code(process.returncode)

Run the App on local system.

Args:
        commands (dict): A dictionary of the CLI commands.

Returns:
        int: The exit code of the subprocess command.


def convert_flatten(params, w_name, scope_name, inputs, layers, weights, names):

    print('Converting flatten ...')

    if names == 'short':
        tf_name = 'R' + random_string(7)
    elif names == 'keep':
        tf_name = w_name
    else:
        tf_name = w_name + str(random.random())

    reshape = keras.layers.Reshape([-1], name=tf_name)
    layers[scope_name] = reshape(layers[inputs[0]])

Convert reshape(view).

Args:
        params: dictionary with layer parameters
        w_name: name prefix in state_dict
        scope_name: pytorch scope name
        inputs: pytorch node inputs
        layers: dictionary with keras tensors
        weights: pytorch state_dict
        names: use short names for keras layers


def DisableInterfaces(interface):

  set_tested_versions = ['vista', '2008']
  set_args = ['/c', 'netsh', 'set', 'interface', interface, 'DISABLED']
  host_version = platform.platform().lower()
  for version in set_tested_versions:
    if host_version.find(version) != -1:
      # pylint: disable=undefined-variable
      res = client_utils_common.Execute(
          'cmd', set_args, time_limit=-1, bypass_whitelist=True)
      return res
  return ('', 'Command not available for this version.', 99, '')

Tries to disable an interface.  Only works on Vista and 7.

Args:
        interface: Name of the interface to disable.

Returns:
        res which is a tuple of (stdout, stderr, exit_status, time_taken).


def _x_flow_ok(self, active):

        args = AMQPWriter()
        args.write_bit(active)
        self._send_method((20, 21), args)

Confirm a flow method

    Confirms to the peer that a flow command was received and
    processed.

    PARAMETERS:
        active: boolean

            current flow setting

            Confirms the setting of the processed flow method:
            True means the peer will start sending or continue
            to send content frames; False means it will not.


def list_storage_accounts_rg(access_token, subscription_id, rgname):

    endpoint = ''.join([get_rm_endpoint(),
                        '/subscriptions/', subscription_id,
                        '/resourcegroups/', rgname,
                        '/providers/Microsoft.Storage/storageAccounts',
                        '?api-version=', STORAGE_API])
    return do_get(endpoint, access_token)

List the storage accounts in the specified resource group.

Args:
        access_token (str): A valid Azure authentication token.
        subscription_id (str): Azure subscription id.
        rgname (str): Azure resource group name.

Returns:
        HTTP response. JSON body list of storage accounts.


def dump_tests(self):

        log.info('Dumping tests')
        for test in self.test_map.values():
            try:
                test.dump()
            except ex.SerializeException as e:
                log.warning('Unable to dump {}: {}'.format(test.name, str(e)))
            else:
                log.info('Dumped {}'.format(test.name))

Dumps all tests, as determined by their .dump() method.

    PARAMETERS:
    tests -- dict; file -> Test. Each Test object has a .dump method
            that takes a filename and serializes the test object.


def interceptable(func):

  @functools.wraps(func)
  def func_wrapped(*args, **kwargs):
    with get_next_interceptor() as interceptor:
      return interceptor(func, *args, **kwargs)

  return func_wrapped

Decorator that wraps `func` so that its execution is intercepted.

    The wrapper passes `func` to the interceptor for the current thread.

    If there is no next interceptor, we perform an "immediate" call to `func`.
    That is, `func` terminates without forwarding its execution to another
    interceptor.

Args:
        func: Function to wrap.

Returns:
        The decorated function.


def use(self, middleware, path=None):

        self.log.info(" Using middleware {}", middleware)
        if path is None:
            path = MiddlewareChain.ROOT_PATTERN
        self.add(HTTPMethod.ALL, path, middleware)
        return self

Call the provided middleware upon requests matching the path.
    If path is not provided or None, all requests will match.

Args:
        middleware (callable): Callable with the signature
            ``(res, req) -> None``
        path (Optional[str or regex]): a specific path the
            request must match for the middleware to be called.

Returns:
        This router


def supported_language(lang):

    try:
      self.get_collection(lang=lang)
      return True
    except LanguageNotSupported as e:
      return False

Return True if polyglot supports the language.

Args:
        lang (string): Language code.


def mapTypeToSql(fld_type=FieldType.NoType, fld_len=0):

        if fld_type == FieldType.Float:
            return "FLOAT"
        elif fld_type == FieldType.String:
            return "VARCHAR(" + str(fld_len) + ")"
        elif fld_type == FieldType.Int:
            return "INT"
        elif fld_type == FieldType.Hex:
            return "VARCHAR(" + str(fld_len * 2) + ")"
        elif fld_type == FieldType.PowerFactor:
            return "VARCHAR(" + str(fld_len) + ")"
        else:
            ekm_log("Type " + str(type) + " not handled by mapTypeToSql, returned VARCHAR(255)")
            return "VARCHAR(255)"

Translate FieldType to portable SQL Type.  Override if needful.

Args:
        fld_type (int): :class:`~ekmmeters.FieldType` in serial block.
        fld_len (int): Binary length in serial block

Returns:
        string: Portable SQL type and length where appropriate.


def bottom(self, features):

    if not self._problem_hparams:
      log_warn("Without a Problem, T2TModel.bottom is a passthrough.")
      return features

    transformed_features = collections.OrderedDict()
    all_previous_modalities = []
    target_modality = _create_target_modality(self._problem_hparams.modality)

    # Transform features via its corresponding modality.
    for feature_name, modality in sorted(
        six.iteritems(self._problem_hparams.modality)):
      if feature_name not in features:
        tf.logging.warning("Missing feature %s - ignoring." % feature_name)
        continue
      vocab_size = self._problem_hparams.vocab_size[feature_name]
      if vocab_size is not None and hasattr(self._hparams, "vocab_divisor"):
        vocab_size += (-vocab_size) % self._hparams.vocab_divisor
      modality_name = self._hparams.name.get(
          feature_name,
          modalities.get_name(modality))(self._hparams, vocab_size)
      # Use if-else clauses to preserve behavior of previous changes: namely,
      # the variable scope name for the targets feature if there is only one
      # target modality; and to reuse variable scopes for only input modalities.
      if feature_name in target_modality:
        if len(target_modality) > 1:
          variable_scope_name = "%s/%s" % (modality_name, feature_name)
        else:
          variable_scope_name = modality_name
        bottom = self._hparams.bottom.get(
            feature_name,
            modalities.get_targets_bottom(modality))
        # TODO(aidangomez): share variables?
        with tf.variable_scope(variable_scope_name) as vs:
          self._add_variable_scope(variable_scope_name, vs)
          log_info("Transforming feature '%s' with %s.targets_bottom",
                   feature_name,
                   modality_name)
          transformed_features[feature_name] = bottom(features[feature_name],
                                                      self._hparams,
                                                      vocab_size)
      else:
        bottom = self._hparams.bottom.get(feature_name,
                                          modalities.get_bottom(modality))
        do_reuse = modality_name in all_previous_modalities
        with tf.variable_scope(modality_name, reuse=do_reuse) as vs:
          self._add_variable_scope(modality_name, vs)
          log_info("Transforming feature '%s' with %s.bottom",
                   feature_name,
                   modality_name)
          transformed_features[feature_name] = bottom(features[feature_name],
                                                      self._hparams,
                                                      vocab_size)
        all_previous_modalities.append(modality_name)

    for key in features:
      if key not in transformed_features:
        # For features without a modality, we pass them along as is
        transformed_features[key] = features[key]
      else:
        # Other features get passed along with the "raw" suffix
        transformed_features[key + "_raw"] = features[key]

    return transformed_features

Transforms features to feed into body.

Args:
        features: dict of str to Tensor. Typically it is the preprocessed data
        batch after Problem's preprocess_example().

Returns:
        transformed_features: dict of same key-value pairs as features. The value
        Tensors are newly transformed.


def timestamp(method='iso8601'):

    if method == 'iso8601':
        # ISO 8601
        # datetime.datetime.utcnow().isoformat()
        # datetime.datetime.now().isoformat()
        # utcnow
        tz_hour = time.timezone // 3600
        utc_offset = str(tz_hour) if tz_hour < 0 else '+' + str(tz_hour)
        stamp = time.strftime('%Y-%m-%dT%H%M%S') + utc_offset
        return stamp
    else:
        raise ValueError('only iso8601 is accepted for now')

make an iso8601 timestamp

Args:
        method (str): type of timestamp

Example:
        >>> stamp = timestamp()
        >>> print('stamp = {!r}'.format(stamp))
        stamp = ...-...-...T...


def _sendtpl(self, sender, to, subject, cc=None, bcc=None, attach=None, replyto=None, **kwargs):

        plain, html = self.body(**kwargs)
        self.mailer.send(sender, to, subject, plain=plain, html=html, cc=cc, bcc=bcc,
                         replyto=replyto, attach=attach)
        return

Send a Letter from SENDER to TO, with the subject SUBJECT.
    Use the current template, with KWARGS as the context.

Args:
    - `sender`: unicode
    - `to`: unicode
    - `subject`: unicode
    - `cc`: str or [str]
    - `bcc`: str or [str]
    - `replyto`: str
    - `**kwargs`: objects

    Return: None
    Exceptions: None


def get_compatible_systems(self, id_or_uri):

        uri = self._client.build_uri(id_or_uri) + "/compatible-systems"
        return self._client.get(uri)

Retrieves a collection of all storage systems that is applicable to this storage volume template.

Args:
        id_or_uri:
            Can be either the power device id or the uri

Returns:
        list: Storage systems.


def _ProcessAMCacheFileKey(self, am_entry, parser_mediator):

    amcache_datetime = am_entry.get_value_by_name(
        self._AMCACHE_DATETIME).get_data_as_integer()
    event_data = AmcacheEventData()

    event_data.full_path = am_entry.get_value_by_name(
        self._AMCACHE_FULL_PATH).get_data_as_string()
    # Strip off the 4 leading zero's from the sha1 hash.
    event_data.sha1 = am_entry.get_value_by_name(
        self._AMCACHE_SHA1).get_data_as_string()[4:]

    productname = am_entry.get_value_by_name(self._AMCACHE_PRODUCTNAME)
    if productname:
      event_data.productname = productname.get_data_as_string()

    companyname = am_entry.get_value_by_name(self._AMCACHE_COMPANYNAME)
    if companyname:
      event_data.companyname = companyname.get_data_as_string()

    fileversion = am_entry.get_value_by_name(self._AMCACHE_FILEVERSION)
    if fileversion:
      event_data.fileversion = fileversion.get_data_as_string()

    languagecode = am_entry.get_value_by_name(self._AMCACHE_LANGUAGECODE)
    if languagecode:
      event_data.languagecode = languagecode.get_data_as_integer()

    filesize = am_entry.get_value_by_name(self._AMCACHE_FILESIZE)
    if filesize:
      event_data.filesize = filesize.get_data_as_integer()

    filedescription = am_entry.get_value_by_name(self._AMCACHE_FILEDESCRIPTION)
    if filedescription:
      event_data.filedescription = filedescription.get_data_as_string()

    linkerts = am_entry.get_value_by_name(self._AMCACHE_LINKERTS)
    if linkerts:
      event_data.linkerts = linkerts.get_data_as_integer()

    lastmodifiedts = am_entry.get_value_by_name(self._AMCACHE_LASTMODIFIEDTS)
    if lastmodifiedts:
      event_data.lastmodifiedts = lastmodifiedts.get_data_as_integer()

    createdts = am_entry.get_value_by_name(self._AMCACHE_CREATEDTS)
    if createdts:
      event_data.createdts = createdts.get_data_as_integer()

    programid = am_entry.get_value_by_name(self._AMCACHE_PROGRAMID)
    if programid:
      event_data.programid = programid.get_data_as_string()

    event = time_events.DateTimeValuesEvent(
        filetime.Filetime(amcache_datetime),
        definitions.TIME_DESCRIPTION_MODIFICATION)
    parser_mediator.ProduceEventWithEventData(event, event_data)

    if event_data.createdts:
      event = time_events.DateTimeValuesEvent(
          filetime.Filetime(event_data.createdts),
          definitions.TIME_DESCRIPTION_CREATION)
      parser_mediator.ProduceEventWithEventData(event, event_data)

    if event_data.lastmodifiedts:
      event = time_events.DateTimeValuesEvent(
          filetime.Filetime(event_data.lastmodifiedts),
          definitions.TIME_DESCRIPTION_MODIFICATION)
      parser_mediator.ProduceEventWithEventData(event, event_data)

    if event_data.linkerts:
      event = time_events.DateTimeValuesEvent(
          posix_time.PosixTime(event_data.linkerts),
          definitions.TIME_DESCRIPTION_CHANGE)
      parser_mediator.ProduceEventWithEventData(event, event_data)

Parses an Amcache Root/File key for events.

Args:
        am_entry (pyregf.key): amcache File key.
        parser_mediator (ParserMediator): mediates interactions between parsers
        and other components, such as storage and dfvfs.


def __init__(self, input_reader=None, output_writer=None):

    super(StorageMediaTool, self).__init__(
        input_reader=input_reader, output_writer=output_writer)
    self._custom_artifacts_path = None
    self._artifact_definitions_path = None
    self._artifact_filters = None
    self._credentials = []
    self._credential_configurations = []
    self._filter_file = None
    self._partitions = None
    self._process_vss = False
    self._source_scanner = source_scanner.SourceScanner()
    self._source_path = None
    self._source_path_specs = []
    self._textwrapper = textwrap.TextWrapper()
    self._user_selected_vss_stores = False
    self._volumes = None
    self._vss_only = False
    self._vss_stores = None

Initializes the CLI tool object.

Args:
        input_reader (Optional[InputReader]): input reader, where None indicates
        that the stdin input reader should be used.
        output_writer (Optional[OutputWriter]): output writer, where None
        indicates that the stdout output writer should be used.


def _construct_w(self, inputs):

    weight_shape = self._kernel_shape + (1, 1)

    if "w" not in self._initializers:
      self._initializers["w"] = create_weight_initializer(weight_shape[:2],
                                                          dtype=inputs.dtype)

    w = tf.get_variable("w",
                        shape=weight_shape,
                        dtype=inputs.dtype,
                        initializer=self._initializers["w"],
                        partitioner=self._partitioners.get("w", None),
                        regularizer=self._regularizers.get("w", None))
    return w

Construct the convolution weight matrix.

    Figures out the shape of the weight matrix, initialize it, and return it.

Args:
        inputs: A Tensor of shape `data_format` and of type `tf.float16`,
        `tf.bfloat16` or `tf.float32`.

Returns:
        w: A weight matrix of the same type as `inputs` and of shape
        [kernel_shape, 1, 1].