def _GetRecordValue(self, record, value_entry):

    column_type = record.get_column_type(value_entry)
    long_value = None

    if record.is_long_value(value_entry):
      long_value = record.get_value_data_as_long_value(value_entry)

    if record.is_multi_value(value_entry):
      # TODO: implement
      raise ValueError('Multi value support not implemented yet.')

    if column_type == pyesedb.column_types.NULL:
      return None

    if column_type == pyesedb.column_types.BOOLEAN:
      # TODO: implement
      raise ValueError('Boolean value support not implemented yet.')

    if column_type in self.INTEGER_COLUMN_TYPES:
      if long_value:
        raise ValueError('Long integer value not supported.')
      return record.get_value_data_as_integer(value_entry)

    if column_type in self.FLOATING_POINT_COLUMN_TYPES:
      if long_value:
        raise ValueError('Long floating point value not supported.')
      return record.get_value_data_as_floating_point(value_entry)

    if column_type in self.STRING_COLUMN_TYPES:
      if long_value:
        return long_value.get_data_as_string()
      return record.get_value_data_as_string(value_entry)

    if column_type == pyesedb.column_types.GUID:
      # TODO: implement
      raise ValueError('GUID value support not implemented yet.')

    if long_value:
      return long_value.get_data()
    return record.get_value_data(value_entry)

Retrieves a specific value from the record.

Args:
        record (pyesedb.record): ESE record.
        value_entry (int): value entry.

Returns:
        object: value.

Raises:
        ValueError: if the value is not supported.


def delete_note(self, note_id):

        # notes have to be trashed before deletion
        note, status = self.trash_note(note_id)
        if (status == -1):
            return note, status

        params = '/i/%s' % (str(note_id))
        request = Request(url=DATA_URL+params, method='DELETE')
        request.add_header(self.header, self.get_token())
        try:
            response = urllib2.urlopen(request)
        except IOError as e:
            return e, -1
        except HTTPError as e:
            if e.code == 401:
                raise SimplenoteLoginFailed('Login to Simplenote API failed! Check Token.')
            else:
                return e, -1
        return {}, 0

Method to permanently delete a note

Args:
        - note_id (string): key of the note to trash

Returns:
        A tuple `(note, status)`

        - note (dict): an empty dict or an error message
        - status (int): 0 on success and -1 otherwise


def db_dp004(self, value=None):

        if value is not None:
            try:
                value = float(value)
            except ValueError:
                raise ValueError('value {} need to be of type float '
                                 'for field `db_dp004`'.format(value))

        self._db_dp004 = value

Corresponds to IDD Field `db_dp004`
    mean coincident dry-bulb temperature to
    Dew-point temperature corresponding to 0.4% annual cumulative frequency of occurrence

Args:
        value (float): value for IDD Field `db_dp004`
            Unit: C
            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 flag_all(self, thresh_dict=None, include=None, exclude=None):

        if thresh_dict is None:
            thresh_dict = {}
        row_idx = set()
        col_idx = set()
        include = self.results if include is None else include
        include = list(
            set(include) - set(exclude)) if exclude is not None else include
        for diagnostic in include:
            if diagnostic in thresh_dict:
                flagged = self.flag(diagnostic, thresh_dict[diagnostic])
            else:
                flagged = self.flag(diagnostic)

            if diagnostic == 'RowMahalanobisDistances':
                row_idx = row_idx.union(flagged)
            else:
                col_idx = col_idx.union(flagged)

        return sorted(list(row_idx)), sorted(list(col_idx))

Returns indices of (rows, columns) that satisfy flag() on any
    diagnostic. Uses user-provided thresholds in thresh_dict/

Args:
        thresh_dict (dict): dictionary of diagnostic->threshold functions
        include (list): optional sublist of diagnostics to flag
        exclude (list): optional sublist of diagnostics to not flag


def where(self, cond, other, **kwargs):

        assert isinstance(
            cond, type(self)
        ), "Must have the same DataManager subclass to perform this operation"
        if isinstance(other, type(self)):
            # Note: Currently we are doing this with two maps across the entire
            # data. This can be done with a single map, but it will take a
            # modification in the `BlockPartition` class.
            # If this were in one pass it would be ~2x faster.
            # TODO (devin-petersohn) rewrite this to take one pass.
            def where_builder_first_pass(cond, other, **kwargs):
                return cond.where(cond, other, **kwargs)

            def where_builder_second_pass(df, new_other, **kwargs):
                return df.where(new_other.eq(True), new_other, **kwargs)

            first_pass = cond._inter_manager_operations(
                other, "left", where_builder_first_pass
            )
            final_pass = self._inter_manager_operations(
                first_pass, "left", where_builder_second_pass
            )
            return self.__constructor__(final_pass.data, self.index, self.columns)
        else:
            axis = kwargs.get("axis", 0)
            # Rather than serializing and passing in the index/columns, we will
            # just change this index to match the internal index.
            if isinstance(other, pandas.Series):
                other.index = pandas.RangeIndex(len(other.index))

            def where_builder_series(df, cond):
                if axis == 0:
                    df.index = pandas.RangeIndex(len(df.index))
                    cond.index = pandas.RangeIndex(len(cond.index))
                else:
                    df.columns = pandas.RangeIndex(len(df.columns))
                    cond.columns = pandas.RangeIndex(len(cond.columns))
                return df.where(cond, other, **kwargs)

            reindexed_self, reindexed_cond, a = self.copartition(
                axis, cond, "left", False
            )
            # Unwrap from list given by `copartition`
            reindexed_cond = reindexed_cond[0]
            new_data = reindexed_self.inter_data_operation(
                axis, lambda l, r: where_builder_series(l, r), reindexed_cond
            )
            return self.__constructor__(new_data, self.index, self.columns)

Gets values from this manager where cond is true else from other.

Args:
        cond: Condition on which to evaluate values.

Returns:
        New DataManager with updated data and index.


def __init__(self, config_files):

        for config_file, is_production in config_files:
            if os.path.isfile(config_file):
                self.config_file = config_file
                self.is_production = is_production
                self.config = configparser.SafeConfigParser()
                self.config.read([self.config_file], encoding='utf-8')
                return

        raise IOError("No configuration file found.")

Creates a new config object.

    Parameters:
    config_files: Dictionary with file_name: is_production setting


def _GetMemberDataTypeMaps(self, data_type_definition, data_type_map_cache):

    if not data_type_definition:
      raise errors.FormatError('Missing data type definition')

    members = getattr(data_type_definition, 'members', None)
    if not members:
      raise errors.FormatError('Invalid data type definition missing members')

    data_type_maps = []

    members_data_size = 0
    for member_definition in members:
      if isinstance(member_definition, data_types.MemberDataTypeDefinition):
        member_definition = member_definition.member_data_type_definition

      if (data_type_definition.byte_order != definitions.BYTE_ORDER_NATIVE and
          member_definition.byte_order == definitions.BYTE_ORDER_NATIVE):
        # Make a copy of the data type definition where byte-order can be
        # safely changed.
        member_definition = copy.copy(member_definition)
        member_definition.name = '_{0:s}_{1:s}'.format(
            data_type_definition.name, member_definition.name)
        member_definition.byte_order = data_type_definition.byte_order

      if member_definition.name not in data_type_map_cache:
        data_type_map = DataTypeMapFactory.CreateDataTypeMapByType(
            member_definition)
        data_type_map_cache[member_definition.name] = data_type_map

      data_type_map = data_type_map_cache[member_definition.name]
      if members_data_size is not None:
        if not isinstance(member_definition, data_types.PaddingDefinition):
          byte_size = member_definition.GetByteSize()
        else:
          _, byte_size = divmod(
              members_data_size, member_definition.alignment_size)
          if byte_size > 0:
            byte_size = member_definition.alignment_size - byte_size

          data_type_map.byte_size = byte_size

        if byte_size is None:
          members_data_size = None
        else:
          members_data_size += byte_size

      data_type_maps.append(data_type_map)

    return data_type_maps

Retrieves the member data type maps.

Args:
        data_type_definition (DataTypeDefinition): data type definition.
        data_type_map_cache (dict[str, DataTypeMap]): cached data type maps.

Returns:
        list[DataTypeMap]: member data type maps.

Raises:
        FormatError: if the data type maps cannot be determined from the data
        type definition.


def _merge(d, u):

    for k, v in u.items():
        # if we have a mapping, recursively merge the values
        if isinstance(v, collections.Mapping):
            d[k] = _merge(d.get(k, {}), v)

        # if d (the dict to merge into) is a dict, just add the
        # value to the dict.
        elif isinstance(d, collections.MutableMapping):
            d[k] = v

        # otherwise if d (the dict to merge into) is not a dict (e.g. when
        # recursing into it, `d.get(k, {})` may not be a dict), then do what
        # `update` does and prefer the new value.
        #
        # this means that something like `{'foo': 1}` when updated with
        # `{'foo': {'bar': 1}}` would have the original value (`1`) overwritten
        # and would become: `{'foo': {'bar': 1}}`
        else:
            d = {k: v}

    return d

Merge two dictionaries (or DotDicts) together.

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


def _backspaced_single_line_animation(animation_, *args, **kwargs):

    animation_gen = animation_(*args, **kwargs)
    yield next(animation_gen)  # no backing up on the first frame
    yield from util.concatechain(
        util.BACKSPACE_GEN(kwargs['width']), animation_gen)

Turn an animation into an automatically backspaced animation.

Args:
        animation: A function that returns a generator that yields
        strings for animation frames.
        args: Arguments for the animation function.
        kwargs: Keyword arguments for the animation function.

Returns:
        the animation generator, with backspaces applied to each but the first
        frame.


def __init__(self, band_type=None, rate=None, burst_size=None):

        super().__init__()
        self.band_type = band_type
        self.rate = rate
        self.burst_size = burst_size
        self.update_length()

Create a MeterBandHeader with the optional parameters below.

Args:
        band_type (MeterBandType): One of OFPMBT_*.
        rate (int): Rate for this band.
        burst_size (int): Size of bursts.


def stack_and_pad_tensors(batch, padding_index=DEFAULT_PADDING_INDEX, dim=0):

    lengths = [tensor.shape[0] for tensor in batch]
    max_len = max(lengths)
    padded = [pad_tensor(tensor, max_len, padding_index) for tensor in batch]
    lengths = torch.tensor(lengths)
    padded = torch.stack(padded, dim=dim).contiguous()
    for _ in range(dim):
        lengths = lengths.unsqueeze(0)
    return padded, lengths

Pad a :class:`list` of ``tensors`` (``batch``) with ``padding_index``.

Args:
        batch (:class:`list` of :class:`torch.Tensor`): Batch of tensors to pad.
        padding_index (int, optional): Index to pad tensors with.
        dim (int, optional): Dimension on to which to concatenate the batch of tensors.

    Returns
        torch.Tensor, torch.Tensor: Padded tensors and original lengths of tensors.


def write_wgetrc(_path):

    http_proxy = str(CFG["gentoo"]["http_proxy"])
    ftp_proxy = str(CFG["gentoo"]["ftp_proxy"])

    path.mkfile_uchroot("/etc/wgetrc")
    with open(_path, 'w') as wgetrc:
        if http_proxy is not None:
            http_s = "http_proxy = {0}".format(http_proxy)
            https_s = "https_proxy = {0}".format(http_proxy)
            wgetrc.write("use_proxy = on\n")
            wgetrc.write(http_s + "\n")
            wgetrc.write(https_s + "\n")

        if ftp_proxy is not None:
            fp_s = "ftp_proxy={0}".format(ftp_proxy)
            wgetrc.write(fp_s + "\n")

Write a valid gentoo wgetrc file to :path:.

Args:
        path - The output path of the wgetrc


def keys(self, full_grid=False):

        keys = super(GridSpace, self).keys()
        if self.ndims == 1 or not full_grid:
            return keys
        dim1_keys = sorted(set(k[0] for k in keys))
        dim2_keys = sorted(set(k[1] for k in keys))
        return [(d1, d2) for d1 in dim1_keys for d2 in dim2_keys]

Returns the keys of the GridSpace

Args:
        full_grid (bool, optional): Return full cross-product of keys

Returns:
        List of keys


def prange(N=1, dim=1):

    A = {}
    r = numpy.arange(N, dtype=int)
    key = numpy.zeros(dim, dtype=int)
    for i in range(N):
        key[-1] = i
        A[tuple(key)] = 1*(r==i)

    return Poly(A, dim, (N,), int)

Constructor to create a range of polynomials where the exponent vary.

Args:
        N (int):
            Number of polynomials in the array.
        dim (int):
            The dimension the polynomial should span.

Returns:
        (Poly):
            A polynomial array of length N containing simple polynomials with
            increasing exponent.

Example:
        >>> print(prange(4))
        [1, q0, q0^2, q0^3]
        >>> print(prange(4, dim=3))
        [1, q2, q2^2, q2^3]


def __init__(self, context):

    self._logdir = context.logdir
    self._db_uri = context.db_uri
    self._window_title = context.window_title
    self._multiplexer = context.multiplexer
    self._db_connection_provider = context.db_connection_provider
    self._assets_zip_provider = context.assets_zip_provider

Instantiates CorePlugin.

Args:
        context: A base_plugin.TBContext instance.


def get(self, id_or_url, default=None):

        if '/' in id_or_url:
            id = urls.SheetUrl.from_string(id_or_url).id
        else:
            id = id_or_url
        try:
            return self[id]
        except KeyError:
            return default

Fetch and return the spreadsheet with the given id or url.

Args:
        id_or_url (str): unique alphanumeric id or URL of the spreadsheet

Returns:
        New SpreadSheet instance or given default if none is found

Raises:
        ValueError: if an URL is given from which no id could be extracted


def set_session(self, headers=None):

        if headers is None:
            headers = {
                'User-Agent':
                ('Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_3)'
                 ' AppleWebKit/537.36 (KHTML, like Gecko) '
                 'Chrome/48.0.2564.116 Safari/537.36')
            }
        elif not isinstance(headers, dict):
            raise TypeError('"headers" must be a dict object')

        self.session = Session(self.proxy_pool)
        self.session.headers.update(headers)

Init session with default or custom headers

Args:
        headers: A dict of headers (default None, thus using the default
                header to init the session)


def getWhoisInfo(domain):

    new = []

    # Grabbing the aliases
    try:
        emails = {}
        emails["type"] = "i3visio.alias"
        emails["value"] = str(domain.split(".")[0])
        emails["attributes"] = []
        new.append(emails)
    except:
        pass

    info = whois.whois(domain)

    if info.status == None:
        raise Exception("UnknownDomainError: " + domain + " could not be resolved.")

    # Grabbing the emails
    try:
        emails = {}
        emails["type"] = "i3visio.email"
        if type(info.emails) is not list:
            aux = [info.emails]
            emails["value"] = json.dumps(aux)
        else:
            emails["value"] = json.dumps(info.emails)
        emails["attributes"] = []
        new.append(emails)
    except:
        pass

    # Grabbing the country
    try:
        tmp = {}
        tmp["type"] = "i3visio.location.country"
        tmp["value"] = str(info.country)
        tmp["attributes"] = []
        new.append(tmp)
    except:
        pass

    # Grabbing the regitrar
    try:
        tmp = {}
        tmp["type"] = "i3visio.registrar"
        tmp["value"] = str(info.registrar)
        tmp["attributes"] = []
        new.append(tmp)
    except:
        pass

    # Grabbing the regitrar
    try:
        tmp = {}
        tmp["type"] = "i3visio.fullname"
        try:
            tmp["value"] = str(info.name)
        except:
            tmp["value"] = info.name
        tmp["attributes"] = []
        new.append(tmp)
    except:
        pass

    return new

Method that trie to recover the whois info from a domain.

Args:
    -----
        domain: The domain to verify.

Returns:
    --------
        dict: A dictionary containing the result as an i3visio entity with its
            `value`, `type` and `attributes`.


def transfer_project(self, to_project_id, **kwargs):

        path = '/groups/%s/projects/%s' % (self.id, to_project_id)
        self.manager.gitlab.http_post(path, **kwargs)

Transfer a project to this group.

Args:
        to_project_id (int): ID of the project to transfer
        **kwargs: Extra options to send to the server (e.g. sudo)

Raises:
        GitlabAuthenticationError: If authentication is not correct
        GitlabTransferProjectError: If the project could not be transfered


def delete_image(self, name: str) -> None:

        logger.debug("deleting Docker image: %s", name)
        path = "docker/images/{}".format(name)
        response = self.__api.delete(path)
        if response.status_code != 204:
            try:
                self.__api.handle_erroneous_response(response)
            except Exception:
                logger.exception("failed to delete Docker image: %s", name)
                raise
        else:
            logger.info("deleted Docker image: %s", name)

Deletes a Docker image with a given name.

    Parameters:
        name: the name of the Docker image.


def statsDF(token='', version=''):

    df = pd.DataFrame(stats(token, version))
    _toDatetime(df)
    return df

https://iexcloud.io/docs/api/#stats-intraday

Args:
        token (string); Access token
        version (string); API version

Returns:
        DataFrame: result


def parsemeta(metadataloc):

    # filename or directory? if several fit, use first one and warn
    if os.path.isdir(metadataloc):
        metalist = glob.glob(os.path.join(metadataloc, METAPATTERN))
        if not metalist:
            raise MTLParseError(
                "No files matching metadata file pattern in directory %s."
                % metadataloc)
        elif len(metalist) > 0:
            metadatafn = metalist[0]
            filehandle = open(metadatafn, 'r')
            if len(metalist) > 1:
                logging.warning(
                    "More than one file in directory match metadata "
                    + "file pattern. Using %s." % metadatafn)
    elif os.path.isfile(metadataloc):
        metadatafn = metadataloc
        filehandle = open(metadatafn, 'r')
        logging.info("Using file %s." % metadatafn)
    elif 'L1_METADATA_FILE' in metadataloc:
        filehandle = StringIO(metadataloc)
    else:
        raise MTLParseError(
            "File location %s is unavailable " % metadataloc
            + "or doesn't contain a suitable metadata file.")

    # Reading file line by line and inserting data into metadata dictionary
    status = 0
    metadata = {}
    grouppath = []
    dictpath = [metadata]

    for line in filehandle:
        if status == 4:
            # we reached the end in the previous iteration,
            # but are still reading lines
            logging.warning(
                "Metadata file %s appears to " % metadatafn
                + "have extra lines after the end of the metadata. "
                + "This is probably, but not necessarily, harmless.")
        status = _checkstatus(status, line)
        grouppath, dictpath = _transstat(status, grouppath, dictpath, line)

    return metadata

Parses the metadata from a Landsat image bundle.

Args:
        metadataloc: a filename or a directory.

    Returns metadata dictionary


def create_profile(profile_name):

    try:
        profile = Profile(profile_name=profile_name)
        profile.full_clean()
        profile.save()
    except ValidationError as err:
        raise ValCannotCreateError(err.message_dict)

Used to create Profile objects in the database

    A profile needs to exists before an EncodedVideo object can be created.

Args:
        profile_name (str): ID of the profile

Raises:
        ValCannotCreateError: Raised if the profile name is invalid or exists


def info(self, message, domain=None):

        if domain is None:
            domain = self.extension_name
        info(message, domain)

Shortcut function for `utils.loggable.info`

Args:
        message: see `utils.loggable.info`
        domain: see `utils.loggable.info`


def update_config_pwd(msg, cfg):

    msg_type = msg.__class__.__name__.lower()
    key_fmt = msg.profile + "_" + msg_type
    if isinstance(msg._auth, (MutableSequence, tuple)):
        cfg.pwd[key_fmt] = " :: ".join(msg._auth)
    else:
        cfg.pwd[key_fmt] = msg._auth

Updates the profile's auth entry with values set by the user.
    This will overwrite existing values.

Args:
        :msg: (Message class) an instance of a message class.
        :cfg: (jsonconfig.Config) config instance.


def _HasDuplicateRegistryKeyPaths(
      self, filename, artifact_definition, source):

    result = False
    intersection = self._artifact_registry_key_paths.intersection(
        set(source.keys))
    if intersection:
      duplicate_key_paths = '\n'.join(intersection)
      logging.warning((
          'Artifact definition: {0:s} in file: {1:s} has duplicate '
          'Registry key paths:\n{2:s}').format(
              artifact_definition.name, filename, duplicate_key_paths))
      result = True

    self._artifact_registry_key_paths.update(source.keys)
    return result

Checks if Registry key paths are not already defined by other artifacts.

    Note that at the moment this function will only find exact duplicate
    Registry key paths.

Args:
        filename (str): name of the artifacts definition file.
        artifact_definition (ArtifactDefinition): artifact definition.
        source (SourceType): source definition.

Returns:
        bool: True if the Registry key paths defined by the source type
        are used in other artifacts.


def write(self, ostream, kmip_version=enums.KMIPVersion.KMIP_1_0):

        # Convert the value to binary and pad it as needed.
        binary = "{0:b}".format(abs(self.value))
        binary = ("0" * (64 - (len(binary) % 64))) + binary

        # If the value is negative, convert via two's complement.
        if self.value < 0:
            binary = binary.replace('1', 'i')
            binary = binary.replace('0', '1')
            binary = binary.replace('i', '0')

            pivot = binary.rfind('0')
            binary = binary[0:pivot] + '1' + ('0' * len(binary[pivot + 1:]))

        # Convert each byte to hex and build the hex string for the value.
        hexadecimal = b''
        for i in range(0, len(binary), 8):
            byte = binary[i:i + 8]
            byte = int(byte, 2)
            hexadecimal += struct.pack('!B', byte)

        self.length = len(hexadecimal)
        super(BigInteger, self).write(ostream, kmip_version=kmip_version)
        ostream.write(hexadecimal)

Write the encoding of the BigInteger to the output stream.

Args:
        ostream (Stream): A buffer to contain the encoded bytes of a
            BigInteger object. Usually a BytearrayStream object.
            Required.
        kmip_version (KMIPVersion): An enumeration defining the KMIP
            version with which the object will be encoded. Optional,
            defaults to KMIP 1.0.


def _enum_from_op_string(op_string):

    try:
        return _COMPARISON_OPERATORS[op_string]
    except KeyError:
        choices = ", ".join(sorted(_COMPARISON_OPERATORS.keys()))
        msg = _BAD_OP_STRING.format(op_string, choices)
        raise ValueError(msg)

Convert a string representation of a binary operator to an enum.

    These enums come from the protobuf message definition
    ``StructuredQuery.FieldFilter.Operator``.

Args:
        op_string (str): A comparison operation in the form of a string.
            Acceptable values are ``<``, ``<=``, ``==``, ``>=``
            and ``>``.

Returns:
        int: The enum corresponding to ``op_string``.

Raises:
        ValueError: If ``op_string`` is not a valid operator.


def __init__(self, mutation_list):

        self.mutation_list = [(i[0], int(i[1]), self._standard_resname(i[2])) for i in mutation_list]
        self.chains_and_residues = [(i[0], int(i[1])) for i in mutation_list]

Initialize the parameters which indicate what mutations will occur

Args:
        chain:
        residue_number:
        mutate_to:


def read_to_offset(self, offset):

    assert offset >= self._offset
    result = self._buffer[self._offset: offset]
    self._offset += len(result)
    return result

Returns bytes from self._buffer and update related offsets.

Args:
        offset: read from current offset to this offset, exclusive.

Returns:
        Requested bytes from buffer.


def compute_strongly_connected_components(function):

    visited = {n:False for n in function.nodes}
    assigned = {n:False for n in function.nodes}
    components = []
    l = []

    def visit(node):
        if not visited[node]:
            visited[node] = True
            for son in node.sons:
                visit(son)
            l.append(node)

    for n in function.nodes:
        visit(n)

    def assign(node, root):
        if not assigned[node]:
            assigned[node] = True
            root.append(node)
            for father in node.fathers:
                assign(father, root)

    for n in l:
        component = []
        assign(n, component)
        if component:
            components.append(component)

    return components

Compute strongly connected components
    Based on Kosaraju algo
    Implem follows wikipedia algo: https://en.wikipedia.org/wiki/Kosaraju%27s_algorithm#The_algorithm

Args:
    function (core.declarations.function.Function)

Returns:
    list(list(nodes))


def weighted_choice(item_probabilities):

    probability_sum = sum(x[1] for x in item_probabilities)
    assert probability_sum > 0
    random_value = random.random() * probability_sum
    summed_probability = 0
    for item, value in item_probabilities:
        summed_probability += value
        if summed_probability > random_value:
            return item

Randomly choses an item according to defined weights

Args:
        item_probabilities: list of (item, probability)-tuples

Returns:
        random item according to the given weights


def eld_complete(U,p_min,p_max,d,brk):

    model = Model("Economic load dispatching")

    p,F = {},{}
    for u in U:
        p[u] = model.addVar(lb=p_min[u], ub=p_max[u], name="p(%s)"%u)    # capacity
        F[u] = model.addVar(lb=0,name="fuel(%s)"%u)

    # set fuel costs based on piecewise linear approximation
    for u in U:
        abrk = [X for (X,Y) in brk[u]]
        bbrk = [Y for (X,Y) in brk[u]]

        # convex combination part:
        K = len(brk[u])-1
        z = {}
        for k in range(K+1):
            z[k] = model.addVar(ub=1) # do not name variables for avoiding clash

        model.addCons(p[u] == quicksum(abrk[k]*z[k] for k in range(K+1)))
        model.addCons(F[u] == quicksum(bbrk[k]*z[k] for k in range(K+1)))
        model.addCons(quicksum(z[k] for k in range(K+1)) == 1)
        model.addConsSOS2([z[k] for k in range(K+1)])

    # demand satisfaction
    model.addCons(quicksum(p[u] for u in U) == d, "demand")

    # objective
    model.setObjective(quicksum(F[u] for u in U), "minimize")

    model.data = p
    return model

eld -- economic load dispatching in electricity generation
    Parameters:
        - U: set of generators (units)
        - p_min[u]: minimum operating power for unit u
        - p_max[u]: maximum operating power for unit u
        - d: demand
        - brk[k]: (x,y) coordinates of breakpoint k, k=0,...,K
    Returns a model, ready to be solved.


def FindModuleIdDefiningFlag(self, flagname, default=None):

    registered_flag = self.FlagDict().get(flagname)
    if registered_flag is None:
      return default
    for module_id, flags in six.iteritems(self.FlagsByModuleIdDict()):
      for flag in flags:
        # It must compare the flag with the one in FlagDict. This is because a
        # flag might be overridden only for its long name (or short name),
        # and only its short name (or long name) is considered registered.
        if (flag.name == registered_flag.name and
            flag.short_name == registered_flag.short_name):
          return module_id
    return default

Return the ID of the module defining this flag, or default.

Args:
        flagname: Name of the flag to lookup.
        default: Value to return if flagname is not defined. Defaults
        to None.

Returns:
        The ID of the module which registered the flag with this name.
        If no such module exists (i.e. no flag with this name exists),
        we return default.


def bootstrap(score_objs, n_boot=1000):

    all_samples = np.random.choice(score_objs, size=(n_boot, len(score_objs)), replace=True)
    return all_samples.sum(axis=1)

Given a set of DistributedROC or DistributedReliability objects, this function performs a
    bootstrap resampling of the objects and returns n_boot aggregations of them.

Args:
        score_objs: A list of DistributedROC or DistributedReliability objects. Objects must have an __add__ method
        n_boot (int): Number of bootstrap samples

Returns:
        An array of DistributedROC or DistributedReliability


def RemoveClientLabels(self, client_id, labels):

    for label in labels:
      keyword = self._NormalizeKeyword(label)
      # This might actually delete a keyword with the same name as the label (if
      # there is one).
      data_store.REL_DB.RemoveClientKeyword(client_id, keyword)
      data_store.REL_DB.RemoveClientKeyword(client_id, "label:%s" % keyword)

Removes all labels for a given client.

Args:
        client_id: The client_id.
        labels: A list of labels to remove.


def predict_on_batch(self, data: Union[list, tuple],
                         return_indexes: bool = False) -> List[List[str]]:

        X = self._transform_batch(data)
        objects_number, lengths = len(X[0]), [len(elem) for elem in data[0]]
        Y = self.model_.predict_on_batch(X)
        labels = np.argmax(Y, axis=-1)
        answer: List[List[str]] = [None] * objects_number
        for i, (elem, length) in enumerate(zip(labels, lengths)):
            elem = elem[:length]
            answer[i] = elem if return_indexes else self.tags.idxs2toks(elem)
        return answer

Makes predictions on a single batch

Args:
        data: a batch of word sequences together with additional inputs
        return_indexes: whether to return tag indexes in vocabulary or tags themselves

Returns:
        a batch of label sequences


def _on_channel_open(self, channel):

        channel.add_on_close_callback(self._on_channel_close)
        channel.add_on_cancel_callback(self._on_cancel)

        channel.basic_qos(callback=self._on_qosok, **config.conf["qos"])

Callback used when a channel is opened.

    This registers all the channel callbacks.

Args:
        channel (pika.channel.Channel): The channel that successfully opened.


def set(self, key, val):

    self._create_file_if_none_exists()
    with open(self.filename, 'r+b') as file_object:
      cache_pickle = pickle.load(file_object)
      cache_pickle[key] = val
      file_object.seek(0)
      pickle.dump(cache_pickle, file_object)

Sets a value in a key.

Args:
        key (str): Key for the value.
        val: Value to set.

Returns:
        Retrieved value.


def exists(self, filename):

        result = True
        for repo in self._children:
            if not repo.exists(filename):
                result = False
        return result

Report whether a file exists on all distribution points.

    Determines file type by extension.

Args:
        filename: Filename you wish to check. (No path! e.g.:
            "AdobeFlashPlayer-14.0.0.176.pkg")

Returns:
        Boolean


def Inference(probability=None, relation=None, name=None, concept=None):

    atts = {}
    if probability is not None:
        atts['probability'] = str(probability)
    if relation is not None:
        atts['relation'] = relation
    inf = objectify.Element('Inference', attrib=atts)
    if name is not None:
        inf.Name = name
    if concept is not None:
        inf.Concept = concept
    return inf

Represents a probable cause / relation between this event and some prior.

Args:
        probability(float): Value 0.0 to 1.0.
        relation(str): e.g. 'associated' or 'identified' (see Voevent spec)
        name(str): e.g. name of identified progenitor.
        concept(str): One of a 'formal UCD-like vocabulary of astronomical
            concepts', e.g. http://ivoat.ivoa.net/stars.supernova.Ia - see
            VOEvent spec.


def _wait_for_any_event(events, timeout_s):

  def any_event_set():
    return any(event.is_set() for event in events)

  result = timeouts.loop_until_timeout_or_true(
      timeout_s, any_event_set, sleep_s=_WAIT_FOR_ANY_EVENT_POLL_S)

  return result or any_event_set()

Wait for any in a list of threading.Event's to be set.

Args:
        events: List of threading.Event's.
        timeout_s: Max duration in seconds to wait before returning.

Returns:
        True if at least one event was set before the timeout expired, else False.


def gene_by_alias(self, symbol, build='37'):

        res = self.hgnc_collection.find({'hgnc_symbol': symbol, 'build':build})
        if res.count() == 0:
            res = self.hgnc_collection.find({'aliases': symbol, 'build':build})

        return res

Return a iterable with hgnc_genes.

    If the gene symbol is listed as primary the iterable will only have
    one result. If not the iterable will include all hgnc genes that have
    the symbol as an alias.

Args:
        symbol(str)
        build(str)

Returns:
        res(pymongo.Cursor(dict))


def __init__(self, context_reading_spec, sequence_reading_spec):  # pylint: disable=super-init-not-called

    self._context_reading_spec = context_reading_spec
    self._sequence_reading_spec = sequence_reading_spec

Constructs a TFRecordSequenceExampleAdapter.

Args:
        context_reading_spec: `dict`, feature name to tf.FixedLenFeature or
        tf.VarLenFeature for the context features. Passed to
        tf.io.parse_single_sequence_example.
        sequence_reading_spec: `dict`, feature name to tf.FixedLenFeature or
        tf.VarLenFeature for the sequence features. Passed to
        tf.io.parse_single_sequence_example.


def recentlyAdded(self, libtype='episode', maxresults=50):

        return self.search(sort='addedAt:desc', libtype=libtype, maxresults=maxresults)

Returns a list of recently added episodes from this library section.

    Parameters:
        maxresults (int): Max number of items to return (default 50).


def delete_asset(self, asset_id, asset_type):

        return self.asset(asset_id, asset_type=asset_type, action='DELETE')

Delete the asset with the provided asset_id.

Args:
        asset_id: The id of the asset.
        asset_type: The asset type.

    Returns:


def add_file_group(self, fileGrp):

        el_fileSec = self._tree.getroot().find('mets:fileSec', NS)
        if el_fileSec is None:
            el_fileSec = ET.SubElement(self._tree.getroot(), TAG_METS_FILESEC)
        el_fileGrp = el_fileSec.find('mets:fileGrp[@USE="%s"]' % fileGrp, NS)
        if el_fileGrp is None:
            el_fileGrp = ET.SubElement(el_fileSec, TAG_METS_FILEGRP)
            el_fileGrp.set('USE', fileGrp)
        return el_fileGrp

Add a new ``mets:fileGrp``.

Args:
        fileGrp (string): ``USE`` attribute of the new filegroup.


def inflate_plugin_dict(plugin_dict, inflate_plugin):

        plugins = []
        for identifier, definition in plugin_dict.items():
            try:
                plugins.append(inflate_plugin(identifier, definition))
            except PluginNotFoundError as e:
                logger.error('Could not import plugin identified by %s. '
                             'Exception: %s.', identifier, e)
        return plugins

Inflate a list of strings/dictionaries to a list of plugin instances.

Args:
        plugin_dict (dict): a dict of dict.
        inflate_plugin (method): the method to inflate the plugin.

Returns:
        list: a plugin instances list.


def swo_set_host_buffer_size(self, buf_size):

        buf = ctypes.c_uint32(buf_size)
        res = self._dll.JLINKARM_SWO_Control(enums.JLinkSWOCommands.SET_BUFFERSIZE_HOST,
                                             ctypes.byref(buf))
        if res < 0:
            raise errors.JLinkException(res)

        return None

Sets the size of the buffer used by the host to collect SWO data.

Args:
        self (JLink): the ``JLink`` instance
        buf_size (int): the new size of the host buffer

Returns:
        ``None``

Raises:
        JLinkException: on error


def get_document(project_id, knowledge_base_id, document_id):

    import dialogflow_v2beta1 as dialogflow
    client = dialogflow.DocumentsClient()
    document_path = client.document_path(project_id, knowledge_base_id,
                                         document_id)

    response = client.get_document(document_path)
    print('Got Document:')
    print(' - Display Name: {}'.format(response.display_name))
    print(' - Knowledge ID: {}'.format(response.name))
    print(' - MIME Type: {}'.format(response.mime_type))
    print(' - Knowledge Types:')
    for knowledge_type in response.knowledge_types:
        print('    - {}'.format(KNOWLEDGE_TYPES[knowledge_type]))
    print(' - Source: {}\n'.format(response.content_uri))

Gets a Document.

Args:
        project_id: The GCP project linked with the agent.
        knowledge_base_id: Id of the Knowledge base.
        document_id: Id of the Document.


def emit(self, record):

        record.task = self.cur_task

        if record.levelno >= self.dump_level and self.cur_task:
            self.tasks[self.cur_task].failed = True
            self.tasks[self.cur_task].force_show = True

        # Makes no sense to start a task with an error log
        is_start = START_TASK_REG.match(str(record.msg))
        if is_start:
            self.handle_new_task(is_start.groupdict()['task_name'], record)
            return

        is_end = END_TASK_REG.match(str(record.msg))
        if is_end:
            self.handle_closed_task(is_end.groupdict()['task_name'], record)
            return

        force_show_record = ALWAYS_SHOW_REG.match(str(record.msg))
        if force_show_record:
            record.msg = force_show_record.groupdict()['message']
            self.pretty_emit(record)

        if (
            not force_show_record and self.should_show_by_level(record)
            and self.should_show_by_depth()
        ):
            self.pretty_emit(record)
            return

        if self.cur_task:
            self.tasks[self.cur_task].append(record)

Handle the given record, this is the entry point from the python
    logging facility

    Params:
        record (logging.LogRecord): log record to handle

Returns:
        None


def find_sanitiser_nodes(
    sanitiser,
    sanitisers_in_file
):

    for sanitiser_tuple in sanitisers_in_file:
        if sanitiser == sanitiser_tuple.trigger_word:
            yield sanitiser_tuple.cfg_node

Find nodes containing a particular sanitiser.

Args:
        sanitiser(string): sanitiser to look for.
        sanitisers_in_file(list[Node]): list of CFG nodes with the sanitiser.

Returns:
        Iterable of sanitiser nodes.


def __init__(self, instrumentation_key, wsgi_application, *args, **kwargs):

        if not instrumentation_key:
            raise Exception('Instrumentation key was required but not provided')
        if not wsgi_application:
            raise Exception('WSGI application was required but not provided')
        telemetry_channel = kwargs.pop('telemetry_channel', None)
        if not telemetry_channel:
            sender = applicationinsights.channel.AsynchronousSender()
            queue = applicationinsights.channel.AsynchronousQueue(sender)
            telemetry_channel = applicationinsights.channel.TelemetryChannel(None, queue)
        self.client = applicationinsights.TelemetryClient(instrumentation_key, telemetry_channel)
        self.client.context.device.type = "PC"
        self._wsgi_application = wsgi_application
        self._common_properties = kwargs.pop('common_properties', {})

Initialize a new instance of the class.

Args:
        instrumentation_key (str). the instrumentation key to use while sending telemetry to the service.\n
        wsgi_application (func). the WSGI application that we're wrapping.


def CopyFromDict(self, attributes):

    for attribute_name, attribute_value in attributes.items():
      # Not using startswith to improve performance.
      if attribute_name[0] == '_':
        continue
      setattr(self, attribute_name, attribute_value)

Copies the attribute container from a dictionary.

Args:
        attributes (dict[str, object]): attribute values per name.


def get_validators(self, id=None, endpoint=None):

        return self._call_endpoint(GET_VALIDATORS, id=id, endpoint=endpoint)

Returns the current NEO consensus nodes information and voting status.

Args:
        id: (int, optional) id to use for response tracking
        endpoint: (RPCEndpoint, optional) endpoint to specify to use

Returns:
        json object of the result or the error encountered in the RPC call


def Sign(self, data, signing_key, verify_key=None):

    if signing_key.KeyLen() < 2048:
      logging.warning("signing key is too short.")

    self.signature = signing_key.Sign(data)
    self.signature_type = self.SignatureType.RSA_PKCS1v15

    self.digest = hashlib.sha256(data).digest()
    self.digest_type = self.HashType.SHA256
    self.data = data

    # Test we can verify before we send it off.
    if verify_key is None:
      verify_key = signing_key.GetPublicKey()

    # Verify our own data.
    self.Verify(verify_key)

    return self

Use the data to sign this blob.

Args:
        data: String containing the blob data.
        signing_key: The key to sign with.
        verify_key: Key to verify with. If None we assume the signing key also
        contains the public key.

Returns:
        self for call chaining.


def _prepare_lambada_data(tmp_dir, data_dir, vocab_size, vocab_filename):

  if not tf.gfile.Exists(data_dir):
    tf.gfile.MakeDirs(data_dir)

  file_path = generator_utils.maybe_download(tmp_dir, _TAR, _URL)
  tar_all = tarfile.open(file_path)
  tar_all.extractall(tmp_dir)
  tar_all.close()
  tar_train = tarfile.open(os.path.join(tmp_dir, "train-novels.tar"))
  tar_train.extractall(tmp_dir)
  tar_train.close()

  vocab_path = os.path.join(data_dir, vocab_filename)
  if not tf.gfile.Exists(vocab_path):
    with tf.gfile.GFile(os.path.join(tmp_dir, _VOCAB), "r") as infile:
      reader = csv.reader(infile, delimiter="\t")
      words = [row[0] for row in reader]
      words = [_UNK] + words[:vocab_size]
    with tf.gfile.GFile(vocab_path, "w") as outfile:
      outfile.write("\n".join(words))

Downloading and preparing the dataset.

Args:
        tmp_dir: tem directory
        data_dir: data directory
        vocab_size: size of vocabulary
        vocab_filename: name of vocab file


def collective_dr_squared( self ):

        return sum( np.square( sum( [ atom.dr for atom in self.atoms ] ) ) )

Squared sum of total displacements for these atoms.

Args:
        None

Returns:
        (Float): The square of the summed total displacements for these atoms.


def dataframe(start_row=0, max_rows=None, use_cache=True):

    output = QueryOutput()
    output._output_type = 'dataframe'
    output._dataframe_start_row = start_row
    output._dataframe_max_rows = max_rows
    output._use_cache = use_cache
    return output

Construct a query output object where the result is a dataframe

Args:
        start_row: the row of the table at which to start the export (default 0).
        max_rows: an upper limit on the number of rows to export (default None).
        use_cache: whether to use cached results or not (default True).


def __init__(self, path, text_field, label_field,
                 fine_grained=False, **kwargs):

        fields = [('text', text_field), ('label', label_field)]
        examples = []

        def get_label_str(label):
            return label.split(':')[0] if not fine_grained else label
        label_field.preprocessing = data.Pipeline(get_label_str)

        for line in open(os.path.expanduser(path), 'rb'):
            # there is one non-ASCII byte: sisterBADBYTEcity; replaced with space
            label, _, text = line.replace(b'\xf0', b' ').decode().partition(' ')
            examples.append(data.Example.fromlist([text, label], fields))

        super(TREC, self).__init__(examples, fields, **kwargs)

Create an TREC dataset instance given a path and fields.

Args:
        path: Path to the data file.
        text_field: The field that will be used for text data.
        label_field: The field that will be used for label data.
        fine_grained: Whether to use the fine-grained (50-class) version of TREC
            or the coarse grained (6-class) version.
        Remaining keyword arguments: Passed to the constructor of
            data.Dataset.


def update_batch(self, loss_per_instance):

        if self.batch_indices is None:
            raise TensorForceError("Need to call get_batch before each update_batch call.")
        # if len(loss_per_instance) != len(self.batch_indices):
        #     raise TensorForceError("For all instances a loss value has to be provided.")

        for index, loss in zip(self.batch_indices, loss_per_instance):
            # Sampling priority is proportional to the largest absolute temporal difference error.
            new_priority = (np.abs(loss) + self.prioritization_constant) ** self.prioritization_weight
            self.observations._move(index, new_priority)
            self.none_priority_index += 1

Computes priorities according to loss.

Args:
        loss_per_instance:


def url_stats(self, short):

        data = dict(action='url-stats', shorturl=short)
        jsondata = self._api_request(params=data)

        return _json_to_shortened_url(jsondata['link'])

Get stats for short URL or keyword.

    Parameters:
        short: Short URL (http://example.com/abc) or keyword (abc).

Returns:
        ShortenedURL: Shortened URL and associated data.

Raises:
        ~yourls.exceptions.YOURLSHTTPError: HTTP error with response from
            YOURLS API.
        requests.exceptions.HTTPError: Generic HTTP error.


def __init__(self, low, high, output_shape):

        self.__low = low
        self.__high = high
        self.__output_shape = output_shape

Init.

Args:
        low:            Lower boundary of the output interval.
                        All values generated will be greater than or equal to low.

        high:           Upper boundary of the output interval.
                        All values generated will be less than high.

        output_shape:   Output shape.
                        the shape is `(batch size, d1, d2, d3, ...)`.


def get_dependent_projects(self, recursive = True):

        projects = {}
        for name, ref in list(self.dependencies.items()):
            try:
                prj = self.vcp.projects[name]
            except KeyError:
                logger.error("Unknown project '%s' in project '%s' dependencies!", name, self.name)
                continue
            projects[name] = prj
            if recursive:
                projects.update(prj.get_dependent_projects())
        return projects

Get the dependencies of the Project

Args:
        recursive (bool): add the dependant project's dependencies too

Returns:
        dict of project name and project instances


def gru_feedfwd(a_t, h_prev, filters, name=None):

  with tf.variable_scope(name, default_name="GRU", values=[a_t, h_prev]):
    # we use right matrix multiplication to handle batches
    # W_z and W_r have shape 2d, d. U_z U_r have shape d,d
    z_t = (
        tf.sigmoid(
            tpu_conv1d(a_t, filters, 1, padding="SAME", name="W_z") +
            tpu_conv1d(h_prev, filters, 1, padding="SAME", name="U_z")))
    r_t = (
        tf.sigmoid(
            tpu_conv1d(a_t, filters, 1, padding="SAME", name="W_r") +
            tpu_conv1d(h_prev, filters, 1, padding="SAME", name="U_r")))
    h_tilde = (
        tf.tanh(
            tpu_conv1d(a_t, filters, 1, padding="SAME", name="W") +
            tpu_conv1d(r_t * h_prev, filters, 1, padding="SAME", name="U")))
    h_t = (1. - z_t) * h_prev + z_t * h_tilde

  return h_t

position-wise Feed-fwd GRU gates following the MPNN.

Args:
        a_t: Tensor of shape [batch, length, depth] of current input
        h_prev: Tensor of shape [batch, length, depth] of prev input
        filters: an integer specifying number of dimensions of the filters
        name: A string

Returns:
        h_t: [batch, length, filters] hidden state


def timeseries_from_mat(filename, varname=None, fs=1.0):

    import scipy.io as sio
    if varname is None:
        mat_dict = sio.loadmat(filename)
        if len(mat_dict) > 1:
            raise ValueError('Must specify varname: file contains '
                             'more than one variable. ')
    else:
        mat_dict = sio.loadmat(filename, variable_names=(varname,))
        array = mat_dict.popitem()[1]
    return Timeseries(array, fs=fs)

load a multi-channel Timeseries from a MATLAB .mat file

Args:
        filename (str): .mat file to load
        varname (str): variable name. only needed if there is more than one
        variable saved in the .mat file
        fs (scalar): sample rate of timeseries in Hz. (constant timestep assumed)

Returns:
        Timeseries


def columns(self, dimensions=None):

        if dimensions is None:
            dimensions = self.dimensions()
        else:
            dimensions = [self.get_dimension(d, strict=True) for d in dimensions]
        return OrderedDict([(d.name, self.dimension_values(d)) for d in dimensions])

Convert dimension values to a dictionary.

    Returns a dictionary of column arrays along each dimension
    of the element.

Args:
        dimensions: Dimensions to return as columns

Returns:
        Dictionary of arrays for each dimension


def _validator(code_or_name, validator_type):

    if validator_type == "error":
        from .errors import codes
        from .errors import EXT
    elif validator_type == "warning":
        from .warnings import codes
        from .warnings import EXT
    else:
        pass # TODO (bev) ValueError?

    def decorator(func):
        def wrapper(*args, **kw):
            extra = func(*args, **kw)
            if extra is None: return []
            if isinstance(code_or_name, string_types):
                code = EXT
                name = codes[code][0] + ":" + code_or_name
            else:
                code = code_or_name
                name = codes[code][0]
            text = codes[code][1]
            return [(code, name, text, extra)]
        wrapper.validator_type = validator_type
        return wrapper

    return decorator

Internal shared implementation to handle both error and warning
    validation checks.

Args:
        code code_or_name (int or str) : a defined error code or custom message
        validator_type (str) : either "error" or "warning"

Returns:
        validation decorator


def print_probabilities(state: State, ndigits: int = 4,
                        file: TextIO = None) -> None:

    prob = bk.evaluate(state.probabilities())
    for index, prob in np.ndenumerate(prob):
        prob = round(prob, ndigits)
        if prob == 0.0:
            continue
        ket = "".join([str(n) for n in index])
        print(ket, ":", prob, file=file)

Pretty print state probabilities.

Args:
        state:
        ndigits: Number of digits of accuracy
        file: Output stream (Defaults to stdout)


def format_color(text, color, use_color_setting):

    if not use_color_setting:
        return text
    else:
        return '{}{}{}'.format(color, text, NORMAL)

Format text with color.

Args:
        text - Text to be formatted with color if `use_color`
        color - The color start string
        use_color_setting - Whether or not to color


def _set_axis(self,traces,on=None,side='right',title=''):

	fig={}
	fig_cpy=fig_to_dict(self).copy()
	fig['data']=fig_cpy['data']
	fig['layout']=fig_cpy['layout']
	fig=Figure(fig)
	traces=make_list(traces)

	def update_data(trace,y):
		anchor=fig.axis['def'][y]['anchor'] if 'anchor' in fig.axis['def'][y] else 'x1'
		idx=fig.trace_dict[trace] if isinstance(trace,str) else trace
		fig['data'][idx]['xaxis']=anchor
		fig['data'][idx]['yaxis']=y

	for trace in traces:
		if on:
			if on not in fig.axis['def']:
				raise Exception('"on" axis does not exists: {0}'.format(on))
			update_data(trace,y=on)
		else:
			curr_x,curr_y=fig.axis['ref'][trace]
			domain='[0.0, 1.0]' if 'domain' not in fig.axis['def'][curr_y] else str(fig.axis['def'][curr_y]['domain'])
			try:
				new_axis=fig.axis['dom']['y'][domain][side]
			except KeyError:
				axis=fig.axis['def'][curr_y].copy()
				### check overlaying values
				axis.update(title=title,overlaying=curr_y,side=side,anchor=curr_x)
				axis_idx=str(fig.axis['len']['y']+1)
				fig['layout']['yaxis{0}'.format(axis_idx)]=axis
				new_axis='y{0}'.format(axis_idx)
			update_data(trace,y=new_axis)

	for k in list(fig.axis['def'].keys()):
		id='{0}axis{1}'.format(k[0],k[-1:])
		if k not in fig.axis['ref_axis']:
			try:
				del fig['layout'][id]
			except KeyError:
				pass

	return fig

Sets the axis in which each trace should appear
    If the axis doesn't exist then a new axis is created

    Parameters:
    -----------
    traces : list(str)
        List of trace names
    on : string
        The axis in which the traces should be placed.
        If this is not indicated then a new axis will be
        created
    side : string
        Side where the axis will be placed
        'left'
        'right'
    title : string
        Sets the title of the axis
        Applies only to new axis


def write_file(path, data, mode='w'):  # type: (str, str, str) -> None

    with open(path, mode) as f:
        f.write(data)

Write data to a file.

Args:
        path (str): path to the file.
        data (str): data to be written to the file.
        mode (str): mode which the file will be open.


def basis_state(str_state, num):

    n = int(str_state, 2)
    if num >= len(str_state):
        state = np.zeros(1 << num, dtype=complex)
        state[n] = 1
        return state
    else:
        raise QiskitError('size of bitstring is greater than num.')

Return a basis state ndarray.

Args:
        str_state (string): a string representing the state.
        num (int): the number of qubits

Returns:
        ndarray:  state(2**num) a quantum state with basis basis state.

Raises:
        QiskitError: if the dimensions is wrong


def get_config(self, name):

        if name not in self.registry:
            msg = "Given config name '{}' is not registered."
            raise NotRegisteredError(msg.format(name))

        return copy.deepcopy(self.registry[name])

Return a registred configuration for given config name.

Args:
        name (string): A registred config name.

Raises:
        NotRegisteredError: If given config name does not exist in
        registry.

Returns:
        dict: Configuration.


def plot_pie(self, key="wall_time", minfract=0.05, **kwargs):

        timers = self.timers()
        n = len(timers)

        # Make square figures and axes
        import matplotlib.pyplot as plt
        from matplotlib.gridspec import GridSpec
        fig = plt.gcf()
        gspec = GridSpec(n, 1)
        for idx, timer in enumerate(timers):
            ax = plt.subplot(gspec[idx, 0])
            ax.set_title(str(timer))
            timer.pie(ax=ax, key=key, minfract=minfract, show=False)

        return fig

Plot pie charts of the different timers.

Args:
        key: Keyword used to extract data from timers.
        minfract: Don't show sections whose relative weight is less that minfract.

Returns:
        `matplotlib` figure


def _get_acorn(self, method, *items):

    #IMPORTANT!! I lost two hours because the ndarray becomes unstable if you
    #don't call the original method first. Somehow passing the array instance to
    #other methods changed its internal representation and made it unusable by
    #the original numpy functions. Putting them first makes it work.

    # Because we had to subclass numpy.ndarray, the original methods get
    # stuck in an infinite loop (max. recursion depth exceeded errors). So,
    # we instead grab the reference to the original ndarray object.
    if method == "slice":
        r = np.ndarray.__acornext__.__getslice__(self, *items)
    else:
        r = np.ndarray.__acornext__.__getitem__(self, *items)

    if not (decorating or streamlining):
        from acorn.logging.decoration import (pre, post, _fqdn)
        if method == "slice":
            fqdn = "numpy.ndarray.__getslice__"
        else:
            fqdn = "numpy.ndarray.__getitem__"
        preres = pre(fqdn, np.ndarray, 5, self, *items)
        entry, bound, ekey = preres
        # This method can trick acorn into thinking that it is a bound
        # method. We want it to behave like it's not.
        post(fqdn, "numpy", r, entry, np.ndarray, ekey)
    return r

Gets either a slice or an item from an array. Used for the __getitem__
    and __getslice__ special methods of the sub-classed array.

Args:
        method (str): on of ['slice', 'item'].


def wasp_snp_directory(vcf, directory, sample_name=None):

    chrom = []
    pos = []
    ref = []
    alt = []
    vcf_reader = pyvcf.Reader(open(vcf, 'r'))
    if sample_name:
        def condition(record, sample_name):
            return sample_name in [x.sample for x in record.get_hets()]
    else:
        def condition(record, sample_name):
            return len(record.get_hets()) > 0
    for record in vcf_reader:
        if condition(record, sample_name):
            if len(record.ALT) == 1:
                chrom.append(record.CHROM)
                pos.append(record.POS)
                ref.append(record.REF)
                alt.append(record.ALT[0].sequence)
    df = pd.DataFrame([chrom, pos, ref, alt],
                      index=['chrom', 'position', 'RefAllele', 'AltAllele']).T
    if not os.path.exists(directory):
        os.makedirs(directory)
    for c in set(df.chrom):
        tdf = df[df.chrom == c]
        if tdf.shape[0] > 0:
            f = gzip.open(os.path.join(directory, '{}.snps.txt.gz'.format(c)),
                          'wb')
            lines = (tdf.position.astype(str) + '\t' + tdf.RefAllele + '\t' +
                     tdf.AltAllele)
            f.write('\n'.join(lines) + '\n')
            f.close()

Convert VCF file into input for WASP. Only bi-allelic heterozygous sites are
    used.

    Parameters:
    -----------
    vcf : str
        Path to VCF file.

    directory : str
        Output directory. This is the directory that will hold the files for
        WASP.

    sample_name : str
        If provided, use this sample name to get heterozygous SNPs from VCF
        file.


def parse_date(datestr):

    match = re.match(
        r'([0-9]{4})(-?([0-9]{1,2}))?(-?([0-9]{1,2}))?(_w)?$', datestr)
    if not match:
        return (arrow.get(datestr,
                          tzinfo=config.timezone).replace(tzinfo=config.timezone),
                'day', 'YYYY-MM-DD')

    year, month, day, week = match.group(1, 3, 5, 6)
    start = arrow.Arrow(year=int(year), month=int(
        month or 1), day=int(day or 1), tzinfo=config.timezone)

    if week:
        return start.span('week')[0], 'week', WEEK_FORMAT
    if day:
        return start, 'day', DAY_FORMAT
    if month:
        return start, 'month', MONTH_FORMAT
    if year:
        return start, 'year', YEAR_FORMAT

    raise ValueError("Could not parse date: {}".format(datestr))

Parse a date expression into a tuple of:

    (start_date, span_type, span_format)

Args:
    datestr -- A date specification, in the format of YYYY-MM-DD (dashes optional)


def m_seg(p1, p2, rad, dist):

    v = vector(p1, p2)
    m = unit(rotate(v, rad), dist)
    return translate(p1, m), translate(p2, m)

move segment by distance

Args:
        p1, p2: point(x, y)
        rad: relative direction angle(radian)
        dist: distance

Returns:
        translated segment(p1, p2)


def dropout(x, keep_prob, noise_shape=None, name=None):

  noise_shape = convert_to_shape(noise_shape)
  if noise_shape is None:
    noise_shape = x.shape
  with tf.variable_scope(name, default_name="dropout"):
    if keep_prob == 1.0:
      return x
    noise = cast(less(random_uniform(
        x.mesh, noise_shape, dtype=x.dtype), keep_prob), x.dtype)
    noise /= keep_prob
    return x * noise

Dropout layer.

Args:
        x: a Tensor
        keep_prob: a float between 0.0 and 1.0
        noise_shape: an optional Shape (a subset of x.shape)
        name: an optional string

Returns:
        a Tensor


def get_box_field(self, box_key, field_key = None):

		#does not work
		self._raise_unimplemented_error()

		uri = '/'.join([self.api_uri,
						self.boxes_suffix,
						box_key,
						self.fields_suffix
						])
		if field_key:
			uri = '/'.join([uri, field_key])

		return self._req('get', uri)

Gets one/all field in a box

Args:
    box_key 		key for pipeline
    field_key 			key for field (default: None i.e. ALL)
    returns				status code, field dict or list thereof


def find_links(url):

    url = protocolise(url)
    content = requests.get(url).content
    flike = StringIO(content)
    root = html.parse(flike).getroot()
    atags = root.cssselect('a')
    hrefs = [a.attrib['href'] for a in atags]
    # !!! This does the wrong thing for bbc.co.uk/index.html
    hrefs = [h if h.startswith('http') else '/'.join([url, h]) for h in hrefs ]
    return hrefs

Find the href destinations of all links at  URL

Args:
    - `url`:

    Return: list[str]
    Exceptions: None


def ParseCacheEntry(self, file_object, block_offset):

    cache_entry_map = self._GetDataTypeMap('chrome_cache_entry')

    try:
      cache_entry, _ = self._ReadStructureFromFileObject(
          file_object, block_offset, cache_entry_map)
    except (ValueError, errors.ParseError) as exception:
      raise errors.UnableToParseFile((
          'Unable to parse cache entry at offset: 0x{0:08x} with error: '
          '{1!s}').format(block_offset, exception))

    cache_entry_object = CacheEntry()

    cache_entry_object.hash = cache_entry.hash
    cache_entry_object.next = CacheAddress(cache_entry.next_address)
    cache_entry_object.rankings_node = CacheAddress(
        cache_entry.rankings_node_address)
    cache_entry_object.creation_time = cache_entry.creation_time

    byte_array = cache_entry.key
    byte_string = bytes(bytearray(byte_array))
    cache_entry_object.key, _, _ = byte_string.partition(b'\x00')

    try:
      cache_entry_object.original_url = cache_entry_object.key.decode('ascii')
    except UnicodeDecodeError as exception:
      raise errors.ParseError(
          'Unable to decode original URL in key with error: {0!s}'.format(
              exception))

    return cache_entry_object

Parses a cache entry.

Args:
        file_object (dfvfs.FileIO): a file-like object to read from.
        block_offset (int): block offset of the cache entry.

Returns:
        CacheEntry: cache entry.

Raises:
        ParseError: if the cache entry cannot be read.


def identifiers(config):

    ids = []
    if (config.klass_name == 'gen'):
        for generator in os.listdir(config.generator_dir):
            if (generator == '__init__.py'):
                continue
            (gid, ext) = os.path.splitext(generator)
            if (ext == '.py' and
                    os.path.isfile(os.path.join(config.generator_dir, generator))):
                ids.append(gid)
    else:
        for image_file in os.listdir(config.image_dir):
            (iid, ext) = os.path.splitext(image_file)
            if (ext in ['.jpg', '.png', '.tif'] and
                    os.path.isfile(os.path.join(config.image_dir, image_file))):
                ids.append(iid)
    return ids

Show list of identifiers for this prefix.

    Handles both the case of local file based identifiers and
    also image generators.

Args:
        config - configuration object in which:
            config.klass_name - 'gen' if a generator function
            config.generator_dir - directory for generator code
            config.image_dir - directory for images

Returns:
        ids - a list of ids


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

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

    # Create virtual environment.
    env_path = os.path.join(destination_directory, env_name)
    # (These files are output by dev_tools/python2.7-generate.sh.)
    req_path = os.path.join(destination_directory, 'requirements.txt')
    dev_req_path = os.path.join(destination_directory,
                                'pip-list-test-tools.txt')
    contrib_req_path = os.path.join(destination_directory,
                                    'cirq',
                                    'contrib',
                                    'contrib-requirements.txt')
    req_paths = [req_path, dev_req_path, contrib_req_path]
    create_virtual_env(venv_path=env_path,
                       python_path=python_path,
                       requirements_paths=req_paths,
                       verbose=verbose)

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

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

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

Returns:
        A description of the environment that was prepared.


def get_lattice_type(number):

        f = lambda i, j: i <= number <= j
        cs = {'triclinic': (1, 2), 'monoclinic': (3, 15),
              'orthorhombic': (16, 74), 'tetragonal': (75, 142),
              'trigonal': (143, 167), 'hexagonal': (168, 194),
              'cubic': (195, 230)}

        crystal_system = None
        for k, v in cs.items():
            if f(*v):
                crystal_system = k
                break

        if number in [146, 148, 155, 160, 161, 166, 167]:
            return "rhombohedral"
        elif crystal_system == "trigonal":
            return "hexagonal"
        else:
            return crystal_system

Return the lattice crystal system.

    Hexagonal cells are differentiated into rhombohedral and hexagonal
    lattices.

Args:
        number (int): The international space group number.

Returns:
        str: The lattice crystal system.


def resize_bytes(fobj, old_size, new_size, offset):

    if new_size < old_size:
        delete_size = old_size - new_size
        delete_at = offset + new_size
        delete_bytes(fobj, delete_size, delete_at)
    elif new_size > old_size:
        insert_size = new_size - old_size
        insert_at = offset + old_size
        insert_bytes(fobj, insert_size, insert_at)

Resize an area in a file adding and deleting at the end of it.
    Does nothing if no resizing is needed.

Args:
        fobj (fileobj)
        old_size (int): The area starting at offset
        new_size (int): The new size of the area
        offset (int): The start of the area

Raises:
        IOError


def get_pending_enrollment_message(cls, pending_users, enrolled_in):

        pending_emails = [pending_user.user_email for pending_user in pending_users]
        return (
            'warning',
            _(
                "The following learners do not have an account on "
                "{platform_name}. They have not been enrolled in "
                "{enrolled_in}. When these learners create an account, they will "
                "be enrolled automatically: {pending_email_list}"
            ).format(
                platform_name=settings.PLATFORM_NAME,
                enrolled_in=enrolled_in,
                pending_email_list=', '.join(pending_emails),
            )
        )

Create message for the users who were enrolled in a course or program.

Args:
        users: An iterable of PendingEnterpriseCustomerUsers who were successfully linked with a pending enrollment
        enrolled_in (str): A string identifier for the course or program the pending users were linked to

Returns:
        tuple: A 2-tuple containing a message type and message text


def setAltInterface(self, alternate):
        r
        if isinstance(alternate, Interface):
           alternate = alternate.alternateSetting

        self.dev.set_interface_altsetting(self.__claimed_interface, alternate)

r"""Sets the active alternate setting of the current interface.

Args:
        alternate: an alternate setting number or an Interface object.


Description:
    Top 2 alternatives 12 moment conditions objective function
    Parameters:
    params:  all parameters for the Plackett-Luce mixture model (numpy ndarray)
    moments: values of the moment conditions from the data (numpy ndarray)


def is_initialised( self ):

        if not self.lattice:
            raise AttributeError('Running a simulation needs the lattice to be initialised')
        if not self.atoms:
            raise AttributeError('Running a simulation needs the atoms to be initialised')
        if not self.number_of_jumps and not self.for_time:
            raise AttributeError('Running a simulation needs number_of_jumps or for_time to be set')

Check whether the simulation has been initialised.

Args:
        None

Returns:
        None


def global_idx_to_numeric_idx(self, axis, indices):

        assert axis in ["row", "col", "columns"]
        if axis == "row":
            return pandas.Index(
                pandas.Series(np.arange(len(self.index)), index=self.index)
                .loc[indices]
                .values
            )
        elif axis in ["col", "columns"]:
            return pandas.Index(
                pandas.Series(np.arange(len(self.columns)), index=self.columns)
                .loc[indices]
                .values
            )

Note: this function involves making copies of the index in memory.

Args:
        axis: Axis to extract indices.
        indices: Indices to convert to numerical.

Returns:
        An Index object.


def __init__(self, json_data):

        super(SimpleDataModel, self).__init__()
        for attribute, value in json_dict(json_data).items():
            setattr(self, attribute, value)

Init a new SimpleDataModel object from a dictionary or JSON string.

Args:
        json_data(dict, basestring): Input JSON string or dictionary.

Raises:
        TypeError: If the input object is not a dictionary or string.


def from_label(cls, label):
        r
        z = np.zeros(len(label), dtype=np.bool)
        x = np.zeros(len(label), dtype=np.bool)
        for i, char in enumerate(label):
            if char == 'X':
                x[-i - 1] = True
            elif char == 'Z':
                z[-i - 1] = True
            elif char == 'Y':
                z[-i - 1] = True
                x[-i - 1] = True
            elif char != 'I':
                raise QiskitError("Pauli string must be only consisted of 'I', 'X', "
                                  "'Y' or 'Z' but you have {}.".format(char))
        return cls(z=z, x=x)

r"""Take pauli string to construct pauli.

    The qubit index of pauli label is q_{n-1} ... q_0.
    E.g., a pauli is $P_{n-1} \otimes ... \otimes P_0$

Args:
        label (str): pauli label

Returns:
        Pauli: the constructed pauli

Raises:
        QiskitError: invalid character in the label


def _maybe_download_corpora(tmp_dir):

  mnli_filename = "MNLI.zip"
  mnli_finalpath = os.path.join(tmp_dir, "MNLI")
  if not tf.gfile.Exists(mnli_finalpath):
    zip_filepath = generator_utils.maybe_download(
        tmp_dir, mnli_filename, _MNLI_URL)
    zip_ref = zipfile.ZipFile(zip_filepath, "r")
    zip_ref.extractall(tmp_dir)
    zip_ref.close()

  return mnli_finalpath

Download corpora for multinli.

Args:
        tmp_dir: a string

Returns:
        a string


def display_required_items(msg_type):

    print("Configure a profile for: " + msg_type)
    print("You will need the following information:")
    for k, v in CONFIG[msg_type]["settings"].items():
        print("   * " + v)
    print("Authorization/credentials required:")
    for k, v in CONFIG[msg_type]["auth"].items():
        print("   * " + v)

Display the required items needed to configure a profile for the given
    message type.

Args:
        :msg_type: (str) message type to create config entry.


def rename_edges(self, old_node_name, new_node_name):

        graph = self.graph
        for node, edges in graph.items():
            if node == old_node_name:
                graph[new_node_name] = copy(edges)
                del graph[old_node_name]

            else:
                if old_node_name in edges:
                    edges.remove(old_node_name)
                    edges.add(new_node_name)

Change references to a node in existing edges.

Args:
        old_node_name (str): The old name for the node.
        new_node_name (str): The new name for the node.


def add_config_paths(**kwargs):

    for k, path in kwargs.items():
        if not os.path.exists(path):
            raise ValueError(
                'Configuration file "{}" does not exist'.format(k))
        if k in cf.get_option('config_paths'):
            raise ValueError('Configuration {!r} already exists'.format(k))

    kwargs.update(**cf.get_option('config_paths'))
    cf.set_option('config_paths', kwargs)

Add to the pool of available configuration files for BIDSLayout.

Args:
        kwargs: dictionary specifying where to find additional config files.
            Keys are names, values are paths to the corresponding .json file.

Example:
        > add_config_paths(my_config='/path/to/config')
        > layout = BIDSLayout('/path/to/bids', config=['bids', 'my_config'])


def inner_content(node):

    from lxml import etree

    # Include text content at the start of the node.
    parts = [node.text]

    for child in node.getchildren():
        # Include the child serialized to raw XML.
        parts.append(etree.tostring(child, encoding="utf-8"))

        # Include any text following the child.
        parts.append(child.tail)

    # Discard any non-existent text parts and return.
    return "".join(filter(None, parts))

Returns the inner content of a given XML node, including tags.

Args:
        node (lxml.etree.Element): The node whose inner content is desired.

Returns:
        str: The inner content of the node.


def pack_tag(field_number, wire_type):

    if not 0 <= wire_type <= _WIRETYPE_MAX:
        raise errors.EncodeError('Unknown wire type: %d' % wire_type)
    return (field_number << TAG_TYPE_BITS) | wire_type

Returns an unsigned 32-bit integer that encodes the field number and
    wire type information in standard protocol message wire format.

Args:
        field_number: Expected to be an integer in the range [1, 1 << 29)
        wire_type: One of the WIRETYPE_* constants.


def to_hdf(self,path,key,mode='a'):

        pd.DataFrame(self.serialize()).to_hdf(path,key,mode=mode,format='table',complib='zlib',complevel=9)
        f = h5py.File(path,'r+')
        f[key].attrs["microns_per_pixel"] = float(self.microns_per_pixel) if self.microns_per_pixel is not None else np.nan
        f.close()

Save the CellDataFrame to an hdf5 file.

Args:
        path (str): the path to save to
        key (str): the name of the location to save it to
        mode (str): write mode


def _construct_operation_id(self, service_name, protorpc_method_name):

    # camelCase the ProtoRPC method name
    method_name_camel = util.snake_case_to_headless_camel_case(
        protorpc_method_name)

    return '{0}_{1}'.format(service_name, method_name_camel)

Return an operation id for a service method.

Args:
        service_name: The name of the service.
        protorpc_method_name: The ProtoRPC method name.

Returns:
        A string representing the operation id.


def expand(self, other):

        if len(other) == 2:
            other += other
        mid = len(other) // 2
        self.ll = map(min, self.ll, other[:mid])
        self.ur = map(max, self.ur, other[mid:])

Expands this envelope by the given Envelope or tuple.

Args:
    other -- Envelope, two-tuple, or four-tuple


def CSS_setMediaText(self, styleSheetId, range, text):

		assert isinstance(text, (str,)
		    ), "Argument 'text' must be of type '['str']'. Received type: '%s'" % type(
		    text)
		subdom_funcs = self.synchronous_command('CSS.setMediaText', styleSheetId=
		    styleSheetId, range=range, text=text)
		return subdom_funcs

Function path: CSS.setMediaText
    Domain: CSS
    Method name: setMediaText

    Parameters:
    Required arguments:
        'styleSheetId' (type: StyleSheetId) -> No description
        'range' (type: SourceRange) -> No description
        'text' (type: string) -> No description

Returns:
    'media' (type: CSSMedia) -> The resulting CSS media rule after modification.

    Description: Modifies the rule selector.


def restore_state(self, state):

        super(ReferenceController, self).restore_state(state)

        state_name = state.get('state_name')
        state_version = state.get('state_version')

        if state_name != self.STATE_NAME or state_version != self.STATE_VERSION:
            raise ArgumentError("Invalid emulated device state name or version", found=(state_name, state_version),
                                expected=(self.STATE_NAME, self.STATE_VERSION))

        self.app_info = state.get('app_info', (0, "0.0"))
        self.os_info = state.get('os_info', (0, "0.0"))

        # Notify all subsystems of our intent to restore in case they need to prepare
        self.sensor_log.prepare_for_restore()

        # Restore all of the subsystems
        self.remote_bridge.restore(state.get('remote_bridge', {}))
        self.tile_manager.restore(state.get('tile_manager', {}))
        self.config_database.restore(state.get('config_database', {}))
        self.sensor_log.restore(state.get('sensor_log', {}))

Restore the current state of this emulated object.

Args:
        state (dict): A previously dumped state produced by dump_state.


def create_object(self, obj_type, payload, return_fields=None):

        self._validate_obj_type_or_die(obj_type)

        query_params = self._build_query_params(return_fields=return_fields)

        url = self._construct_url(obj_type, query_params)
        opts = self._get_request_options(data=payload)
        self._log_request('post', url, opts)
        if(self.session.cookies):
            # the first 'get' or 'post' action will generate a cookie
            # after that, we don't need to re-authenticate
            self.session.auth = None
        r = self.session.post(url, **opts)

        self._validate_authorized(r)

        if r.status_code != requests.codes.CREATED:
            response = utils.safe_json_load(r.content)
            already_assigned = 'is assigned to another network view'
            if response and already_assigned in response.get('text'):
                exception = ib_ex.InfobloxMemberAlreadyAssigned
            else:
                exception = ib_ex.InfobloxCannotCreateObject
            raise exception(
                response=response,
                obj_type=obj_type,
                content=r.content,
                args=payload,
                code=r.status_code)

        return self._parse_reply(r)

Create an Infoblox object of type 'obj_type'

Args:
        obj_type        (str): Infoblox object type,
                            e.g. 'network', 'range', etc.
        payload       (dict): Payload with data to send
        return_fields (list): List of fields to be returned

Returns:
        The object reference of the newly create object

Raises:
        InfobloxException


def _ExportEvent(self, output_module, event, deduplicate_events=True):

    if event.timestamp != self._export_event_timestamp:
      self._FlushExportBuffer(
          output_module, deduplicate_events=deduplicate_events)
      self._export_event_timestamp = event.timestamp

    self._export_event_heap.PushEvent(event)

Exports an event using an output module.

Args:
        output_module (OutputModule): output module.
        event (EventObject): event.
        deduplicate_events (Optional[bool]): True if events should be
        deduplicated.


def export_default_scripts(target_folder, source_folder = None, raise_errors = False, verbose=False):

    scripts_to_load = get_classes_in_folder(source_folder, Script)

    if verbose:
        print(('attempt to load {:d} scripts: '.format(len(scripts_to_load))))

    loaded_scripts, failed, loaded_instruments = Script.load_and_append(scripts_to_load, raise_errors=raise_errors)

    for name, value in loaded_scripts.items():
        filename = os.path.join(target_folder, '{:s}.b26'.format(name))
        value.save_b26(filename)

    if verbose:
        print('\n================================================')
        print('================================================')
        print(('saved {:d} scripts, {:d} failed'.format(len(loaded_scripts), len(failed))))
        if failed != {}:
            for error_name, error in failed.items():
                print(('failed to create script: ', error_name, error))

tries to instantiate all the scripts that are imported in /scripts/__init__.py
    saves each script that could be instantiated into a .b26 file in the folder path

Args:
        target_folder: target path for .b26 files
        source_folder: location of python script files


def add_symbol(self, symbol_name, namespace_stack, node, module):

        # TODO(nnorwitz): verify symbol_name doesn't contain :: ?
        if namespace_stack:
            # Handle non-global symbols (ie, in some namespace).
            last_namespace = self.namespaces
            for namespace in namespace_stack:
                last_namespace = last_namespace.setdefault(namespace, {})
        else:
            last_namespace = self.namespaces[None]
        return self._add(symbol_name, last_namespace, node, module)

Adds symbol_name defined in namespace_stack to the symbol table.

Args:
        symbol_name: 'name of the symbol to lookup'
        namespace_stack: None or ['namespaces', 'symbol', 'defined', 'in']
        node: ast.Node that defines this symbol
        module: module (any object) this symbol is defined in

Returns:
        bool(if symbol was *not* already present)


def range(self, dim, data_range=True, dimension_range=True):

        iskdim = self.get_dimension(dim) not in self.vdims
        return super(StatisticsElement, self).range(dim, iskdim, dimension_range)

Return the lower and upper bounds of values along dimension.

Args:
        dimension: The dimension to compute the range on.
        data_range (bool): Compute range from data values
        dimension_range (bool): Include Dimension ranges
            Whether to include Dimension range and soft_range
            in range calculation

Returns:
        Tuple containing the lower and upper bound


def _register_preallocated_ips(self, conf):

        for dom_name, dom_spec in conf.get('domains', {}).items():
            for idx, nic in enumerate(dom_spec.get('nics', [])):
                if 'ip' not in nic:
                    continue

                net = conf['nets'][nic['net']]
                if self._subnet_store.is_leasable_subnet(net['gw']):
                    nic['ip'] = _create_ip(
                        net['gw'], int(nic['ip'].split('.')[-1])
                    )

                dom_name = dom_spec['name']
                if not _ip_in_subnet(net['gw'], nic['ip']):
                    raise RuntimeError(
                        "%s:nic%d's IP [%s] is outside the subnet [%s]" % (
                            dom_name,
                            dom_spec['nics'].index(nic),
                            nic['ip'],
                            net['gw'],
                        ),
                    )

                if nic['ip'] in net['mapping'].values():
                    conflict_list = [
                        name for name, ip in net['mapping'].items()
                        if ip == net['ip']
                    ]
                    raise RuntimeError(
                        'IP %s was to several domains: %s %s' % (
                            nic['ip'],
                            dom_name,
                            ' '.join(conflict_list),
                        ),
                    )

                self._add_nic_to_mapping(net, dom_spec, nic)

Parse all the domains in the given conf and preallocate all their ips
    into the networks mappings, raising exception on duplicated ips or ips
    out of the allowed ranges

    See Also:
        :mod:`lago.subnet_lease`

Args:
        conf (dict): Configuration spec to parse

Returns:
        None

Raises:
        RuntimeError: if there are any duplicated ips or any ip out of the
            allowed range


def ensure_proc_terminate(proc):

    if isinstance(proc, list):
        for p in proc:
            ensure_proc_terminate(p)
        return

    def stop_proc_by_weak_ref(ref):
        proc = ref()
        if proc is None:
            return
        if not proc.is_alive():
            return
        proc.terminate()
        proc.join()

    assert isinstance(proc, mp.Process)
    atexit.register(stop_proc_by_weak_ref, weakref.ref(proc))

Make sure processes terminate when main process exit.

Args:
        proc (multiprocessing.Process or list)


def get_measurements(region, core_info, data, extra_offset=0):

    measurements = []
    clean_core_info = [x for x in core_info if x]
    cores = len(clean_core_info)
    for k in data:
        if k not in ["1", "Region Info", "Event", "Metric", "CPU clock"]:
            slot = data[k]
            for i in range(cores):
                core = core_info[i]
                idx = extra_offset + i
                if core and slot[idx]:
                    measurements.append((region, k, core, slot[idx]))

    return measurements

Get the complete measurement info from likwid's region info.

Args:
        region: The region we took a measurement in.
        core_info: The core information.
        data: The raw data.
        extra_offset (int): default = 0

    Returns (list((region, metric, core, value))):
        A list of measurement tuples, a tuple contains the information about
        the region, the metric, the core and the actual value.


def query(self, queryEngine, query=None, vendorSpecific=None, **kwargs):

        response = self.queryResponse(queryEngine, query, vendorSpecific, **kwargs)
        return self._read_stream_response(response)

See Also: queryResponse()

Args:
        queryEngine:
        query:
        vendorSpecific:
        **kwargs:

    Returns:


def create_cloudwatch_event(app_name, env, region, rules):

    session = boto3.Session(profile_name=env, region_name=region)
    cloudwatch_client = session.client('events')

    rule_name = rules.get('rule_name')
    schedule = rules.get('schedule')
    rule_description = rules.get('rule_description')
    json_input = rules.get('json_input', {})

    if schedule is None:
        LOG.critical('Schedule is required and no schedule is defined!')
        raise InvalidEventConfiguration('Schedule is required and no schedule is defined!')

    if rule_name is None:
        LOG.critical('Rule name is required and no rule_name is defined!')
        raise InvalidEventConfiguration('Rule name is required and no rule_name is defined!')
    else:
        LOG.info('%s and %s', app_name, rule_name)
        rule_name = "{}_{}".format(app_name, rule_name.replace(' ', '_'))

    if rule_description is None:
        rule_description = "{} - {}".format(app_name, rule_name)

    lambda_arn = get_lambda_arn(app=app_name, account=env, region=region)

    # Add lambda permissions
    account_id = get_env_credential(env=env)['accountId']
    principal = "events.amazonaws.com"
    statement_id = '{}_cloudwatch_{}'.format(app_name, rule_name)
    source_arn = 'arn:aws:events:{}:{}:rule/{}'.format(region, account_id, rule_name)
    add_lambda_permissions(
        function=lambda_arn,
        statement_id=statement_id,
        action='lambda:InvokeFunction',
        principal=principal,
        source_arn=source_arn,
        env=env,
        region=region, )

    # Create Cloudwatch rule
    cloudwatch_client.put_rule(
        Name=rule_name,
        ScheduleExpression=schedule,
        State='ENABLED',
        Description=rule_description, )

    targets = []
    # TODO: read this one from file event-config-*.json
    json_payload = '{}'.format(json.dumps(json_input))

    target = {
        "Id": app_name,
        "Arn": lambda_arn,
        "Input": json_payload,
    }

    targets.append(target)

    put_targets_response = cloudwatch_client.put_targets(Rule=rule_name, Targets=targets)
    LOG.debug('Cloudwatch put targets response: %s', put_targets_response)

    LOG.info('Created Cloudwatch event "%s" with schedule: %s', rule_name, schedule)

Create cloudwatch event for lambda from rules.

Args:
        app_name (str): name of the lambda function
        env (str): Environment/Account for lambda function
        region (str): AWS region of the lambda function
        rules (dict): Trigger rules from the settings


def set_pattern_actual_step(self, patternnumber, value):

        _checkPatternNumber(patternnumber)
        _checkStepNumber(value)

        address = _calculateRegisterAddress('actualstep', patternnumber)
        self.write_register(address, value, 0)

Set the 'actual step' parameter for a given pattern.

Args:
        * patternnumber (integer): 0-7
        * value (integer): 0-7


def django_cache_function(timeout: int = 5 * 60,
                          cache_key: str = '',
                          debug_cache: bool = False):

    cache_key = cache_key or None

    def decorator(fn):
        def wrapper(*args, **kwargs):
            # - NOTE that Django returns None from cache.get() for "not in
            #   cache", so can't cache a None value;
            #   https://docs.djangoproject.com/en/1.10/topics/cache/#basic-usage  # noqa
            # - We need to store a bit more than just the function result
            #   anyway, to detect hash collisions when the user doesn't specify
            #   the cache_key, so we may as well use that format even if the
            #   user does specify the cache_key, and then we can store a None
            #   result properly as well.
            if cache_key:
                # User specified a cache key. This is easy.
                call_sig = ''
                _cache_key = cache_key
                check_stored_call_sig = False
            else:
                # User didn't specify a cache key, so we'll do one
                # automatically. Since we do this via a hash, there is a small
                # but non-zero chance of a hash collision.
                call_sig = get_call_signature(fn, args, kwargs)
                _cache_key = make_cache_key(call_sig)
                check_stored_call_sig = True
            if debug_cache:
                log.critical("Checking cache for key: " + _cache_key)
            cache_result_tuple = cache.get(_cache_key)  # TALKS TO CACHE HERE
            if cache_result_tuple is None:
                if debug_cache:
                    log.debug("Cache miss")
            else:
                if debug_cache:
                    log.debug("Cache hit")
                cached_call_sig, func_result = cache_result_tuple
                if (not check_stored_call_sig) or cached_call_sig == call_sig:
                    return func_result
                log.warning(
                    "... Cache hit was due to hash collision; cached_call_sig "
                    "{} != call_sig {}".format(
                        repr(cached_call_sig), repr(call_sig)))
                # If we get here, either it wasn't in the cache, or something
                # was in the cache that matched by cache_key but was actually a
                # hash collision. Either way, we must do the real work.
            func_result = fn(*args, **kwargs)
            cache_result_tuple = (call_sig, func_result)
            cache.set(key=_cache_key, value=cache_result_tuple,
                      timeout=timeout)  # TALKS TO CACHE HERE
            return func_result

        return wrapper

    return decorator

Decorator to add caching to a function in Django.
    Uses the Django default cache.

Args:
        timeout: timeout in seconds; use None for "never expire", as 0 means
            "do not cache".

        cache_key: optional cache key to use (if falsy, we'll invent one)
        debug_cache: show hits/misses?


def next_population(self, population, fitnesses):

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

Make a new population after each optimization iteration.

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

Returns:
        list; a list of solutions.


def windows_from_blocksize(self, blocksize_xy=512):

        meta = self._get_template_for_given_resolution(self.dst_res, "meta")
        width = meta["width"]
        height = meta["height"]
        blocksize_wins = windows_from_blocksize(blocksize_xy, width, height)

        self.windows = np.array([win[1] for win in blocksize_wins])
        self.windows_row = np.array([win[0][0] for win in blocksize_wins])
        self.windows_col = np.array([win[0][1] for win in blocksize_wins])
        return self

Create rasterio.windows.Window instances with given size which fully cover the raster.

Args:
        blocksize_xy {int or list of two int} -- Size of the window. If one integer is given it defines
            the width and height of the window. If a list of two integers if given the first defines the
            width and the second the height.

Returns:
        None -- But the attributes ``windows``, ``windows_row`` and ``windows_col`` are updated.


def __cloudflare_request(self, *, account, path, args=None):

        if not args:
            args = {}

        if not self.cloudflare_initialized[account.account_id]:
            self.cloudflare_session[account.account_id] = requests.Session()
            self.cloudflare_session[account.account_id].headers.update({
                'X-Auth-Email': account.email,
                'X-Auth-Key': account.api_key,
                'Content-Type': 'application/json'
            })
            self.cloudflare_initialized[account.account_id] = True

        if 'per_page' not in args:
            args['per_page'] = 100

        response = self.cloudflare_session[account.account_id].get(account.endpoint + path, params=args)
        if response.status_code != 200:
            raise CloudFlareError('Request failed: {}'.format(response.text))

        return response.json()

Helper function to interact with the CloudFlare API.

Args:
        account (:obj:`CloudFlareAccount`): CloudFlare Account object
        path (`str`): URL endpoint to communicate with
        args (:obj:`dict` of `str`: `str`): A dictionary of arguments for the endpoint to consume

Returns:
        `dict`


def diff_xIndex(self, diffs, loc):

    chars1 = 0
    chars2 = 0
    last_chars1 = 0
    last_chars2 = 0
    for x in range(len(diffs)):
      (op, text) = diffs[x]
      if op != self.DIFF_INSERT:  # Equality or deletion.
        chars1 += len(text)
      if op != self.DIFF_DELETE:  # Equality or insertion.
        chars2 += len(text)
      if chars1 > loc:  # Overshot the location.
        break
      last_chars1 = chars1
      last_chars2 = chars2

    if len(diffs) != x and diffs[x][0] == self.DIFF_DELETE:
      # The location was deleted.
      return last_chars2
    # Add the remaining len(character).
    return last_chars2 + (loc - last_chars1)

loc is a location in text1, compute and return the equivalent location
    in text2.  e.g. "The cat" vs "The big cat", 1->1, 5->8

Args:
        diffs: Array of diff tuples.
        loc: Location within text1.

Returns:
        Location within text2.