def clone_source_dir(source_dir, dest_dir):

    if os.path.isdir(dest_dir):
        print('removing', dest_dir)
        shutil.rmtree(dest_dir)
    shutil.copytree(source_dir, dest_dir)

Copies the source Protobuf files into a build directory.

Args:
        source_dir (str): source directory of the Protobuf files
        dest_dir (str): destination directory of the Protobuf files


def setMaximum(self, maximum):

        if not isinstance(maximum, int):
            raise TypeError("Argument is not of type int or long")
        self._maximum = maximum

setter to _maximum.

Args:
        maximum (int or long): new _maximum value


def predict_proba(self, L):

        # First, get the estimated probability distribution over the feasible
        # set defined by the TaskGraph
        # This is an [n,k] array, where k = |(feasible set)|
        Y_pf = LabelModel.predict_proba(self, L)
        n, k = Y_pf.shape

        # Now get the per-task marginals
        # TODO: Make this optional, versus just returning the above
        Y_p = [np.zeros((n, k_t)) for k_t in self.task_graph.K]
        for yi, y in enumerate(self.task_graph.feasible_set()):
            for t in range(self.t):
                k_t = int(y[t])
                Y_p[t][:, k_t - 1] += Y_pf[:, yi]
        return Y_p

Returns the task marginals estimated by the model: a t-length list of
    [n,k_t] matrices where the (i,j) entry of the sth matrix represents the
    estimated P((Y_i)_s | \lambda_j(x_i))

Args:
        L: A t-length list of [n,m] scipy.sparse label matrices with values
            in {0,1,...,k}


def add_backend_policy(self, json_data):

        env = boto3.session.Session(profile_name=self.env, region_name=self.region)
        elbclient = env.client('elb')

        # Attach backend server policies to created ELB
        for job in json.loads(json_data)['job']:
            for listener in job['listeners']:
                instance_port = listener['internalPort']
                backend_policy_list = listener['backendPolicies']
                if backend_policy_list:
                    LOG.info('Adding backend server policies: %s', backend_policy_list)
                    elbclient.set_load_balancer_policies_for_backend_server(
                        LoadBalancerName=self.app, InstancePort=instance_port, PolicyNames=backend_policy_list)

Attaches backend server policies to an ELB

Args:
        json_data (json): return data from ELB upsert


def decompress_file(filepath):

    toks = filepath.split(".")
    file_ext = toks[-1].upper()
    from monty.io import zopen
    if file_ext in ["BZ2", "GZ", "Z"]:
        with open(".".join(toks[0:-1]), 'wb') as f_out, \
                zopen(filepath, 'rb') as f_in:
            f_out.writelines(f_in)
        os.remove(filepath)

Decompresses a file with the correct extension. Automatically detects
    gz, bz2 or z extension.

Args:
        filepath (str): Path to file.
        compression (str): A compression mode. Valid options are "gz" or
            "bz2". Defaults to "gz".


def title_of_design_condition(self, value=None):

        if value is not None:
            try:
                value = str(value)
            except ValueError:
                raise ValueError(
                    'value {} need to be of type str '
                    'for field `title_of_design_condition`'.format(value))
            if ',' in value:
                raise ValueError('value should not contain a comma '
                                 'for field `title_of_design_condition`')

        self._title_of_design_condition = value

Corresponds to IDD Field `title_of_design_condition`

Args:
        value (str): value for IDD Field `title_of_design_condition`
            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 __init__(self, process: Process):

        self.process = process
        self.stopped_due_to_worker_shutdown = False

Constructor.

Args:
        process (Process): task process


def complete(command_line,
             current_token,
             position,
             shell: arg(choices=('bash', 'fish'))):

    position = int(position)
    tokens = shlex.split(command_line[:position])

    all_argv, run_argv, command_argv = run.partition_argv(tokens[1:])
    run_args = run.parse_args(run_argv)

    module = run_args.get('commands_module')
    module = module or DEFAULT_COMMANDS_MODULE
    module = normalize_path(module)

    try:
        collection = Collection.load_from_module(module)
    except Exception:
        collection = {}

    found_command = find_command(collection, tokens) or run

    if current_token:
        # Completing either a command name, option name, or path.
        if current_token.startswith('-'):
            if current_token not in found_command.option_map:
                print_command_options(found_command, current_token)
        else:
            print_commands(collection, shell)
            path = os.path.expanduser(current_token)
            path = os.path.expandvars(path)
            paths = glob.glob('%s*' % path)
            if paths:
                for entry in paths:
                    if os.path.isdir(entry):
                        print('%s/' % entry)
                    else:
                        print(entry)
    else:
        # Completing option value. If a value isn't expected, show the
        # options for the current command and the list of commands
        # instead.
        option = found_command.option_map.get(tokens[-1])

        if option and option.takes_value:
            if option.choices:
                for choice in option.choices:
                    print(choice)
            else:
                for entry in os.listdir():
                    if os.path.isdir(entry):
                        print('%s/' % entry)
                    else:
                        print(entry)
        else:
            print_command_options(found_command)
            print_commands(collection, shell)

Find completions for current command.

    This assumes that we'll handle all completion logic here and that
    the shell's automatic file name completion is disabled.

Args:
        command_line: Command line
        current_token: Token at cursor
        position: Current cursor position
        shell: Name of shell


def fastcc_is_consistent(model, epsilon, solver):

    for reaction in fastcc(model, epsilon, solver):
        return False
    return True

Quickly check whether model is consistent

    Return true if the model is consistent. If it is only necessary to know
    whether a model is consistent, this function is fast as it will return
    the result as soon as it finds a single inconsistent reaction.

Args:
        model: :class:`MetabolicModel` to solve.
        epsilon: Flux threshold value.
        solver: LP solver instance to use.


def EnablePlugins(self, plugin_includes):

    super(SyslogParser, self).EnablePlugins(plugin_includes)

    self._plugin_by_reporter = {}
    for plugin in self._plugins:
      self._plugin_by_reporter[plugin.REPORTER] = plugin

Enables parser plugins.

Args:
        plugin_includes (list[str]): names of the plugins to enable, where None
        or an empty list represents all plugins. Note that the default plugin
        is handled separately.


def in_cache(self, objpath, metahash):

        try:
            self.path_in_cache(objpath, metahash)
            return True
        except CacheMiss:
            return False

Returns true if object is cached.

Args:
        objpath: Filename relative to buildroot.
        metahash: hash object


def fit_size_distribution_models(self, model_names, model_objs, input_columns,
                                     output_columns=None, calibrate=False):

        if output_columns is None:
            output_columns = ["Shape", "Location", "Scale"]
        groups = np.unique(self.data["train"]["member"][self.group_col])

        weights=None

        for group in groups:
            group_data = self.data["train"]["combo"].loc[self.data["train"]["combo"][self.group_col] == group]
            group_data = group_data.dropna()
            group_data = group_data[group_data[output_columns[-1]] > 0]
            if self.sector:

                lon_obj = group_data.loc[:,'Centroid_Lon']
                lat_obj = group_data.loc[:,'Centroid_Lat']

                conus_lat_lon_points = zip(lon_obj.values.ravel(),lat_obj.values.ravel())
                center_lon, center_lat = self.proj_dict["lon_0"],self.proj_dict["lat_0"]

                distances = np.array([np.sqrt((x-center_lon)**2+\
                        (y-center_lat)**2) for (x, y) in conus_lat_lon_points])

                min_dist, max_minus_min = min(distances),max(distances)-min(distances)

                distance_0_1 = [1.0-((d - min_dist)/(max_minus_min)) for d in distances]
                weights = np.array(distance_0_1)

            self.size_distribution_models[group] = {"multi": {}, "lognorm": {}}
            if calibrate:
                self.size_distribution_models[group]["calshape"] = {}
                self.size_distribution_models[group]["calscale"] = {}
            log_labels = np.log(group_data[output_columns].values)
            log_means = log_labels.mean(axis=0)
            log_sds = log_labels.std(axis=0)
            self.size_distribution_models[group]['lognorm']['mean'] = log_means
            self.size_distribution_models[group]['lognorm']['sd'] = log_sds
            for m, model_name in enumerate(model_names):
                print(group, model_name)
                self.size_distribution_models[group]["multi"][model_name] = deepcopy(model_objs[m])
                try:
                    self.size_distribution_models[group]["multi"][model_name].fit(group_data[input_columns],
                                                                              (log_labels - log_means) / log_sds,
                                                                        sample_weight=weights)
                except:
                    self.size_distribution_models[group]["multi"][model_name].fit(group_data[input_columns],
                                                                              (log_labels - log_means) / log_sds)
                if calibrate:
                    training_predictions = self.size_distribution_models[
                        group]["multi"][model_name].predict(group_data[input_columns])
                    self.size_distribution_models[group]["calshape"][model_name] = LinearRegression()
                    self.size_distribution_models[group]["calshape"][model_name].fit(training_predictions[:, 0:1],
                                                                                (log_labels[:, 0] - log_means[0]) /
                                                                                log_sds[
                                                                                0],
                                                                                sample_weight=weights)
                    self.size_distribution_models[group]["calscale"][model_name] = LinearRegression()
                    self.size_distribution_models[group]["calscale"][model_name].fit(training_predictions[:, 1:],
                                                                                (log_labels[:, 1] - log_means[1]) /
                                                                                log_sds[
                                                                                1],
                                                                            sample_weight=weights)

Fits multitask machine learning models to predict the parameters of a size distribution

Args:
        model_names: List of machine learning model names
        model_objs: scikit-learn style machine learning model objects
        input_columns: Training data columns used as input for ML model
        output_columns: Training data columns used for prediction
        calibrate: Whether or not to fit a log-linear regression to predictions from ML model


def get_template(template):

    from cloud_inquisitor.database import db

    tmpl = db.Template.find_one(template_name=template)
    if not tmpl:
        raise InquisitorError('No such template found: {}'.format(template))

    tmplenv = Environment(loader=BaseLoader, autoescape=True)
    tmplenv.filters['json_loads'] = json.loads
    tmplenv.filters['slack_quote_join'] = lambda data: ', '.join('`{}`'.format(x) for x in data)

    return tmplenv.from_string(tmpl.template)

Return a Jinja2 template by filename

Args:
        template (str): Name of the template to return

Returns:
        A Jinja2 Template object


def get_response(response: Dict[str, Any]) -> JSONRPCResponse:

    if "error" in response:
        return ErrorResponse(**response)
    return SuccessResponse(**response)

Converts a deserialized response into a JSONRPCResponse object.

    The dictionary be either an error or success response, never a notification.

Args:
        response: Deserialized response dictionary. We can assume the response is valid
            JSON-RPC here, since it passed the jsonschema validation.


def resize(self, container, height, width):

        params = {'h': height, 'w': width}
        url = self._url("/containers/{0}/resize", container)
        res = self._post(url, params=params)
        self._raise_for_status(res)

Resize the tty session.

Args:
        container (str or dict): The container to resize
        height (int): Height of tty session
        width (int): Width of tty session

Raises:
        :py:class:`docker.errors.APIError`
            If the server returns an error.


def read(self, path):

        with open(path, "r") as f:
            for line in f:
                line = line.strip()
                match_obj_name = re.search(r"^([A-Z][A-Z/ \d]+),", line)
                if match_obj_name is not None:
                    internal_name = match_obj_name.group(1)
                    if internal_name in self._data:
                        self._data[internal_name] = self._create_datadict(
                            internal_name)
                        data_line = line[len(internal_name) + 1:]
                        vals = data_line.strip().split(',')
                        self._data[internal_name].read(vals)
                else:
                    wd = WeatherData()
                    wd.read(line.strip().split(','))
                    self.add_weatherdata(wd)

Read EPW weather data from path.

Args:
        path (str): path to read weather data from


def _validate_instantiation_options(self, datafile, skip_json_validation):

    if not skip_json_validation and not validator.is_datafile_valid(datafile):
      raise exceptions.InvalidInputException(enums.Errors.INVALID_INPUT_ERROR.format('datafile'))

    if not validator.is_event_dispatcher_valid(self.event_dispatcher):
      raise exceptions.InvalidInputException(enums.Errors.INVALID_INPUT_ERROR.format('event_dispatcher'))

    if not validator.is_logger_valid(self.logger):
      raise exceptions.InvalidInputException(enums.Errors.INVALID_INPUT_ERROR.format('logger'))

    if not validator.is_error_handler_valid(self.error_handler):
      raise exceptions.InvalidInputException(enums.Errors.INVALID_INPUT_ERROR.format('error_handler'))

Helper method to validate all instantiation parameters.

Args:
        datafile: JSON string representing the project.
        skip_json_validation: Boolean representing whether JSON schema validation needs to be skipped or not.

Raises:
        Exception if provided instantiation options are valid.


def convert(self, vroot, entry_variables):

        self.graph_info = GraphInfo(vroot)
        self.entry_variables = entry_variables

        with nn.parameter_scope(self.name):
            # Function loop in the forward order
            for func in self.graph_info.funcs:
                o = self._identity_conversion(func)
            self.end_variable = o
        return self.end_variable

All functions are replaced with the same `new` function.

Args:
        vroot (:obj:`Variable`): NNabla Variable
        entry_variables (:obj:`Variable`): Entry variable from which the conversion starts.


def destroy_sg(app='', env='', region='', **_):

    vpc = get_vpc_id(account=env, region=region)

    url = '{api}/securityGroups/{env}/{region}/{app}'.format(api=API_URL, env=env, region=region, app=app)
    payload = {'vpcId': vpc}
    security_group = requests.get(url, params=payload, verify=GATE_CA_BUNDLE, cert=GATE_CLIENT_CERT)

    if not security_group:
        LOG.info('Nothing to delete.')
    else:
        LOG.info('Found Security Group in %(region)s: %(name)s', security_group)

        destroy_request = get_template('destroy/destroy_sg.json.j2', app=app, env=env, region=region, vpc=vpc)
        wait_for_task(destroy_request)

    return True

Destroy Security Group.

Args:
        app (str): Spinnaker Application name.
        env (str): Deployment environment.
        region (str): Region name, e.g. us-east-1.

Returns:
        True upon successful completion.


def ParseFileObject(self, parser_mediator, file_object):

    if not self.LINE_STRUCTURES:
      raise errors.UnableToParseFile('Missing line structures.')

    encoding = self._ENCODING or parser_mediator.codepage
    text_reader = EncodedTextReader(
        encoding, buffer_size=self.BUFFER_SIZE)

    text_reader.Reset()

    try:
      text_reader.ReadLines(file_object)
    except UnicodeDecodeError as exception:
      raise errors.UnableToParseFile(
          'Not a text file, with error: {0!s}'.format(exception))

    if not self.VerifyStructure(parser_mediator, text_reader.lines):
      raise errors.UnableToParseFile('Wrong file structure.')

    # Using parseWithTabs() overrides Pyparsing's default replacement of tabs
    # with spaces to SkipAhead() the correct number of bytes after a match.
    for key, structure in self.LINE_STRUCTURES:
      structure.parseWithTabs()

    consecutive_line_failures = 0
    # Read every line in the text file.
    while text_reader.lines:
      if parser_mediator.abort:
        break

      # Initialize pyparsing objects.
      tokens = None
      start = 0
      end = 0

      key = None

      index = None

      # Try to parse the line using all the line structures.
      for index, (key, structure) in enumerate(self._line_structures):
        try:
          structure_generator = structure.scanString(
              text_reader.lines, maxMatches=1)
          parsed_structure = next(structure_generator, None)
        except pyparsing.ParseException:
          parsed_structure = None

        if not parsed_structure:
          continue

        tokens, start, end = parsed_structure

        # Only want to parse the structure if it starts
        # at the beginning of the buffer.
        if start == 0:
          break

      if tokens and start == 0:
        # Move matching key, structure pair to the front of the list, so that
        # structures that are more likely to match are tried first.
        if index is not None and index != 0:
          key_structure = self._line_structures.pop(index)
          self._line_structures.insert(0, key_structure)

        try:
          self.ParseRecord(parser_mediator, key, tokens)
          consecutive_line_failures = 0
        except (errors.ParseError, errors.TimestampError) as exception:
          parser_mediator.ProduceExtractionWarning(
              'unable to parse record: {0:s} with error: {1!s}'.format(
                  key, exception))

        text_reader.SkipAhead(file_object, end)

      else:
        odd_line = text_reader.ReadLine(file_object)
        if odd_line:
          if len(odd_line) > 80:
            odd_line = '{0:s}...'.format(odd_line[:77])
          parser_mediator.ProduceExtractionWarning(
              'unable to parse log line: {0:s}'.format(repr(odd_line)))
          consecutive_line_failures += 1
          if (consecutive_line_failures >
              self.MAXIMUM_CONSECUTIVE_LINE_FAILURES):
            raise errors.UnableToParseFile(
                'more than {0:d} consecutive failures to parse lines.'.format(
                    self.MAXIMUM_CONSECUTIVE_LINE_FAILURES))
      try:
        text_reader.ReadLines(file_object)
      except UnicodeDecodeError as exception:
        parser_mediator.ProduceExtractionWarning(
            'unable to read lines with error: {0!s}'.format(exception))

Parses a text file-like object using a pyparsing definition.

Args:
        parser_mediator (ParserMediator): mediates interactions between parsers
        and other components, such as storage and dfvfs.
        file_object (dfvfs.FileIO): file-like object.

Raises:
        UnableToParseFile: when the file cannot be parsed.


def __init__(self,
                 entries: Iterable[Tuple[int, TItem]] = (),
                 *,
                 drop_duplicate_entries: bool=False):

        self._buckets = []  # type: List[List[TItem]]
        self._offset = 0
        self._len = 0
        self._drop_set = (set()
                          if drop_duplicate_entries
                          else None)  # type: Optional[Set[Tuple[int, TItem]]]

        for p, e in entries:
            self.enqueue(p, e)

Initializes a new priority queue.

Args:
        entries: Initial contents of the priority queue.
        drop_duplicate_entries: If set, the priority queue will ignore
            operations that enqueue a (priority, item) pair that is already
            in the priority queue. Note that duplicates of an item may still
            be enqueued, as long as they have different priorities.


def export(self, top=True):

        out = []
        if top:
            out.append(self._internal_name)
        out.append(self._to_str(self.number_of_records_per_hour))
        out.append(self._to_str(self.data_period_name_or_description))
        out.append(self._to_str(self.data_period_start_day_of_week))
        out.append(self._to_str(self.data_period_start_day))
        out.append(self._to_str(self.data_period_end_day))
        return ",".join(out)

Exports object to its string representation.

Args:
        top (bool):  if True appends `internal_name` before values.
            All non list objects should be exported with value top=True,
            all list objects, that are embedded in as fields inlist objects
            should be exported with `top`=False

Returns:
        str: The objects string representation


def tuplize(nested):

  if isinstance(nested, str):
    return nested
  try:
    return tuple(map(tuplize, nested))
  except TypeError:
    return nested

Recursively converts iterables into tuples.

Args:
        nested: A nested structure of items and iterables.

Returns:
        A nested structure of items and tuples.


def _build_projection_expression(clean_table_keys):

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

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

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

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


def append(self, text, afterline=None):

        if afterline:
            self._vim.current.buffer.append(text, afterline)
        else:
            self._vim.current.buffer.append(text)

Append text to the current buffer.

Args:
        text (str or Sequence[str]): One or many lines of text to append.
        afterline (Optional[int]):
            Line number to append after. If 0, text is prepended before the
            first line; if ``None``, at end of the buffer.


def has_extana(self, cached=True):

        if cached and self.hardware != -1:
            return True if (self.hardware & EXT_HW_EXTANA) else False

        result = self._check_hardware()
        return True if (result & EXT_HW_EXTANA) != 0 else False

Can be used to check if an SK8-ExtAna device is currently connected.
    NOTE: do not attempt to call while data streaming is active!

Args:
    cached (bool): if True, use the cached value of the connected hardware
        state rather than querying the device. Set to False to force a query.

Returns:
    bool. True if the SK8 currently has an SK8-ExtAna device attached, False otherwise.


def add_implem(self, transition, attribute, function, **kwargs):

        implem = ImplementationProperty(
            field_name=self.state_field,
            transition=transition,
            workflow=self.workflow,
            implementation=function,
            **kwargs)
        self.implementations[transition.name] = implem
        self.transitions_at[transition.name] = attribute
        return implem

Add an implementation.

Args:
        transition (Transition): the transition for which the implementation
            is added
        attribute (str): the name of the attribute where the implementation
            will be available
        function (callable): the actual implementation function
        **kwargs: extra arguments for the related ImplementationProperty.


def __call__(self, product):

        reviewers = self.reviewers(product)
        Nq = len(reviewers)

        if Nq == 1:
            return 0.5

        else:
            # Computing the unbiased variance of scores.
            var = np.var([self.review_score(r, product)
                          for r in reviewers], ddof=1)
            return np.log(Nq) / (var + 1)

Compute credibility of a given product.

Args:
        product: An instance of :class:`bipartite.Product`.

Returns:
        The credibility of the product. It is >= 0.5.


def unique(self, token_list_x, token_list_y):

        x = set(list(token_list_x))
        y = set(list(token_list_y))
        return (x, y)

Remove duplicated elements.

Args:
        token_list_x:    [token, token, token, ...]
        token_list_y:    [token, token, token, ...]

Returns:
        Tuple(token_list_x, token_list_y)


def limitReal(x, max_denominator=1000000):

    f = Fraction(x).limit_denominator(max_denominator)
    return Real((f.numerator, f.denominator))

Creates an pysmt Real constant from x.

Args:
        x (number): A number to be cast to a pysmt constant.
        max_denominator (int, optional): The maximum size of the denominator.
            Default 1000000.

Returns:
        A Real constant with the given value and the denominator limited.


def _ParseShellItem(self, parser_mediator, shell_item):

    path_segment = self._ParseShellItemPathSegment(shell_item)
    self._path_segments.append(path_segment)

    event_data = shell_item_events.ShellItemFileEntryEventData()
    event_data.origin = self._origin
    event_data.shell_item_path = self.CopyToPath()

    if isinstance(shell_item, pyfwsi.file_entry):
      event_data.name = shell_item.name

      for extension_block in shell_item.extension_blocks:
        if isinstance(extension_block, pyfwsi.file_entry_extension):
          long_name = extension_block.long_name
          localized_name = extension_block.localized_name
          file_reference = extension_block.file_reference
          if file_reference:
            file_reference = '{0:d}-{1:d}'.format(
                file_reference & 0xffffffffffff, file_reference >> 48)

          event_data.file_reference = file_reference
          event_data.localized_name = localized_name
          event_data.long_name = long_name

          fat_date_time = extension_block.get_creation_time_as_integer()
          if fat_date_time != 0:
            date_time = dfdatetime_fat_date_time.FATDateTime(
                fat_date_time=fat_date_time)
            event = time_events.DateTimeValuesEvent(
                date_time, definitions.TIME_DESCRIPTION_CREATION)
            parser_mediator.ProduceEventWithEventData(event, event_data)

          fat_date_time = extension_block.get_access_time_as_integer()
          if fat_date_time != 0:
            date_time = dfdatetime_fat_date_time.FATDateTime(
                fat_date_time=fat_date_time)
            event = time_events.DateTimeValuesEvent(
                date_time, definitions.TIME_DESCRIPTION_LAST_ACCESS)
            parser_mediator.ProduceEventWithEventData(event, event_data)

      fat_date_time = shell_item.get_modification_time_as_integer()
      if fat_date_time != 0:
        date_time = dfdatetime_fat_date_time.FATDateTime(
            fat_date_time=fat_date_time)
        event = time_events.DateTimeValuesEvent(
            date_time, definitions.TIME_DESCRIPTION_MODIFICATION)
        parser_mediator.ProduceEventWithEventData(event, event_data)

Parses a shell item.

Args:
        parser_mediator (ParserMediator): mediates interactions between parsers
        and other components, such as storage and dfvfs.
        shell_item (pyfwsi.item): shell item.


def resolve_one_of(tags, at_least_one):

    if len(tags) < len(at_least_one):
        return None
    for possible_resolution in choose_1_from_each(at_least_one):
        resolution = {}
        pr = possible_resolution[:]
        for entity_type in pr:
            last_end_index = -1
            if entity_type in resolution:
                last_end_index = resolution.get[entity_type][-1].get('end_token')
            tag, value, c = find_first_tag(tags, entity_type, after_index=last_end_index)
            if not tag:
                break
            else:
                if entity_type not in resolution:
                    resolution[entity_type] = []
                resolution[entity_type].append(tag)
        if len(resolution) == len(possible_resolution):
            return resolution

    return None

This searches tags for Entites in at_least_one and returns any match

Args:
        tags(list): List of tags with Entities to search for Entities
        at_least_one(list): List of Entities to find in tags

Returns:
        object: returns None if no match is found but returns any match as an object


def FoldValue(self, value):

    if value is False and self._data_type_definition.false_value is not None:
      return self._data_type_definition.false_value

    if value is True and self._data_type_definition.true_value is not None:
      return self._data_type_definition.true_value

    raise ValueError('No matching True and False values')

Folds the data type into a value.

Args:
        value (object): value.

Returns:
        object: folded value.

Raises:
        ValueError: if the data type definition cannot be folded into the value.


def newPacker(mode=PackingMode.Offline,
         bin_algo=PackingBin.BBF,
        pack_algo=MaxRectsBssf,
        sort_algo=SORT_AREA,
        rotation=True):

    packer_class = None

    # Online Mode
    if mode == PackingMode.Online:
        sort_algo=None
        if bin_algo == PackingBin.BNF:
            packer_class = PackerOnlineBNF
        elif bin_algo == PackingBin.BFF:
            packer_class = PackerOnlineBFF
        elif bin_algo == PackingBin.BBF:
            packer_class = PackerOnlineBBF
        else:
            raise AttributeError("Unsupported bin selection heuristic")

    # Offline Mode
    elif mode == PackingMode.Offline:
        if bin_algo == PackingBin.BNF:
            packer_class = PackerBNF
        elif bin_algo == PackingBin.BFF:
            packer_class = PackerBFF
        elif bin_algo == PackingBin.BBF:
            packer_class = PackerBBF
        elif bin_algo == PackingBin.Global:
            packer_class = PackerGlobal
            sort_algo=None
        else:
            raise AttributeError("Unsupported bin selection heuristic")

    else:
        raise AttributeError("Unknown packing mode.")

    if sort_algo:
        return packer_class(pack_algo=pack_algo, sort_algo=sort_algo,
            rotation=rotation)
    else:
        return packer_class(pack_algo=pack_algo, rotation=rotation)

Packer factory helper function

Args:
        mode (PackingMode): Packing mode
            Online: Rectangles are packed as soon are they are added
            Offline: Rectangles aren't packed untils pack() is called
        bin_algo (PackingBin): Bin selection heuristic
        pack_algo (PackingAlgorithm): Algorithm used
        rotation (boolean): Enable or disable rectangle rotation.

Returns:
        Packer: Initialized packer instance.


def rewards_to_go(rewards, mask, gamma=0.99):
  r
  B, T = rewards.shape  # pylint: disable=invalid-name,unused-variable

  masked_rewards = rewards * mask  # (B, T)

  # We use the following recurrence relation, derived from the equation above:
  #
  # r2g[t+1] = (r2g[t] - r[t]) / gamma
  #
  # This means we'll need to calculate r2g[0] first and then r2g[1] and so on ..
  #
  # **However** this leads to overflows for long sequences: r2g[t] - r[t] > 0
  # and gamma < 1.0, so the division keeps increasing.
  #
  # So we just run the recurrence in reverse, i.e.
  #
  # r2g[t] = r[t] + (gamma*r2g[t+1])
  #
  # This is much better, but might have lost updates since the (small) rewards
  # at earlier time-steps may get added to a (very?) large sum.

  # Compute r2g_{T-1} at the start and then compute backwards in time.
  r2gs = [masked_rewards[:, -1]]

  # Go from T-2 down to 0.
  for t in reversed(range(T - 1)):
    r2gs.append(masked_rewards[:, t] + (gamma * r2gs[-1]))

  # The list should have length T.
  assert T == len(r2gs)

  # First we stack them in the correct way to make it (B, T), but these are
  # still from newest (T-1) to oldest (0), so then we flip it on time axis.
  return np.flip(np.stack(r2gs, axis=1), axis=1)

r"""Computes rewards to go.

    Reward to go is defined as follows, the discounted reward that we have to
    yet collect, going forward from this point, i.e.:

    r2g_t = \sum_{l=0}^{\infty} (\gamma^{l} * reward_{t+l})

Args:
        rewards: np.ndarray of shape (B, T) of rewards.
        mask: np.ndarray of shape (B, T) of mask for the rewards.
        gamma: float, discount factor.

Returns:
        rewards to go, np.ndarray of shape (B, T).


def _QueryHash(self, digest):

    if not self._url:
      self._url = '{0:s}://{1:s}:{2:d}/file/find'.format(
          self._protocol, self._host, self._port)

    request_data = {self.lookup_hash: digest}

    try:
      json_response = self.MakeRequestAndDecodeJSON(
          self._url, 'POST', data=request_data)

    except errors.ConnectionError as exception:
      json_response = None
      logger.error('Unable to query Viper with error: {0!s}.'.format(
          exception))

    return json_response

Queries the Viper Server for a specfic hash.

Args:
        digest (str): hash to look up.

Returns:
        dict[str, object]: JSON response or None on error.


def merge(self, workdir, pot_files, out_dvdb, delete_source=True):

        # We work with absolute paths.
        pot_files = [os.path.abspath(s) for s in list_strings(pot_files)]
        if not os.path.isabs(out_dvdb):
            out_dvdb = os.path.join(os.path.abspath(workdir), os.path.basename(out_dvdb))

        if self.verbose:
            print("Will merge %d files into output DVDB %s" % (len(pot_files), out_dvdb))
            for i, f in enumerate(pot_files):
                print(" [%d] %s" % (i, f))

        # Handle the case of a single file since mrgddb uses 1 to denote GS files!
        if len(pot_files) == 1:
            with open(pot_files[0], "r") as inh, open(out_dvdb, "w") as out:
                for line in inh:
                    out.write(line)
            return out_dvdb

        self.stdin_fname, self.stdout_fname, self.stderr_fname = \
            map(os.path.join, 3 * [os.path.abspath(workdir)], ["mrgdvdb.stdin", "mrgdvdb.stdout", "mrgdvdb.stderr"])

        inp = StringIO()
        inp.write(out_dvdb + "\n")             # Name of the output file.
        inp.write(str(len(pot_files)) + "\n")  # Number of input POT files.

        # Names of the POT files.
        for fname in pot_files:
            inp.write(fname + "\n")

        self.stdin_data = [s for s in inp.getvalue()]

        with open(self.stdin_fname, "wt") as fh:
            fh.writelines(self.stdin_data)
            # Force OS to write data to disk.
            fh.flush()
            os.fsync(fh.fileno())

        retcode = self.execute(workdir)
        if retcode == 0 and delete_source:
            # Remove pot files.
            for f in pot_files:
                try:
                    os.remove(f)
                except IOError:
                    pass

        return out_dvdb

Merge POT files containing 1st order DFPT potential
    return the absolute path of the new database in workdir.

Args:
        delete_source: True if POT1 files should be removed after (successful) merge.


def __init__(self,
                 description=None,
                 **kwargs):

        super(DisplayAlarm, self).__init__(**kwargs)
        self.description = description

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

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

Args:
        description (string) : RFC5545 DESCRIPTION property
        kwargs (dict) : Args to :func:`ics.alarm.Alarm.__init__`


def parse_raw_fact(raw_fact):

    def at_split(string):

        result = string.split('@', 1)
        length = len(result)
        if length == 1:
            front, back = result[0].strip(), None
        else:
            front, back = result
            front, back = front.strip(), back.strip()
        return (front, back)

    def comma_split(string):

        result = string.split(',', 1)
        length = len(result)
        if length == 1:
            category, description = result[0].strip(), None
        else:
            category, description = tuple(result)
            category, description = category.strip(), description.strip()
        return (category.strip(), description)

    time_info, rest = time_helpers.extract_time_info(raw_fact)
    activity_name, back = at_split(rest)

    if back:
        category_name, description = comma_split(back)
    else:
        category_name, description = None, None

    return {
        'timeinfo': time_info,
        'category': category_name,
        'activity': activity_name,
        'description': description,
    }

Extract semantically meaningful sub-components from a ``raw fact`` text.

Args:
        raw_fact (text_type): ``raw fact`` text to be parsed.

Returns:
        dict: dict with sub-components as values.


def __init__(self, window, root):

        self.root = root
        self.selenium = window.selenium
        self.wait = window.wait
        self.window = window

Create a Region object.

Args:
        window (:py:class:`BaseWindow`): Window object this region appears
            in.
        root
            (:py:class:`~selenium.webdriver.remote.webelement.WebElement`):
            WebDriver element object that serves as the root for the
            region.


def glyph_has_ink(font: TTFont, name: Text) -> bool:

  if 'glyf' in font:
    return ttf_glyph_has_ink(font, name)
  elif ('CFF ' in font) or ('CFF2' in font):
    return cff_glyph_has_ink(font, name)
  else:
    raise Exception("Could not find 'glyf', 'CFF ', or 'CFF2' table.")

Checks if specified glyph has any ink.

    That is, that it has at least one defined contour associated.
    Composites are considered to have ink if any of their components have ink.

Args:
        font:       the font
        glyph_name: The name of the glyph to check for ink.

Returns:
        True if the font has at least one contour associated with it.


def Relay(self, inventory):

        inventory = InvPayload(type=inventory.InventoryType, hashes=[inventory.Hash.ToBytes()])
        m = Message("inv", inventory)
        self.SendSerializedMessage(m)

        return True

Wrap the inventory in a InvPayload object and send it over the write to the remote node.

Args:
        inventory:

Returns:
        bool: True (fixed)


def get(self, status_item):

        lg = logging.getLogger("%s.%s" % (self.ln, inspect.stack()[0][3]))
        lg.setLevel(self.log_level)

        sparql =
        value = self.conn.query(sparql=sparql.format(self.group, status_item))
        if len(value) > 0 and \
                cbool(value[0].get('loaded',{}).get("value",False)):
            return True
        else:
            return False

queries the database and returns that status of the item.

Args:
        status_item: the name of the item to check


def check_panels(adapter, panels, default_panels=None):

    default_panels = default_panels or []
    panels_exist = True
    for panel in default_panels:
        if panel not in panels:
            log.warning("Default panels have to be defined in panels")
            panels_exist = False
    for panel in panels:
        if not adapter.gene_panel(panel):
            log.warning("Panel {} does not exist in database".format(panel))
            panels_exist = False
    return panels_exist

Make sure that the gene panels exist in the database
    Also check if the default panels are defined in gene panels

Args:
        adapter(MongoAdapter)
        panels(list(str)): A list with panel names

Returns:
        panels_exists(bool)


def are_equal(self, sp1, sp2):

        comp1 = Composition(sp1)
        comp2 = Composition(sp2)
        return comp1.get_el_amt_dict() == comp2.get_el_amt_dict()

True if element:amounts are exactly the same, i.e.,
    oxidation state is not considered.

Args:
        sp1: First species. A dict of {specie/element: amt} as per the
            definition in Site and PeriodicSite.
        sp2: Second species. A dict of {specie/element: amt} as per the
            definition in Site and PeriodicSite.

Returns:
        Boolean indicating whether species are the same based on element
        and amounts.


def key_for_namespace(cls, namespace):

    if namespace:
      return model.Key(cls.KIND_NAME, namespace)
    else:
      return model.Key(cls.KIND_NAME, cls.EMPTY_NAMESPACE_ID)

Return the Key for a namespace.

Args:
        namespace: A string giving the namespace whose key is requested.

Returns:
        The Key for the namespace.


def _create_min_max_boundaries(
    max_length, min_boundary=_MIN_BOUNDARY, boundary_scale=_BOUNDARY_SCALE):

  # Create bucket boundaries list by scaling the previous boundary or adding 1
  # (to ensure increasing boundary sizes).
  bucket_boundaries = []
  x = min_boundary
  while x < max_length:
    bucket_boundaries.append(x)
    x = max(x + 1, int(x * boundary_scale))

  # Create min and max boundary lists from the initial list.
  buckets_min = [0] + bucket_boundaries
  buckets_max = bucket_boundaries + [max_length + 1]
  return buckets_min, buckets_max

Create min and max boundary lists up to max_length.

    For example, when max_length=24, min_boundary=4 and boundary_scale=2, the
    returned values will be:
        buckets_min = [0, 4, 8, 16, 24]
        buckets_max = [4, 8, 16, 24, 25]

Args:
        max_length: The maximum length of example in dataset.
        min_boundary: Minimum length in boundary.
        boundary_scale: Amount to scale consecutive boundaries in the list.

Returns:
        min and max boundary lists


def _ParsePropertiesXMLFile(self, xml_data):

    xml_root = ElementTree.fromstring(xml_data)

    properties = {}
    for xml_element in xml_root.iter():
      if not xml_element.text:
        continue

      # The property name is formatted as: {URL}name
      # For example: {http://purl.org/dc/terms/}modified
      _, _, name = xml_element.tag.partition('}')

      # Do not including the 'lpstr' attribute because it is very verbose.
      if name == 'lpstr':
        continue

      property_name = self._PROPERTY_NAMES.get(name, None)
      if not property_name:
        property_name = self._FormatPropertyName(name)

      properties[property_name] = xml_element.text

    return properties

Parses a properties XML file.

Args:
        xml_data (bytes): data of a _rels/.rels XML file.

Returns:
        dict[str, object]: properties.

Raises:
        zipfile.BadZipfile: if the properties XML file cannot be read.


def download_uniprot_file(uniprot_id, filetype, outdir='', force_rerun=False):

    my_file = '{}.{}'.format(uniprot_id, filetype)
    url = 'http://www.uniprot.org/uniprot/{}'.format(my_file)
    outfile = op.join(outdir, my_file)

    if ssbio.utils.force_rerun(flag=force_rerun, outfile=outfile):
        urlretrieve(url, outfile)

    return outfile

Download a UniProt file for a UniProt ID/ACC

Args:
        uniprot_id: Valid UniProt ID
        filetype: txt, fasta, xml, rdf, or gff
        outdir: Directory to download the file

Returns:
        str: Absolute path to file


def load(path):

    importpath = path.replace("/", ".").replace("\\", ".")
    if importpath[-3:] == ".py":
        importpath = importpath[:-3]

    try:
        importlib.import_module(importpath)
    except (ModuleNotFoundError, TypeError):
        exec(open(path).read())

Helper function that tries to load a filepath (or python module notation)
    as a python module and on failure `exec` it.

Args:
        path (str): Path or module to load

    The function tries to import `example.module` when either `example.module`,
    `example/module` or `example/module.py` is given.


def draw_layer(ax, layer):

    ax.set_aspect('equal', 'datalim')
    ax.plot(*layer)
    ax.axis('off')

Draws a layer on the given matplotlib axis.

Args:
        ax (axis): the matplotlib axis to draw on
        layer (layer): the layers to plot


def Process(self, parser_mediator, root_item=None, **kwargs):

    # This will raise if unhandled keyword arguments are passed.
    super(DefaultOLECFPlugin, self).Process(parser_mediator, **kwargs)

    if not root_item:
      raise ValueError('Root item not set.')

    if not self._ParseItem(parser_mediator, root_item):
      event_data = OLECFItemEventData()
      event_data.name = root_item.name
      event_data.offset = 0
      event_data.size = root_item.size

      # If no event was produced, produce at least one for the root item.
      date_time = dfdatetime_semantic_time.SemanticTime('Not set')
      event = time_events.DateTimeValuesEvent(
          date_time, definitions.TIME_DESCRIPTION_CREATION)
      parser_mediator.ProduceEventWithEventData(event, event_data)

Parses an OLECF file.

Args:
        parser_mediator (ParserMediator): mediates interactions between parsers
        and other components, such as storage and dfvfs.
        root_item (Optional[pyolecf.item]): root item of the OLECF file.

Raises:
        ValueError: If the root item is not set.


def reset(self, blocking=True):

    promise = self.call('reset')
    if blocking:
      return promise()
    else:
      return promise

Reset the environment.

Args:
        blocking: Whether to wait for the result.

Returns:
        New observation when blocking, otherwise callable that returns the new
        observation.


def extract_keywords_from_text(index_page, no_items=5):

    index_page = MLStripper.strip_tags(index_page)
    tokenized_index = TextBlob(index_page).lower()

    def to_str(key):
        if isinstance(key, unicode):
            return key.encode("utf-8")

        return key

    present_keywords = [
        KEYWORDS_LOWER[key]
        for key in KEYWORDS_LOWER.keys()
        if len(key) > 3 and key in tokenized_index
    ]

    def to_source_string(key):
        source = "Keyword analysis"
        try:
            return SourceString(key, source)
        except UnicodeEncodeError:
            return SourceString(key.encode("utf-8"), source)

    multi_keywords = [
        to_source_string(key)
        for key in present_keywords
        if tokenized_index.words.count(key) >= 1
    ]

    multi_keywords = sorted(multi_keywords, key=lambda x: len(x), reverse=True)

    if len(multi_keywords) > no_items:
        return multi_keywords[:no_items]

    return multi_keywords

Try to process text on the `index_page` deduce the keywords and then try
    to match them on the Aleph's dataset.

    Function returns maximally `no_items` items, to prevent spamming the user.

Args:
        index_page (str): Content of the page as UTF-8 string
        no_items (int, default 5): Number of items to return.

Returns:
        list: List of :class:`.SourceString` objects.


def decode_body(headers: MutableMapping, body: bytes) -> dict:

    type_, encoding = parse_content_type(headers)
    decoded_body = body.decode(encoding)

    # There is one api that just returns `ok` instead of json. In order to have a consistent API we decided to modify the returned payload into a dict.
    if type_ == "application/json":
        payload = json.loads(decoded_body)
    else:
        if decoded_body == "ok":
            payload = {"ok": True}
        else:
            payload = {"ok": False, "data": decoded_body}

    return payload

Decode the response body

    For 'application/json' content-type load the body as a dictionary

Args:
        headers: Response headers
        body: Response body

Returns:
        decoded body


def from_hoy(cls, hoy, leap_year=False):

        return cls.from_moy(round(hoy * 60), leap_year)

Create Ladybug Datetime from an hour of the year.

Args:
        hoy: A float value 0 <= and < 8760


def getHostCertPath(self, name):

        path = s_common.genpath(self.certdir, 'hosts', '%s.crt' % name)
        if not os.path.isfile(path):
            return None
        return path

Gets the path to a host certificate.

Args:
        name (str): The name of the host keypair.

Example:
        Get the path to the host certificate for the host "myhost":

            mypath = cdir.getHostCertPath('myhost')

Returns:
        str: The path if exists.


def SetEnvironmentVariable(self, name, value):

    if isinstance(value, py2to3.STRING_TYPES):
      value = self._PathStripPrefix(value)

    if value is not None:
      self._environment_variables[name.upper()] = value

Sets an environment variable in the Windows path helper.

Args:
        name (str): name of the environment variable without enclosing
        %-characters, e.g. SystemRoot as in %SystemRoot%.
        value (str): value of the environment variable.


def create_and_register_access2000_db(filename: str,
                                      dsn: str,
                                      description: str) -> bool:

    fullfilename = os.path.abspath(filename)
    create_string = fullfilename + " General"
    # ... filename, space, sort order ("General" for English)
    return (create_user_dsn(access_driver, CREATE_DB4=create_string) and
            register_access_db(filename, dsn, description))

(Windows only.)
    Creates a Microsoft Access 2000 database and registers it with ODBC.

Args:
        filename: filename of the database to create
        dsn: ODBC data source name to create
        description: description of the database

Returns:
        bool: was the DSN created?


def query_put_bounders(query, partition_column, start, end):

    where = " WHERE TMP_TABLE.{0} >= {1} AND TMP_TABLE.{0} <= {2}".format(
        partition_column, start, end
    )
    query_with_bounders = "SELECT * FROM ({0}) AS TMP_TABLE {1}".format(query, where)
    return query_with_bounders

Put bounders in the query

Args:
        query: SQL query string
        partition_column: partition_column name
        start: lower_bound
        end: upper_bound

Returns:
        Query with bounders


def contains(self, key):

    try:
      self._api.objects_get(self._bucket, key)
    except datalab.utils.RequestException as e:
      if e.status == 404:
        return False
      raise e
    except Exception as e:
      raise e
    return True

Checks if the specified item exists.

Args:
        key: the key of the item to lookup.

Returns:
        True if the item exists; False otherwise.

Raises:
        Exception if there was an error requesting information about the item.


def diff(self, container):

        return self._result(
            self._get(self._url("/containers/{0}/changes", container)), True
        )

Inspect changes on a container's filesystem.

Args:
        container (str): The container to diff

Returns:
        (str)

Raises:
        :py:class:`docker.errors.APIError`
            If the server returns an error.


def sg_lookup(tensor, opt):
    r
    assert opt.emb is not None, 'emb is mandatory.'
    return tf.nn.embedding_lookup(opt.emb, tensor, name=opt.name)

r"""Looks up the `tensor`, which is the embedding matrix.

Args:
        tensor: A tensor ( automatically given by chain )
        opt:
        emb: A 2-D `Tensor`. An embedding matrix.
        name: If provided, replace current tensor's name.

Returns:
        A `Tensor`.


def __init__(self, args, assignment):

        self.args = args
        self.assignment = assignment

Constructor.

    PARAMETERS:
    args       -- Namespace; parsed command line arguments by argparse.
    assignment -- dict; general information about the assignment.


def setup_ui(uifile, base_instance=None):

    ui = QtCompat.loadUi(uifile)  # Qt.py mapped function
    if not base_instance:
        return ui
    else:
        for member in dir(ui):
            if not member.startswith('__') and \
               member is not 'staticMetaObject':
                setattr(base_instance, member, getattr(ui, member))
        return ui

Load a Qt Designer .ui file and returns an instance of the user interface

Args:
        uifile (str): Absolute path to .ui file
        base_instance (QWidget): The widget into which UI widgets are loaded

Returns:
        QWidget: the base instance


def tfidf_corpus(docs=CORPUS):

    vectorizer = TfidfVectorizer()
    vectorizer = vectorizer.fit(docs)
    return vectorizer, vectorizer.transform(docs)

Count the words in a corpus and return a TfidfVectorizer() as well as all the TFIDF vecgtors for the corpus

Args:
        docs (iterable of strs): a sequence of documents (strings)

Returns:
        (TfidfVectorizer, tfidf_vectors)


def get_realtime_urls(admin_view_func=lambda x: x):

    from .widgets import REALTIME_WIDGETS
    return [url(w.url_regex, admin_view_func(w.as_view()), name=w.url_name)
            for w in REALTIME_WIDGETS]

Get the URL for real-time widgets.

Args:
        admin_view_func (callable): an admin_view method from an AdminSite
            instance. By default: identity.

Returns:
        list: the list of the real-time URLs as django's ``url()``.


def _add_exac(self, variant_obj, info_dict):

        exac = None
        exac_keys = ['ExAC', 'EXAC', 'ExACAF', 'EXACAF']
        for key in exac_keys:
            if info_dict.get(key):
                exac = float(info_dict[key])
        #If not found in vcf search transcripts
        if not exac:
            for transcript in variant_obj.transcripts:
                exac_raw = transcript.ExAC_MAF
                if exac_raw:
                    exac = float(exac_raw.split(':')[-1])

        if exac:
            variant_obj.add_frequency('ExAC', exac)

Add the gmaf frequency

Args:
        variant_obj (puzzle.models.Variant)
        info_dict (dict): A info dictionary


def point_consensus(self, consensus_type):

        if "mean" in consensus_type:
            consensus_data = np.mean(self.data, axis=0)
        elif "std" in consensus_type:
            consensus_data = np.std(self.data, axis=0)
        elif "median" in consensus_type:
            consensus_data = np.median(self.data, axis=0)
        elif "max" in consensus_type:
            consensus_data = np.max(self.data, axis=0)
        elif "percentile" in consensus_type:
            percentile = int(consensus_type.split("_")[1])
            consensus_data = np.percentile(self.data, percentile, axis=0)
        else:
            consensus_data = np.zeros(self.data.shape[1:])
        consensus = EnsembleConsensus(consensus_data, consensus_type, self.ensemble_name,
                                      self.run_date, self.variable, self.start_date, self.end_date, self.units)
        return consensus

Calculate grid-point statistics across ensemble members.

Args:
        consensus_type: mean, std, median, max, or percentile_nn

Returns:
        EnsembleConsensus containing point statistic


def DocumentPackages(self, packages, index_base=None, showprivate=False,
                         notify=True, showinh=False, intro_pages=None,
                         append_material=None, extra=None):

        if index_base is None:
            gram = ''
            if isinstance(packages, list) and len(packages) > 1:
                gram = 's'
                if len(packages) < 3:
                    names = ' and '.join(['``%s``' % p.__name__ for p in packages])
                else:
                    names = ['``%s``' % p.__name__ for p in packages]
                    names[-1] = ' and %s' % names[-1]
                    names = ', '.join(names)
            else:
                names = '``%s``' % packages.__name__
            index = SAMPLE_INDEX.format(names, gram)
        else:
            index = self.OpenIndex(index_base)
        app = self._DocPackageFromTop(packages, showprivate=showprivate, showinh=showinh)
        index += self._GenerateStaticsTable()
        index +=
        if intro_pages is not None:
            if isinstance(intro_pages, str):
                intro_pages = [intro_pages]
            for page in intro_pages:
                index += '   {}\n'.format(page.strip())
        index += '\n'
        if append_material is not None:
            index += append_material
        index += app

        if extra is not None:
            index += extra
        if notify:
            index +=
        self.WriteIndex(index)
        return None

This is the high level API to use to generate documentation pages for any given package(s).

Args:
        packages (list(module)): A list of packages that contain submodules to document
        index_base (str): The index page file name. This content will be appended
        showprivate (bool): A flag for whether or not to display private members


def trim_docstring(docstring):

  if not docstring:
    return ''

  # If you've got a line longer than this you have other problems...
  max_indent = 1 << 29

  # Convert tabs to spaces (following the normal Python rules)
  # and split into a list of lines:
  lines = docstring.expandtabs().splitlines()

  # Determine minimum indentation (first line doesn't count):
  indent = max_indent
  for line in lines[1:]:
    stripped = line.lstrip()
    if stripped:
      indent = min(indent, len(line) - len(stripped))
  # Remove indentation (first line is special):
  trimmed = [lines[0].strip()]
  if indent < max_indent:
    for line in lines[1:]:
      trimmed.append(line[indent:].rstrip())
  # Strip off trailing and leading blank lines:
  while trimmed and not trimmed[-1]:
    trimmed.pop()
  while trimmed and not trimmed[0]:
    trimmed.pop(0)
  # Return a single string:
  return '\n'.join(trimmed)

Removes indentation from triple-quoted strings.

    This is the function specified in PEP 257 to handle docstrings:
    https://www.python.org/dev/peps/pep-0257/.

Args:
        docstring: str, a python docstring.

Returns:
        str, docstring with indentation removed.


def __init__(self, name, description, creator='', raw={}):

        self.name = name
        self.description = description
        self.creator = creator
        self.raw = raw

Constructor.

Args:
        name (string): Name of resource.
        description (string): Description of resource.
        creator (optional[string]): Resource creator.
        raw (optional[dictionary]): Holds JSON data returned by the Boss API on a POST (create) or GET operation.


def __init__(self, name, aliases=None, description=None, urls=None):

    super(DataTypeDefinitionWithMembers, self).__init__(
        name, aliases=aliases, description=description, urls=urls)
    self._byte_size = None
    self.members = []
    self.sections = []

Initializes a data type definition.

Args:
        name (str): name.
        aliases (Optional[list[str]]): aliases.
        description (Optional[str]): description.
        urls (Optional[list[str]]): URLs.


def easeInBack(n, s=1.70158):

    _checkRange(n)
    return n * n * ((s + 1) * n - s)

A tween function that backs up first at the start and then goes to the destination.

Args:
        n (float): The time progress, starting at 0.0 and ending at 1.0.

Returns:
        (float) The line progress, starting at 0.0 and ending at 1.0. Suitable for passing to getPointOnLine().


def get_arrive_stop(self, **kwargs):

        # Endpoint parameters
        params = {
            'idStop': kwargs.get('stop_number'),
            'cultureInfo': util.language_code(kwargs.get('lang'))
        }

        # Request
        result = self.make_request('geo', 'get_arrive_stop', **params)

        # Funny endpoint, no status code
        if not util.check_result(result, 'arrives'):
            return False, 'UNKNOWN ERROR'

        # Parse
        values = util.response_list(result, 'arrives')
        return True, [emtype.Arrival(**a) for a in values]

Obtain bus arrival info in target stop.

Args:
        stop_number (int): Stop number to query.
        lang (str): Language code (*es* or *en*).

Returns:
        Status boolean and parsed response (list[Arrival]), or message string
        in case of error.


def get_absl_log_prefix(record):

  created_tuple = time.localtime(record.created)
  created_microsecond = int(record.created % 1.0 * 1e6)

  critical_prefix = ''
  level = record.levelno
  if _is_non_absl_fatal_record(record):
    # When the level is FATAL, but not logged from absl, lower the level so
    # it's treated as ERROR.
    level = logging.ERROR
    critical_prefix = _CRITICAL_PREFIX
  severity = converter.get_initial_for_level(level)

  return '%c%02d%02d %02d:%02d:%02d.%06d %5d %s:%d] %s' % (
      severity,
      created_tuple.tm_mon,
      created_tuple.tm_mday,
      created_tuple.tm_hour,
      created_tuple.tm_min,
      created_tuple.tm_sec,
      created_microsecond,
      _get_thread_id(),
      record.filename,
      record.lineno,
      critical_prefix)

Returns the absl log prefix for the log record.

Args:
        record: logging.LogRecord, the record to get prefix for.


def compress(a, b):

    from difflib import ndiff
    left = a.splitlines(1) if isinstance(a, string_types) else a
    right = b.splitlines(1) if isinstance(b, string_types) else b
    ldiff = list(ndiff(left, right))

    result = {}
    latest = None
    combo = None
    icombo = 0
    iorig = 0

    for i, line in enumerate(ldiff):
        cs = [l[0] for l in ldiff[i:min((i+4, len(ldiff)))]]
        if cs[0] != ' ':
            #Initialize a new entry in the diff list.
            if latest is None:
                latest = iorig
                result[latest] = []

            #We have to be careful. At a minimum, there may be a '-' or a '+' when the lines are
            #completely added or deleted. When they are *altered*, then we also expect one or
            #more '?' lines showing the differences.
            if combo is None:
                if cs[0] == '-':
                    #Check whether the next lines have one of these combinations:
                    if (len(cs) >=3 and cs[1] == '+' and cs[2] == '?'):
                        combo = 3
                    elif (len(cs) >= 4 and cs[1] == '?' and cs[2] == '+'
                          and cs[3] == '?'):
                        combo = 4
                    else:
                        #This is a stand-alone deletion.
                        combo = 1
                elif cs[0] == '+':
                    #This is for the stand-alone addition.
                    combo = 1

            if icombo < combo:
                result[latest].append(line)
                icombo += 1

            if icombo == combo:
                if combo > 1:
                    latest = None
                combo = None
                icombo = 0
                if cs[0] != '+':
                    iorig += 1
        else:
            latest = None
            iorig += 1

    return result

Performs the *compressed* diff of `a` and `b` such that the original
    contents of the :func:`difflib.ndiff` call can be reconstructed using
    :func:`~acorn.logging.diff.restore`.

Args:
        a (str or list): *original* string or list of strings to diff.
        b (str or list): *edited* string or list of strings to diff.


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

        return super(Payment, self).fetch(payment_id, data, **kwargs)

Fetch Payment for given Id

Args:
        payment_id : Id for which payment object has to be retrieved

Returns:
        Payment dict for given payment Id


def run_bottleneck_on_image(sess, image_data, image_data_tensor,
                            decoded_image_tensor, resized_input_tensor,
                            bottleneck_tensor):

  # First decode the JPEG image, resize it, and rescale the pixel values.
  resized_input_values = sess.run(decoded_image_tensor,
                                  {image_data_tensor: image_data})
  # Then run it through the recognition network.
  bottleneck_values = sess.run(bottleneck_tensor,
                               {resized_input_tensor: resized_input_values})
  bottleneck_values = np.squeeze(bottleneck_values)
  return bottleneck_values

Runs inference on an image to extract the 'bottleneck' summary layer.

Args:
        sess: Current active TensorFlow Session.
        image_data: String of raw JPEG data.
        image_data_tensor: Input data layer in the graph.
        decoded_image_tensor: Output of initial image resizing and preprocessing.
        resized_input_tensor: The input node of the recognition graph.
        bottleneck_tensor: Layer before the final softmax.

Returns:
        Numpy array of bottleneck values.


def piola_kirchoff_1(self, def_grad):

        if not self.is_symmetric:
            raise ValueError("The stress tensor is not symmetric, \
                             PK stress is based on a symmetric stress tensor.")
        def_grad = SquareTensor(def_grad)
        return def_grad.det*np.dot(self, def_grad.inv.trans)

calculates the first Piola-Kirchoff stress

Args:
        def_grad (3x3 array-like): deformation gradient tensor


def subprogram_signature(vo, fullname=None):

  if fullname is None:
    fullname = vo.name

  if isinstance(vo, VhdlFunction):
    plist = ','.join(p.data_type for p in vo.parameters)
    sig = '{}[{} return {}]'.format(fullname, plist, vo.return_type)
  else: # procedure
    plist = ','.join(p.data_type for p in vo.parameters)
    sig = '{}[{}]'.format(fullname, plist)

  return sig

Generate a signature string

Args:
        vo (VhdlFunction, VhdlProcedure): Subprogram object

Returns:
        Signature string.


def __init__(self, custID):

        self.custID = custID
        self.addr1 = None
        self.addr2 = None
        self.city = None
        self.postal = None
        self.province = None
        self.country = None
        self.name = None
        self.phone = None
        self.recordID = None

__init__

    Defines attributes for Personator Object.

Args:
            custID (str): ID for Melissa Data account


def PilToRgb(pil):

    r = 0xff & pil
    g = 0xff & (pil >> 8)
    b = 0xff & (pil >> 16)
    return tuple((v / 255.0 for v in (r, g, b)))

Convert the color from a PIL-compatible integer to RGB.

    Parameters:
        pil: a PIL compatible color representation (0xBBGGRR)

Returns:
        The color as an (r, g, b) tuple in the range:
        the range:
        r: [0...1]
        g: [0...1]
        b: [0...1]

    >>> '(%g, %g, %g)' % Color.PilToRgb(0x0080ff)
    '(1, 0.501961, 0)'


def insert(self, part):

        params = {k: str(v) for k,v in part.params.items()}
        res=c.create_assembly_instance(self.uri.as_dict(), part.uri.as_dict(), params)
        return res

Insert a part into this assembly.

Args:
        - part (onshapepy.part.Part) A Part instance that will be inserted.

Returns:
        - requests.Response: Onshape response data


def Parse(self, filename, feed):

    dom = minidom.parse(filename)
    self.ParseDom(dom, feed)

Reads the kml file, parses it and updated the Google transit feed
    object with the extracted information.

Args:
        filename - kml file name
        feed - an instance of Schedule class to be updated


def locate_resource(name, lang, filter=None):

  task_dir = resource_dir.get(name, name)
  package_id = u"{}.{}".format(task_dir, lang)
  p = path.join(polyglot_path, task_dir, lang)
  if not path.isdir(p):
    if downloader.status(package_id) != downloader.INSTALLED:
      raise ValueError("This resource is available in the index "
                       "but not downloaded, yet. Try to run\n\n"
                       "polyglot download {}".format(package_id))
  return path.join(p, os.listdir(p)[0])

Return filename that contains specific language resource name.

Args:
        name (string): Name of the resource.
        lang (string): language code to be loaded.


def register_flag_by_module_id(self, module_id, flag):

    flags_by_module_id = self.flags_by_module_id_dict()
    flags_by_module_id.setdefault(module_id, []).append(flag)

Records the module that defines a specific flag.

Args:
        module_id: int, the ID of the Python module.
        flag: Flag, the Flag instance that is key to the module.


def get_servo_status(self):

        data = []
        data.append(0x09)
        data.append(self.servoid)
        data.append(RAM_READ_REQ)
        data.append(STATUS_ERROR_RAM)
        data.append(BYTE1)
        send_data(data)

        rxdata = []
        try:
            rxdata = SERPORT.read(12)
            return ord(rxdata[9])&0xFF
        except:
            raise HerkulexError("could not communicate with motors")

Get the error status of servo

    This function gets the  error status (if any) of the servo

Args:
        none

Returns:
        int:  an integer corresponding to the servo status
            * refer datasheet


def generate(cls, strategy, **kwargs):

        assert strategy in (enums.STUB_STRATEGY, enums.BUILD_STRATEGY, enums.CREATE_STRATEGY)
        action = getattr(cls, strategy)
        return action(**kwargs)

Generate a new instance.

    The instance will be created with the given strategy (one of
    BUILD_STRATEGY, CREATE_STRATEGY, STUB_STRATEGY).

Args:
        strategy (str): the strategy to use for generating the instance.

Returns:
        object: the generated instance


def unpackVersion(ver):

    major = (ver >> 20 * 2) & mask20
    minor = (ver >> 20) & mask20
    patch = ver & mask20
    return major, minor, patch

Unpack a system normalized integer representing a softare version into its component parts.

Args:
        ver (int): System normalized integer value to unpack into a tuple.

Returns:
        (int, int, int): A tuple containing the major, minor and patch values shifted out of the integer.


def exp(vector):

    weld_type = None
    if isinstance(vector, LazyOpResult):
        weld_type = vector.weld_type
        vector = vector.expr
    elif isinstance(vector, np.ndarray):
        weld_type = numpy_weld_impl.numpy_to_weld_type_mapping[
            str(vector.dtype)]
    return NumpyArrayWeld(numpy_weld_impl.exp(vector, weld_type), WeldDouble())

Computes a per-element exponent of the passed-in vector.

Args:
        vector (TYPE): Description


def multiply(self, other):

        if not isinstance(other, Number):
            raise QiskitError("other is not a number")
        return Operator(other * self.data, self.input_dims(),
                        self.output_dims())

Return the operator self + other.

Args:
        other (complex): a complex number.

Returns:
        Operator: the operator other * self.

Raises:
        QiskitError: if other is not a valid complex number.


def json_dumps(self, data):

        return json.dumps(
            data,
            separators=(',', ':'),
            sort_keys=True,
            cls=self.json_encoder,
            ensure_ascii=False
        ).encode('utf8')

Standardized json.dumps function with separators and sorted keys set

Args:
        data (dict or list): data to be dumped

Returns:
        string: json


def remove_team_member(self, account_id=None, email_address=None):

        return self._add_remove_team_member(self.TEAM_REMOVE_MEMBER_URL, email_address, account_id)

Remove a user from your Team

Args:
        account_id (str):       The id of the account of the user to remove from your team.

        email_address (str):    The email address of the account to remove from your team. The account id prevails if both account_id and email_address are provided.

Returns:
        A Team object


def invitation_backend(backend=None, namespace=None):
    # type: (Optional[Text], Optional[Text]) -> BaseBackend

    backend = backend or ORGS_INVITATION_BACKEND
    class_module, class_name = backend.rsplit(".", 1)
    mod = import_module(class_module)
    return getattr(mod, class_name)(namespace=namespace)

Returns a specified invitation backend

Args:
        backend: dotted path to the invitation backend class
        namespace: URL namespace to use

Returns:
        an instance of an InvitationBackend


def entropy(rho: Density, base: float = None) -> float:

    op = asarray(rho.asoperator())
    probs = np.linalg.eigvalsh(op)
    probs = np.maximum(probs, 0.0)  # Compensate for floating point errors
    return scipy.stats.entropy(probs, base=base)

Returns the von-Neumann entropy of a mixed quantum state.

Args:
        rho:    A density matrix
        base:   Optional logarithm base. Default is base e, and entropy is
                measures in nats. For bits set base to 2.

Returns:
        The von-Neumann entropy of rho


def true_num_reactions(model, custom_spont_id=None):

    true_num = 0
    for rxn in model.reactions:
        if len(rxn.genes) == 0:
            continue
        if len(rxn.genes) == 1 and is_spontaneous(list(rxn.genes)[0], custom_id=custom_spont_id):
            continue
        else:
            true_num += 1
    return true_num

Return the number of reactions associated with a gene.

Args:
        model (Model):
        custom_spont_id (str): Optional custom spontaneous ID if it does not match the regular expression ``[Ss](_|)0001``

Returns:
        int: Number of reactions associated with a gene


def search(self, term: str, case_sensitive: bool = False) -> 'PrettyDir':

        if case_sensitive:
            return PrettyDir(
                self.obj, [pattr for pattr in self.pattrs if term in pattr.name]
            )
        else:
            term = term.lower()
            return PrettyDir(
                self.obj, [pattr for pattr in self.pattrs if term in pattr.name.lower()]
            )

Searches for names that match some pattern.

Args:
        term: String used to match names. A name is returned if it matches
        the whole search term.
        case_sensitive: Boolean to match case or not, default is False
        (case insensitive).

Returns:
        A PrettyDir object with matched names.


def get_column(self, X, column):

        if isinstance(X, pd.DataFrame):
            return X[column].values

        return X[:, column]

Return a column of the given matrix.

Args:
        X: `numpy.ndarray` or `pandas.DataFrame`.
        column: `int` or `str`.

Returns:
        np.ndarray: Selected column.


def replace_case(self, case_obj):

        # Todo: Figure out and describe when this method destroys a case if invoked instead of
        # update_case
        LOG.info("Saving case %s", case_obj['_id'])
        # update updated_at of case to "today"

        case_obj['updated_at'] = datetime.datetime.now(),

        updated_case = self.case_collection.find_one_and_replace(
            {'_id': case_obj['_id']},
            case_obj,
            return_document=pymongo.ReturnDocument.AFTER
        )

        return updated_case

Replace a existing case with a new one

    Keeps the object id

Args:
        case_obj(dict)

Returns:
        updated_case(dict)


def __init__(self, **sections):

        self._sections = []
        for sct_name, sct_meta in sections.items():
            if _is_valid(sct_name):
                setattr(self, sct_name, Section(**sct_meta.def_))
                self._sections.append(sct_name)
            else:
                raise error.SectionError(sct_name)
        self._parser = None
        self._nosub_valid = False
        self._subcmds = {}
        self._config_files = ()

Initialization of instances.

Args:
        sections (:class:`~loam.manager.Section`): section metadata. The
            name of each *section* is the name of the keyword argument
            passed on to this function. Section names should be valid
            identifiers, otherwise a :class:`~loam.error.SectionError` is
            raised.


def rotate(p, rad, o=(0, 0)):

    v = vector(o, p)
    fx = lambda x, y, d: x * cos(d) - y * sin(d)
    fy = lambda x, y, d: x * sin(d) + y * cos(d)
    rv = fx(v[0], v[1], rad), fy(v[0], v[1], rad)
    return translate(rv, o)

rotate vector

Args:
        p: point (x, y)
        rad: angle(radian)
        o: origin (x, y)


def new(self, boot_system_id):
        # type: (bytes) -> None

        if self._initialized:
            raise Exception('Boot Record already initialized')

        self.boot_system_identifier = boot_system_id.ljust(32, b'\x00')
        self.boot_identifier = b'\x00' * 32
        self.boot_system_use = b'\x00' * 197  # This will be set later

        self._initialized = True

A method to create a new Boot Record.

    Parameters:
    boot_system_id - The system identifier to associate with this Boot
                    Record.

Returns:
    Nothing.


def log_error(cls, msg):

        cls.error_logger.error(msg)
        cls.debug_logger.debug(msg)

Logs the provided error message to both the error logger and the debug logger logging
    instances.

Args:
        msg: `str`. The error message to log.


def _create(cls, model_class, *args, **kwargs):

        manager = cls._get_manager(model_class)

        return manager.create_user(*args, **kwargs)

Create a new user instance.

Args:
        model_class:
            The type of model to create an instance of.

Args:
            Positional arguments to create the instance with.
        kwargs:
            Keyword arguments to create the instance with.

Returns:
        A new user instance of the type specified by
        ``model_class``.


def from_function(cls, f, *args, **kwargs):

        return cls.from_code(six.get_function_code(f), *args, **kwargs)

Create a new instance from a function. Gets the code object from
    the function and passes it and any other specified parameters to
    :meth:`from_code`.

Args:
        f(function): The function to get the code object from.

Returns:
        CodeObject: A new :class:`CodeObject` instance.


def chi_squared(source_frequency, target_frequency):

    # Ignore any symbols from source that are not in target.
    # TODO: raise Error if source_len is 0?
    target_prob = frequency_to_probability(target_frequency)
    source_len = sum(v for k, v in source_frequency.items() if k in target_frequency)

    result = 0
    for symbol, prob in target_prob.items():
        symbol_frequency = source_frequency.get(symbol, 0)  # Frequecy is 0 if it doesnt appear in source
        result += _calculate_chi_squared(symbol_frequency, prob, source_len)

    return result

Calculate the Chi Squared statistic by comparing ``source_frequency`` with ``target_frequency``.

Example:
        >>> chi_squared({'a': 2, 'b': 3}, {'a': 1, 'b': 2})
        0.1

Args:
        source_frequency (dict): Frequency map of the text you are analyzing
        target_frequency (dict): Frequency map of the target language to compare with

Returns:
        Decimal value of the chi-squared statistic


def mapping_ref(self, es_mappings):

        new_map = {}
        for key, value in es_mappings.items():
            for sub_key, sub_value in value.items():
                new_map["/".join([key, sub_key])] = \
                        mapping_fields(sub_value['properties'])
        return new_map

Retruns a dictionary of mappings and the fiels names in dot notation

Args:
        mappings: es mapping defitions to parse


def predict_features(self, df_features, df_target, idx=0, **kwargs):

        estimator = SVR(kernel='linear')
        selector = RFECV(estimator, step=1)
        selector = selector.fit(df_features.values, df_target.values[:, 0])

        return selector.grid_scores_

For one variable, predict its neighbouring nodes.

Args:
        df_features (pandas.DataFrame):
        df_target (pandas.Series):
        idx (int): (optional) for printing purposes
        kwargs (dict): additional options for algorithms

Returns:
        list: scores of each feature relatively to the target


def get_obj(self, objpath, metahash, dst_path):

        incachepath = self.path_in_cache(objpath, metahash)
        if not os.path.exists(incachepath):
            raise CacheMiss('%s not in cache.' % incachepath)
        else:
            log.debug('Cache hit! %s~%s', objpath, metahash.hexdigest())
            if not os.path.exists(os.path.dirname(dst_path)):
                os.makedirs(os.path.dirname(dst_path))
            os.link(incachepath, dst_path)

Get object from cache, write it to dst_path.

Args:
        objpath: filename relative to buildroot
            (example: mini-boot/blahblah/somefile.bin)
        metahash: metahash. See targets/base.py
        dst_path: Absolute path where the file should be written.

Raises:
        CacheMiss: if the item is not in the cache


def send_recv(self, message, timeout=10.0):

        response_queue = self.send(message)
        response = self.recv(response_queue, timeout)
        return response

Send a message to a PandABox and wait for the response

Args:
        message (str): The message to send
        timeout (float): How long to wait before raising queue.Empty

Returns:
        str: The response


def _read_tags(self):

        tags = self._config.get('tags', {})
        logging.info('Tags:')
        for tag_name in tags.keys():
            tag = {}
            tag['Key'] = tag_name
            tag['Value'] = tags[tag_name]
            self._tags.append(tag)
            logging.info('{} = {}'.format(tag_name, tags[tag_name]))

        logging.debug(json.dumps(
            self._tags,
            indent=2,
            sort_keys=True
        ))
        return True

Fill in the _tags dict from the tags file.

Args:
        None

Returns:
        True

    Todo:
        Figure what could go wrong and at least acknowledge the
        the fact that Murphy was an optimist.


def update_site(self, client_secret_expires_at=None):

        params = {
            "oxd_id": self.oxd_id,
            "authorization_redirect_uri": self.authorization_redirect_uri
        }

        if client_secret_expires_at:
            params["client_secret_expires_at"] = client_secret_expires_at

        for param in self.opt_params:
            if self.config.get("client", param):
                value = self.config.get("client", param)
                params[param] = value

        for param in self.opt_list_params:
            if self.config.get("client", param):
                value = self.config.get("client", param).split(",")
                params[param] = value

        logger.debug("Sending `update_site` with params %s",
                     params)
        response = self.msgr.request("update_site", **params)
        logger.debug("Received response: %s", response)

        if response['status'] == 'error':
            raise OxdServerError(response['data'])

        return True

Function to update the site's information with OpenID Provider.
    This should be called after changing the values in the cfg file.

    Parameters:
        * **client_secret_expires_at (long, OPTIONAL):** milliseconds since 1970, can be used to extends client lifetime

Returns:
        **bool:** The status for update. True for success and False for failure

Raises:
        **OxdServerError:** When the update fails and oxd server returns error


def maybe_broadcast_structure(from_structure: Any, to_structure: Any) -> Any:

  flat_from = tf.nest.flatten(from_structure)
  flat_to = tf.nest.flatten(to_structure)
  if len(flat_from) == 1:
    flat_from *= len(flat_to)
  return tf.nest.pack_sequence_as(to_structure, flat_from)

Maybe broadcasts `from_structure` to `to_structure`.

    If `from_structure` is a singleton, it is tiled to match the structure of
    `to_structure`. Note that the elements in `from_structure` are not copied if
    this tiling occurs.

Args:
        from_structure: A structure.
        to_structure: A structure.

Returns:
        new_from_structure: Same structure as `to_structure`.


def zip(self, *others):

        args = [_unwrap(item) for item in (self,) + others]
        ct = self.count()
        if not all(len(arg) == ct for arg in args):
            raise ValueError("Arguments are not all the same length")
        return Collection(map(Wrapper.wrap, zip(*args)))

Zip the items of this collection with one or more
    other sequences, and wrap the result.

    Unlike Python's zip, all sequences must be the same length.

    Parameters:

        others: One or more iterables or Collections

Returns:
        A new collection.

Example:
        >>> c1 = Collection([Scalar(1), Scalar(2)])
        >>> c2 = Collection([Scalar(3), Scalar(4)])
        >>> c1.zip(c2).val()
        [(1, 3), (2, 4)]


def request(self, endpoint, method='GET', headers=None, params=None, data=None):

        if not headers:
            headers = {}
        if method in ['POST', 'PATCH', 'PUT']:
            headers['Content-Type'] = 'application/json'
        url = '/'.join([self.api_url, 'v' + self.api_version, endpoint])
        data = json.dumps(data) if data else None
        try:
            response = requests.request(method=method, url=url, params=params, headers=headers, data=data)
        # TODO Does recreating the exception classes 'requests' use suck? Yes, but it sucks more to expose the underlying library I use
        except requests.exceptions.Timeout as e:
            raise wp_exceptions.TimeoutError(e)
        except requests.exceptions.ConnectionError as e:
            raise wp_exceptions.ConnectionError(e)
        self._validate_response(method, response)
        return response

Send a request to the given Wunderlist API endpoint

    Params:
    endpoint -- API endpoint to send request to

    Keyword Args:
    headers -- headers to add to the request
    method -- GET, PUT, PATCH, DELETE, etc.
    params -- parameters to encode in the request
    data -- data to send with the request


def __le__(self, other):

        other = self._cast_to_frameset(other)
        if other is NotImplemented:
            return NotImplemented
        return self.items <= other.items

Check if `self` <= `other` via a comparison of the contents.
    If `other` is not a :class:`FrameSet`, but is a set, frozenset, or
    is iterable, it will be cast to a :class:`FrameSet`.

Args:
        other (:class:`FrameSet`): Also accepts an object that can be cast to a :class:`FrameSet`

Returns:
        bool:
        :class:`NotImplemented`: if `other` fails to convert to a :class:`FrameSet`


def get_interpolated_value(self, energy, integrated=False):

        inter = {}
        for spin in self.cohp:
            if not integrated:
                inter[spin] = get_linear_interpolated_value(self.energies,
                                                            self.cohp[spin],
                                                            energy)
            elif self.icohp is not None:
                inter[spin] = get_linear_interpolated_value(self.energies,
                                                            self.icohp[spin],
                                                            energy)
            else:
                raise ValueError("ICOHP is empty.")
        return inter

Returns the COHP for a particular energy.

Args:
        energy: Energy to return the COHP value for.


def _get_anchor(module_to_name, fullname):

  if not _anchor_re.match(fullname):
    raise ValueError("'%s' is not a valid anchor" % fullname)
  anchor = fullname
  for module_name in module_to_name.values():
    if fullname.startswith(module_name + "."):
      rest = fullname[len(module_name)+1:]
      # Use this prefix iff it is longer than any found before
      if len(anchor) > len(rest):
        anchor = rest
  return anchor

Turn a full member name into an anchor.

Args:
        module_to_name: Dictionary mapping modules to short names.
        fullname: Fully qualified name of symbol.

Returns:
        HTML anchor string.  The longest module name prefix of fullname is
        removed to make the anchor.

Raises:
        ValueError: If fullname uses characters invalid in an anchor.


def close_position(self, repay_only):

        params = {'repay_only': repay_only}
        return self._send_message('post', '/position/close',
                                  data=json.dumps(params))

Close position.

Args:
        repay_only (bool): Undocumented by cbpro.

Returns:
        Undocumented


def getElementDeclaration(cls, namespaceURI, name, isref=False, lazy=False):

        key = (namespaceURI, name)
        if isref:
            klass = cls.elements.get(key,None)
            if klass is not None and lazy is True:
                return _Mirage(klass)
            return klass

        typecode = cls.element_typecode_cache.get(key, None)
        if typecode is None:
            tcls = cls.elements.get(key,None)
            if tcls is not None:
                typecode = cls.element_typecode_cache[key] = tcls()
                typecode.typed = False

        return typecode

Grab an element declaration, returns a typecode instance
    representation or a typecode class definition.  An element
    reference has its own facets, and is local so it will not be
    cached.

    Parameters:
        namespaceURI --
        name --
        isref -- if element reference, return class definition.


def __init__(self, server, spider, key, exchange=None):

        self.server = server
        self.spider = spider
        self.key = key % {'spider': spider.name}

Initialize per-spider RabbitMQ queue.

    Parameters:
        server -- rabbitmq connection
        spider -- spider instance
        key -- key for this queue (e.g. "%(spider)s:queue")


def _build_vocab(filename, vocab_dir, vocab_name):

  vocab_path = os.path.join(vocab_dir, vocab_name)
  if not tf.gfile.Exists(vocab_path):
    with tf.gfile.GFile(filename, "r") as f:
      data = f.read().split()
    counter = collections.Counter(data)
    count_pairs = sorted(counter.items(), key=lambda x: (-x[1], x[0]))
    words, _ = list(zip(*count_pairs))
    encoder = text_encoder.TokenTextEncoder(None, vocab_list=words)
    encoder.store_to_file(vocab_path)
  else:
    encoder = text_encoder.TokenTextEncoder(vocab_path)
  return encoder

Reads a file to build a vocabulary.

Args:
        filename: file to read list of words from.
        vocab_dir: directory where to save the vocabulary.
        vocab_name: vocab file name.

Returns:
        text encoder.


def from_string(species_string: str):

        m = re.search(r"([A-Z][a-z]*)([0-9.]*)([+\-]*)(.*)", species_string)
        if m:
            sym = m.group(1)
            if m.group(2) == "" and m.group(3) == "":
                oxi = 0
            else:
                oxi = 1 if m.group(2) == "" else float(m.group(2))
                oxi = -oxi if m.group(3) == "-" else oxi
            properties = None
            if m.group(4):
                toks = m.group(4).split("=")
                properties = {toks[0]: float(toks[1])}
            return DummySpecie(sym, oxi, properties)
        raise ValueError("Invalid DummySpecies String")

Returns a Dummy from a string representation.

Args:
        species_string (str): A string representation of a dummy
            species, e.g., "X2+", "X3+".

Returns:
        A DummySpecie object.

Raises:
        ValueError if species_string cannot be intepreted.


def ip_network(address, strict=True):

    try:
        return IPv4Network(address, strict)
    except (AddressValueError, NetmaskValueError):
        pass

    try:
        return IPv6Network(address, strict)
    except (AddressValueError, NetmaskValueError):
        pass

    raise ValueError('%r does not appear to be an IPv4 or IPv6 network' %
                     address)

Take an IP string/int and return an object of the correct type.

Args:
        address: A string or integer, the IP network.  Either IPv4 or
        IPv6 networks may be supplied; integers less than 2**32 will
        be considered to be IPv4 by default.

Returns:
        An IPv4Network or IPv6Network object.

Raises:
        ValueError: if the string passed isn't either a v4 or a v6
        address. Or if the network has host bits set.


def ipv6_is_defined(address):

    # Initialize the IP address object.
    query_ip = IPv6Address(str(address))

    # Initialize the results named tuple
    results = namedtuple('ipv6_is_defined_results', 'is_defined, ietf_name, '
                                                    'ietf_rfc')
    # Multicast
    if query_ip.is_multicast:

        return results(True, 'Multicast', 'RFC 4291, Section 2.7')

    # Unspecified
    elif query_ip.is_unspecified:

        return results(True, 'Unspecified', 'RFC 4291, Section 2.5.2')

    # Loopback.
    elif query_ip.is_loopback:

        return results(True, 'Loopback', 'RFC 4291, Section 2.5.3')

    # Reserved
    elif query_ip.is_reserved:

        return results(True, 'Reserved', 'RFC 4291')

    # Link-Local
    elif query_ip.is_link_local:

        return results(True, 'Link-Local', 'RFC 4291, Section 2.5.6')

    # Site-Local
    elif query_ip.is_site_local:

        return results(True, 'Site-Local', 'RFC 4291, Section 2.5.7')

    # Unique Local Unicast
    elif query_ip.is_private:

        return results(True, 'Unique Local Unicast', 'RFC 4193')

    return results(False, '', '')

The function for checking if an IPv6 address is defined (does not need to
    be resolved).

Args:
        address (:obj:`str`): An IPv6 address.

Returns:
        namedtuple:

        :is_defined (bool): True if given address is defined, otherwise
            False
        :ietf_name (str): IETF assignment name if given address is
            defined, otherwise ''
        :ietf_rfc (str): IETF assignment RFC if given address is defined,
            otherwise ''


def external_ids(self, **kwargs):

        path = self._get_series_id_season_number_episode_number_path(
            'external_ids')

        response = self._GET(path, kwargs)
        self._set_attrs_to_values(response)
        return response

Get the external ids for a TV episode by combination of a season and
    episode number.

Args:
        language: (optional) ISO 639 code.

Returns:
        A dict respresentation of the JSON returned from the API.


def _initialize_slots(self, seed, hashvalues):

        self.seed = seed
        self.hashvalues = self._parse_hashvalues(hashvalues)

Initialize the slots of the LeanMinHash.

Args:
        seed (int): The random seed controls the set of random
            permutation functions generated for this LeanMinHash.
        hashvalues: The hash values is the internal state of the LeanMinHash.


def match(self, subject: Union[Expression, FlatTerm]) -> Iterator[Tuple[T, Substitution]]:

        for index in self._match(subject):
            pattern, label = self._patterns[index]
            subst = Substitution()
            if subst.extract_substitution(subject, pattern.expression):
                for constraint in pattern.constraints:
                    if not constraint(subst):
                        break
                else:
                    yield label, subst

Match the given subject against all patterns in the net.

Args:
        subject:
            The subject that is matched. Must be constant.

Yields:
        A tuple :code:`(final label, substitution)`, where the first component is the final label associated with
        the pattern as given when using :meth:`add()` and the second one is the match substitution.


def get_summary(result):

    summary = {
        "success": result.wasSuccessful(),
        "stat": {
            'total': result.testsRun,
            'failures': len(result.failures),
            'errors': len(result.errors),
            'skipped': len(result.skipped),
            'expectedFailures': len(result.expectedFailures),
            'unexpectedSuccesses': len(result.unexpectedSuccesses)
        }
    }
    summary["stat"]["successes"] = summary["stat"]["total"] \
        - summary["stat"]["failures"] \
        - summary["stat"]["errors"] \
        - summary["stat"]["skipped"] \
        - summary["stat"]["expectedFailures"] \
        - summary["stat"]["unexpectedSuccesses"]

    summary["time"] = {
        'start_at': result.start_at,
        'duration': result.duration
    }
    summary["records"] = result.records

    return summary

get summary from test result

Args:
        result (instance): HtmlTestResult() instance

Returns:
        dict: summary extracted from result.

            {
                "success": True,
                "stat": {},
                "time": {},
                "records": []
            }


def select_segments(self, jsonpath: str) -> List[Segment]:

        path = self.etk.parse_json_path(jsonpath)
        matches = path.find(self.cdr_document)

        segments = list()
        for a_match in matches:
            this_segment = Segment(str(a_match.full_path), a_match.value, self)
            segments.append(this_segment)

        return segments

Dereferences the json_path inside the document and returns the selected elements.
    This method should compile and cache the compiled json_path in case the same path
    is reused by multiple extractors.

Args:
        jsonpath (str): a valid JSON path.

    Returns: A list of Segments object that contains the elements selected by the json path.


def mkpath(self, url, path, filename=None, gzip=False):

        if path:
            url = "%s/%s" % (url.rstrip('/'), path.strip('/'))

        if filename:
            url = "%s/%s" % (url, filename.lstrip('/'))

        content_type = mimetypes.guess_type(url)[0]
        if gzip and content_type in mediasync.TYPES_TO_COMPRESS:
            url = "%s.gzt" % url

        cb = msettings['CACHE_BUSTER']
        if cb:
            # Cache busters help tell the client to re-download the file after
            # a change. This can either be a callable or a constant defined
            # in settings.py.
            cb_val = cb(url) if callable(cb) else cb
            url = "%s?%s" % (url, cb_val)

        return msettings['URL_PROCESSOR'](url)

Assembles various components to form a complete resource URL.

Args:
        url: (str) A base media URL.
        path: (str) The path on the host (specified in 'url') leading up
                to the file.
        filename: (str) The file name to serve.
        gzip: (bool) True if client should receive *.gzt version of file.