def __init__(self, ind_id, case_id=None, mother=None,
                 father=None, sex=None, phenotype=None, ind_index=None,
                 profile=None, similar_samples=None):

        super(Individual, self).__init__(
            ind_id=ind_id,
            name=ind_id,
            case_id=case_id,
            ind_index=ind_index,
            sex=sex,
        )

        if profile: self['profile'] = profile
        if similar_samples: self['similar_samples'] = similar_samples

Construct a individual object

Args:
        ind_id (str): The individual id
        case_id (str): What case it belongs to
        mother (str): The mother id
        father (str): The father id
        sex (str): Sex in ped format
        phenotype (str): Phenotype in ped format
        ind_index (int): Column in the vcf.


def get_details(self, ids):

        if isinstance(ids, list):
            if len(ids) > 5:
                ids = ids[:5]
            id_param = ';'.join(ids) + '/'
        else:
            ids = str(ids)
            id_param = ids + '/'

        header, content = self._http_request(id_param)
        resp = json.loads(content)
        if not self._is_http_response_ok(header):
            error = resp.get('error_message', 'Unknown Error')
            raise HttpException(header.status, header.reason, error)
        return resp

Locu Venue Details API Call Wrapper

Args:
        list of ids : ids of a particular venues to get insights about. Can process up to 5 ids


def __init__(self, latitude, longitude, name, units='km'):

        super(NumberedPoint, self).__init__(latitude, longitude, units)

        self.name = name

Initialise a new ``NumberedPoint`` object.

Args:
        latitude (float): Location's latitude
        longitude (float): Location's longitude
        name (str): Location's name or command line position
        units (str): Unit type to be used for distances


def _serialize_scalar_from_string_representation_factory(type_name, types, str_func=str):

    def serialize(ion_event):
        value = ion_event.value
        validate_scalar_value(value, types)
        return six.b(str_func(value))
    serialize.__name__ = '_serialize_' + type_name
    return serialize

Builds functions that leverage Python ``str()`` or similar functionality.

Args:
        type_name (str): The name of the Ion type.
        types (Union[Sequence[type],type]): The Python types to validate for.
        str_func (Optional[Callable]): The function to convert the value with, defaults to ``str``.

Returns:
        function: The function for serializing scalars of a given type to Ion text bytes.


def indent_css(f, output):

    line_count = get_line_count(f)
    f = open(f, 'r+')
    output = open(output, 'r+')
    for line in range(line_count):
        string = f.readline().rstrip()
        if len(string) > 0:
            if string[-1] == ";":
                output.write("    " + string + "\n")
            else:
                output.write(string + "\n")
    output.close()
    f.close()

Indentes css that has not been indented and saves it to a new file.
    A new file is created if the output destination does not already exist.

Args:
        f: string, path to file.

        output: string, path/name of the output file (e.g. /directory/output.css).
    print type(response.read())

Returns:
        None.


def GetFileEntryByPathSpec(self, path_spec):

    tsk_vs_part, partition_index = tsk_partition.GetTSKVsPartByPathSpec(
        self._tsk_volume, path_spec)

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

    # The virtual root file has not corresponding TSK volume system part object
    # but should have a location.
    if tsk_vs_part is None:
      if location is None or location != self.LOCATION_ROOT:
        return None

      return tsk_partition_file_entry.TSKPartitionFileEntry(
          self._resolver_context, self, path_spec, is_root=True,
          is_virtual=True)

    if location is None and partition_index is not None:
      path_spec.location = '/p{0:d}'.format(partition_index)

    return tsk_partition_file_entry.TSKPartitionFileEntry(
        self._resolver_context, self, path_spec)

Retrieves a file entry for a path specification.

Args:
        path_spec (PathSpec): a path specification.

Returns:
        TSKPartitionFileEntry: a file entry or None of not available.


def _load_config_include(self, include_directory):

        include_directory = os.path.join(self.app_path, include_directory)
        if not os.path.isdir(include_directory):
            msg = 'Provided include directory does not exist ({}).'.format(include_directory)
            sys.exit(msg)

        profiles = []
        for filename in sorted(os.listdir(include_directory)):
            if filename.endswith('.json'):
                self.log.info('Loading config: {}'.format(filename))
                print('Include File: {}{}{}'.format(c.Style.BRIGHT, c.Fore.MAGENTA, filename))
                config_file = os.path.join(include_directory, filename)
                with open(config_file) as data_file:
                    try:
                        profiles.extend(json.load(data_file))
                    except ValueError as e:
                        print('Invalid JSON file: {}{}{}'.format(c.Style.BRIGHT, c.Fore.RED, e))
                        sys.exit(1)
        return profiles

Load included configuration files.

Args:
        include_directory (str): The name of the config include directory.

Returns:
        list: A list of all profiles for the current App.


def swo_supported_speeds(self, cpu_speed, num_speeds=3):

        buf_size = num_speeds
        buf = (ctypes.c_uint32 * buf_size)()
        res = self._dll.JLINKARM_SWO_GetCompatibleSpeeds(cpu_speed, 0, buf, buf_size)
        if res < 0:
            raise errors.JLinkException(res)

        return list(buf)[:res]

Retrives a list of SWO speeds supported by both the target and the
    connected J-Link.

    The supported speeds are returned in order from highest to lowest.

Args:
        self (JLink): the ``JLink`` instance
        cpu_speed (int): the target's CPU speed in Hz
        num_speeds (int): the number of compatible speeds to return

Returns:
        A list of compatible SWO speeds in Hz in order from highest to lowest.


def _get_lattices(self, target_lattice, s, supercell_size=1):

        lattices = s.lattice.find_all_mappings(
            target_lattice, ltol=self.ltol, atol=self.angle_tol,
            skip_rotation_matrix=True)
        for l, _, scale_m in lattices:
            if abs(abs(np.linalg.det(scale_m)) - supercell_size) < 0.5:
                yield l, scale_m

Yields lattices for s with lengths and angles close to the
    lattice of target_s. If supercell_size is specified, the
    returned lattice will have that number of primitive cells
    in it

Args:
        s, target_s: Structure objects


def approve(self, sha=None, **kwargs):

        path = '%s/%s/approve' % (self.manager.path, self.get_id())
        data = {}
        if sha:
            data['sha'] = sha

        server_data = self.manager.gitlab.http_post(path, post_data=data,
                                                    **kwargs)
        self._update_attrs(server_data)

Approve the merge request.

Args:
        sha (str): Head SHA of MR
        **kwargs: Extra options to send to the server (e.g. sudo)

Raises:
        GitlabAuthenticationError: If authentication is not correct
        GitlabMRApprovalError: If the approval failed


def get_predicted_structure(self, structure, ref_structure):

        new_structure = structure.copy()
        new_structure.scale_lattice(self.predict(structure, ref_structure))

        return new_structure

Given a structure, returns back the structure scaled to predicted
    volume.

Args:
        structure (Structure): structure w/unknown volume
        ref_structure (Structure): A reference structure with a similar
            structure but different species.

Returns:
        a Structure object with predicted volume


def _read_data_handler(length, whence, ctx, skip=False, stream_event=ION_STREAM_INCOMPLETE_EVENT):

    trans = None
    queue = ctx.queue

    if length > ctx.remaining:
        raise IonException('Length overrun: %d bytes, %d remaining' % (length, ctx.remaining))

    # Make sure to check the queue first.
    queue_len = len(queue)
    if queue_len > 0:
        # Any data available means we can only be incomplete.
        stream_event = ION_STREAM_INCOMPLETE_EVENT
    length -= queue_len

    if skip:
        # For skipping we need to consume any remnant in the buffer queue.
        if length >= 0:
            queue.skip(queue_len)
        else:
            queue.skip(queue_len + length)

    while True:
        data_event, self = (yield trans)
        if data_event is not None and data_event.data is not None:
            data = data_event.data
            data_len = len(data)
            if data_len > 0:
                # We got something so we can only be incomplete.
                stream_event = ION_STREAM_INCOMPLETE_EVENT
            length -= data_len
            if not skip:
                queue.extend(data)
            else:
                pos_adjustment = data_len
                if length < 0:
                    pos_adjustment += length
                    # More data than we need to skip, so make sure to accumulate that remnant.
                    queue.extend(data[length:])
                queue.position += pos_adjustment
        if length <= 0:
            # We got all the data we need, go back immediately
            yield Transition(None, whence)

        trans = Transition(stream_event, self)

Creates a co-routine for retrieving data up to a requested size.

Args:
        length (int): The minimum length requested.
        whence (Coroutine): The co-routine to return to after the data is satisfied.
        ctx (_HandlerContext): The context for the read.
        skip (Optional[bool]): Whether the requested number of bytes should be skipped.
        stream_event (Optional[IonEvent]): The stream event to return if no bytes are read or
            available.


def get_collection(self, lang=None, task=None):

    if lang: id = "{}{}".format(Downloader.LANG_PREFIX, lang)
    elif task: id = "{}{}".format(Downloader.TASK_PREFIX, task)
    else: raise ValueError("You should pass either the task or the lang")
    try:
      return self.info(id)
    except ValueError as e:
      if lang: raise LanguageNotSupported("Language {} is not supported".format(id))
      if task: raise TaskNotSupported("Task {} is not supported".format(id))

Return the collection that represents a specific language or task.

Args:
        lang (string): Language code.
        task (string): Task name.


def QA_SU_save_stock_info(engine, client=DATABASE):

    engine = select_save_engine(engine)
    engine.QA_SU_save_stock_info(client=client)

save stock info

Args:
        engine {[type]} -- [description]

    Keyword Arguments:
        client {[type]} -- [description] (default: {DATABASE})


def _combineResults(result, *namedTuples):

    results = ClientJobsDAO.partitionAtIntervals(
      result, [len(nt._fields) for nt in namedTuples])
    return [nt._make(result) for nt, result in zip(namedTuples, results)]

Return a list of namedtuples from the result of a join query.  A
    single database result is partitioned at intervals corresponding to the
    fields in namedTuples.  The return value is the result of applying
    namedtuple._make() to each of the partitions, for each of the namedTuples.

    Parameters:
    ----------------------------------------------------------------
    result:         Tuple representing a single result from a database query
    *namedTuples:   List of named tuples.


def restrict_bond_dict(self, bond_dict):

        return {j: bond_dict[j] & set(self.index) for j in self.index}

Restrict a bond dictionary to self.

Args:
        bond_dict (dict): Look into :meth:`~chemcoord.Cartesian.get_bonds`,
            to see examples for a bond_dict.

Returns:
        bond dictionary


def _FormatUsername(self, event):

    username = self._output_mediator.GetUsername(event)
    return self._SanitizeField(username)

Formats the username.

Args:
        event (EventObject): event.

Returns:
        str: formatted username field.


def minimum(self, vars_list: List[str]) -> 'TensorFluent':

        return self._aggregation_op(tf.reduce_min, self, vars_list)

Returns the TensorFluent for the minimum aggregation function.

Args:
        vars_list: The list of variables to be aggregated over.

Returns:
        A TensorFluent wrapping the minimum aggregation function.


def outline(self, level=logging.INFO, message=""):

        steps = 1
        logger.log(level, "Plan \"%s\":", self.description)
        for step in self.steps:
            logger.log(
                level,
                "  - step: %s: target: \"%s\", action: \"%s\"",
                steps,
                step.name,
                step.fn.__name__,
            )
            steps += 1

        if message:
            logger.log(level, message)

Print an outline of the actions the plan is going to take.
    The outline will represent the rough ordering of the steps that will be
    taken.

Args:
        level (int, optional): a valid log level that should be used to log
            the outline
        message (str, optional): a message that will be logged to
            the user after the outline has been logged.


def get_suggestions(self, iteration_config=None):

        matrix = self.hptuning_config.matrix

        suggestions = []
        keys = list(matrix.keys())
        values = [v.to_numpy() for v in matrix.values()]
        for v in itertools.product(*values):
            suggestions.append(dict(zip(keys, v)))

        if self.hptuning_config.grid_search:
            n_suggestions = self.hptuning_config.grid_search.n_experiments
            if n_suggestions:
                return suggestions[:n_suggestions]
        return suggestions

Return a list of suggestions based on grid search.

    Params:
        matrix: `dict` representing the {hyperparam: hyperparam matrix config}.
        n_suggestions: number of suggestions to make.


def _load_yaml_(file_name):

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

    with open(file_name, 'r', encoding='utf-8') as fp:
        return YAML().load(stream=fp)

Load assets infomation from file

Args:
        file_name: file name

Returns:
        dict


def extract(self, file_path, is_drum=False):

        midi_data = pretty_midi.PrettyMIDI(file_path)
        note_tuple_list = []
        for instrument in midi_data.instruments:
            if (is_drum is False and instrument.is_drum is False) or (is_drum is True and instrument.is_drum is True):
                for note in instrument.notes:
                    note_tuple_list.append((instrument.program, note.start, note.end, note.pitch, note.velocity))
        note_df = pd.DataFrame(note_tuple_list, columns=["program", "start", "end", "pitch", "velocity"])
        note_df = note_df.sort_values(by=["program", "start", "end"])
        note_df["duration"] = note_df.end - note_df.start

        return note_df

Extract MIDI file.

Args:
        file_path:    File path of MIDI.
        is_drum:      Extract drum data or not.

Returns:
        pd.DataFrame(columns=["program", "start", "end", "pitch", "velocity", "duration"])


def write_content(self, content, destination):

        directory = os.path.dirname(destination)

        if directory and not os.path.exists(directory):
            os.makedirs(directory)

        with io.open(destination, 'w', encoding='utf-8') as f:
            f.write(content)

        return destination

Write given content to destination path.

    It will create needed directory structure first if it contain some
    directories that does not allready exists.

Args:
        content (str): Content to write to target file.
        destination (str): Destination path for target file.

Returns:
        str: Path where target file has been written.


def get(self, resource):

        return self.service.get(
            resource, self.url_prefix, self.auth, self.session,
            self.session_send_opts)

Get attributes of the data model object named by the given resource.

Args:
        resource (intern.resource.boss.BossResource): resource.name as well as any parents must be identified to succeed.

Returns:
        (intern.resource.boss.BossResource): Returns resource of type requested on success.

Raises:
        requests.HTTPError on failure.


def _pre_action(self, action):

        # clip actions into valid range
        assert len(action) == self.dof, "environment got invalid action dimension"
        low, high = self.action_spec
        action = np.clip(action, low, high)

        if self.has_gripper:
            arm_action = action[: self.mujoco_robot.dof]
            gripper_action_in = action[
                self.mujoco_robot.dof : self.mujoco_robot.dof + self.gripper.dof
            ]
            gripper_action_actual = self.gripper.format_action(gripper_action_in)
            action = np.concatenate([arm_action, gripper_action_actual])

        # rescale normalized action to control ranges
        ctrl_range = self.sim.model.actuator_ctrlrange
        bias = 0.5 * (ctrl_range[:, 1] + ctrl_range[:, 0])
        weight = 0.5 * (ctrl_range[:, 1] - ctrl_range[:, 0])
        applied_action = bias + weight * action
        self.sim.data.ctrl[:] = applied_action

        # gravity compensation
        self.sim.data.qfrc_applied[
            self._ref_joint_vel_indexes
        ] = self.sim.data.qfrc_bias[self._ref_joint_vel_indexes]

        if self.use_indicator_object:
            self.sim.data.qfrc_applied[
                self._ref_indicator_vel_low : self._ref_indicator_vel_high
            ] = self.sim.data.qfrc_bias[
                self._ref_indicator_vel_low : self._ref_indicator_vel_high
            ]

Overrides the superclass method to actuate the robot with the
    passed joint velocities and gripper control.

Args:
        action (numpy array): The control to apply to the robot. The first
            @self.mujoco_robot.dof dimensions should be the desired
            normalized joint velocities and if the robot has
            a gripper, the next @self.gripper.dof dimensions should be
            actuation controls for the gripper.


def create(self, body):

        return self.client.post(self._url(), data=body)

Creates a new connection.

Args:
        body (dict): Attributes used to create the connection. Mandatory
            attributes are: 'name' and 'strategy'.
            See: https://auth0.com/docs/api/management/v2#!/Connections/post_connections


def download_file(bucket_name, path, target, sagemaker_session):

    path = path.lstrip('/')
    boto_session = sagemaker_session.boto_session

    s3 = boto_session.resource('s3')
    bucket = s3.Bucket(bucket_name)
    bucket.download_file(path, target)

Download a Single File from S3 into a local path

Args:
        bucket_name (str): S3 bucket name
        path (str): file path within the bucket
        target (str): destination directory for the downloaded file.
        sagemaker_session (:class:`sagemaker.session.Session`): a sagemaker session to interact with S3.


def reset(self, indices=None):

    if self._store_rollouts and self.current_epoch is None:
      raise ValueError(
          "No current epoch. start_new_epoch() should first be called."
      )

    if indices is None:
      indices = np.arange(self.batch_size)
    new_obs = self._reset(indices)
    if self._should_preprocess_on_reset:
      new_obs = self._preprocess_observations(new_obs)
    if self._store_rollouts:
      encoded_obs = self._encode_observations(new_obs)
      for (index, ob) in zip(indices, encoded_obs):
        frame = self._current_batch_frames[index]
        if frame is not None:
          rollout = self._current_batch_rollouts[index]
          rollout.append(frame._replace(action=0))
          self._current_epoch_rollouts.append(rollout)
          self._current_batch_rollouts[index] = []
        self._current_batch_frames[index] = Frame(
            observation=ob, reward=0, unclipped_reward=0, done=False,
            action=None
        )
    return new_obs

Resets environments at given indices.

    Does any preprocessing and adds rollouts to history.

Args:
        indices: Indices of environments to reset.

Returns:
        Batch of initial observations of reset environments.

Raises:
        ValueError: when there's no current epoch.


def _GetSources(self, event_object):

    try:
      source_short, source_long = (
          formatters_manager.FormattersManager.GetSourceStrings(event_object))
    except KeyError as exception:
      logging.warning(
          'Unable to correctly assemble event with error: {0!s}'.format(
              exception))

    return source_short, source_long

Returns properly formatted source strings.

Args:
        event_object: the event object (instance od EventObject).


def load(self, context):

    try:
      # pylint: disable=g-import-not-at-top,unused-import
      import tensorflow
    except ImportError:
      return
    # pylint: disable=g-import-not-at-top
    from tensorboard.plugins.hparams.hparams_plugin import HParamsPlugin
    return HParamsPlugin(context)

Returns the plugin, if possible.

Args:
        context: The TBContext flags.

Returns:
        A HParamsPlugin instance or None if it couldn't be loaded.


def _CreateFeedItems(client, feed_details, label_name):

  # Get the FeedItemService.
  feed_item_service = client.GetService('FeedItemService', version='v201809')

  # For page feed URL recommendations and rules, see:
  # https://support.google.com/adwords/answer/7166527
  urls = ('http://www.example.com/discounts/rental-cars?id={feeditem}',
          'http://www.example.com/discounts/hotel-deals?id={feeditem}',
          'http://www.example.com/discounts/flight-deals?id={feeditem}')

  # Create the operation.
  operations = [{
      # Create the feed item.
      'operand': {
          'feedId': feed_details.feed_id,
          'attributeValues': [
              {
                  'feedAttributeId': feed_details.url_attribute_id,
                  'stringValues': [url]
              },
              {
                  'feedAttributeId': feed_details.label_attribute_id,
                  'stringValues': [label_name]
              }
          ]
      },
      'operator': 'ADD'
  } for url in urls]

  # Add the feed item.
  feed_item_service.mutate(operations)

Creates the page URLs in the DSA page feed.

Args:
        client: an AdWordsClient instance.
        feed_details: a _DSAFeedDetails instance.
        label_name: a str containing the page feed URL label.


def constant(duration: int, amp: complex, name: str = None) -> SamplePulse:

    return _sampled_constant_pulse(duration, amp, name=name)

Generates constant-sampled `SamplePulse`.

    Applies `left` sampling strategy to generate discrete pulse from continuous function.

Args:
        duration: Duration of pulse. Must be greater than zero.
        amp: Complex pulse amplitude.
        name: Name of pulse.


def setup(app):

    event = 'html-page-context' if six.PY3 else b'html-page-context'
    app.connect(event, update_context)

    return {
        'parallel_read_safe': True,
        'parallel_write_safe': True,
        'version': __version__,
    }

Sphinx extension to update the rendering context with the feedback form URL.

Args:
        app (Sphinx): Application object for the Sphinx process

Returns:
        a dictionary of metadata (http://www.sphinx-doc.org/en/stable/extdev/#extension-metadata)


def __init__(self, filepath, eps=10, max_rows=None):

        # Compute EPS timer
        # Logic:
        #     - Normal distribution centered around 1.0/eps
        #     - Make sure never less than 0
        #     - Precompute 1000 deltas and then just cycle around
        self.eps_timer = itertools.cycle([max(0, delta) for delta in np.random.normal(1.0/float(eps), .5/float(eps), size=1000)])

        # Initialize the Bro log reader
        self.log_reader = bro_log_reader.BroLogReader(filepath, tail=False)

        # Store max_rows
        self.max_rows = max_rows

Initialization for the LiveSimulator Class

Args:
        eps (int): Events Per Second that the simulator will emit events (default = 10)
        max_rows (int): The maximum number of rows to generate (default = None (go forever))


def RegisterDecoder(cls, decoder):

    encoding_method = decoder.ENCODING_METHOD.lower()
    if encoding_method in cls._decoders:
      raise KeyError(
          'Decoder for encoding method: {0:s} already set.'.format(
              decoder.ENCODING_METHOD))

    cls._decoders[encoding_method] = decoder

Registers a decoder for a specific encoding method.

Args:
        decoder (type): decoder class.

Raises:
        KeyError: if the corresponding decoder is already set.


def filter_by_months_per_hour(self, months_per_hour):

        _filt_values = []
        _filt_datetimes = []
        for i, d in enumerate(self.datetimes):
            if d in months_per_hour:
                _filt_datetimes.append(d)
                _filt_values.append(self._values[i])
        return MonthlyPerHourCollection(
            self.header.duplicate(), _filt_values, _filt_datetimes)

Filter the Data Collection based on a list of months per hour (as strings).

Args:
        months_per_hour: A list of tuples representing months per hour.
        Each tuple should possess two values: the first is the month
        and the second is the hour. (eg. (12, 23) = December at 11 PM)

Returns:
        A new Data Collection with filtered data


def teleport(self, location=None, rotation=None):

        val = 0
        if location is not None:
            val += 1
            np.copyto(self._teleport_buffer, location)
        if rotation is not None:
            np.copyto(self._rotation_buffer, rotation)
            val += 2
        self._teleport_bool_buffer[0] = val

Teleports the agent to a specific location, with a specific rotation.

Args:
        location (np.ndarray, optional): An array with three elements specifying the target world coordinate in meters.
        If None, keeps the current location. Defaults to None.
        rotation (np.ndarray, optional): An array with three elements specifying the target rotation of the agent.
        If None, keeps the current rotation. Defaults to None.

Returns:
        None


def get_files(self, retrieve=False):

		if self.exists and hasattr(self.rdf.triples, 'pcdm') and hasattr(self.rdf.triples.pcdm, 'hasFile'):
			files = [ self.repo.parse_uri(uri) for uri in self.rdf.triples.pcdm.hasFile ]

			# return
			return files

		else:
			return []

get pcdm:hasFile for this resource

Args:
    retrieve (bool): if True, issue .refresh() on resource thereby confirming existence and retrieving payload


def get_library_barcode_sequence_hash(self, inverse=False):

        action = os.path.join(self.record_url, "get_library_barcode_sequence_hash")
        res = requests.get(url=action, headers=HEADERS, verify=False)
        res.raise_for_status()
        res_json = res.json()
        # Convert library ID from string to int
        new_res = {}
        for lib_id in res_json:
            new_res[int(lib_id)] = res_json[lib_id]
        res_json = new_res

        if inverse:
            rev = {}
            for lib_id in res_json:
                rev[res_json[lib_id]] = lib_id
        res_json = rev
        return res_json

Calls the SequencingRequest's get_library_barcode_sequence_hash server-side endpoint to
    create a hash of the form {LibraryID -> barcode_sequence} for all Libraries on the
    SequencingRequest.

Args:
        inverse: `bool`. True means to inverse the key and value pairs such that the barcode
            sequence serves as the key.

    Returns: `dict`.


def flatten(data):

    if not data:
        return data

    if type(data[0]) in (list, tuple):
        return list(flatten(data[0])) + list(flatten(data[1:]))

    return list(data[:1]) + list(flatten(data[1:]))

Returns a flattened version of a list.

    Courtesy of https://stackoverflow.com/a/12472564

Args:
        data (`tuple` or `list`): Input data

Returns:
        `list`


def send_notice(self, room_id, text_content, timestamp=None):

        body = {
            "msgtype": "m.notice",
            "body": text_content
        }
        return self.send_message_event(room_id, "m.room.message", body,
                                       timestamp=timestamp)

Perform PUT /rooms/$room_id/send/m.room.message with m.notice msgtype

Args:
        room_id (str): The room ID to send the event in.
        text_content (str): The m.notice body to send.
        timestamp (int): Set origin_server_ts (For application services only)


def get_first(self, status):

        items = self.get_all(status)

        if items:
            return list(items.items())[0][1]

        return None

Get the first item in the queue that has the given status.

Args:
        status (str): return the first item with this status.

Returns:
        :class:`nyawc.QueueItem`: The first queue item with the given status.


def cancel(self, consumers):

        for consumer in consumers:
            del self._consumers[consumer.queue]
            protocol = yield self.when_connected()
            yield protocol.cancel(consumer)

Cancel a consumer that was previously started with consume.

Args:
        consumer (list of fedora_messaging.api.Consumer): The consumers to cancel.


def find_pad_index(self, array):

        try:
            return list(array).index(self.pad_value)
        except ValueError:
            return len(array)

Find padding index.

Args:
        array (list): integer list.

Returns:
        idx: padding index.

Example:
        >>> array = [1, 2, 0]
        >>> self.find_pad_index(array)
        2


def write(self, message, cur_time=None):

        if cur_time is None:
            cur_time = time.time()
        lines = self._line_buffer.add_string(message)
        for line in lines:
            #print('ts line', repr(line))
            timestamp = ''
            if self._prepend_timestamp:
                timestamp = datetime.datetime.utcfromtimestamp(
                    cur_time).isoformat() + ' '
            line = u'{}{}{}'.format(self._line_prepend, timestamp, line)
            self._fsapi.push(self._filename, line)

Write some text to the pusher.

Args:
        message: a string to push for this file.
        cur_time: used for unit testing. override line timestamp.


def structure_path(self, path):

        if not path:
            self.structure_dir = None
            self.structure_file = None

        else:
            if not op.exists(path):
                raise OSError('{}: file does not exist!'.format(path))

            if not op.dirname(path):
                self.structure_dir = '.'
            else:
                self.structure_dir = op.dirname(path)
            self.structure_file = op.basename(path)

Provide pointers to the paths of the structure file

Args:
        path: Path to structure file


def _prepare_for_training(self, job_name=None):

        if job_name is not None:
            self._current_job_name = job_name
        else:
            # honor supplied base_job_name or generate it
            if self.base_job_name:
                base_name = self.base_job_name
            elif isinstance(self, sagemaker.algorithm.AlgorithmEstimator):
                base_name = self.algorithm_arn.split('/')[-1]  # pylint: disable=no-member
            else:
                base_name = base_name_from_image(self.train_image())

            self._current_job_name = name_from_base(base_name)

        # if output_path was specified we use it otherwise initialize here.
        # For Local Mode with local_code=True we don't need an explicit output_path
        if self.output_path is None:
            local_code = get_config_value('local.local_code', self.sagemaker_session.config)
            if self.sagemaker_session.local_mode and local_code:
                self.output_path = ''
            else:
                self.output_path = 's3://{}/'.format(self.sagemaker_session.default_bucket())

Set any values in the estimator that need to be set before training.

Args:
        * job_name (str): Name of the training job to be created. If not specified, one is generated,
            using the base name given to the constructor if applicable.


def get_dimension_indices(self, query):

        ids = self['id'] if self.get('id') else self['dimension']['id']
        indices = []

        for idx, id in enumerate(ids):
            indices.append(self.get_dimension_index(id,
                                                    [d.get(id) for d in query
                                                     if id in d][0]))

        return indices

Converts a dimension/category list of dicts into a list of \
    dimensions’ indices.

Args:
    query(list): dimension/category list of dicts.

Returns:
    indices(list): list of dimensions' indices.


def parse_delete_zone(prs, conn):

    prs_zone_delete = prs.add_parser('zone_delete', help='delete zone')
    prs_zone_delete.add_argument('--domain', action='store', required=True,
                                 help='specify zone')
    conn_options(prs_zone_delete, conn)
    prs_zone_delete.set_defaults(func=delete_zone)

Delete zone.

Args:
        prs:  parser object of argparse
        conn: dictionary of connection information


def tensor_layout(self, arg):

    if isinstance(arg, Tensor):
      arg = arg.shape
    return self.layout_rules.tensor_layout(arg, self.shape)

Compute TensorLayout for a Tensor or a Shape.

Args:
        arg: Tensor or Shape.

Returns:
        TensorLayout.


def set_servo_angle(self, goalangle, goaltime, led):

        if (self.servomodel==0x06) or (self.servomodel == 0x04):
            goalposition = scale(goalangle, -159.9, 159.6, 10627, 22129)
        else:
            goalposition = scale(goalangle, -150, 150, 21, 1002)

        self.set_servo_position(goalposition, goaltime, led)

Sets the servo angle (in degrees)

    Enable torque using torque_on function before calling this

Args:
        goalangle (int): The desired angle in degrees, range -150 to 150
        goaltime (int): the time taken to move from present
        position to goalposition
        led (int): the LED color
                0x00 LED off
                0x04 GREEN
                0x08 BLUE
                0x10 RED


def position(self, partition):

        if not isinstance(partition, TopicPartition):
            raise TypeError('partition must be a TopicPartition namedtuple')
        assert self._subscription.is_assigned(partition), 'Partition is not assigned'
        offset = self._subscription.assignment[partition].position
        if offset is None:
            self._update_fetch_positions([partition])
            offset = self._subscription.assignment[partition].position
        return offset

Get the offset of the next record that will be fetched

Args:
        partition (TopicPartition): Partition to check

Returns:
        int: Offset


def __init__(self, couplinglist=None):

        # the coupling map graph
        self.graph = nx.DiGraph()
        # a dict of dicts from node pairs to distances
        self._dist_matrix = None
        # a sorted list of physical qubits (integers) in this coupling map
        self._qubit_list = None

        if couplinglist is not None:
            for source, target in couplinglist:
                self.add_edge(source, target)

Create coupling graph. By default, the generated coupling has no nodes.

Args:
        couplinglist (list or None): An initial coupling graph, specified as
            an adjacency list containing couplings, e.g. [[0,1], [0,2], [1,2]].


def get_recipe(self, recipe_name):

        if recipe_name.endswith('.yaml'):
            recipe = self._recipes.get(RecipeObject.FromFile(recipe_name, self._recipe_actions, self._recipe_resources).name)
        else:
            recipe = self._recipes.get(recipe_name)
        if recipe is None:
            raise RecipeNotFoundError("Could not find recipe", recipe_name=recipe_name, known_recipes=[x for x in self._recipes.keys()])

        return recipe

Get a recipe by name.

Args:
        recipe_name (str): The name of the recipe to fetch. Can be either the
            yaml file name or the name of the recipe.


def __getitem__(self, index):

        getter = coordinates.Coordinates.from_string(index)
        return getter(self._values)

Return the value(s) of the given cell(s).

Args:
        index (str): cell/row/col index ('A1', '2', 'B') or slice ('A1':'C3')

Returns:
        value (cell), list(col, row), or nested list (two-dimentional slice)

Raises:
        TypeError: if ``index`` is not a string or slice of strings
        ValueError: if ``index`` canot be parsed
        IndexError: if ``index`` is out of range


def generate_encoded_samples(self, data_dir, tmp_dir, dataset_split):

    generator = self.generate_samples(data_dir, tmp_dir, dataset_split)
    encoder = self.get_or_create_vocab(data_dir, tmp_dir)
    label_encoder = self.get_labels_encoder(data_dir)
    for sample in generator:
      inputs = encoder.encode(sample["inputs"])
      inputs.append(text_encoder.EOS_ID)
      context = encoder.encode(sample["context"])
      context.append(text_encoder.EOS_ID)
      targets = label_encoder.encode(sample["targets"])
      sample["targets"] = targets
      yield {"inputs": inputs, "context": context, "targets": targets}

A generator that generates samples that are encoded.

Args:
        data_dir: data directory
        tmp_dir: temp directory
        dataset_split: dataset split

Yields:
        A dict.


def set_device_name(self, new_name):

        device_name = self.get_characteristic_handle_from_uuid(UUID_DEVICE_NAME)
        if device_name is None:
            logger.warn('Failed to find handle for device name')
            return False

        if len(new_name) > MAX_DEVICE_NAME_LEN:
            logger.error('Device name exceeds maximum length ({} > {})'.format(len(new_name), MAX_DEVICE_NAME_LEN))
            return False

        if self.dongle._write_attribute(self.conn_handle, device_name, new_name.encode('ascii')):
            self.name = new_name
            return True

        return False

Sets a new BLE device name for this SK8.

Args:
        new_name (str): the new device name as an ASCII string, max 20 characters.

Returns:
        True if the name was updated successfully, False otherwise.


def Reboot(self, destination=b''):

        self.protocol_handler.Open(self._handle, b'reboot:%s' % destination)

Reboot the device.

Args:
        destination: Specify 'bootloader' for fastboot.


def _StartProfiling(self, configuration):

    if not configuration:
      return

    if configuration.HaveProfileMemoryGuppy():
      self._guppy_memory_profiler = profilers.GuppyMemoryProfiler(
          self._name, configuration)
      self._guppy_memory_profiler.Start()

    if configuration.HaveProfileMemory():
      self._memory_profiler = profilers.MemoryProfiler(
          self._name, configuration)
      self._memory_profiler.Start()

    if configuration.HaveProfileProcessing():
      identifier = '{0:s}-processing'.format(self._name)
      self._processing_profiler = profilers.ProcessingProfiler(
          identifier, configuration)
      self._processing_profiler.Start()

    if configuration.HaveProfileSerializers():
      identifier = '{0:s}-serializers'.format(self._name)
      self._serializers_profiler = profilers.SerializersProfiler(
          identifier, configuration)
      self._serializers_profiler.Start()

    if configuration.HaveProfileStorage():
      self._storage_profiler = profilers.StorageProfiler(
          self._name, configuration)
      self._storage_profiler.Start()

    if configuration.HaveProfileTasks():
      self._tasks_profiler = profilers.TasksProfiler(self._name, configuration)
      self._tasks_profiler.Start()

Starts profiling.

Args:
        configuration (ProfilingConfiguration): profiling configuration.


def get_cohp(self, spin=None, integrated=False):

        if not integrated:
            populations = self.cohp
        else:
            populations = self.icohp

        if populations is None:
            return None
        elif spin is None:
            return populations
        else:
            if isinstance(spin, int):
                spin = Spin(spin)
            elif isinstance(spin, str):
                s = {"up": 1, "down": -1}[spin.lower()]
                spin = Spin(s)
            return {spin: populations[spin]}

Returns the COHP or ICOHP for a particular spin.

Args:
        spin: Spin. Can be parsed as spin object, integer (-1/1)
            or str ("up"/"down")
        integrated: Return COHP (False) or ICOHP (True)

Returns:
        Returns the CHOP or ICOHP for the input spin. If Spin is
        None and both spins are present, both spins will be returned
        as a dictionary.


def Verify(self, mempool):

        for descriptor in self.Descriptors:
            if not descriptor.Verify():
                return False

        return super(StateTransaction, self).Verify(mempool)

Verify the transaction.

Args:
        mempool:

Returns:
        bool: True if verified. False otherwise.


def add_plugin(self, f):

        if f.endswith('.py'):

            # Just the basename without extension
            plugin_name = os.path.splitext(os.path.basename(f))[0]

            # It's possible the plugin has been modified and needs to be reloaded
            if plugin_name in sys.modules:
                try:
                    handler = reload(sys.modules[plugin_name])
                    print'\t- %s %sRELOAD%s' % (plugin_name, color.Yellow, color.Normal)
                except ImportError, error:
                    print 'Failed to import plugin: %s (%s)' % (plugin_name, error)
                    return
            else:
                # Not already loaded so try to import it
                try:
                    handler = __import__(plugin_name, globals(), locals(), [], -1)
                except ImportError, error:
                    print 'Failed to import plugin: %s (%s)' % (plugin_name, error)
                    return

            # Run the handler through plugin validation
            plugin = self.validate(handler)
            print '\t- %s %sOK%s' % (plugin_name, color.Green, color.Normal)
            if plugin:

                # Okay must be successfully loaded so capture the plugin meta-data,
                # modification time and register the plugin through the callback
                plugin['name'] = plugin_name
                plugin['dependencies'] = plugin['class'].dependencies
                plugin['docstring'] = plugin['class'].__doc__
                plugin['mod_time'] = datetime.utcfromtimestamp(os.path.getmtime(f))

                # Plugin may accept sample_sets as input
                try:
                    plugin['sample_set_input'] = getattr(plugin['class'], 'sample_set_input')
                except AttributeError:
                    plugin['sample_set_input'] = False

                # Now pass the plugin back to workbench
                self.plugin_callback(plugin)

Adding and verifying plugin.

Args:
        f: the filepath for the plugin.


def get_vmss_vm(access_token, subscription_id, resource_group, vmss_name, instance_id):

    endpoint = ''.join([get_rm_endpoint(),
                        '/subscriptions/', subscription_id,
                        '/resourceGroups/', resource_group,
                        '/providers/Microsoft.Compute/virtualMachineScaleSets/', vmss_name,
                        '/virtualMachines/', str(instance_id),
                        '?api-version=', COMP_API])
    return do_get(endpoint, access_token)

Get individual VMSS VM details.

Args:
        access_token (str): A valid Azure authentication token.
        subscription_id (str): Azure subscription id.
        resource_group (str): Azure resource group name.
        vmss_name (str): Name of the virtual machine scale set.
        instance_id (int): VM ID of the scale set VM.

Returns:
        HTTP response. JSON body of VMSS VM model view.


def add_filter_set(name):

    factory = FilterSetFactory(name)
    yield factory
    filter_sets[name] = factory.build_filter_set()

Builds and registers a global :class:`FilterSet`.

Args:
        name (str): The name of the set.

Yields:
        FilterSetFactory: A configurable factory for building a :class:`FilterSet`.


def load_institute(adapter, internal_id, display_name, sanger_recipients=None):

    institute_obj = build_institute(
        internal_id=internal_id,
        display_name=display_name,
        sanger_recipients=sanger_recipients
    )
    log.info("Loading institute {0} with display name {1}" \
             " into database".format(internal_id, display_name))

    adapter.add_institute(institute_obj)

Load a institute into the database

Args:
        adapter(MongoAdapter)
        internal_id(str)
        display_name(str)
        sanger_recipients(list(email))


def __init__(self, data_type_definition):

    super(UUIDMap, self).__init__(data_type_definition)
    self._byte_order = data_type_definition.byte_order

Initializes an UUID (or GUID) data type map.

Args:
        data_type_definition (DataTypeDefinition): data type definition.


def eval_adiabatic_limit(YABFGN, Ytilde, P0):

    Y, A, B, F, G, N = YABFGN

    Klim = (P0 * (B - A * Ytilde * A) * P0).expand().simplify_scalar()
    Hlim = ((Klim - Klim.dag())/2/I).expand().simplify_scalar()

    Ldlim = (P0 * (G - A * Ytilde * F) * P0).expand().simplify_scalar()

    dN = identity_matrix(N.shape[0]) + F.H * Ytilde * F
    Nlim = (P0 * N * dN * P0).expand().simplify_scalar()

    return SLH(Nlim.dag(), Ldlim.dag(), Hlim.dag())

Compute the limiting SLH model for the adiabatic approximation

Args:
        YABFGN: The tuple (Y, A, B, F, G, N)
            as returned by prepare_adiabatic_limit.
        Ytilde: The pseudo-inverse of Y, satisfying Y * Ytilde = P0.
        P0: The projector onto the null-space of Y.

Returns:
        SLH: Limiting SLH model


def ParseFileEntry(self, parser_mediator, file_entry):

    index_file_parser = ChromeCacheIndexFileParser()

    file_object = file_entry.GetFileObject()
    try:
      index_file_parser.ParseFileObject(parser_mediator, file_object)
    except (IOError, errors.ParseError) as exception:
      file_object.close()

      display_name = parser_mediator.GetDisplayName()
      raise errors.UnableToParseFile(
          '[{0:s}] unable to parse index file {1:s} with error: {2!s}'.format(
              self.NAME, display_name, exception))

    # TODO: create event based on index file creation time.

    try:
      file_system = file_entry.GetFileSystem()
      self._ParseIndexTable(
          parser_mediator, file_system, file_entry,
          index_file_parser.index_table)
    finally:
      file_object.close()

Parses Chrome Cache files.

Args:
        parser_mediator (ParserMediator): mediates interactions between parsers
        and other components, such as storage and dfvfs.
        file_entry (dfvfs.FileEntry): file entry.

Raises:
        UnableToParseFile: when the file cannot be parsed.


def set_files(self, files_downloaded, files_failed):

        self.files_downloaded = files_downloaded
        self.files_failed = files_failed
        self.__record_progress(Status.GET_FILE_DIFF)

set_files: records progress from downloading files

Args:
        files_downloaded ([str]): list of files that have been downloaded
        files_failed ([str]): list of files that failed to download
    Returns: None


def validate_functions(ast: BELAst, bo):

    if isinstance(ast, Function):
        log.debug(f"Validating: {ast.name}, {ast.function_type}, {ast.args}")
        function_signatures = bo.spec["functions"]["signatures"][ast.name]["signatures"]

        function_name = ast.name
        (valid_function, messages) = check_function_args(
            ast.args, function_signatures, function_name
        )
        if not valid_function:
            message = ", ".join(messages)
            bo.validation_messages.append(
                (
                    "ERROR",
                    "Invalid BEL Statement function {} - problem with function signatures: {}".format(
                        ast.to_string(), message
                    ),
                )
            )
            bo.parse_valid = False

    # Recursively process every NSArg by processing BELAst and Functions
    if hasattr(ast, "args"):
        for arg in ast.args:
            validate_functions(arg, bo)

    return bo

Recursively validate function signatures

    Determine if function matches one of the available signatures. Also,

    1. Add entity types to AST NSArg, e.g. Abundance, ...
    2. Add optional to  AST Arg (optional means it is not a
        fixed, required argument and needs to be sorted for
        canonicalization, e.g. reactants(A, B, C) )

Args:
        bo: bel object

Returns:
        bel object


def wire_names(self, with_initial_value=True):

        qubit_labels = self._get_qubit_labels()
        clbit_labels = self._get_clbit_labels()

        if with_initial_value:
            qubit_labels = ['%s: |0>' % qubit for qubit in qubit_labels]
            clbit_labels = ['%s: 0 ' % clbit for clbit in clbit_labels]
        else:
            qubit_labels = ['%s: ' % qubit for qubit in qubit_labels]
            clbit_labels = ['%s: ' % clbit for clbit in clbit_labels]

        return qubit_labels + clbit_labels

Returns a list of names for each wire.

Args:
        with_initial_value (bool): Optional (Default: True). If true, adds the initial value to
                                the name.

Returns:
        List: The list of wire names.


def update_power_state(self, id_or_uri, power_state):

        uri = self._client.build_uri(id_or_uri) + "/powerState"
        return self._client.update(power_state, uri)

Sets the power state of the specified power delivery device. The device must be an HP Intelligent Outlet.

Args:
        id_or_uri:
            Can be either the power device id or the uri
        power_state:
            {"powerState":"On|Off"}

Returns:
        str: The power state


def _get_ruuvitag_datas(macs=[], search_duratio_sec=None, run_flag=RunFlag(), bt_device=''):

        mac_blacklist = []
        start_time = time.time()
        data_iter = ble.get_datas(mac_blacklist, bt_device)

        for ble_data in data_iter:
            # Check duration
            if search_duratio_sec and time.time() - start_time > search_duratio_sec:
                data_iter.send(StopIteration)
                break
            # Check running flag
            if not run_flag.running:
                data_iter.send(StopIteration)
                break
            # Check MAC whitelist
            if macs and not ble_data[0] in macs:
                continue
            (data_format, data) = RuuviTagSensor.convert_data(ble_data[1])
            # Check that encoded data is valid RuuviTag data and it is sensor data
            # If data is not valid RuuviTag data add MAC to blacklist
            if data is not None:
                state = get_decoder(data_format).decode_data(data)
                if state is not None:
                    yield (ble_data[0], state)
            else:
                mac_blacklist.append(ble_data[0])

Get data from BluetoothCommunication and handle data encoding.

Args:
        macs (list): MAC addresses. Default empty list
        search_duratio_sec (int): Search duration in seconds. Default None
        run_flag (object): RunFlag object. Function executes while run_flag.running. Default new RunFlag
        bt_device (string): Bluetooth device id

Yields:
        tuple: MAC and State of RuuviTag sensor data


def __setattr__(cls, name, value):

        if cls.__initialized and name not in _POST_INIT_ATTRIBUTE_NAMES:
            raise AttributeError('May not change values: %s' % name)
        else:
            type.__setattr__(cls, name, value)

Overridden to avoid setting variables after init.

    Setting attributes on a class must work during the period of
    initialization to set the enumation value class variables and
    build the name/number maps. Once __init__ has set the
    __initialized flag to True prohibits setting any more values
    on the class. The class is in effect frozen.

Args:
        name: Name of value to set.
        value: Value to set.


def _get_update(self, variant):

        update = {
                '$inc': {
                    'homozygote': variant.get('homozygote', 0),
                    'hemizygote': variant.get('hemizygote', 0),
                    'observations': 1
                },
                '$set': {
                    'chrom': variant.get('chrom'),
                    'start': variant.get('pos'),
                    'end': variant.get('end'),
                    'ref': variant.get('ref'),
                    'alt': variant.get('alt'),
                }
             }
        if variant.get('case_id'):
            update['$push'] = {
                                'families': {
                                '$each': [variant.get('case_id')],
                                '$slice': -50
                                }
                            }
        return update

Convert a variant to a proper update

Args:
        variant(dict)

Returns:
        update(dict)


def _find_image_bounding_boxes(filenames, image_to_bboxes):

  num_image_bbox = 0
  bboxes = []
  for f in filenames:
    basename = os.path.basename(f)
    if basename in image_to_bboxes:
      bboxes.append(image_to_bboxes[basename])
      num_image_bbox += 1
    else:
      bboxes.append([])
  print('Found %d images with bboxes out of %d images' % (
      num_image_bbox, len(filenames)))
  return bboxes

Find the bounding boxes for a given image file.

Args:
        filenames: list of strings; each string is a path to an image file.
        image_to_bboxes: dictionary mapping image file names to a list of
        bounding boxes. This list contains 0+ bounding boxes.

Returns:
        List of bounding boxes for each image. Note that each entry in this
        list might contain from 0+ entries corresponding to the number of bounding
        box annotations for the image.


def IsEquivalent(self, other):

    if self.name and other.name:
      return self.name == other.name

    if self.name:
      self_family, self_version_tuple = self._FAMILY_AND_VERSION_PER_NAME.get(
          self.name, self._DEFAULT_FAMILY_AND_VERSION)
      return (
          self_family == other.family and
          self_version_tuple == other.version_tuple)

    if self.family and self.version:
      if other.name:
        other_family, other_version_tuple = (
            self._FAMILY_AND_VERSION_PER_NAME.get(
                other.name, self._DEFAULT_FAMILY_AND_VERSION))
      else:
        other_family = other.family
        other_version_tuple = other.version_tuple

      return (
          self.family == other_family and
          self.version_tuple == other_version_tuple)

    if self.family:
      if other.name:
        other_family, _ = self._FAMILY_AND_VERSION_PER_NAME.get(
            other.name, self._DEFAULT_FAMILY_AND_VERSION)
      else:
        other_family = other.family

      return self.family == other_family

    return False

Determines if 2 operating system artifacts are equivalent.

    This function compares the operating systems based in order of:
    * name derived from product
    * family and version
    * family

Args:
        other (OperatingSystemArtifact): operating system artifact attribute
        container to compare with.

Returns:
        bool: True if the operating systems are considered equivalent, False if
        the most specific criteria do no match, or no criteria are available.


def CheckAltTokens(filename, clean_lines, linenum, error):

  line = clean_lines.elided[linenum]

  # Avoid preprocessor lines
  if Match(r'^\s*#', line):
    return

  # Last ditch effort to avoid multi-line comments.  This will not help
  # if the comment started before the current line or ended after the
  # current line, but it catches most of the false positives.  At least,
  # it provides a way to workaround this warning for people who use
  # multi-line comments in preprocessor macros.
  #
  # TODO(unknown): remove this once cpplint has better support for
  # multi-line comments.
  if line.find('/*') >= 0 or line.find('*/') >= 0:
    return

  for match in _ALT_TOKEN_REPLACEMENT_PATTERN.finditer(line):
    error(filename, linenum, 'readability/alt_tokens', 2,
          'Use operator %s instead of %s' % (
              _ALT_TOKEN_REPLACEMENT[match.group(1)], match.group(1)))

Check alternative keywords being used in boolean expressions.

Args:
        filename: The name of the current file.
        clean_lines: A CleansedLines instance containing the file.
        linenum: The number of the line to check.
        error: The function to call with any errors found.


def _pack_with_tf_ops(dataset, keys, length):

  empty_example = {}
  for k in keys:
    empty_example[k] = tf.zeros([0], dtype=tf.int32)
    empty_example[k + "_position"] = tf.zeros([0], dtype=tf.int32)
  keys_etc = empty_example.keys()

  def write_packed_example(partial, outputs):
    new_partial = empty_example.copy()
    new_outputs = {}
    for k in keys_etc:
      new_outputs[k] = outputs[k].write(
          outputs[k].size(),
          tf.pad(partial[k], [[0, length - tf.size(partial[k])]]))
    return new_partial, new_outputs

  def map_fn(x):

    partial = empty_example.copy()
    i = tf.zeros([], dtype=tf.int32)
    dynamic_batch_size = tf.shape(x[keys[0]])[0]
    outputs = {}
    for k in keys:
      outputs[k] = tf.TensorArray(
          tf.int32, size=0, dynamic_size=True, element_shape=[length])
      outputs[k + "_position"] = tf.TensorArray(
          tf.int32, size=0, dynamic_size=True, element_shape=[length])
    def cond_fn(i, partial, outputs):
      del partial, outputs
      return i < dynamic_batch_size
    def body_fn(i, partial, outputs):

      can_append = True
      one_example = {}
      for k in keys:
        val = tf.cast(x[k][i], tf.int32)
        val = val[:tf.reduce_sum(tf.cast(tf.not_equal(val, 0), tf.int32))]
        one_example[k] = val
      for k in keys:
        can_append = tf.logical_and(
            can_append,
            tf.less_equal(
                tf.size(partial[k]) + tf.size(one_example[k]), length))
      def false_fn():
        return write_packed_example(partial, outputs)
      def true_fn():
        return partial, outputs
      partial, outputs = tf.cond(can_append, true_fn, false_fn)
      new_partial = {}
      for k in keys:
        new_seq = one_example[k][:length]
        new_seq_len = tf.size(new_seq)
        new_partial[k] = tf.concat([partial[k], new_seq], 0)
        new_partial[k + "_position"] = tf.concat(
            [partial[k + "_position"],
             tf.range(new_seq_len, dtype=tf.int32)], 0)
      partial = new_partial
      return i+1, partial, outputs

    i, partial, outputs = tf.while_loop(
        cond_fn, body_fn, (i, partial, outputs),
        back_prop=False,
        shape_invariants=(
            tf.TensorShape([]),
            {k: tf.TensorShape([None]) for k in keys_etc},
            {k: tf.TensorShape(None) for k in keys_etc},
            ))
    partial, outputs = write_packed_example(partial, outputs)
    packed = {k: outputs[k].stack() for k in keys_etc}
    for k in keys:
      packed[k + "_segmentation"] = (
          tf.cumsum(
              tf.cast(tf.equal(packed[k + "_position"], 0), tf.int32), axis=1) *
          tf.cast(tf.not_equal(packed[k], 0), tf.int32))
    return packed
  dataset = dataset.map(map_fn,
                        num_parallel_calls=tf.data.experimental.AUTOTUNE)
  return dataset.flat_map(tf.data.Dataset.from_tensor_slices)

Helper-function for packing a dataset which has already been batched.

    See pack_dataset()

    Uses tf.while_loop.  Slow.

Args:
        dataset: a dataset containing padded batches of examples.
        keys: a list of strings
        length: an integer

Returns:
        a dataset.


def generate_sjson_from_srt(srt_subs):

        sub_starts = []
        sub_ends = []
        sub_texts = []
        for sub in srt_subs:
            sub_starts.append(sub.start.ordinal)
            sub_ends.append(sub.end.ordinal)
            sub_texts.append(sub.text.replace('\n', ' '))

        sjson_subs = {
            'start': sub_starts,
            'end': sub_ends,
            'text': sub_texts
        }
        return sjson_subs

Generate transcripts from sjson to SubRip (*.srt).

Args:
        srt_subs(SubRip): "SRT" subs object

Returns:
        Subs converted to "SJSON" format.


def create_single_token(self, *, payer_id, name, identification_number, payment_method, number, expiration_date):

        payload = {
            "language": self.client.language.value,
            "command": PaymentCommand.CREATE_TOKEN.value,
            "merchant": {
                "apiLogin": self.client.api_login,
                "apiKey": self.client.api_key
            },
            "creditCardToken": {
                "payerId": payer_id,
                "name": name,
                "identificationNumber": identification_number,
                "paymentMethod": payment_method,
                "number": number,
                "expirationDate": expiration_date
            },
            "test": self.client.is_test
        }
        return self.client._post(self.url, json=payload)

Using this feature you can register a customer’s credit card data and get a token sequential number.

Args:
        payer_id:
        name:
        identification_number:
        payment_method:
        number:
        expiration_date:

    Returns:


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

        self._wb004 = value

Corresponds to IDD Field `wb004`
    Wet-bulb temperature corresponding to 0.4% annual cumulative frequency of occurrence

Args:
        value (float): value for IDD Field `wb004`
            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 get_raw_data(self, url, *args, **kwargs):

        res = self._conn.get(url, headers=self._prepare_headers(**kwargs))
        if res.status_code == 200:
            return res.content
        else:
            return None

Gets data from url as bytes

    Returns content under the provided url as bytes
    ie. for binary data

Args:
        **url**: address of the wanted data

        .. versionadded:: 0.3.2
            **additional_headers**: (optional) Additional headers
            to be used with request

Returns:
        bytes


def tonicdns_client(uri, method, token='', data='', keyword='',
                    content='', raw_flag=False):

    res = request(uri, method, data, token)
    if token:
        if keyword == 'serial':
            args = {"token": token, "keyword": keyword, "content": content}
            cur_soa, new_soa = response(uri, method, res, **args)
            return cur_soa, new_soa

        else:
            if content is None:
                args = {"token": token, "keyword": keyword,
                        "content": content.get('domain')}
                response(uri, method, res, **args)
            else:
                # get sub command
                args = {"token": token, "keyword": keyword,
                        "raw_flag": raw_flag}
                data = response(uri, method, res, **args)
                return data

    else:
        args = {"token": token, "keyword": keyword}
        token = response(uri, method, res, **args)
        return token

TonicDNS API client

Args:
        uri:      TonicDNS API URI
        method:   TonicDNS API request method
        token:    TonicDNS API authentication token
        data:     Post data to TonicDNS API
        keyword:  Processing keyword of response
        content:  data exist flag
        raw_flag: True is return response data, False is pretty printing


def _average_precision(self, rec, prec):

        ap = 0.
        for t in np.arange(0., 1.1, 0.1):
            if np.sum(rec >= t) == 0:
                p = 0
            else:
                p = np.max(prec[rec >= t])
            ap += p / 11.
        return ap

calculate average precision, override the default one,
    special 11-point metric

    Params:
    ----------
    rec : numpy.array
        cumulated recall
    prec : numpy.array
        cumulated precision

Returns:
    ----------
    ap as float


def delayedQuoteDF(symbol, token='', version=''):

    df = pd.io.json.json_normalize(delayedQuote(symbol, token, version))
    _toDatetime(df)
    _reindex(df, 'symbol')
    return df

This returns the 15 minute delayed market quote.

    https://iexcloud.io/docs/api/#delayed-quote
    15min delayed
    4:30am - 8pm ET M-F when market is open

Args:
        symbol (string); Ticker to request
        token (string); Access token
        version (string); API version

Returns:
        DataFrame: result


def major_complex(network, state):

    log.info('Calculating major complex...')

    result = complexes(network, state)
    if result:
        result = max(result)
    else:
        empty_subsystem = Subsystem(network, state, ())
        result = _null_sia(empty_subsystem)

    log.info("Finished calculating major complex.")

    return result

Return the major complex of the network.

Args:
        network (Network): The |Network| of interest.
        state (tuple[int]): The state of the network (a binary tuple).

Returns:
        SystemIrreducibilityAnalysis: The |SIA| for the |Subsystem| with
        maximal |big_phi|.


def GetBlockHash(self, height):

        if self._current_block_height < height:
            return

        if len(self._header_index) <= height:
            return

        return self._header_index[height]

Get the block hash by its block height

Args:
        height(int): height of the block to retrieve hash from.

Returns:
        bytes: a non-raw block hash (e.g. b'6dd83ed8a3fc02e322f91f30431bf3662a8c8e8ebe976c3565f0d21c70620991', but not b'\x6d\xd8...etc'


def __set_mutation_type(self, hgvs_string):

        self.__set_lost_stop_status(hgvs_string)
        self.__set_lost_start_status(hgvs_string)
        self.__set_missense_status(hgvs_string)  # missense mutations
        self.__set_indel_status()  # indel mutations
        self.__set_frame_shift_status()  # check for fs
        self.__set_premature_stop_codon_status(hgvs_string)

Interpret the mutation type (missense, etc.) and set appropriate flags.

Args:
        hgvs_string (str): hgvs syntax with "p." removed


def _ParseKey(self, knowledge_base, registry_key, value_name):

    try:
      registry_value = registry_key.GetValueByName(value_name)
    except IOError as exception:
      raise errors.PreProcessFail((
          'Unable to retrieve Windows Registry key: {0:s} value: {1:s} '
          'with error: {2!s}').format(
              registry_key.path, value_name, exception))

    if registry_value:
      value_object = registry_value.GetDataAsObject()
      if value_object:
        self._ParseValueData(knowledge_base, value_object)

Parses a Windows Registry key for a preprocessing attribute.

Args:
        knowledge_base (KnowledgeBase): to fill with preprocessing information.
        registry_key (dfwinreg.WinRegistryKey): Windows Registry key.
        value_name (str): name of the Windows Registry value.

Raises:
        PreProcessFail: if the preprocessing fails.


def validate_tag(self, key, value):

        if key == 'owner':
            return validate_email(value, self.partial_owner_match)
        elif key == self.gdpr_tag:
            return value in self.gdpr_tag_values
        else:
            return True

Check whether a tag value is valid

Args:
        key: A tag key
        value: A tag value

Returns:
        `(True or False)`
        A boolean indicating whether or not the value is valid


def add_direct(self, target, var_id, var_type, data):

        data = struct.pack("<H", var_id) + _convert_to_bytes(var_type, data)

        if self.data_size - self.data_index < len(data):
            raise DataError("Not enough space for data in new conig entry", needed_space=len(data), actual_space=(self.data_size - self.data_index))

        new_entry = ConfigEntry(target, var_id, data)

        for entry in self.entries:
            if entry.target == new_entry.target and entry.var_id == new_entry.var_id:
                entry.valid = False

        self.entries.append(new_entry)
        self.data_index += new_entry.data_space()

Directly add a config variable.

    This method is meant to be called from emulation scenarios that
    want to directly set config database entries from python.

Args:
        target (SlotIdentifer): The target slot for this config variable.
        var_id (int): The config variable ID
        var_type (str): The config variable type
        data (bytes or int or str): The data that will be encoded according
            to var_type.


def success(channel, post):

    # Create datapacks
    datapacks = [("Game", post[0], True), ("Upvotes", post[2], True)]

    # Create embed UI object
    gui = ui_embed.UI(
        channel,
        "Link",
        post[1],
        modulename=modulename,
        colour=0xFF8800,
        thumbnail=post[1],
        datapacks=datapacks
    )

    return gui

Creates an embed UI containing the Reddit posts

Args:
        channel (discord.Channel): The Discord channel to bind the embed to
        post (tuple): Tuples of (field, value, percentile)

    Returns:


def __init__(self,
                 attach=None,
                 attach_params=None,
                 **kwargs):

        super(AudioAlarm, self).__init__(**kwargs)
        self.attach = attach
        self.attach_params = attach_params

Instantiates a new :class:`ics.alarm.AudioAlarm`.

    Adheres to RFC5545 VALARM standard: http://icalendar.org/iCalendar-RFC-5545/3-6-6-alarm-component.html

Args:
        attach (string) : RFC5545 ATTACH property, pointing to an audio object
        attach_params (dict) : RFC5545 attachparam values
        kwargs (dict) : Args to :func:`ics.alarm.Alarm.__init__`


def sample(self, num_rows=1):

        self.check_fit()

        res = {}
        means = np.zeros(self.covariance.shape[0])
        size = (num_rows,)

        clean_cov = np.nan_to_num(self.covariance)
        samples = np.random.multivariate_normal(means, clean_cov, size=size)

        for i, (label, distrib) in enumerate(self.distribs.items()):
            cdf = stats.norm.cdf(samples[:, i])
            res[label] = distrib.percent_point(cdf)

        return pd.DataFrame(data=res)

Creates sintentic values stadistically similar to the original dataset.

Args:
        num_rows: `int` amount of samples to generate.

Returns:
        np.ndarray: Sampled data.


def __init__(self, lst):

        list.__init__(self, lst)
        self.server = None
        self.port = find_free_port()
        self.html_path = get_cur_path()+'/data/math_list/index.html'

MathList Constructor

    todo:: share a port among lists. Or maybe close the server after serving from it?

Args:
        lst (list):  A list of LaTeX math to be rendered by KaTeX

Returns:
        A math list object

    Usage example
    >>> lst = ["\int x = y", "x + 6"]
    >>> MathList(lst)
    ... see nicely formatted math.


def _ParseIntegerValue(self, byte_stream, file_offset):

    data_type_map = self._GetDataTypeMap('int32be')

    try:
      return self._ReadStructureFromByteStream(
          byte_stream, file_offset, data_type_map)
    except (ValueError, errors.ParseError) as exception:
      raise errors.ParseError(
          'Unable to parse integer value with error: {0!s}'.format(exception))

Parses an integer value.

Args:
        byte_stream (bytes): byte stream.
        file_offset (int): offset of the attribute data relative to the start of
        the file-like object.

Returns:
        int: integer value.

Raises:
        ParseError: when the integer value cannot be parsed.


def ldirectory(inpath, outpath, args, scope):

    yacctab = 'yacctab' if args.debug else None
    if not outpath:
        sys.exit("Compile directory option needs -o ...")
    else:
        if not os.path.isdir(outpath):
            if args.verbose:
                print("Creating '%s'" % outpath, file=sys.stderr)
            if not args.dry_run:
                os.mkdir(outpath)
    less = glob.glob(os.path.join(inpath, '*.less'))
    f = formatter.Formatter(args)
    for lf in less:
        outf = os.path.splitext(os.path.basename(lf))
        minx = '.min' if args.min_ending else ''
        outf = "%s/%s%s.css" % (outpath, outf[0], minx)
        if not args.force and os.path.exists(outf):
            recompile = os.path.getmtime(outf) < os.path.getmtime(lf)
        else:
            recompile = True
        if recompile:
            print('%s -> %s' % (lf, outf))
            p = parser.LessParser(
                yacc_debug=(args.debug),
                lex_optimize=True,
                yacc_optimize=(not args.debug),
                scope=scope,
                tabfile=yacctab,
                verbose=args.verbose)
            p.parse(filename=lf, debuglevel=0)
            css = f.format(p)
            if not args.dry_run:
                with open(outf, 'w') as outfile:
                    outfile.write(css)
        elif args.verbose:
            print('skipping %s, not modified' % lf, file=sys.stderr)
        sys.stdout.flush()
    if args.recurse:
        [
            ldirectory(
                os.path.join(inpath, name), os.path.join(outpath, name), args,
                scope) for name in os.listdir(inpath)
            if os.path.isdir(os.path.join(inpath, name))
            and not name.startswith('.') and not name == outpath
        ]

Compile all *.less files in directory

Args:
        inpath (str): Path to compile
        outpath (str): Output directory
        args (object): Argparse Object
        scope (Scope): Scope object or None


def _GetPropertyValue(self, parser_mediator, properties, property_name):

    property_value = properties.get(property_name, None)
    if isinstance(property_value, py2to3.BYTES_TYPE):
      try:
        # TODO: get encoding form XML metadata.
        property_value = property_value.decode('utf-8')
      except UnicodeDecodeError:
        parser_mediator.ProduceExtractionWarning(
            'unable to decode property: {0:s}'.format(property_name))

    return property_value

Retrieves a property value.

Args:
        parser_mediator (ParserMediator): mediates interactions between parsers
        and other components, such as storage and dfvfs.
        properties (dict[str, object]): properties.
        property_name (str): name of the property.

Returns:
        str: property value.


def reformat_to_pretty_xml(doc_xml):

    assert isinstance(doc_xml, str)
    dom_obj = xml.dom.minidom.parseString(doc_xml)
    pretty_xml = dom_obj.toprettyxml(indent='  ')
    # Remove empty lines in the result caused by a bug in toprettyxml()
    return re.sub(r'^\s*$\n', r'', pretty_xml, flags=re.MULTILINE)

Pretty print XML doc.

Args:
        doc_xml : str
        Well formed XML doc

Returns:
        str: Pretty printed XML doc


def parse_config(data: dict) -> dict:

    return {
        'email': data.get('email'),
        'family': data['family_id'],
        'samples': [{
            'id': sample_id,
            'type': analysis_type,
        } for sample_id, analysis_type in data['analysis_type'].items()],
        'config_path': data['config_file_analysis'],
        'is_dryrun': True if 'dry_run_all' in data else False,
        'log_path': data['log_file'],
        'out_dir': data['outdata_dir'],
        'priority': data['slurm_quality_of_service'],
        'sampleinfo_path': data['sample_info_file'],
    }

Parse MIP config file.

Args:
        data (dict): raw YAML input from MIP analysis config file

Returns:
        dict: parsed data


def char_spacing(self, dots):

        if dots in range(0,127):
            self.send(chr(27)+chr(32)+chr(dots))
        else:
            raise RuntimeError('Invalid dot amount in function charSpacing')

Specifes character spacing in dots.

Args:
        dots: the character spacing you desire, in dots

Returns:
        None

Raises:
        RuntimeError: Invalid dot amount.


def noise_set_type(n: tcod.noise.Noise, typ: int) -> None:

    n.algorithm = typ

Set a Noise objects default noise algorithm.

Args:
        typ (int): Any NOISE_* constant.


def LoadFromStorage(cls, path=None):

    if path is None:
      path = os.path.join(os.path.expanduser('~'), 'googleads.yaml')

    return cls(**googleads.common.LoadFromStorage(
        path, cls._YAML_KEY, cls._REQUIRED_INIT_VALUES,
        cls._OPTIONAL_INIT_VALUES))

Creates an AdWordsClient with information stored in a yaml file.

Args:
        [optional]
        path: The path string to the file containing cached AdWords data.

Returns:
        An AdWordsClient initialized with the values cached in the file.

Raises:
        A GoogleAdsValueError if the given yaml file does not contain the
        information necessary to instantiate a client object - either a
        required key was missing or an OAuth2 key was missing.


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

        with self.graph.as_default():
            with tf.name_scope('action_preconditions_checking'):
                preconds = self.compile_action_preconditions(state, action)
                all_preconds = tf.stack([p.tensor for p in preconds], axis=1)
                checking = tf.reduce_all(all_preconds, axis=1)
                return checking

Combines the action preconditions into an applicability checking op.

Args:
        state (Sequence[tf.Tensor]): The current state fluents.
        action (Sequence[tf.Tensor]): The action fluents.

Returns:
        A boolean tensor for checking if `action` is application in `state`.


def inference(self, observed_arr):

        if observed_arr.ndim < 4:
            # Add rank for channel.
            observed_arr = np.expand_dims(observed_arr, axis=1)
            self.__add_channel_flag = True
        else:
            self.__add_channel_flag = False

        return super().inference(observed_arr)

Draws samples from the `true` distribution.

Args:
        observed_arr:     `np.ndarray` of observed data points.

Returns:
        `np.ndarray` of inferenced.


def generate_supremacy_circuit_google_v2_bristlecone(n_rows: int,
                                                     cz_depth: int, seed: int
                                                     ) -> circuits.Circuit:

    def get_qubits(n_rows):
        def count_neighbors(qubits, qubit):

            possibles = [
                devices.GridQubit(qubit.row + 1, qubit.col),
                devices.GridQubit(qubit.row - 1, qubit.col),
                devices.GridQubit(qubit.row, qubit.col + 1),
                devices.GridQubit(qubit.row, qubit.col - 1),
                ]
            return len(list(e for e in possibles if e in qubits))

        assert 1 <= n_rows <= 11
        max_row = n_rows - 1
        dev = google.Bristlecone
        # we need a consistent order of qubits
        qubits = list(dev.qubits)
        qubits.sort()
        qubits = [q for q in qubits
                      if  q.row <= max_row and  q.row + q.col < n_rows + 6
                      and q.row - q.col < n_rows - 5]
        qubits = [q for q in qubits if count_neighbors(qubits, q) > 1]
        return qubits

    qubits = get_qubits(n_rows)
    return generate_supremacy_circuit_google_v2(qubits, cz_depth, seed)

Generates Google Random Circuits v2 in Bristlecone.
    See also https://arxiv.org/abs/1807.10749

Args:
        n_rows: number of rows in a Bristlecone lattice.
        Note that we do not include single qubit corners.
        cz_depth: number of layers with CZ gates.
        seed: seed for the random instance.

Returns:
        A circuit with given size and seed.


def get_updated(node):

  if isinstance(node, gast.Assign):
    return set.union(*(_get_target(target)
                       for target in node.targets))
  elif isinstance(node, (gast.For, gast.AugAssign)):
    return _get_target(node.target)
  elif isinstance(node, gast.arguments):
    targets = set(arg.id for arg in node.args + node.kwonlyargs)
    if node.vararg:
      targets.add(node.vararg.id)
    if node.kwarg:
      targets.add(node.kwarg.id)
    return targets
  else:
    return set()

Return the variable names created or mutated by this statement.

    This function considers assign statements, augmented assign statements, and
    the targets of for loops, as well as function arguments.

    For example, `x[0] = 2` will return `x`, `x, y = 3, 4` will return `x` and
    `y`, `for i in range(x)` will return `i`, etc.

Args:
        node: An AST node

Returns:
        A set of variable names (strings) of all the variables created or mutated.


def short(cls, path):

        if not path:
            return path

        path = str(path)
        if cls.paths:
            for p in cls.paths:
                if p:
                    path = path.replace(p + "/", "")

        path = path.replace(cls.home, "~")
        return path

Example:
    short("examined /Users/joe/foo") => "examined ~/foo"

Args:
    path: Path to represent in its short form

Returns:
    (str): Short form, using '~' if applicable


def __init__(self, gans_value_function=None):

        if gans_value_function is None:
            gans_value_function = MiniMax()

        if isinstance(gans_value_function, GANsValueFunction) is False:
            raise TypeError("The type of `gans_value_function` must be `GANsValueFunction`.")
        self.__gans_value_function = gans_value_function
        self.__logger = getLogger("pygan")

        super().__init__(gans_value_function)

Init.

Args:
        gans_value_function:        is-a `GANsValueFunction`.


def AddRow(self, values):

    if self._number_of_columns and len(values) != self._number_of_columns:
      raise ValueError('Number of values is out of bounds.')

    if not self._column_sizes and self._columns:
      self._column_sizes = [len(column) for column in self._columns]

    value_strings = []
    for value_index, value_string in enumerate(values):
      if not isinstance(value_string, py2to3.UNICODE_TYPE):
        value_string = '{0!s}'.format(value_string)
      value_strings.append(value_string)

      self._column_sizes[value_index] = max(
          self._column_sizes[value_index], len(value_string))

    self._rows.append(value_strings)

    if not self._number_of_columns:
      self._number_of_columns = len(value_strings)

Adds a row of values.

Args:
        values (list[object]): values.

Raises:
        ValueError: if the number of values is out of bounds.


def fetch(self, plan_id, data={}, **kwargs):

        return super(Plan, self).fetch(plan_id, data, **kwargs)

Fetch Plan for given Id

Args:
        plan_id : Id for which Plan object has to be retrieved

Returns:
        Plan dict for given subscription Id


def read_gold_standard_file(data_dir, fileroot, encoding=None, cetr=False):

    fname = os.path.join(
        data_dir, GOLD_STANDARD_DIRNAME, fileroot + GOLD_STANDARD_EXT)
    encodings = (encoding,) if encoding else ('utf-8', 'utf-16', 'iso-8859-1')
    for encoding in encodings:
        try:
            with io.open(fname, mode='rt', encoding=encoding) as f:
                gold_standard = f.read()
            break
        except (UnicodeDecodeError, UnicodeError):
            gold_standard = None

    if not gold_standard:
        return [u'', u'']

    if not cetr:
        content_comments = RE_COMMENTS_DELIM.split(gold_standard, maxsplit=1)
        # if no comments delimiter found, append empty comments string
        if len(content_comments) == 1:
            content_comments = [content_comments[0], u'']
    else:
        tree = etree.fromstring(gold_standard, parser=etree.HTMLParser())
        content_comments = [u' '.join(text_from_subtree(tree)), u'']

    # fix text in case of mangled encodings
    content_comments = [ftfy.fix_encoding(content_comments[0]).strip(),
                        ftfy.fix_encoding(content_comments[1]).strip()]

    return content_comments

Read the gold standard content file corresponding to identifier ``fileroot``
    in the gold standard directory below the root ``data_dir``.

Args:
        data_dir (str)
        fileroot (str)
        encoding (str)
        cetr (bool): if True, assume no comments and parse the gold standard
            to remove tags

Returns:
        List[str, str]: contents string and comments string, respectively


def GetArchiveTypeIndicators(cls, path_spec, resolver_context=None):

    if (cls._archive_remainder_list is None or
        cls._archive_store is None):
      specification_store, remainder_list = cls._GetSpecificationStore(
          definitions.FORMAT_CATEGORY_ARCHIVE)
      cls._archive_remainder_list = remainder_list
      cls._archive_store = specification_store

    if cls._archive_scanner is None:
      cls._archive_scanner = cls._GetSignatureScanner(cls._archive_store)

    return cls._GetTypeIndicators(
        cls._archive_scanner, cls._archive_store,
        cls._archive_remainder_list, path_spec,
        resolver_context=resolver_context)

Determines if a file contains a supported archive types.

Args:
        path_spec (PathSpec): path specification.
        resolver_context (Optional[Context]): resolver context, where None
        represents the built-in context which is not multi process safe.

Returns:
        list[str]: supported format type indicators.


def parse_meta(meta):

    resources = {}
    for name in meta:
        if name.startswith("$"):
            continue
        resources[name] = resource = {}
        for action in meta[name]:
            if action.startswith("$"):
                continue
            url, httpmethod = res_to_url(name, action)
            resource[action] = {
                "url": url,
                "method": httpmethod
            }
    url_prefix = meta.get("$url_prefix", "").rstrip("/")
    return url_prefix, meta["$auth"]["header"].lower(), resources

Parse metadata of API

Args:
        meta: metadata of API

Returns:
        tuple(url_prefix, auth_header, resources)


def _HashRow(cls, row):

    values = []
    for value in row:
      try:
        value = '{0!s}'.format(value)
      except UnicodeDecodeError:
        # In Python 2, blobs are "read-write buffer" and will cause a
        # UnicodeDecodeError exception if we try format it as a string.
        # Since Python 3 does not support the buffer type we cannot check
        # the type of value.
        value = repr(value)

      values.append(value)

    return hash(' '.join(values))

Hashes the given row.

Args:
        row (sqlite3.Row): row.

Returns:
        int: hash value of the given row.


def parse(self, ident_str):
        # type: (bytes) -> None

        if self._initialized:
            raise pycdlibexception.PyCdlibInternalError('This File or Text identifier is already initialized')
        self.text = ident_str

        # FIXME: we do not support a file identifier here.  In the future, we
        # might want to implement this.

        self._initialized = True

Parse a file or text identifier out of a string.

    Parameters:
        ident_str  - The string to parse the file or text identifier from.

Returns:
        Nothing.


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

        self._wb010 = value

Corresponds to IDD Field `wb010`
    Wet-bulb temperature corresponding to 1.0% annual cumulative frequency of occurrence

Args:
        value (float): value for IDD Field `wb010`
            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 model(self, value):

        if value == self._defaults['ai.device.model'] and 'ai.device.model' in self._values:
            del self._values['ai.device.model']
        else:
            self._values['ai.device.model'] = value

The model property.

Args:
        value (string). the property value.


def CaptureFrameLocals(self, frame):

    # Capture all local variables (including method arguments).
    variables = {n: self.CaptureNamedVariable(n, v, 1,
                                              self.default_capture_limits)
                 for n, v in six.viewitems(frame.f_locals)}

    # Split between locals and arguments (keeping arguments in the right order).
    nargs = frame.f_code.co_argcount
    if frame.f_code.co_flags & inspect.CO_VARARGS: nargs += 1
    if frame.f_code.co_flags & inspect.CO_VARKEYWORDS: nargs += 1

    frame_arguments = []
    for argname in frame.f_code.co_varnames[:nargs]:
      if argname in variables: frame_arguments.append(variables.pop(argname))

    return (frame_arguments, list(six.viewvalues(variables)))

Captures local variables and arguments of the specified frame.

Args:
        frame: frame to capture locals and arguments.

Returns:
        (arguments, locals) tuple.


def __request_finish(self, queue_item, new_requests, request_failed=False):

        if self.__stopping:
            return

        del self.__threads[queue_item.get_hash()]

        if request_failed:
            new_queue_items = []
            self.queue.move(queue_item, QueueItem.STATUS_ERRORED)
        else:
            self.routing.increase_route_count(queue_item.request)
            new_queue_items = self.__add_scraped_requests_to_queue(queue_item, new_requests)
            self.queue.move(queue_item, QueueItem.STATUS_FINISHED)

        try:
            action = self.__options.callbacks.request_after_finish(self.queue, queue_item, new_queue_items)
        except Exception as e:
            action = None
            print(e)
            print(traceback.format_exc())

        queue_item.decompose()

        if action == CrawlerActions.DO_STOP_CRAWLING:
            self.__should_stop = True

        if action == CrawlerActions.DO_CONTINUE_CRAWLING or action is None:
            self.__should_spawn_new_requests = True

Called when the crawler finished the given queue item.

Args:
        queue_item (:class:`nyawc.QueueItem`): The request/response pair that finished.
        new_requests list(:class:`nyawc.http.Request`): All the requests that were found during this request.
        request_failed (bool): True if the request failed (if needs to be moved to errored).


def list_folder(cls, session, mailbox, folder):

        return cls(
            '/mailboxes/%d/folders/%s/conversations.json' % (
                mailbox.id, folder.id,
            ),
            session=session,
        )

Return conversations in a specific folder of a mailbox.

Args:
        session (requests.sessions.Session): Authenticated session.
        mailbox (helpscout.models.Mailbox): Mailbox that folder is in.
        folder (helpscout.models.Folder): Folder to list.

Returns:
        RequestPaginator(output_type=helpscout.models.Conversation):
            Conversations iterator.


def cpfs(self,
             state: Sequence[tf.Tensor],
             action: Sequence[tf.Tensor],
             noise: Optional[Noise] = None) -> Tuple[List[TensorFluent], List[TensorFluent]]:

        scope = self.transition_scope(state, action)
        batch_size = int(state[0].shape[0])
        interm_fluents, next_state_fluents = self.compile_cpfs(scope, batch_size, noise)
        interms = [fluent for _, fluent in interm_fluents]
        next_state = [fluent for _, fluent in next_state_fluents]
        return interms, next_state

Compiles the intermediate and next state fluent CPFs given
    the current `state` and `action`.

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

Returns:
        Tuple[List[TensorFluent], List[TensorFluent]]: A pair of lists of TensorFluent
        representing the intermediate and state CPFs.


def GetNTFSFileEntryByPathSpec(self, path_spec):

    # Opening a file by MFT entry is faster than opening a file by location.
    # However we need the index of the corresponding $FILE_NAME MFT attribute.
    location = getattr(path_spec, 'location', None)
    mft_attribute = getattr(path_spec, 'mft_attribute', None)
    mft_entry = getattr(path_spec, 'mft_entry', None)

    if mft_attribute is not None and mft_entry is not None:
      fsntfs_file_entry = self._fsntfs_volume.get_file_entry(mft_entry)
    elif location is not None:
      fsntfs_file_entry = self._fsntfs_volume.get_file_entry_by_path(location)
    else:
      raise errors.PathSpecError(
          'Path specification missing location and MFT entry.')

    return fsntfs_file_entry

Retrieves the NTFS file entry for a path specification.

Args:
        path_spec (PathSpec): a path specification.

Returns:
        pyfsntfs.file_entry: NTFS file entry.

Raises:
        PathSpecError: if the path specification is missing location and
        MFT entry.


def member_del(self, repl_id, member_id):

        repl = self[repl_id]
        result = repl.member_del(member_id)
        self[repl_id] = repl
        return result

remove member from replica set (reconfig replica)

Args:
        repl_id - replica set identity
        member_id - member index


def post_async(self, path, params=None):

        request = Post(self._get_next_id(), path, params)
        request.set_callback(self._q.put)
        future = self._dispatch_request(request)
        return future

Asynchronously calls a function on a child block

Args:
        path (list): The path to post to
        params (dict): parameters for the call

Returns:
        Future: as single Future that will resolve to the result


def AsDict(self, dt=True):

        data = {}

        if self.body:
            data['body'] = self.body
        if self.posted_at:
            data['posted_at'] = self.posted_at
        if self.user:
            data['user'] = self.user.AsDict()

        return data

A dict representation of this Comment instance.

    The return value uses the same key names as the JSON representation.

Args:
        dt (bool): If True, return dates as python datetime objects. If
        False, return dates as ISO strings.

Returns:
        A dict representing this Comment instance


def map_err(self, op: Callable[[E], F]) -> 'Union[Result[T, F], Result[T, E]]':

        return self if self._is_ok else cast(
            'Result[T, F]',
            self._type.Err(op(cast(E, self._val)))
        )

Applies a function to the contained :meth:`Result.Err` value.

Args:
        op: The function to apply to the :meth:`Result.Err` value.

Returns:
        A :class:`Result` with its error value as the function result
        if `self` is a :meth:`Result.Err` value, otherwise returns
        `self`.

Example:
        >>> Ok(1).map_err(lambda x: x * 2)
        Ok(1)
        >>> Err(1).map_err(lambda x: x * 2)
        Err(2)


def _strip_unnecessary_contents_from_stack(result, processed):

  # pylint: disable=protected-access
  if isinstance(result, (PrettyTensor, Loss)):
    if result.is_sequence():
      for tensor in result.sequence:
        _strip_unnecessary_contents_from_stack(tensor, processed)
        return
    else:
      result = result.tensor
  if hasattr(result, 'op'):
    result = result.op
  if result in processed:
    return
  else:
    processed.add(result)
  trace = []
  found = False
  for f, line_no, method, _ in result._traceback:
    if (method in ('_replace_deferred', '_construct') and
        f.endswith('pretty_tensor_class.py')):
      found = True
      continue
    trace.append((f, line_no, method, {}))
  result._traceback = trace

  # Assume that if we didn't find any PT deferred lines, then this node is
  # not part of the deferred construction.
  if not found:
    return
  for inp in result.inputs:
    _strip_unnecessary_contents_from_stack(inp, processed)

Remove the distracting lines from the stored tracebacks.

    This also reduces memory overhead by removing the frame contents. This is very
    important when doing long unrolls.

Args:
        result: The result to process.
        processed: A set of already processed nodes, used to stop early.


def deep_update(d, u):

  for k, v in u.items():
    if isinstance(v, Mapping):
      d[k] = deep_update(d.get(k, {}), v)
    elif isinstance(v, list):
      existing_elements = d.get(k, [])
      d[k] = existing_elements + [ele for ele in v if ele not in existing_elements]
    else:
      d[k] = v

  return d

Deeply updates a dictionary. List values are concatenated.

Args:
        d (dict): First dictionary which will be updated
        u (dict): Second dictionary use to extend the first one

Returns:
        dict: The merge dictionary


def indexSearch(self, indexes):

        if not self._dataFrame.empty:
            filter0 = self._dataFrame.index == -9999
            for index in indexes:
                filter1 = self._dataFrame.index == index
                filter0 = np.logical_or(filter0, filter1)

            return filter0
        else:
            return []

Filters the data by a list of indexes.

Args:
        indexes (list of int): List of index numbers to return.

Returns:
        list: A list containing all indexes with filtered data. Matches
        will be `True`, the remaining items will be `False`. If the
        dataFrame is empty, an empty list will be returned.


def BatchConvert(self, metadata_value_pairs, token=None):

    if data_store.RelationalDBEnabled():
      result_generator = self._BatchConvertRelational(metadata_value_pairs)
    else:
      result_generator = self._BatchConvertLegacy(
          metadata_value_pairs, token=token)

    for r in result_generator:
      yield r

Converts a batch of StatEntry value to ExportedFile values at once.

Args:
        metadata_value_pairs: a list or a generator of tuples (metadata, value),
        where metadata is ExportedMetadata to be used for conversion and value
        is a StatEntry to be converted.
        token: Security token:

Yields:
        Resulting ExportedFile values. Empty list is a valid result and means that
        conversion wasn't possible.