def merge_level_and_latent_dist(level_dist, latent_dist,
                                merge_std="prev_level"):

  level_mean, level_std = level_dist.loc, level_dist.scale
  latent_mean, latent_std = latent_dist.loc, latent_dist.scale
  new_mean = level_mean + latent_mean
  if merge_std == "normal":
    z_shape = common_layers.shape_list(latent_mean)
    log_scale = tf.get_variable(
        "merge_std", shape=z_shape, dtype=tf.float32,
        initializer=tf.zeros_initializer(), trainable=False)
    scale = tf.exp(log_scale * 3.0)
  elif merge_std == "prev_level":
    scale = level_std
  elif merge_std == "prev_step":
    scale = latent_std
  return tfp.distributions.Normal(loc=new_mean, scale=scale)

Merge level_dist and latent_dist.

    new_dist ~ N(level_dist.mean + latent_dis.mean, std) where std is determined
    according to merge_std.

Args:
        level_dist: instance of tfp.distributions.Normal
        latent_dist: instance of tfp.distributions.Normal
        merge_std: can be "prev_level", "prev_step" or "normal".

Returns:
        merged_dist: instance of tfp.distributions.Normal


def run(self, gin):

        with ScratchDir("."):
            p = subprocess.Popen(
                self._gulp_cmd, stdout=subprocess.PIPE,
                stdin=subprocess.PIPE, stderr=subprocess.PIPE
            )

            out, err = p.communicate(bytearray(gin, "utf-8"))
            out = out.decode("utf-8")
            err = err.decode("utf-8")

            if "Error" in err or "error" in err:
                print(gin)
                print("----output_0---------")
                print(out)
                print("----End of output_0------\n\n\n")
                print("----output_1--------")
                print(out)
                print("----End of output_1------")
                raise GulpError(err)

            # We may not need this
            if "ERROR" in out:
                raise GulpError(out)

            # Sometimes optimisation may fail to reach convergence
            conv_err_string = "Conditions for a minimum have not been satisfied"
            if conv_err_string in out:
                raise GulpConvergenceError()

            gout = ""
            for line in out.split("\n"):
                gout = gout + line + "\n"
            return gout

Run GULP using the gin as input

Args:
        gin: GULP input string

Returns:
        gout: GULP output string


def message_factory(msg_type, msg_types=MESSAGE_TYPES, *args, **kwargs):

    try:
        return msg_types[msg_type.lower()](*args, **kwargs)
    except (UnknownProfileError, InvalidMessageInputError) as e:
        err_exit("Unable to send message: ", e)
    except KeyError:
        raise UnsupportedMessageTypeError(msg_type, msg_types)

Factory function to return the specified message instance.

Args:
        :msg_type: (str) the type of message to send, i.e. 'Email'
        :msg_types: (str, list, or set) the supported message types
        :kwargs: (dict) keywords arguments that are required for the
            various message types.  See docstrings for each type.
            i.e. help(messages.Email), help(messages.Twilio), etc.


def scale(self, width: int, height: int) -> None:

        lib.TCOD_image_scale(self.image_c, width, height)
        self.width, self.height = width, height

Scale this Image to the new width and height.

Args:
        width (int): The new width of the Image after scaling.
        height (int): The new height of the Image after scaling.


def fit(self, train_x, train_y):

        if self.first_fitted:
            self.incremental_fit(train_x, train_y)
        else:
            self.first_fit(train_x, train_y)

Fit the regressor with more data.

Args:
        train_x: A list of NetworkDescriptor.
        train_y: A list of metric values.


def add_listener(self, callback, event_type=None):

        listener_uid = uuid4()
        # TODO: listeners should be stored in dict and accessed/deleted directly. Add
        # convenience method such that MatrixClient.listeners.new(Listener(...)) performs
        # MatrixClient.listeners[uuid4()] = Listener(...)
        self.listeners.append(
            {
                'uid': listener_uid,
                'callback': callback,
                'event_type': event_type
            }
        )
        return listener_uid

Add a listener that will send a callback when the client recieves
    an event.

Args:
        callback (func(roomchunk)): Callback called when an event arrives.
        event_type (str): The event_type to filter for.

Returns:
        uuid.UUID: Unique id of the listener, can be used to identify the listener.


def GetDecoder(cls, encoding_method):

    encoding_method = encoding_method.lower()
    decoder = cls._decoders.get(encoding_method, None)
    if not decoder:
      return None

    return decoder()

Retrieves the decoder object for a specific encoding method.

Args:
        encoding_method (str): encoding method identifier.

Returns:
        Decoder: decoder or None if the encoding method does not exists.


def loads(s, single=False, version=_default_version,
          strict=False, errors='warn'):

    ms = deserialize(s, version=version, strict=strict, errors=errors)
    if single:
        return next(ms)
    else:
        return ms

Deserialize SimpleMRS string representations

Args:
        s (str): a SimpleMRS string
        single (bool): if `True`, only return the first Xmrs object

Returns:
        a generator of Xmrs objects (unless *single* is `True`)


def AddClass(self, class_name, gtfs_class):

    if class_name in self._class_mapping:
      raise problems.DuplicateMapping(class_name)
    self._class_mapping[class_name] = gtfs_class

Adds an entry to the list of known classes.

Args:
        class_name: A string with name through which gtfs_class is to be made
                    accessible.
        gtfs_class: The class to be added.

Raises:
        DuplicateMapping if class_name is already present in the class mapping.


def airborne_position_with_ref(msg, lat_ref, lon_ref):

    mb = common.hex2bin(msg)[32:]

    cprlat = common.bin2int(mb[22:39]) / 131072.0
    cprlon = common.bin2int(mb[39:56]) / 131072.0

    i = int(mb[21])
    d_lat = 360.0/59 if i else 360.0/60

    j = common.floor(lat_ref / d_lat) \
        + common.floor(0.5 + ((lat_ref % d_lat) / d_lat) - cprlat)

    lat = d_lat * (j + cprlat)

    ni = common.cprNL(lat) - i

    if ni > 0:
        d_lon = 360.0 / ni
    else:
        d_lon = 360.0

    m = common.floor(lon_ref / d_lon) \
        + common.floor(0.5 + ((lon_ref % d_lon) / d_lon) - cprlon)

    lon = d_lon * (m + cprlon)

    return round(lat, 5), round(lon, 5)

Decode airborne position with only one message,
    knowing reference nearby location, such as previously calculated location,
    ground station, or airport location, etc. The reference position shall
    be with in 180NM of the true position.

Args:
        msg (string): even message (28 bytes hexadecimal string)
        lat_ref: previous known latitude
        lon_ref: previous known longitude

Returns:
        (float, float): (latitude, longitude) of the aircraft


def get_random_email(ltd="com"):

        email = [
            RandomInputHelper.get_random_value(6, [string.ascii_lowercase]),
            "@",
            RandomInputHelper.get_random_value(6, [string.ascii_lowercase]),
            ".",
            ltd
        ]

        return "".join(email)

Get a random email address with the given ltd.

Args:
        ltd (str): The ltd to use (e.g. com).

Returns:
        str: The random email.


def transformer_revnet_decoder(decoder_input,
                               encoder_output,
                               decoder_self_attention_bias,
                               encoder_decoder_attention_bias,
                               hparams,
                               name="decoder"):

  def f(x, side_input):

    decoder_self_attention_bias = side_input[0]
    encoder_decoder_attention_bias = side_input[1]
    encoder_output = side_input[2]

    old_hid_size = hparams.hidden_size
    hparams.hidden_size = old_hid_size // 2

    with tf.variable_scope("self_attention"):
      y = common_attention.multihead_attention(
          common_layers.layer_preprocess(
              x, hparams), None, decoder_self_attention_bias,
          hparams.attention_key_channels or hparams.hidden_size,
          hparams.attention_value_channels or hparams.hidden_size,
          hparams.hidden_size, hparams.num_heads, hparams.attention_dropout)
      y = common_layers.layer_postprocess(x, y, hparams)
      if encoder_output is not None:
        with tf.variable_scope("encdec_attention"):
          y = common_attention.multihead_attention(
              common_layers.layer_preprocess(
                  x, hparams), encoder_output, encoder_decoder_attention_bias,
              hparams.attention_key_channels or hparams.hidden_size,
              hparams.attention_value_channels or hparams.hidden_size,
              hparams.hidden_size, hparams.num_heads, hparams.attention_dropout)
          y = common_layers.layer_postprocess(x, y, hparams)
    hparams.hidden_size = old_hid_size
    return y

  def g(x):

    old_hid_size = hparams.hidden_size
    hparams.hidden_size = old_hid_size // 2
    with tf.variable_scope("ffn"):
      y = transformer.transformer_ffn_layer(
          common_layers.layer_preprocess(x, hparams), hparams)
      y = common_layers.layer_postprocess(x, y, hparams)
    hparams.hidden_size = old_hid_size
    return y

  x1, x2 = tf.split(decoder_input, 2, axis=-1)

  with tf.variable_scope(name):
    y1, y2 = tf.contrib.layers.rev_block(
        x1,
        x2,
        f,
        g,
        num_layers=hparams.num_hidden_layers,
        f_side_input=[
            decoder_self_attention_bias, encoder_decoder_attention_bias,
            encoder_output
        ],
        is_training=hparams.mode == tf.estimator.ModeKeys.TRAIN)
    y = tf.concat([y1, y2], axis=-1)
    return common_layers.layer_preprocess(y, hparams)

A stack of transformer layers.

Args:
        decoder_input: a Tensor
        encoder_output: a Tensor
        decoder_self_attention_bias: bias Tensor for self-attention
        (see common_attention.attention_bias())
        encoder_decoder_attention_bias: bias Tensor for encoder-decoder attention
        (see common_attention.attention_bias())
        hparams: hyperparameters for model
        name: a string

Returns:
        y: a Tensors


def heatmap(n_x=5,n_y=10):

	x=['x_'+str(_) for _ in range(n_x)]
	y=['y_'+str(_) for _ in range(n_y)]
	return pd.DataFrame(surface(n_x-1,n_y-1).values,index=x,columns=y)

Returns a DataFrame with the required format for
    a heatmap plot

    Parameters:
    -----------
    n_x : int
        Number of x categories
    n_y : int
        Number of y categories


def ParseInteger(text, is_signed=False, is_long=False):

  # Do the actual parsing. Exception handling is propagated to caller.
  result = _ParseAbstractInteger(text, is_long=is_long)

  # Check if the integer is sane. Exceptions handled by callers.
  checker = _INTEGER_CHECKERS[2 * int(is_long) + int(is_signed)]
  checker.CheckValue(result)
  return result

Parses an integer.

Args:
        text: The text to parse.
        is_signed: True if a signed integer must be parsed.
        is_long: True if a long integer must be parsed.

Returns:
        The integer value.

Raises:
        ValueError: Thrown Iff the text is not a valid integer.


def parse_config_file(config_file, skip_unknown=False):

  for reader, existence_check in _FILE_READERS:
    if existence_check(config_file):
      with reader(config_file) as f:
        parse_config(f, skip_unknown=skip_unknown)
        return
  raise IOError('Unable to open file: {}'.format(config_file))

Parse a Gin config file.

Args:
        config_file: The path to a Gin config file.
        skip_unknown: A boolean indicating whether unknown configurables and imports
        should be skipped instead of causing errors (alternatively a list of
        configurable names to skip if unknown). See `parse_config` for additional
        details.

Raises:
        IOError: If `config_file` cannot be read using any register file reader.


def __call__(self, name, value):

        if not isinstance(value, self.base_type):
            raise ValueError("%s must be %s, not %s" % (name, self.base_type, value.__class__))

Call method.

Args:
        name (str): the value's name.
        value (object): the value to check.

Raises:
        ValueError: if value is not type base_type.


def flush_redis_unsafe(redis_client=None):

    if redis_client is None:
        ray.worker.global_worker.check_connected()
        redis_client = ray.worker.global_worker.redis_client

    # Delete the log files from the primary Redis shard.
    keys = redis_client.keys("LOGFILE:*")
    if len(keys) > 0:
        num_deleted = redis_client.delete(*keys)
    else:
        num_deleted = 0
    print("Deleted {} log files from Redis.".format(num_deleted))

    # Delete the event log from the primary Redis shard.
    keys = redis_client.keys("event_log:*")
    if len(keys) > 0:
        num_deleted = redis_client.delete(*keys)
    else:
        num_deleted = 0
    print("Deleted {} event logs from Redis.".format(num_deleted))

This removes some non-critical state from the primary Redis shard.

    This removes the log files as well as the event log from Redis. This can
    be used to try to address out-of-memory errors caused by the accumulation
    of metadata in Redis. However, it will only partially address the issue as
    much of the data is in the task table (and object table), which are not
    flushed.

Args:
        redis_client: optional, if not provided then ray.init() must have been
        called.


def run_tpm(tpm, time_scale):

    sbs_tpm = convert.state_by_node2state_by_state(tpm)
    if sparse(tpm):
        tpm = sparse_time(sbs_tpm, time_scale)
    else:
        tpm = dense_time(sbs_tpm, time_scale)
    return convert.state_by_state2state_by_node(tpm)

Iterate a TPM by the specified number of time steps.

Args:
        tpm (np.ndarray): A state-by-node tpm.
        time_scale (int): The number of steps to run the tpm.

Returns:
        np.ndarray


def from_json_file(cls, file_name):

        with open(file_name) as json_data:
            config = json.load(json_data)

        return cls(config)

Construct OneViewClient using a json file.

Args:
        file_name: json full path.

Returns:
        OneViewClient:


def symlink_to_bytes(symlink_target):
    # type: (str) -> bytes

    symlink_data = bytearray()
    for comp in symlink_target.split('/'):
        if comp == '':
            # If comp is empty, then we know this is the leading slash
            # and we should make an absolute entry (double slashes and
            # such are weeded out by the earlier utils.normpath).
            symlink_data.extend(b'\x02\x00\x00\x00')
        elif comp == '.':
            symlink_data.extend(b'\x04\x00\x00\x00')
        elif comp == '..':
            symlink_data.extend(b'\x03\x00\x00\x00')
        else:
            symlink_data.extend(b'\x05')
            ostaname = _ostaunicode(comp)
            symlink_data.append(len(ostaname))
            symlink_data.extend(b'\x00\x00')
            symlink_data.extend(ostaname)

    return symlink_data

A function to generate UDF symlink data from a Unix-like path.

    Parameters:
    symlink_target - The Unix-like path that is the symlink.

Returns:
    The UDF data corresponding to the symlink.


def _TerminateProcessByPid(self, pid):

    self._RaiseIfNotRegistered(pid)

    process = self._processes_per_pid[pid]

    self._TerminateProcess(process)
    self._StopMonitoringProcess(process)

Terminate a process that's monitored by the engine.

Args:
        pid (int): process identifier (PID).

Raises:
        KeyError: if the process is not registered with and monitored by the
        engine.


def import_image_from_url(self, url, repository=None, tag=None,
                              changes=None):

        return self.import_image(
            src=url, repository=repository, tag=tag, changes=changes
        )

Like :py:meth:`~docker.api.image.ImageApiMixin.import_image`, but only
    supports importing from a URL.

Args:
        url (str): A URL pointing to a tar file.
        repository (str): The repository to create
        tag (str): The tag to apply


def add_time_dimension(padded_inputs, seq_lens):

    # Sequence lengths have to be specified for LSTM batch inputs. The
    # input batch must be padded to the max seq length given here. That is,
    # batch_size == len(seq_lens) * max(seq_lens)
    padded_batch_size = tf.shape(padded_inputs)[0]
    max_seq_len = padded_batch_size // tf.shape(seq_lens)[0]

    # Dynamically reshape the padded batch to introduce a time dimension.
    new_batch_size = padded_batch_size // max_seq_len
    new_shape = ([new_batch_size, max_seq_len] +
                 padded_inputs.get_shape().as_list()[1:])
    return tf.reshape(padded_inputs, new_shape)

Adds a time dimension to padded inputs.

Args:
        padded_inputs (Tensor): a padded batch of sequences. That is,
            for seq_lens=[1, 2, 2], then inputs=[A, *, B, B, C, C], where
            A, B, C are sequence elements and * denotes padding.
        seq_lens (Tensor): the sequence lengths within the input batch,
            suitable for passing to tf.nn.dynamic_rnn().

Returns:
        Reshaped tensor of shape [NUM_SEQUENCES, MAX_SEQ_LEN, ...].


def interpret_obj(
        self,
        obj,
        v_level_indexes,
        h_level_indexes,
        v_level_visibility,
        h_level_visibility,
        v_level_sort_keys,
        h_level_sort_keys,
        v_level_titles,
        h_level_titles,
    ):

        if not isinstance(obj, NonStringIterable):
            raise self.error("Cannot make a table from object {!r}".format(obj))

        rectangular_rows = tabulate(
            obj,
            v_level_indexes=v_level_indexes,
            h_level_indexes=h_level_indexes,
            v_level_visibility=v_level_visibility,
            h_level_visibility=h_level_visibility,
            v_level_sort_keys=v_level_sort_keys,
            h_level_sort_keys=h_level_sort_keys,
            v_level_titles=v_level_titles,
            h_level_titles=h_level_titles,
        )
        assert is_rectangular(rectangular_rows)
        num_rows, num_cols = size(rectangular_rows)
        return rectangular_rows, num_cols

Interpret the given Python object as a table.

Args:
        obj: A sequence (later a mapping, too)

Returns:
        A list of lists represents rows of cells.

Raises:
        TypeError: If the type couldn't be interpreted as a table.


def __init__(self, mol):

        if isinstance(mol, Molecule):
            if not mol.is_ordered:
                raise ValueError("OpenBabel Molecule only supports ordered "
                                 "molecules.")

            # For some reason, manually adding atoms does not seem to create
            # the correct OBMol representation to do things like force field
            # optimization. So we go through the indirect route of creating
            # an XYZ file and reading in that file.
            obmol = ob.OBMol()
            obmol.BeginModify()
            for site in mol:
                coords = [c for c in site.coords]
                atomno = site.specie.Z
                obatom = ob.OBAtom()
                obatom.thisown = 0
                obatom.SetAtomicNum(atomno)
                obatom.SetVector(*coords)
                obmol.AddAtom(obatom)
                del obatom
            obmol.ConnectTheDots()
            obmol.PerceiveBondOrders()
            obmol.SetTotalSpinMultiplicity(mol.spin_multiplicity)
            obmol.SetTotalCharge(mol.charge)
            obmol.Center()
            obmol.Kekulize()
            obmol.EndModify()
            self._obmol = obmol
        elif isinstance(mol, ob.OBMol):
            self._obmol = mol

Initializes with pymatgen Molecule or OpenBabel"s OBMol.

Args:
        mol: pymatgen's Molecule or OpenBabel OBMol


def __contains__(self, k):

        chain = ChainMap(self.scopes, self.globals)
        return chain.__contains__(k)

Check whether a variable has been assigned to.

    This is **not** the same kind of element-of as described in the
    class documentation.

Args:
        k (str): The name of the variable to check.

Returns:
        bool: Whether or not the variable has been assigned to.


def remove(self, *l):

        removeList = list(flatten(l))
        self._remove(removeList, self.value)

remove elements from self.value by matching.

    Create the exactly same single you want to delete and pass it(them) in.
    Normally this method needs to be overwrited by subclass. It only looks inside current instance's value, not recursive. There is no need for a recursive one anyway.

Args:
        *l: a single element, a bunch of element seperated by comma, or a list of elements, or any combination. Element is what you match with.


def unpack(self, buff, offset=0):

        header = UBInt16()
        header.unpack(buff[offset:offset+2])
        self.tlv_type = header.value >> 9
        length = header.value & 511
        begin, end = offset + 2, offset + 2 + length
        sub_type = UBInt8()
        sub_type.unpack(buff[begin:begin+1])
        self.sub_type = sub_type.value
        self.sub_value = BinaryData(buff[begin+1:end])

Unpack a binary message into this object's attributes.

    Unpack the binary value *buff* and update this object attributes based
    on the results.

Args:
        buff (bytes): Binary data package to be unpacked.
        offset (int): Where to begin unpacking.

Raises:
        Exception: If there is a struct unpacking error.


def _CreateShapePointFolder(self, shapes_folder, shape):

    folder_name = shape.shape_id + ' Shape Points'
    folder = self._CreateFolder(shapes_folder, folder_name, visible=False)
    for (index, (lat, lon, dist)) in enumerate(shape.points):
      placemark = self._CreatePlacemark(folder, str(index+1))
      point = ET.SubElement(placemark, 'Point')
      coordinates = ET.SubElement(point, 'coordinates')
      coordinates.text = '%.6f,%.6f' % (lon, lat)
    return folder

Create a KML Folder containing all the shape points in a shape.

    The folder contains placemarks for each shapepoint.

Args:
        shapes_folder: A KML Shape Folder ElementTree.Element instance
        shape: The shape to plot.

Returns:
        The Folder ElementTree.Element instance or None.


def terminate_session(self, token):

        url = self.rest_url + "/session/%s" % token
        response = self._delete(url)

        # For consistency between methods use None rather than False
        # If token validation failed for any reason return None
        if not response.ok:
            return None

        # Otherwise return True
        return True

Terminates the session token, effectively logging out the user
    from all crowd-enabled services.

Args:
        token: The session token.

Returns:
        True: If session terminated

        None: If session termination failed


def log_correction(self, event, action):

        # TODO: Create CorrectionObject
        action = str(action)
        self.history.info(action)

        self._corrections.append(dict(
            event=event.as_dict(),
            action=action,
        ))

This method should be called once we have fixed the problem associated to this event.
    It adds a new entry in the correction history of the node.

Args:
        event: :class:`AbinitEvent` that triggered the correction.
        action (str): Human-readable string with info on the action perfomed to solve the problem.


def __init__(self, *futures):

    for f in futures:
      if not isinstance(f, PipelineFuture):
        raise TypeError('May only pass PipelineFuture instances to After(). %r',
                        type(f))
    self._futures = set(futures)

Initializer.

Args:
        *futures: PipelineFutures that all subsequent pipelines should follow.
        May be empty, in which case this statement does nothing.


def connect(portname, baudrate):

    global SERPORT
    try:
        SERPORT = serial.Serial(portname, baudrate, timeout = 0.1)

    except:
        raise HerkulexError("could not open the serial port")

Connect to the Herkulex bus

    Connect to serial port to which Herkulex Servos are attatched

Args:
        portname (str): The serial port name
        baudrate (int): The serial port baudrate

Raises:
        SerialException: Error occured while opening serial port


def batch_mutate(self, mutation_map, consistency_level):

    self._seqid += 1
    d = self._reqs[self._seqid] = defer.Deferred()
    self.send_batch_mutate(mutation_map, consistency_level)
    return d

Mutate many columns or super columns for many row keys. See also: Mutation.

    mutation_map maps key to column family to a list of Mutation objects to take place at that scope.
    *

    Parameters:
    - mutation_map
    - consistency_level


def new_body(name=None, pos=None, **kwargs):

    if name is not None:
        kwargs["name"] = name
    if pos is not None:
        kwargs["pos"] = array_to_string(pos)
    element = ET.Element("body", attrib=kwargs)
    return element

Creates a body element with attributes specified by @**kwargs.

Args:
        name (str): body name.
        pos: 3d position of the body frame.


def git_clone(prettyname: str, url: str, directory: str,
              branch: str = None,
              commit: str = None,
              clone_options: List[str] = None,
              run_func: Callable[[List[str]], Any] = None) -> bool:

    run_func = run_func or subprocess.check_call
    clone_options = clone_options or []  # type: List[str]
    if os.path.isdir(directory):
        log.info("Not re-cloning {} Git repository: using existing source "
                 "in {}".format(prettyname, directory))
        return False
    log.info("Fetching {} source from {} into {}",
             prettyname, url, directory)
    require_executable(GIT)
    gitargs = [GIT, "clone"] + clone_options
    if branch:
        gitargs += ["--branch", branch]
    gitargs += [url, directory]
    run_func(gitargs)
    if commit:
        log.info("Resetting {} local Git repository to commit {}",
                 prettyname, commit)
        run_func([GIT,
                  "-C", directory,
                  "reset", "--hard", commit])
        # Using a Git repository that's not in the working directory:
        # https://stackoverflow.com/questions/1386291/git-git-dir-not-working-as-expected  # noqa
    return True

Fetches a Git repository, unless we have it already.

Args:
        prettyname: name to display to user
        url: URL
        directory: destination directory
        branch: repository branch
        commit: repository commit tag
        clone_options: additional options to pass to ``git clone``
        run_func: function to use to call an external command

Returns:
        did we need to do anything?


def __call__(self, value):

        fmt = self.fmt(value)
        if len(fmt) > self.col_width:
            fmt = fmt[:self.col_width - 3] + '...'
        fmt = self.just(fmt, self.col_width)
        return fmt

Formats a given value

Args:
        value: value to format

Returns:
        str: formatted value


def get(self, url, params=None, **kwargs):

        return self.call_api(
            "GET",
            url,
            params=params,
            **kwargs
        )

Call the API with a GET request.

Args:
        url (str): Resource location relative to the base URL.
        params (dict or None): Query-string parameters.

Returns:
        ResultParser or ErrorParser.


def serialize_to_transport(self, doc_format="xml", *args, **kwargs):

        return super(ResourceMap, self).serialize(
            format=doc_format, encoding="utf-8", *args, **kwargs
        )

Serialize ResourceMap to UTF-8 encoded XML document.

Args:
        doc_format: str
        One of: ``xml``, ``n3``, ``turtle``, ``nt``, ``pretty-xml``, ``trix``,
        ``trig`` and ``nquads``.

        args and kwargs:
        Optional arguments forwarded to rdflib.ConjunctiveGraph.serialize().

Returns:
        bytes: UTF-8 encoded XML doc.

Note:
        Only the default, "xml", is automatically indexed by DataONE.


def __init__(self, provider, template, **kwargs):

        super(StatikJinjaTemplate, self).__init__(template.filename, **kwargs)
        self.provider = provider
        self.template = template

Constructor.

Args:
        provider: The provider that created this template.
        template: The Jinja2 template to wrap.


def parse_flags_with_usage(args):

  try:
    return FLAGS(args)
  except flags.Error as error:
    sys.stderr.write('FATAL Flags parsing error: %s\n' % error)
    sys.stderr.write('Pass --helpshort or --helpfull to see help on flags.\n')
    sys.exit(1)

Tries to parse the flags, print usage, and exit if unparseable.

Args:
        args: [str], a non-empty list of the command line arguments including
        program name.

Returns:
        [str], a non-empty list of remaining command line arguments after parsing
        flags, including program name.


def configure_logging(verbosity):

    root = logging.getLogger()

    formatter = logging.Formatter('%(asctime)s.%(msecs)03d %(levelname).3s %(name)s %(message)s',
                                  '%y-%m-%d %H:%M:%S')
    handler = logging.StreamHandler()
    handler.setFormatter(formatter)

    loglevels = [logging.CRITICAL, logging.ERROR, logging.WARNING, logging.INFO, logging.DEBUG]
    if verbosity >= len(loglevels):
        verbosity = len(loglevels) - 1

    level = loglevels[verbosity]

    root.setLevel(level)
    root.addHandler(handler)

Set up the global logging level.

Args:
        verbosity (int): The logging verbosity


def gen_binary_files_from_urls(
        urls: Iterable[str],
        on_disk: bool = False,
        show_info: bool = True) -> Generator[BinaryIO, None, None]:

    for url in urls:
        if on_disk:
            # Necessary for e.g. zip processing (random access)
            with tempfile.TemporaryDirectory() as tmpdir:
                filename = os.path.join(tmpdir, "tempfile")
                download(url=url, filename=filename)
                with open(filename, 'rb') as f:
                    yield f
        else:
            if show_info:
                log.info("Reading from URL: {}", url)
            with urllib.request.urlopen(url) as f:
                yield f
        if show_info:
            log.info("... finished reading from URL: {}", url)

Generate binary files from a series of URLs (one per URL).

Args:
        urls: iterable of URLs
        on_disk: if ``True``, yields files that are on disk (permitting
            random access); if ``False``, yields in-memory files (which will
            not permit random access)
        show_info: show progress to the log?

Yields:
        files, each of type :class:`BinaryIO`


def groups(self, group_type=None, filters=None, params=None):

        group = self._tcex.ti.group(group_type)
        for g in self.tc_requests.groups_from_tag(group, self.name, filters=filters, params=params):
            yield g

Gets all groups from a tag.

Args:
        filters:
        params:
        group_type:


def _unescape_token(escaped_token):

    def match(m):
        if m.group(1) is None:
            return u"_" if m.group(0) == u"\\u" else u"\\"

        try:
            return six.unichr(int(m.group(1)))
        except (ValueError, OverflowError):
            return ""

    trimmed = escaped_token[:-1] if escaped_token.endswith("_") else escaped_token
    return _UNESCAPE_REGEX.sub(match, trimmed)

Inverse of _escape_token().

Args:
        escaped_token: a unicode string

Returns:
        token: a unicode string


def from_files(path_dir, dos_spin=1):

        run_type, warning, efermi, gap, doping_levels = \
            BoltztrapAnalyzer.parse_outputtrans(path_dir)

        vol = BoltztrapAnalyzer.parse_struct(path_dir)

        intrans = BoltztrapAnalyzer.parse_intrans(path_dir)

        if run_type == "BOLTZ":
            dos, pdos = BoltztrapAnalyzer.parse_transdos(
                path_dir, efermi, dos_spin=dos_spin, trim_dos=False)

            mu_steps, cond, seebeck, kappa, hall, pn_doping_levels, mu_doping, \
            seebeck_doping, cond_doping, kappa_doping, hall_doping, \
            carrier_conc = BoltztrapAnalyzer. \
                parse_cond_and_hall(path_dir, doping_levels)

            return BoltztrapAnalyzer(
                gap, mu_steps, cond, seebeck, kappa, hall, pn_doping_levels,
                mu_doping, seebeck_doping, cond_doping, kappa_doping,
                hall_doping, intrans, dos, pdos, carrier_conc, vol, warning)

        elif run_type == "DOS":
            trim = True if intrans["dos_type"] == "HISTO" else False
            dos, pdos = BoltztrapAnalyzer.parse_transdos(
                path_dir, efermi, dos_spin=dos_spin, trim_dos=trim)

            return BoltztrapAnalyzer(gap=gap, dos=dos, dos_partial=pdos,
                                     warning=warning, vol=vol)

        elif run_type == "BANDS":
            bz_kpoints = np.loadtxt(
                os.path.join(path_dir, "boltztrap_band.dat"))[:, -3:]
            bz_bands = np.loadtxt(
                os.path.join(path_dir, "boltztrap_band.dat"))[:, 1:-6]
            return BoltztrapAnalyzer(bz_bands=bz_bands, bz_kpoints=bz_kpoints,
                                     warning=warning, vol=vol)

        elif run_type == "FERMI":

            if os.path.exists(os.path.join(path_dir, 'boltztrap_BZ.cube')):
                fs_data = read_cube_file(
                    os.path.join(path_dir, 'boltztrap_BZ.cube'))
            elif os.path.exists(os.path.join(path_dir, 'fort.30')):
                fs_data = read_cube_file(os.path.join(path_dir, 'fort.30'))
            else:
                raise BoltztrapError("No data file found for fermi surface")
            return BoltztrapAnalyzer(fermi_surface_data=fs_data)

        else:
            raise ValueError("Run type: {} not recognized!".format(run_type))

get a BoltztrapAnalyzer object from a set of files

Args:
        path_dir: directory where the boltztrap files are
        dos_spin: in DOS mode, set to 1 for spin up and -1 for spin down

Returns:
        a BoltztrapAnalyzer object


def delete_subscription(self, subscription_id):

        return self.client._delete(self.url + 'subscriptions/{}'.format(subscription_id), headers=self.get_headers())

Unsubscribe, delete the relationship of the customer with the plan.

Args:
        subscription_id: Identification of the subscription.

    Returns:


def deps_from_pydit_json(requires, runtime=True):

    parsed = []
    for req in requires:
        # req looks like 'some-name (>=X.Y,!=Y.X)' or 'someme-name' where
        # 'some-name' is the name of required package and '(>=X.Y,!=Y.X)'
        # are specs
        name, specs = None, None
        # len(reqs) == 1 if there are not specified versions, 2 otherwise
        reqs = req.split(' ')
        name = reqs[0]
        if len(reqs) == 2:
            specs = reqs[1]
            # try if there are more specs in spec part of the requires
            specs = specs.split(",")
            # strip brackets
            specs = [re.sub('[()]', '', spec) for spec in specs]
            # this will divide (>=0.1.2) to ['>=', '0', '.1.2']
            # or (0.1.2) into ['', '0', '.1.2']
            specs = [re.split('([0-9])', spec, 1) for spec in specs]
            # we have separated specs based on number as delimiter
            # so we need to join it back to rest of version number
            # e.g ['>=', '0', '.1.2'] to ['>=', '0.1.2']
            for spec in specs:
                spec[1:3] = [''.join(spec[1:3])]
        if specs:
            for spec in specs:
                if '!' in spec[0]:
                    parsed.append(['Conflicts', name, '=', spec[1]])
                elif specs[0] == '==':
                    parsed.append(['Requires', name, '=', spec[1]])
                else:
                    parsed.append(['Requires', name, spec[0], spec[1]])
        else:
            parsed.append(['Requires', name])

    if not runtime:
        for pars in parsed:
            pars[0] = 'Build' + pars[0]

    return parsed

Parses dependencies returned by pydist.json, since versions
    uses brackets we can't use pkg_resources to parse and we need a separate
    method

Args:
        requires: list of dependencies as written in pydist.json of the package
        runtime: are the dependencies runtime (True) or build time (False)

Returns:
        List of semi-SPECFILE dependecies (see dependency_to_rpm for format)


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

        super().__init__(MeterBandType.OFPMBT_EXPERIMENTER, rate, burst_size)
        self.experimenter = experimenter

Create a MeterBandExperimenter with the optional parameters below.

Args:
        rate (int): Rate for remarking packets.
        burst_size (int): Size of bursts.
        experimenter (int): Experimenter ID which takes the same form as in
            :class:`.ExperimenterHeader`.


def _find_best_fit(self, pbin):

        fit = ((pbin.fitness(r[0], r[1]), k) for k, r in self._sorted_rect.items())
        fit = (f for f in fit if f[0] is not None)
        try:
            _, rect = min(fit, key=self.first_item)
            return rect
        except ValueError:
            return None

Return best fitness rectangle from rectangles packing _sorted_rect list

Args:
        pbin (PackingAlgorithm): Packing bin

Returns:
        key of the rectangle with best fitness


def _ListActiveBreakpoints(self, service):

    try:
      response = service.debuggees().breakpoints().list(
          debuggeeId=self._debuggee_id, waitToken=self._wait_token,
          successOnTimeout=True).execute()
      if not response.get('waitExpired'):
        self._wait_token = response.get('nextWaitToken')
        breakpoints = response.get('breakpoints') or []
        if self._breakpoints != breakpoints:
          self._breakpoints = breakpoints
          native.LogInfo(
              'Breakpoints list changed, %d active, wait token: %s' % (
                  len(self._breakpoints), self._wait_token))
          self.on_active_breakpoints_changed(copy.deepcopy(self._breakpoints))
    except BaseException:
      native.LogInfo('Failed to query active breakpoints: ' +
                     traceback.format_exc())

      # Forget debuggee ID to trigger repeated debuggee registration. Once the
      # registration succeeds, the worker thread will retry this query
      self._debuggee_id = None

      return (True, self.list_backoff.Failed())

    self.list_backoff.Succeeded()
    return (False, 0)

Single attempt query the list of active breakpoints.

    Must not be called before the debuggee has been registered. If the request
    fails, this function resets self._debuggee_id, which triggers repeated
    debuggee registration.

Args:
        service: client to use for API calls

Returns:
        (registration_required, delay) tuple


def save_spectre_plot(self, filename="spectre.pdf", img_format="pdf",
                          sigma=0.05, step=0.01):

        d, plt = self.get_spectre_plot(sigma, step)
        plt.savefig(filename, format=img_format)

Save matplotlib plot of the spectre to a file.

Args:
        filename: Filename to write to.
        img_format: Image format to use. Defaults to EPS.
        sigma: Full width at half maximum in eV for normal functions.
        step: bin interval in eV


def resolve_aliases(data_type):

    if not is_alias(data_type):
        return data_type

    resolved = resolve_aliases(data_type.data_type)
    data_type.data_type = resolved

    return resolved

Resolve all chained / nested aliases. This will recursively point
    nested aliases to their resolved data type (first non-alias in the chain).

    Note: This differs from unwrap_alias which simply identifies/returns
    the resolved data type.

Args:
        data_type (DataType): The target DataType/Alias to resolve.

Returns:
        DataType: The resolved type.


def compare_mim_panels(self, existing_panel, new_panel):

        existing_genes = set([gene['hgnc_id'] for gene in existing_panel['genes']])
        new_genes = set([gene['hgnc_id'] for gene in new_panel['genes']])

        return new_genes.difference(existing_genes)

Check if the latest version of OMIM differs from the most recent in database
    Return all genes that where not in the previous version.

Args:
    existing_panel(dict)
    new_panel(dict)

Returns:
    new_genes(set(str))


def GetMetadataAttribute(self, attribute_name):

    table_name = 'metadata'

    has_table = self._database_file.HasTable(table_name)
    if not has_table:
      return None

    column_names = ['value']
    condition = 'name == "{0:s}"'.format(attribute_name)

    values = list(self._database_file.GetValues(
        [table_name], column_names, condition))

    number_of_values = len(values)
    if number_of_values == 0:
      return None

    if number_of_values == 1:
      return values[0]['value']

    raise RuntimeError('More than one value found in database.')

Retrieves the metadata attribute.

Args:
        attribute_name (str): name of the metadata attribute.

Returns:
        str: the metadata attribute or None.

Raises:
        RuntimeError: if more than one value is found in the database.


def reward(self,
               state: Sequence[tf.Tensor],
               action: Sequence[tf.Tensor],
               next_state: Sequence[tf.Tensor]) -> tf.Tensor:

        scope = self.reward_scope(state, action, next_state)
        r = self.compile_reward(scope).tensor
        with self.graph.as_default():
            with tf.name_scope('reward'):
                return tf.expand_dims(r, -1)

Compiles the reward function given the current `state`, `action` and
    `next_state`.

Args:
        state (Sequence[tf.Tensor]): A tuple of current state tensors.
        action (Sequence[tf.Tensor]): A tuple of action tensors.
        next_state (Sequence[tf.Tensor]): A tuple of next state tensors.

Returns:
        (:obj:`tf.Tensor`): A tensor representing the reward function.


def read(self, viewport=None, components=3, *, attachment=0, alignment=1, dtype='f1') -> bytes:

        return self.mglo.read(viewport, components, attachment, alignment, dtype)

Read the content of the framebuffer.

Args:
        viewport (tuple): The viewport.
        components (int): The number of components to read.

    Keyword Args:
        attachment (int): The color attachment.
        alignment (int): The byte alignment of the pixels.
        dtype (str): Data type.

Returns:
        bytes


def register_menu_item(self, items):

        for itm in items:
            if itm.group in self.menu_items:
                # Only add the menu item if we don't already have it registered
                if itm not in self.menu_items[itm.group]['items']:
                    self.menu_items[itm.group]['items'].append(itm)
            else:
                logger.warning('Tried registering menu item to unknown group {}'.format(itm.group))

Registers a views menu items into the metadata for the application. Skip if the item is already present

Args:
        items (`list` of `MenuItem`): A list of `MenuItem`s

Returns:
        `None`


def __init__(self, cell_ctor, *args, **kwargs):

    super(RNNCellWrapper, self).__init__(
        name=kwargs.get("name"),
        custom_getter=kwargs.pop("custom_getter", None))

    with self._enter_variable_scope():
      self._cell = cell_ctor(*args, **kwargs)

Constructs the cell, within this module's variable scope.

Args:
        cell_ctor: Callable that instantiates a `tf.contrib.rnn.RNNCell`.
        *args: Arguments to pass to `cell_ctor`.
        **kwargs: Keyword arguments to pass to `cell_ctor`.
        If `name` is provided, it is passed to `RNNCore.__init__` as well.
        If `custom_getter` is provided, it is passed to `RNNCore.__init__`
        but not to `cell_ctor`.


def lf_polarities(L):

    polarities = [sorted(list(set(L[:, i].data))) for i in range(L.shape[1])]
    return [p[0] if len(p) == 1 else p for p in polarities]

Return the polarities of each LF based on evidence in a label matrix.

Args:
        L: an n x m scipy.sparse matrix where L_{i,j} is the label given by the
            jth LF to the ith candidate


def check_grandparents(self, mother = None, father = None):

        if mother:
            if mother.mother != '0':
                self.grandparents[mother.mother] =  ''
            elif mother.father != '0':
                self.grandparents[mother.father] = ''
        if father:
            if father.mother != '0':
                self.grandparents[father.mother] =  ''
            elif father.father != '0':
                self.grandparents[father.father] = ''
        return

Check if there are any grand parents.

    Set the grandparents id:s

Args:
        mother (Individual): An Individual object that represents the mother
        father (Individual): An Individual object that represents the father


def learn(self, grad_arr):

        encoder_delta_arr, _, encoder_grads_list = self.__encoder_decoder_controller.encoder.hidden_back_propagate(
            grad_arr[:, -1]
        )
        encoder_grads_list.insert(0, None)
        encoder_grads_list.insert(0, None)

        self.__encoder_decoder_controller.encoder.optimize(
            encoder_grads_list,
            self.__learning_rate,
            1
        )

        return encoder_delta_arr

Update this Discriminator by ascending its stochastic gradient.

Args:
        grad_arr:   `np.ndarray` of gradients.

Returns:
        `np.ndarray` of delta or gradients.


def set(self, prop, value):

        prop_parts = prop.split(".")
        if self.copy_dict:
            new_dict = copy.deepcopy(self.obj)
        else:
            new_dict = self.obj
        pointer = None
        parts_length = len(prop_parts) - 1
        for i, part in enumerate(prop_parts):
            if pointer is None and i == parts_length:
                new_dict[part] = value
            elif pointer is None:
                pointer = new_dict.get(part)
            elif i == parts_length:
                pointer[part] = value
            else:
                pointer = pointer.get(part)
        return new_dict

sets the dot notated property to the passed in value

Args:
        prop: a string of the property to retreive
            "a.b.c" ~ dictionary['a']['b']['c']
        value: the value to set the prop object


def make_slot_check(wanted):

    if isinstance(wanted, types.FunctionType):
        return wanted  # just forward the slot check function

    if isinstance(wanted, int):
        item, meta = wanted, None
    elif isinstance(wanted, Slot):
        item, meta = wanted.item_id, wanted.damage  # TODO compare NBT
    elif isinstance(wanted, (Item, Block)):
        item, meta = wanted.id, wanted.metadata
    elif isinstance(wanted, str):
        item_or_block = get_item_or_block(wanted, init=True)
        item, meta = item_or_block.id, item_or_block.metadata
    else:  # wanted is (id, meta)
        try:
            item, meta = wanted
        except TypeError:
            raise ValueError('Illegal args for make_slot_check(): %s' % wanted)

    return lambda slot: item == slot.item_id and meta in (None, slot.damage)

Creates and returns a function that takes a slot
    and checks if it matches the wanted item.

Args:
        wanted: function(Slot) or Slot or itemID or (itemID, metadata)


def login_with_password(self, username, password, limit=10):

        warn("login_with_password is deprecated. Use login with sync=True.",
             DeprecationWarning)
        return self.login(username, password, limit, sync=True)

Deprecated. Use ``login`` with ``sync=True``.

    Login to the homeserver.

Args:
        username (str): Account username
        password (str): Account password
        limit (int): Deprecated. How many messages to return when syncing.
            This will be replaced by a filter API in a later release.

Returns:
        str: Access token

Raises:
        MatrixRequestError


def incrementKeySequenceCounter(self, iIncrementValue=1):

        print '%s call incrementKeySequenceCounter' % self.port
        print iIncrementValue
        currentKeySeq = ''
        try:
            currentKeySeq = self.getKeySequenceCounter()
            keySequence = int(currentKeySeq, 10) + iIncrementValue
            print keySequence
            return self.setKeySequenceCounter(keySequence)
        except Exception, e:
            ModuleHelper.WriteIntoDebugLogger('incrementKeySequenceCounter() Error: ' + str(e))

increment the key sequence with a given value

Args:
        iIncrementValue: specific increment value to be added

Returns:
        True: successful to increment the key sequence with a given value
        False: fail to increment the key sequence with a given value


def generate(self, descriptors):

        model_ids = self.search_tree.adj_list.keys()

        target_graph = None
        father_id = None
        descriptors = deepcopy(descriptors)
        elem_class = Elem
        if self.optimizemode is OptimizeMode.Maximize:
            elem_class = ReverseElem

        # Initialize the priority queue.
        pq = PriorityQueue()
        temp_list = []
        for model_id in model_ids:
            metric_value = self.searcher.get_metric_value_by_id(model_id)
            temp_list.append((metric_value, model_id))
        temp_list = sorted(temp_list)
        for metric_value, model_id in temp_list:
            graph = self.searcher.load_model_by_id(model_id)
            graph.clear_operation_history()
            graph.clear_weights()
            pq.put(elem_class(metric_value, model_id, graph))

        t = 1.0
        t_min = self.t_min
        alpha = 0.9
        opt_acq = self._get_init_opt_acq_value()
        while not pq.empty() and t > t_min:
            elem = pq.get()
            if self.optimizemode is OptimizeMode.Maximize:
                temp_exp = min((elem.metric_value - opt_acq) / t, 1.0)
            else:
                temp_exp = min((opt_acq - elem.metric_value) / t, 1.0)
            ap = math.exp(temp_exp)
            if ap >= random.uniform(0, 1):
                for temp_graph in transform(elem.graph):
                    if contain(descriptors, temp_graph.extract_descriptor()):
                        continue

                    temp_acq_value = self.acq(temp_graph)
                    pq.put(elem_class(temp_acq_value, elem.father_id, temp_graph))
                    descriptors.append(temp_graph.extract_descriptor())
                    if self._accept_new_acq_value(opt_acq, temp_acq_value):
                        opt_acq = temp_acq_value
                        father_id = elem.father_id
                        target_graph = deepcopy(temp_graph)
            t *= alpha

        # Did not found a not duplicated architecture
        if father_id is None:
            return None, None
        nm_graph = self.searcher.load_model_by_id(father_id)
        for args in target_graph.operation_history:
            getattr(nm_graph, args[0])(*list(args[1:]))
        return nm_graph, father_id

Generate new architecture.

Args:
        descriptors: All the searched neural architectures.

Returns:
        graph: An instance of Graph. A morphed neural network with weights.
        father_id: The father node ID in the search tree.


def getTraitCovarStdErrors(self,term_i):

        assert self.init,        'GP not initialised'
        assert self.fast==False, 'Not supported for fast implementation'

        if self.P==1:
            out = (2*self.getScales()[term_i])**2*self._getLaplaceCovar()[term_i,term_i]
        else:
            C = self.vd.getTerm(term_i).getTraitCovar()
            n_params = C.getNumberParams()
            par_index = 0
            for term in range(term_i-1):
                par_index += self.vd.getTerm(term_i).getNumberScales()
            Sigma1 = self._getLaplaceCovar()[par_index:(par_index+n_params),:][:,par_index:(par_index+n_params)]
            out = sp.zeros((self.P,self.P))
            for param_i in range(n_params):
                out += C.Kgrad_param(param_i)**2*Sigma1[param_i,param_i]
                for param_j in range(param_i):
                    out += 2*abs(C.Kgrad_param(param_i)*C.Kgrad_param(param_j))*Sigma1[param_i,param_j]
        out = sp.sqrt(out)
        return out

Returns standard errors on trait covariances from term_i (for the covariance estimate \see getTraitCovar)

Args:
        term_i:     index of the term we are interested in


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

        self._cdfp = BytesIO()
        self.svds = []  # type: List[headervd.PrimaryOrSupplementaryVD]
        self.brs = []  # type: List[headervd.BootRecord]
        self.vdsts = []  # type: List[headervd.VolumeDescriptorSetTerminator]
        self.eltorito_boot_catalog = None  # type: Optional[eltorito.EltoritoBootCatalog]
        self._initialized = False
        self.rock_ridge = ''
        self.isohybrid_mbr = None  # type: Optional[isohybrid.IsoHybrid]
        self.xa = False
        self._managing_fp = False
        self.pvds = []  # type: List[headervd.PrimaryOrSupplementaryVD]
        self._has_udf = False
        self.udf_bea = udfmod.BEAVolumeStructure()  # type: udfmod.BEAVolumeStructure
        self.udf_nsr = udfmod.NSRVolumeStructure()  # type: udfmod.NSRVolumeStructure
        self.udf_tea = udfmod.TEAVolumeStructure()  # type: udfmod.TEAVolumeStructure
        self.udf_anchors = []  # type: List[udfmod.UDFAnchorVolumeStructure]
        self.udf_main_descs = self._UDFDescriptors()
        self.udf_reserve_descs = self._UDFDescriptors()
        self.udf_logical_volume_integrity = udfmod.UDFLogicalVolumeIntegrityDescriptor()
        self.udf_logical_volume_integrity_terminator = udfmod.UDFTerminatingDescriptor()
        self.udf_root = None  # type: Optional[udfmod.UDFFileEntry]
        self.udf_file_set = udfmod.UDFFileSetDescriptor()
        self.udf_file_set_terminator = udfmod.UDFTerminatingDescriptor()
        self._needs_reshuffle = False
        self._rr_moved_record = None  # type: ignore
        self._rr_moved_name = None  # type: Optional[bytes]
        self._rr_moved_rr_name = None  # type: Optional[bytes]
        self.enhanced_vd = None  # type: Optional[headervd.PrimaryOrSupplementaryVD]
        self.joliet_vd = None  # type: Optional[headervd.PrimaryOrSupplementaryVD]
        self._find_iso_record.cache_clear()  # pylint: disable=no-member
        self._find_rr_record.cache_clear()  # pylint: disable=no-member
        self._find_joliet_record.cache_clear()  # pylint: disable=no-member
        self._find_udf_record.cache_clear()  # pylint: disable=no-member
        self._write_check_list = []  # type: List[PyCdlib._WriteRange]
        self.version_vd = None  # type: Optional[headervd.VersionVolumeDescriptor]
        self.inodes = []

An internal method to re-initialize the object.  Called from
    both __init__ and close.

    Parameters:
    None.

Returns:
    Nothing.


def copy_remote_file(web_file, destination):

    size = 0
    dir_name = os.path.dirname(destination)
    if not os.path.exists(dir_name):
        os.makedirs(dir_name)

    with open(destination, 'wb') as file_:
        chunk_size = 8 * 1024
        for chunk in web_file.iter_content(chunk_size=chunk_size):
            if chunk:
                file_.write(chunk)
                size += len(chunk)
    return size

Check if exist the destination path, and copy the online resource
    file to local.

Args:
        :web_file: reference to online file resource to take.
        :destination: path to store the file.


def max(cls, x: 'TensorFluent', y: 'TensorFluent') -> 'TensorFluent':

        return cls._binary_op(x, y, tf.maximum, tf.float32)

Returns a TensorFluent for the maximum function.TensorFluent

Args:
        x: The first operand.
        y: The second operand.

Returns:
        A TensorFluent wrapping the maximum function.


def parse_outputtrans(path_dir):

        run_type = None
        warning = None
        efermi = None
        gap = None
        doping_levels = []

        with open(os.path.join(path_dir, "boltztrap.outputtrans"), 'r') \
                as f:
            for line in f:
                if "WARNING" in line:
                    warning = line
                elif "Calc type:" in line:
                    run_type = line.split()[-1]
                elif line.startswith("VBM"):
                    efermi = Energy(line.split()[1], "Ry").to("eV")
                elif line.startswith("Egap:"):
                    gap = Energy(float(line.split()[1]), "Ry").to("eV")
                elif line.startswith("Doping level number"):
                    doping_levels.append(float(line.split()[6]))

        return run_type, warning, efermi, gap, doping_levels

Parses .outputtrans file

Args:
        path_dir: dir containing boltztrap.outputtrans

Returns:
        tuple - (run_type, warning, efermi, gap, doping_levels)


def get_function_id(sig):

    s = sha3.keccak_256()
    s.update(sig.encode('utf-8'))
    return int("0x" + s.hexdigest()[:8], 16)

Return the function id of the given signature

Args:
        sig (str)

Returns:
        (int)


def dbmin50years(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 `dbmin50years`'.format(value))

        self._dbmin50years = value

Corresponds to IDD Field `dbmin50years`
    50-year return period values for minimum extreme dry-bulb temperature

Args:
        value (float): value for IDD Field `dbmin50years`
            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 dump_as_two_item_tsv(record, output_file):

    for ordered_stats in record.ordered_statistics:
        if len(ordered_stats.items_base) != 1:
            continue
        if len(ordered_stats.items_add) != 1:
            continue
        output_file.write('{0}\t{1}\t{2:.8f}\t{3:.8f}\t{4:.8f}{5}'.format(
            list(ordered_stats.items_base)[0], list(ordered_stats.items_add)[0],
            record.support, ordered_stats.confidence, ordered_stats.lift,
            os.linesep))

Dump a relation record as TSV only for 2 item relations.

Args:
        record -- A RelationRecord instance to dump.
        output_file -- A file to output.


def _ParseInformationalOptions(self, options):

    self._debug_mode = getattr(options, 'debug', False)
    self._quiet_mode = getattr(options, 'quiet', False)

    if self._debug_mode and self._quiet_mode:
      logger.warning(
          'Cannot use debug and quiet mode at the same time, defaulting to '
          'debug output.')

Parses the informational options.

Args:
        options (argparse.Namespace): command line arguments.


def from_tuplelist(tuple_list):

        out = Layout()
        for physical, virtual in enumerate(tuple_list):
            if virtual is None:
                continue
            elif Layout.is_virtual(virtual):
                if virtual in out._v2p:
                    raise LayoutError('Duplicate values not permitted; Layout is bijective.')
                out[virtual] = physical
            else:
                raise LayoutError("The list should contain elements of the form"
                                  " (Register, integer) or None")
        return out

Populates a Layout from a list containing virtual
    qubits---(QuantumRegister, int) tuples---, or None.

Args:
        tuple_list (list):
            e.g.: [qr[0], None, qr[2], qr[3]]

Returns:
        Layout: the corresponding Layout object

Raises:
        LayoutError: If the elements are not (Register, integer) or None


def add_new_entry(self, entry):
        # type: (EltoritoEntry) -> None

        if not self._initialized:
            raise pycdlibexception.PyCdlibInternalError('El Torito Section Header not yet initialized')

        self.num_section_entries += 1

        self.section_entries.append(entry)

A method to add a completely new entry to the list of entries of this
    header.

    Parameters:
    entry - The new EltoritoEntry object to add to the list of entries.

Returns:
    Nothing.


def add_case(self, case, update=False):

        existing_case = self.case(case)
        if existing_case and not update:
            raise CaseError("Case {} already exists".format(case['case_id']))
        if existing_case:
            self.db.case.find_one_and_replace(
                {'case_id': case['case_id']},
                case,
            )
        else:
            self.db.case.insert_one(case)

        return case

Add a case to the case collection

    If the case exists and update is False raise error.

Args:
        db (MongoClient): A connection to the mongodb
        case (dict): A case dictionary
        update(bool): If existing case should be updated

Returns:
        mongo_case_id(ObjectId)


def load_glove(file):

    model = {}
    with open(file, encoding="utf8", errors='ignore') as f:
        for line in f:
            line = line.split(' ')
            word = line[0]
            vector = np.array([float(val) for val in line[1:]])
            model[word] = vector

    return model

Loads GloVe vectors in numpy array.

Args:
        file (str): a path to a glove file.

Returns:
        dict: a dict of numpy arrays.


def addSearchers(self, *searchers):

        self._searchers.extend(searchers)

        debug.logger & debug.flagCompiler and debug.logger(
            'current compiled MIBs location(s): %s' % ', '.join([str(x) for x in self._searchers]))

        return self

Add more transformed MIBs repositories.

    MibCompiler.compile will invoke each of configured searcher objects
    in order of their addition asking each if already transformed MIB
    module already exists and is more recent than specified.

Args:
        searchers: searcher object(s)

Returns:
        reference to itself (can be used for call chaining)


def __init__(self, parameter, value, valid_values=None):
        # type: (str, str, typing.Sequence[str]) -> None

        msg = 'Invalid value "{value}" supplied to {parameter}.'.format(
            parameter=parameter, value=value)
        if valid_values:
            msg += ' Valid options are: {}'.format(', '.join(valid_values))
        super(InvalidCliValueError, self).__init__(msg)

Instantiate the exception with a descriptive message.

Args:
        parameter: The CLI parameter with the invalid value.
        value: The invalid value passed to the CLI parameter.
        valid_values: The values that would have been accepted by the
            parameter.


def CaptureVariablesList(self, items, depth, empty_message, limits):

    v = []
    for name, value in items:
      if (self._total_size >= self.max_size) or (
          len(v) >= limits.max_list_items):
        v.append({
            'status': {
                'refersTo': 'VARIABLE_VALUE',
                'description': {
                    'format':
                        ('Only first $0 items were captured. Use in an '
                         'expression to see all items.'),
                    'parameters': [str(len(v))]}}})
        break
      v.append(self.CaptureNamedVariable(name, value, depth, limits))

    if not v:
      return [{'status': {
          'refersTo': 'VARIABLE_NAME',
          'description': {'format': empty_message}}}]

    return v

Captures list of named items.

Args:
        items: iterable of (name, value) tuples.
        depth: nested depth of dictionaries and vectors for items.
        empty_message: info status message to set if items is empty.
        limits: Per-object limits for capturing variable data.

Returns:
        List of formatted variable objects.


def _get_common_params(self, user_id, attributes):

    commonParams = {}

    commonParams[self.EventParams.PROJECT_ID] = self._get_project_id()
    commonParams[self.EventParams.ACCOUNT_ID] = self._get_account_id()

    visitor = {}
    visitor[self.EventParams.END_USER_ID] = user_id
    visitor[self.EventParams.SNAPSHOTS] = []

    commonParams[self.EventParams.USERS] = []
    commonParams[self.EventParams.USERS].append(visitor)
    commonParams[self.EventParams.USERS][0][self.EventParams.ATTRIBUTES] = self._get_attributes(attributes)

    commonParams[self.EventParams.SOURCE_SDK_TYPE] = 'python-sdk'
    commonParams[self.EventParams.ENRICH_DECISIONS] = True
    commonParams[self.EventParams.SOURCE_SDK_VERSION] = version.__version__
    commonParams[self.EventParams.ANONYMIZE_IP] = self._get_anonymize_ip()
    commonParams[self.EventParams.REVISION] = self._get_revision()

    return commonParams

Get params which are used same in both conversion and impression events.

Args:
        user_id: ID for user.
        attributes: Dict representing user attributes and values which need to be recorded.

Returns:
    Dict consisting of parameters common to both impression and conversion events.


def ServiceWorker_deliverPushMessage(self, origin, registrationId, data):

		assert isinstance(origin, (str,)
		    ), "Argument 'origin' must be of type '['str']'. Received type: '%s'" % type(
		    origin)
		assert isinstance(registrationId, (str,)
		    ), "Argument 'registrationId' must be of type '['str']'. Received type: '%s'" % type(
		    registrationId)
		assert isinstance(data, (str,)
		    ), "Argument 'data' must be of type '['str']'. Received type: '%s'" % type(
		    data)
		subdom_funcs = self.synchronous_command('ServiceWorker.deliverPushMessage',
		    origin=origin, registrationId=registrationId, data=data)
		return subdom_funcs

Function path: ServiceWorker.deliverPushMessage
    Domain: ServiceWorker
    Method name: deliverPushMessage

    Parameters:
    Required arguments:
        'origin' (type: string) -> No description
        'registrationId' (type: string) -> No description
        'data' (type: string) -> No description
    No return value.


def __init__(self, desc, scope=None, syn_type=None, xref=None):

        if isinstance(desc, six.binary_type):
            self.desc = desc.decode('utf-8')
        elif isinstance(desc, six.text_type):
            self.desc = desc
        else:
            raise ValueError("desc must be bytes or str, not {}".format(type(desc).__name__))

        if isinstance(scope, six.binary_type):
            self.scope = scope.decode('utf-8')
        elif isinstance(scope, six.text_type):
            self.scope = scope
        elif scope is None:
            self.scope = "RELATED"

        if syn_type is not None:
            try:
                self.syn_type = SynonymType._instances[syn_type]
                self.scope = self.syn_type.scope or self.scope or 'RELATED'
            except KeyError as e:
                raise ValueError("Undefined synonym type: {}".format(syn_type))
        else:
            self.syn_type = None

        if self.scope not in {'EXACT', 'BROAD', 'NARROW', 'RELATED', None}:
            raise ValueError("scope must be 'NARROW', 'BROAD', 'EXACT', 'RELATED' or None")

        self.xref = xref or []

Create a new synonym.

Args:
        desc (str): a description of the synonym.
        scope (str, optional): the scope of the synonym (either
            EXACT, BROAD, NARROW or RELATED).
        syn_type (SynonymType, optional): the type of synonym if
            relying on a synonym type defined in the *Typedef*
            section of the ontology.
        xref (list, optional): a list of cross-references for the
            synonym.


def encode_field(self, field, value):

        if isinstance(field, messages.BytesField):
            if field.repeated:
                value = [base64.b64encode(byte) for byte in value]
            else:
                value = base64.b64encode(value)
        elif isinstance(field, message_types.DateTimeField):
            # DateTimeField stores its data as a RFC 3339 compliant string.
            if field.repeated:
                value = [i.isoformat() for i in value]
            else:
                value = value.isoformat()
        return value

Encode a python field value to a JSON value.

Args:
        field: A ProtoRPC field instance.
        value: A python value supported by field.

Returns:
        A JSON serializable value appropriate for field.


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

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

Create a media service in a resource group.

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

Returns:
        HTTP response. JSON body.


def __init__(self, parent=None):

        super(BigIntSpinbox, self).__init__(parent)

        self._singleStep = 1
        self._minimum = -18446744073709551616
        self._maximum = 18446744073709551615

        rx = QtCore.QRegExp("[0-9]\\d{0,20}")
        validator = QtGui.QRegExpValidator(rx, self)

        self._lineEdit = QtGui.QLineEdit(self)
        self._lineEdit.setText('0')
        self._lineEdit.setValidator(validator)
        self.setLineEdit(self._lineEdit)

the __init__ method.

Args:
        parent (QObject): defaults to None. If parent is 0, the new widget becomes a window.
            If parent is another widget, this widget becomes a child window inside parent.
            The new widget is deleted when its parent is deleted.


def VerifyStructure(self, parser_mediator, line):

    try:
      structure = self._LOG_LINE.parseString(line)
    except pyparsing.ParseException:
      logger.debug('Not a Sophos Anti-Virus log file')
      return False

    # Expect spaces at position 9 and 16.
    if ' ' not in (line[8], line[15]):
      logger.debug('Not a Sophos Anti-Virus log file')
      return False

    try:
      dfdatetime_time_elements.TimeElements(
          time_elements_tuple=structure.date_time)
    except ValueError:
      logger.debug((
          'Not a Sophos Anti-Virus log file, invalid date and time: '
          '{0!s}').format(structure.date_time))
      return False

    return True

Verify that this file is a Sophos Anti-Virus log file.

Args:
        parser_mediator (ParserMediator): mediates interactions between parsers
        and other components, such as storage and dfVFS.
        line (str): line from a text file.

Returns:
        bool: True if the line is in the expected format, False if not.


def download_models(self, uniprot_acc, outdir='', force_rerun=False):

        downloaded = []
        subset = self.get_models(uniprot_acc)

        for entry in subset:
            ident = '{}_{}_{}_{}'.format(uniprot_acc, entry['template'], entry['from'], entry['to'])
            outfile = op.join(outdir, ident + '.pdb')

            if ssbio.utils.force_rerun(flag=force_rerun, outfile=outfile):
                response = requests.get(entry['url'])

                if response.status_code == 404:
                    log.error('{}: 404 returned, no model available.'.format(ident))

                else:
                    with open(outfile, 'w') as f:
                        f.write(response.text)

                    log.debug('{}: downloaded homology model'.format(ident))
                    downloaded.append(outfile)
            else:
                downloaded.append(outfile)

        return downloaded

Download all models available for a UniProt accession number.

Args:
        uniprot_acc (str): UniProt ACC/ID
        outdir (str): Path to output directory, uses working directory if not set
        force_rerun (bool): Force a redownload the models if they already exist

Returns:
        list: Paths to the downloaded models


def activate_nsxcontroller(self, **kwargs):

        name = kwargs.pop('name')
        name_args = dict(name=name)
        method_name = 'nsx_controller_activate'
        method_class = self._brocade_tunnels
        nsxcontroller_attr = getattr(method_class, method_name)
        config = nsxcontroller_attr(**name_args)
        output = self._callback(config)
        return output

Activate NSX Controller

Args:
        name (str): nsxcontroller name
        callback (function): A function executed upon completion of the
            method.

Returns:
        Return value of `callback`.

Raises:
        None


def _operator(attr):

  @functools.wraps(attr)
  def func(a, *args):
    return attr(a.value, *args)
  return func

Defers an operator overload to `attr`.

Args:
        attr: Operator attribute to use.

Returns:
        Function calling operator attribute.


def verify_account(self, email_address):

        request = self._get_request()
        resp = request.post(self.ACCOUNT_VERIFY_URL, {
            'email_address': email_address
        })
        return ('account' in resp)

Verify whether a HelloSign Account exists

Args:
        email_address (str): Email address for the account to verify

Returns:
        True or False


def __init__(self, etk, cdr_document: Dict, mime_type, url, doc_id=None) -> None:

        Segment.__init__(self, json_path="$", _value=cdr_document, _document=self)
        self.etk = etk
        self.cdr_document = cdr_document
        self.mime_type = mime_type
        self.url = url
        if doc_id:
            self.cdr_document["doc_id"] = doc_id
        self.extraction_provenance_records = list()
        if self.etk.kg_schema:
            self.kg = KnowledgeGraph(self.etk.kg_schema, self.etk.ontology, self)
        else:
            self.kg = None
            if not self.etk.kg_schema:
                self.etk.log("Schema not found.", "warning", self.doc_id, self.url)
        self._provenance_id_index = 0
        self._provenances = dict()
        self._jsonpath_provenances = dict()
        self._kg_provenances = dict()

Wrapper object for CDR documents.

Args:
        etk (ETK): embed the etk object so that docs have access to global info.
        cdr_document (JSON): the raw CDR document received in ETK.

    Returns: the wrapped CDR document


def run_step(self, representer):

        assert representer, ("ObjectRepresenter instance required to run "
                             "ObjectRewriterStep.")
        rewriter = ObjectRewriter(self.context.get_formatted_iterable,
                                  representer)
        super().run_step(rewriter)

Do the object in-out rewrite.

Args:
        representer: A pypyr.filesystem.ObjectRepresenter instance.


def member_update(self, repl_id, member_id, params):

        repl = self[repl_id]
        result = repl.member_update(member_id, params)
        self[repl_id] = repl
        return result

apply new params to replica set member

Args:
        repl_id - replica set identity
        member_id - member index
        params - new member's params

    return True if operation success otherwise False


def p_portfolio(I,sigma,r,alpha,beta):

    model = Model("p_portfolio")

    x = {}
    for i in I:
        x[i] = model.addVar(vtype="C", name="x(%s)"%i)  # quantity of i to buy
    rho = model.addVar(vtype="C", name="rho")
    rhoaux = model.addVar(vtype="C", name="rhoaux")

    model.addCons(rho == quicksum(r[i]*x[i] for i in I))
    model.addCons(quicksum(x[i] for i in I) == 1)

    model.addCons(rhoaux == (alpha - rho)*(1/phi_inv(beta))) #todo
    model.addCons(quicksum(sigma[i]**2 * x[i] * x[i] for i in I) <=  rhoaux * rhoaux)

    model.setObjective(rho, "maximize")

    model.data = x
    return model

p_portfolio -- modified markowitz model for portfolio optimization.
    Parameters:
        - I: set of items
        - sigma[i]: standard deviation of item i
        - r[i]: revenue of item i
        - alpha: acceptance threshold
        - beta: desired confidence level
    Returns a model, ready to be solved.


def __str__(self):

        text = super(Baken, self).__format__('dms')
        if self._locator:
            text = '%s (%s)' % (self._locator, text)
        return text

Pretty printed location string.

Args:
        mode (str): Coordinate formatting system to use

Returns:
        str: Human readable string representation of ``Baken`` object


def __call__(self, data, dtype=None):

        if isinstance(data, np.ndarray):
            if not data.size > 0:
                raise ValueError("empty array can't be serialized")
            return _npy_serialize(data)

        if isinstance(data, list):
            if not len(data) > 0:
                raise ValueError("empty array can't be serialized")
            return _npy_serialize(np.array(data, dtype))

        # files and buffers. Assumed to hold npy-formatted data.
        if hasattr(data, 'read'):
            return data.read()

        return _npy_serialize(np.array(data))

Serialize data into the request body in NPY format.

Args:
        data (object): Data to be serialized. Can be a numpy array, list, file, or buffer.

Returns:
        object: NPY serialized data used for the request.


def resize_imgs(self, targ, new_path, resume=True, fn=None):

        dest = resize_imgs(self.fnames, targ, self.path, new_path, resume, fn)
        return self.__class__(self.fnames, self.y, self.transform, dest)

resize all images in the dataset and save them to `new_path`

Args:
    targ (int): the target size
    new_path (string): the new folder to save the images
    resume (bool): if true (default), allow resuming a partial resize operation by checking for the existence
    of individual images rather than the existence of the directory
    fn (function): custom resizing function Img -> Img


def extend(self, *iterables):

        for value in iterables:
            list.extend(self, value)
        return self

Add all values of all iterables at the end of the list

Args:
        iterables: iterable which content to add at the end

Example:
        >>> from ww import l
        >>> lst = l([])
        >>> lst.extend([1, 2])
        [1, 2]
        >>> lst
        [1, 2]
        >>> lst.extend([3, 4]).extend([5, 6])
        [1, 2, 3, 4, 5, 6]
        >>> lst
        [1, 2, 3, 4, 5, 6]


def convert_snapshot(self, shift, instruction):

        command_dict = {
            'name': 'snapshot',
            't0': shift+instruction.start_time,
            'label': instruction.name,
            'type': instruction.type
        }
        return self._qobj_model(**command_dict)

Return converted `Snapshot`.

Args:
        shift(int): Offset time.
        instruction (Snapshot): snapshot instruction.

Returns:
        dict: Dictionary of required parameters.


def PC_varExplained(Y,standardized=True):

    # figuring out the number of latent factors
    if standardized:
        Y-=Y.mean(0)
        Y/=Y.std(0)
    covY = sp.cov(Y)
    S,U = linalg.eigh(covY+1e-6*sp.eye(covY.shape[0]))
    S = S[::-1]
    rv = np.array([S[0:i].sum() for i in range(1,S.shape[0])])
    rv/= S.sum()
    return rv

Run PCA and calculate the cumulative fraction of variance

Args:
        Y: phenotype values
        standardize: if True, phenotypes are standardized

Returns:
        var: cumulative distribution of variance explained


def __init__(self, filesystem, os_module=None):

        self.filesystem = filesystem
        self._os_path = self._OS_PATH_COPY
        if os_module is None:
            warnings.warn(FAKE_PATH_MODULE_DEPRECATION, DeprecationWarning,
                          stacklevel=2)
        self._os_path.os = self.os = os_module
        self.sep = self.filesystem.path_separator
        self.altsep = self.filesystem.alternative_path_separator

Init.

Args:
        filesystem: FakeFilesystem used to provide file system information
        os_module: (deprecated) FakeOsModule to assign to self.os


def reset(self, indices=None):

    if indices is None:
      indices = np.arange(len(self._envs))
    if self._blocking:
      observs = [self._envs[index].reset() for index in indices]
    else:
      observs = [self._envs[index].reset(blocking=False) for index in indices]
      observs = [observ() for observ in observs]
    observ = np.stack(observs)
    return observ

Reset the environment and convert the resulting observation.

Args:
        indices: The batch indices of environments to reset; defaults to all.

Returns:
        Batch of observations.


def file_to_list(file_name, file_location):

    file = __os.path.join(file_location, file_name)
    read_file = open(file, "r")
    temp_list = read_file.read().splitlines()
    read_file.close()
    return temp_list

Function to import a text file to a list

Args:
        file_name: The name of file to be import
        file_location: The location of the file, derive from the os module

    Returns: returns a list


def save_index(self, filename):

        data = {}
        for f in self.files.values():
            entities = {v.entity.id: v.value for k, v in f.tags.items()}
            data[f.path] = {'domains': f.domains, 'entities': entities}
        with open(filename, 'w') as outfile:
            json.dump(data, outfile)

Save the current Layout's index to a .json file.

Args:
        filename (str): Filename to write to.

    Note: At the moment, this won't serialize directory-specific config
    files. This means reconstructed indexes will only work properly in
    cases where there aren't multiple layout specs within a project.


def orphan_entry(self, rval: RawObject) -> "ArrayEntry":

        val = self.entry_from_raw(rval)
        return ArrayEntry(0, EmptyList(), EmptyList(), val, None, self,
                          val.timestamp)

Return an isolated entry of the receiver.

Args:
        rval: Raw object to be used for the returned entry.


def build_query_string(self, data):

        query = []
        keys_to_be_removed = []
        for key, value in data.items():
            if key not in ['version', 'restApi', 'resourcePath']:
                if not key == 'method':
                    if key == 'points':
                        value = ','.join(str(val) for val in value)
                        keys_to_be_removed.append(key)
                    query.append('{0}={1}'.format(key, value))
                    keys_to_be_removed.append(key)
                keys_to_be_removed.append(key)
        querystring = '&'.join(query)
        data['query'] = '{0}?{1}'.format(data['method'], querystring)
        for k in list(set(keys_to_be_removed)):
            del data[k]
        return data

This method occurs after dumping the data into the class.

Args:
        data (dict): dictionary of all the query values

Returns:
        data (dict): ordered dict of all the values


def push(self, filename, data):

        self._queue.put(Chunk(filename, data))

Push a chunk of a file to the streaming endpoint.

Args:
        filename: Name of file that this is a chunk of.
        chunk_id: TODO: change to 'offset'
        chunk: File data.


def get_electron_number(self, charge=0):

        atomic_number = constants.elements['atomic_number'].to_dict()
        return sum([atomic_number[atom] for atom in self['atom']]) - charge

Return the number of electrons.

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

Returns:
        int:


def get_nn(self, structure, n):

        return [e['site'] for e in self.get_nn_info(structure, n)]

Get near neighbors of site with index n in structure.

Args:
        structure (Structure): input structure.
        n (integer): index of site in structure for which to determine
                neighbors.

Returns:
        sites (list of Site objects): near neighbors.


def clean_for_storage(self, data):

        data = self.data_to_unicode(data)
        if isinstance(data, dict):
            for k in dict(data).keys():
                if k == '_id':
                    del data[k]
                    continue
                if '.' in k:
                    new_k = k.replace('.', '_')
                    data[new_k] = data[k]
                    del data[k]
                    k = new_k
                if isinstance(data[k], dict):
                    data[k] = self.clean_for_storage(data[k])
                elif isinstance(data[k], list):
                    data[k] = [self.clean_for_storage(item) for item in data[k]]
        return data

Clean data in preparation for storage.

    Deletes items with key having a '.' or is '_id'. Also deletes those items
    whose value is a dictionary or a list.

Args:
        data: Sample data dictionary to be cleaned.

Returns:
        Cleaned data dictionary.


def batch(self, timelimit=None):

        from .launcher import BatchLauncher
        # Create a batch dir from the flow.workdir.
        prev_dir = os.path.join(*self.workdir.split(os.path.sep)[:-1])
        prev_dir = os.path.join(os.path.sep, prev_dir)
        workdir = os.path.join(prev_dir, os.path.basename(self.workdir) + "_batch")

        return BatchLauncher(workdir=workdir, flows=self).submit(timelimit=timelimit)

Run the flow in batch mode, return exit status of the job script.
    Requires a manager.yml file and a batch_adapter adapter.

Args:
        timelimit: Time limit (int with seconds or string with time given with the slurm convention:
        "days-hours:minutes:seconds"). If timelimit is None, the default value specified in the
        `batch_adapter` entry of `manager.yml` is used.


def model_fn_sharded(self, sharded_features):

    dp = self._data_parallelism

    # [{str: Tensor}]. Transpose of 'sharded_features'.
    datashard_to_features = self._to_features_per_datashard(sharded_features)
    if self.use_body_sharded():
      if  self.hparams.scheduled_sampling_prob > 0.0:
        raise NotImplementedError(
            "Scheduled sampling for non-sharded body only.")

      # MoE models override body_sharded
      transformed_features = dp(self.bottom, datashard_to_features)
      body_out = self.body_sharded(
          self._to_single_features_dict(transformed_features))
      body_out, losses = self._normalize_body_output(body_out)
      if "training" in losses:
        log_info("Skipping T2TModel top and loss because training loss "
                 "returned from body")
        sharded_logits = body_out
      else:
        if isinstance(body_out, dict):
          sharded_logits = collections.OrderedDict()
          sharded_losses = collections.OrderedDict()
          for k, v in sorted(six.iteritems(body_out)):
            sharded_logits[k] = dp(self.top, v, datashard_to_features)
            sharded_losses[k] = dp(self.loss, sharded_logits[k],
                                   datashard_to_features)
          training_loss_dict = average_sharded_losses([({
              "training": l
          } for l in loss) for loss in sharded_losses.values()])
          losses.update(training_loss_dict)
        else:
          sharded_logits = dp(self.top, body_out, datashard_to_features)
          sharded_losses = dp(self.loss, sharded_logits, datashard_to_features)
          if isinstance(sharded_losses, tuple):
            nums, dens = sharded_losses
            sharded_losses = zip(nums, dens)
          training_loss_dict = average_sharded_losses([{
              "training": loss
          } for loss in sharded_losses])
          losses.update(training_loss_dict)
    else:
      sharded_logits, sharded_losses = dp(self.model_fn, datashard_to_features)
      sharded_logits, sharded_losses = dp(
          self.maybe_scheduled_sampling,
          datashard_to_features, sharded_logits, sharded_losses)
      if isinstance(sharded_logits[0], dict):
        temp_dict = {k: [] for k, _ in six.iteritems(sharded_logits[0])}
        for k, _ in six.iteritems(sharded_logits[0]):
          for l in sharded_logits:
            temp_dict[k].append(l[k])
        sharded_logits = temp_dict
      losses = average_sharded_losses(sharded_losses)

    return sharded_logits, losses

Estimator model_fn sharded along batch dimension.

Args:
        sharded_features: {str: [Tensor]}. Features sharded along batch dimension.
        Each list is the same length (== number of shards).

Returns:
        sharded_logits: [Tensor]. Logits for each shard of examples.
        losses: {str: 0-D Tensor}. Loss averaged across shards.


def start(self, request: Request) -> Response:

        if self._session_state != SessionState.ready:
            raise RuntimeError('Session already started')

        assert not self._request
        self._request = request
        _logger.debug(__('Client fetch request {0}.', request))

        connection = yield from self._acquire_request_connection(request)
        full_url = connection.proxied and not connection.tunneled

        self._stream = stream = self._stream_factory(connection)

        yield from self._stream.reconnect()

        request.address = connection.address

        self.event_dispatcher.notify(self.Event.begin_request, request)
        write_callback = functools.partial(self.event_dispatcher.notify, self.Event.request_data)
        stream.data_event_dispatcher.add_write_listener(write_callback)

        yield from stream.write_request(request, full_url=full_url)

        if request.body:
            assert 'Content-Length' in request.fields
            length = int(request.fields['Content-Length'])
            yield from stream.write_body(request.body, length=length)

        stream.data_event_dispatcher.remove_write_listener(write_callback)
        self.event_dispatcher.notify(self.Event.end_request, request)

        read_callback = functools.partial(self.event_dispatcher.notify, self.Event.response_data)
        stream.data_event_dispatcher.add_read_listener(read_callback)

        self._response = response = yield from stream.read_response()
        response.request = request

        self.event_dispatcher.notify(self.Event.begin_response, response)

        self._session_state = SessionState.request_sent

        return response

Begin a HTTP request

Args:
        request: Request information.

Returns:
        A response populated with the HTTP headers.

    Once the headers are received, call :meth:`download`.

    Coroutine.


def is_feature_enabled(self, feature_key, user_id, attributes=None):

    if not self.is_valid:
      self.logger.error(enums.Errors.INVALID_DATAFILE.format('is_feature_enabled'))
      return False

    if not validator.is_non_empty_string(feature_key):
      self.logger.error(enums.Errors.INVALID_INPUT_ERROR.format('feature_key'))
      return False

    if not isinstance(user_id, string_types):
      self.logger.error(enums.Errors.INVALID_INPUT_ERROR.format('user_id'))
      return False

    if not self._validate_user_inputs(attributes):
      return False

    feature = self.config.get_feature_from_key(feature_key)
    if not feature:
      return False

    feature_enabled = False
    source_info = {}
    decision = self.decision_service.get_variation_for_feature(feature, user_id, attributes)
    is_source_experiment = decision.source == enums.DecisionSources.FEATURE_TEST

    if decision.variation:
      if decision.variation.featureEnabled is True:
        feature_enabled = True
      # Send event if Decision came from an experiment.
      if is_source_experiment:
        source_info = {
          'experiment_key': decision.experiment.key,
          'variation_key': decision.variation.key
        }
        self._send_impression_event(decision.experiment,
                                    decision.variation,
                                    user_id,
                                    attributes)

    if feature_enabled:
      self.logger.info('Feature "%s" is enabled for user "%s".' % (feature_key, user_id))
    else:
      self.logger.info('Feature "%s" is not enabled for user "%s".' % (feature_key, user_id))

    self.notification_center.send_notifications(
        enums.NotificationTypes.DECISION,
        enums.DecisionNotificationTypes.FEATURE,
        user_id,
        attributes or {},
        {
          'feature_key': feature_key,
          'feature_enabled': feature_enabled,
          'source': decision.source,
          'source_info': source_info
        }
    )

    return feature_enabled

Returns true if the feature is enabled for the given user.

Args:
        feature_key: The key of the feature for which we are determining if it is enabled or not for the given user.
        user_id: ID for user.
        attributes: Dict representing user attributes.

Returns:
        True if the feature is enabled for the user. False otherwise.


def _make_generic(of, coll):

    assert(issubclass(coll, Collection))
    key = (coll.__name__, "%s.%s" % (of.__module__, of.__name__))
    if key in GENERIC_TYPES:
        if GENERIC_TYPES[key].itemtype != of:
            raise exc.PropertyNotUnique(key=key)
    else:
        # oh, we get to name it?  Goodie!
        generic_name = "%s%s" % (of.__name__, coll.suffix)
        GENERIC_TYPES[key] = type(
            generic_name, (coll, _Generic), dict(itemtype=of, generic_key=key)
        )
        mod = sys.modules[of.__module__]
        if not hasattr(mod, generic_name):
            setattr(mod, generic_name, GENERIC_TYPES[key])
    return GENERIC_TYPES[key]

Used to make a new Collection type, without that type having to be
    defined explicitly.  Generates a new type name using the item type and a
    'suffix' Collection class property.

Args:
        ``of=``\ *Record type*
            The type of values of the collection

        ``coll=``\ *Collection sub-class*
            The container class.


def grab_data(self, f_start=None, f_stop=None,t_start=None, t_stop=None, if_id=0):

        self.freqs = self.populate_freqs()
        self.timestamps = self.populate_timestamps()

        if f_start is None:
            f_start = self.freqs[0]
        if f_stop is None:
            f_stop = self.freqs[-1]

        i0 = np.argmin(np.abs(self.freqs - f_start))
        i1 = np.argmin(np.abs(self.freqs - f_stop))

        if i0 < i1:
            plot_f    = self.freqs[i0:i1 + 1]
            plot_data = np.squeeze(self.data[t_start:t_stop, ..., i0:i1 + 1])
        else:
            plot_f    = self.freqs[i1:i0 + 1]
            plot_data = np.squeeze(self.data[t_start:t_stop, ..., i1:i0 + 1])

        return plot_f, plot_data

Extract a portion of data by frequency range.

Args:
        f_start (float): start frequency in MHz
        f_stop (float): stop frequency in MHz
        if_id (int): IF input identification (req. when multiple IFs in file)

Returns:
        (freqs, data) (np.arrays): frequency axis in MHz and data subset


def camelize(word):

    return ''.join(w[0].upper() + w[1:]
                   for w in re.sub('[^A-Z^a-z^0-9^:]+', ' ', word).split(' '))

Convert a word from lower_with_underscores to CamelCase.

Args:
        word: The string to convert.

Returns:
        The modified string.


def map_template(category, template_list):

    if isinstance(template_list, str):
        template_list = [template_list]

    for template in template_list:
        path = os.path.normpath(category)
        while path is not None:
            for extension in ['', '.html', '.htm', '.xml', '.json']:
                candidate = os.path.join(path, template + extension)
                file_path = os.path.join(config.template_folder, candidate)
                if os.path.isfile(file_path):
                    return Template(template, candidate, file_path)
            parent = os.path.dirname(path)
            if parent != path:
                path = parent
            else:
                path = None

Given a file path and an acceptable list of templates, return the
    best-matching template's path relative to the configured template
    directory.

Args:
    category -- The path to map
    template_list -- A template to look up (as a string), or a list of templates.


def record(self):
        # type: () -> bytes

        if not self._initialized:
            raise pycdlibexception.PyCdlibInternalError('El Torito Boot Catalog not yet initialized')

        outlist = [self.validation_entry.record(), self.initial_entry.record()]

        for sec in self.sections:
            outlist.append(sec.record())

        for entry in self.standalone_entries:
            outlist.append(entry.record())

        return b''.join(outlist)

A method to generate a string representing this El Torito Boot Catalog.

    Parameters:
    None.

Returns:
    A string representing this El Torito Boot Catalog.


def __init__(self, checker, message):

    self.checker = checker
    self.message = message
    Validator.validators_count += 1
    # Used to assert validators in the order they were registered.
    self.insertion_index = Validator.validators_count

Constructor to create all validators.

Args:
        checker: function to verify the constraint.
        Input of this method varies, see SingleFlagValidator and
        multi_flags_validator for a detailed description.
        message: str, error message to be shown to the user.