def run(self, dag):

        # Walk through the DAG and expand each non-basis node
        for node in dag.op_nodes():
            basic_insts = ['measure', 'reset', 'barrier', 'snapshot']
            if node.name in basic_insts:
                # TODO: this is legacy behavior.Basis_insts should be removed that these
                #  instructions should be part of the device-reported basis. Currently, no
                #  backend reports "measure", for example.
                continue
            if node.name in self.basis:  # If already a base, ignore.
                continue

            # TODO: allow choosing other possible decompositions
            rule = node.op.definition
            if not rule:
                raise QiskitError("Cannot unroll the circuit to the given basis, %s. "
                                  "No rule to expand instruction %s." %
                                  (str(self.basis), node.op.name))

            # hacky way to build a dag on the same register as the rule is defined
            # TODO: need anonymous rules to address wires by index
            decomposition = DAGCircuit()
            decomposition.add_qreg(rule[0][1][0][0])
            for inst in rule:
                decomposition.apply_operation_back(*inst)

            unrolled_dag = self.run(decomposition)  # recursively unroll ops
            dag.substitute_node_with_dag(node, unrolled_dag)
        return dag

Expand all op nodes to the given basis.

Args:
        dag(DAGCircuit): input dag

Raises:
        QiskitError: if unable to unroll given the basis due to undefined
        decomposition rules (such as a bad basis) or excessive recursion.

Returns:
        DAGCircuit: output unrolled dag


def _astimezone_ts(self, timezone):

    if self.created.tzinfo is timezone:
        return self
    else:
        nw_obj = Timestamps((None,)*4)
        nw_obj.created = self.created.astimezone(timezone)
        nw_obj.changed = self.changed.astimezone(timezone)
        nw_obj.mft_changed = self.mft_changed.astimezone(timezone)
        nw_obj.accessed = self.accessed.astimezone(timezone)

        return nw_obj

Changes the time zones of all timestamps.

    Receives a new timezone and applies to all timestamps, if necessary.

Args:
        timezone (:obj:`tzinfo`): Time zone to be applied

Returns:
        A new ``Timestamps`` object if the time zone changes, otherwise returns ``self``.


def get_op_or_tensor_by_name(name):

    G = tfv1.get_default_graph()

    def f(n):
        if len(n) >= 3 and n[-2] == ':':
            return G.get_tensor_by_name(n)
        else:
            return G.get_operation_by_name(n)

    if not isinstance(name, list):
        return f(name)
    else:
        return list(map(f, name))

Get either tf.Operation of tf.Tensor from names.

Args:
        name (list[str] or str): names of operations or tensors.

Raises:
        KeyError, if the name doesn't exist


def __init__(self, version: str = None, api_url: str = None) -> None:

        bel_versions = bel_specification.get_bel_versions()

        # use bel_utils._default_to_version to check if valid version, and if it exists or not
        if not version:
            self.version = config["bel"]["lang"]["default_bel_version"]
        else:
            self.version = version

        if self.version not in bel_versions:
            log.warning(
                f"Cannot validate with invalid version: {self.version} in BEL Versions: {bel_versions}"
            )

        if not api_url:
            self.api_url = config["bel_api"]["servers"]["api_url"]
        else:
            self.api_url = api_url

        # Validation error/warning messages
        # List[Tuple[str, str]], e.g. [('ERROR', 'this is an error msg'), ('WARNING', 'this is a warning'), ]
        self.validation_messages = []

        # self.semantics = BELSemantics()  # each instance also instantiates a BELSemantics object used in parsing statements
        self.spec = bel_specification.get_specification(self.version)

        # bel_utils._dump_spec(self.spec)

        # Import Tatsu parser
        # use importlib to import our parser (a .py file) and set the BELParse object as an instance variable
        try:
            parser_fn = self.spec["admin"]["parser_fn"]

            parser_name = os.path.basename(parser_fn).replace(".py", "")
            module_spec = importlib.util.spec_from_file_location(parser_name, parser_fn)
            imported_parser = importlib.util.module_from_spec(module_spec)
            module_spec.loader.exec_module(imported_parser)
            self.parser = imported_parser.BELParser()
        except Exception as e:
            # if not found, we raise the NoParserFound exception which can be found in bel.lang.exceptions
            raise bel_ex.NoParserFound(f"Version: {self.version} Msg: {e}")

Initialize BEL object used for validating/processing/etc BEL statements

Args:
        version (str): BEL Version, defaults to config['bel']['lang']['default_bel_version']
        api_url (str): BEL API endpoint,  defaults to config['bel_api']['servers']['api_url']


def encode_consumer_metadata_request(cls, client_id, correlation_id, payloads):

        message = []
        message.append(cls._encode_message_header(client_id, correlation_id,
                                                  KafkaProtocol.CONSUMER_METADATA_KEY))
        message.append(struct.pack('>h%ds' % len(payloads), len(payloads), payloads))

        msg = b''.join(message)
        return write_int_string(msg)

Encode a ConsumerMetadataRequest

Args:
        client_id: string
        correlation_id: int
        payloads: string (consumer group)


def get_transcript_format(transcript_content):

    try:
        sjson_obj = json.loads(transcript_content)
    except ValueError:
        # With error handling (set to 'ERROR_RAISE'), we will be getting
        # the exception if something went wrong in parsing the transcript.
        srt_subs = SubRipFile.from_string(transcript_content, error_handling=SubRipFile.ERROR_RAISE)
        if len(srt_subs) > 0:
            return TranscriptFormat.SRT
    return TranscriptFormat.SJSON

Returns transcript format.

Args:
        transcript_content (str): Transcript file content.


def get(self, key):

        data = self._store.get(key)
        if not data:
            return None
        value, expire = data
        if expire and time.time() > expire:
            del self._store[key]
            return None
        return value

Get an item from the cache

Args:
        key: item key

Returns:
        the value of the item or None if the item isn't in the cache


def list_resource_groups(access_token, subscription_id):

    endpoint = ''.join([get_rm_endpoint(),
                        '/subscriptions/', subscription_id,
                        '/resourceGroups/',
                        '?api-version=', RESOURCE_API])
    return do_get(endpoint, access_token)

List the resource groups in a subscription.

Args:
        access_token (str): A valid Azure authentication token.
        subscription_id (str): Azure subscription id.

Returns:
        HTTP response.


def _check_special_kwargs(self, name):

        keys = []
        # find any %method names in the template string
        functions = re.findall(r"\%\w+", self.templates[name])
        if not functions:
            return keys

        # loop over special method names and extract keywords
        for function in functions:
            method = getattr(self, function[1:])
            # get source code of special method
            source = self._find_source(method)
            fkeys = re.findall(r'kwargs\[(.*?)\]', source)
            if fkeys:
                # evaluate to proper string
                fkeys = [ast.literal_eval(k) for k in fkeys]
                keys.extend(fkeys)
        return keys

check special functions for kwargs

    Checks the content of the special functions (%methodname) for
    any keyword arguments referenced within

    Parameters:
        name (str):
            A path key name

Returns:
        A list of keyword arguments found in any special functions


def render_secrets(
        config_path,
        secret_path,
):

    with open(secret_path, 'r') as s_fh:
        secret_ini = anyconfig.load(s_fh, ac_parser='ini')

    with open(config_path, 'r') as c_fh:
        raw_cfg = c_fh.read()

    rendered_cfg = anytemplate.renders(raw_cfg, secret_ini, at_engine='jinja2')

    p_config = ProsperConfig(config_path)
    local_config = configparser.ConfigParser()
    local_config.optionxform = str
    local_config.read_string(rendered_cfg)

    p_config.local_config = local_config

    return p_config

combine a jinja template with a secret .ini file

Args:
        config_path (str): path to .cfg file with jinja templating
        secret_path (str): path to .ini-like secrets file

Returns:
        ProsperConfig: rendered configuration object


def NotIn(self, *values):

    self._awql = self._CreateMultipleValuesCondition(values, 'NOT_IN')
    return self._query_builder

Sets the type of the WHERE clause as "in".

Args:
        *values: The values to be used in the WHERE condition.

Returns:
        The query builder that this WHERE builder links to.


def parse_case(config):

    if 'owner' not in config:
        raise ConfigError("A case has to have a owner")

    if 'family' not in config:
        raise ConfigError("A case has to have a 'family'")

    individuals = parse_individuals(config['samples'])
    case_data = {
        'owner': config['owner'],
        'collaborators': [config['owner']],
        'case_id': config['family'],
        'display_name': config.get('family_name', config['family']),
        'genome_build': config.get('human_genome_build'),
        'rank_model_version': config.get('rank_model_version'),
        'rank_score_threshold': config.get('rank_score_threshold', 0),
        'analysis_date': config['analysis_date'],
        'individuals': individuals,
        'vcf_files': {
            'vcf_snv': config.get('vcf_snv'),
            'vcf_sv': config.get('vcf_sv'),
            'vcf_str': config.get('vcf_str'),
            'vcf_cancer': config.get('vcf_cancer'),
            'vcf_snv_research': config.get('vcf_snv_research'),
            'vcf_sv_research': config.get('vcf_sv_research'),
            'vcf_cancer_research': config.get('vcf_cancer_research'),
        },
        'default_panels': config.get('default_gene_panels', []),
        'gene_panels': config.get('gene_panels', []),
        'assignee': config.get('assignee'),
        'peddy_ped': config.get('peddy_ped'),
        'peddy_sex': config.get('peddy_sex'),
        'peddy_check': config.get('peddy_check'),
        'delivery_report': config.get('delivery_report'),
        'multiqc': config.get('multiqc'),
        'track': config.get('track', 'rare'),
    }

    # add the pedigree figure, this is a xml file which is dumped in the db
    if 'madeline' in config:
        mad_path = Path(config['madeline'])
        if not mad_path.exists():
            raise ValueError("madeline path not found: {}".format(mad_path))
        with mad_path.open('r') as in_handle:
            case_data['madeline_info'] = in_handle.read()

    if (case_data['vcf_files']['vcf_cancer'] or case_data['vcf_files']['vcf_cancer_research']):
        case_data['track'] = 'cancer'

    return case_data

Parse case information from config or PED files.

Args:
        config (dict): case config with detailed information

Returns:
        dict: parsed case data


def pymmh3_hash64(key: Union[bytes, bytearray],
                  seed: int = 0,
                  x64arch: bool = True) -> Tuple[int, int]:

    hash_128 = pymmh3_hash128(key, seed, x64arch)

    unsigned_val1 = hash_128 & 0xFFFFFFFFFFFFFFFF  # low half
    if unsigned_val1 & 0x8000000000000000 == 0:
        signed_val1 = unsigned_val1
    else:
        signed_val1 = -((unsigned_val1 ^ 0xFFFFFFFFFFFFFFFF) + 1)

    unsigned_val2 = (hash_128 >> 64) & 0xFFFFFFFFFFFFFFFF  # high half
    if unsigned_val2 & 0x8000000000000000 == 0:
        signed_val2 = unsigned_val2
    else:
        signed_val2 = -((unsigned_val2 ^ 0xFFFFFFFFFFFFFFFF) + 1)

    return signed_val1, signed_val2

Implements 64bit murmur3 hash, as per ``pymmh3``. Returns a tuple.

Args:
        key: data to hash
        seed: seed
        x64arch: is a 64-bit architecture available?

Returns:
        tuple: tuple of integers, ``(signed_val1, signed_val2)``


def set_control_mode(self, modevalue):

        minimalmodbus._checkInt(modevalue, minvalue=0, maxvalue=3, description='control mode')
        self.write_register(4101, modevalue)

Set the control method using the corresponding integer value.

Args:
        modevalue(int): 0-3

    The modevalue is one of the keys in :data:`CONTROL_MODES`.


def export(self, composite=False):

        if composite:
            if rname_rfc6680 is None:
                raise NotImplementedError("Your GSSAPI implementation does "
                                          "not support RFC 6680 (the GSSAPI "
                                          "naming extensions)")

            return rname_rfc6680.export_name_composite(self)
        else:
            return rname.export_name(self)

Export this name as a token.

    This method exports the name into a byte string which can then be
    imported by using the `token` argument of the constructor.

Args:
        composite (bool): whether or not use to a composite token --
            :requires-ext:`rfc6680`

Returns:
        bytes: the exported name in token form

Raises:
        MechanismNameRequiredError
        BadNameTypeError
        BadNameError


def kcenter(I,J,c,k):

    model = Model("k-center")
    z = model.addVar(vtype="C", name="z")
    x,y = {},{}

    for j in J:
        y[j] = model.addVar(vtype="B", name="y(%s)"%j)
        for i in I:
            x[i,j] = model.addVar(vtype="B", name="x(%s,%s)"%(i,j))

    for i in I:
        model.addCons(quicksum(x[i,j] for j in J) == 1, "Assign(%s)"%i)

        for j in J:
            model.addCons(x[i,j] <= y[j], "Strong(%s,%s)"%(i,j))
            model.addCons(c[i,j]*x[i,j] <= z, "Max_x(%s,%s)"%(i,j))

    model.addCons(quicksum(y[j] for j in J) == k, "Facilities")

    model.setObjective(z, "minimize")
    model.data = x,y

    return model

kcenter -- minimize the maximum travel cost from customers to k facilities.
    Parameters:
        - I: set of customers
        - J: set of potential facilities
        - c[i,j]: cost of servicing customer i from facility j
        - k: number of facilities to be used
    Returns a model, ready to be solved.


def setDirname(self, dirname):

        # Make sure the dirname always ends in
        # a path separator character
        sep = utils._getPathSep(dirname)
        if not dirname.endswith(sep):
            dirname += sep

        self._dir = utils.asString(dirname)

Set a new directory name for the sequence.

Args:
        dirname (str): the new directory name


def startstop(inst_id, cmdtodo):

    tar_inst = EC2R.Instance(inst_id)
    thecmd = getattr(tar_inst, cmdtodo)
    response = thecmd()
    return response

Start or Stop the Specified Instance.

Args:
        inst_id (str): instance-id to perform command against
        cmdtodo (str): command to perform (start or stop)

Returns:
        response (dict): reponse returned from AWS after
                        performing specified action.


def last_timestamp(self, event_key=None):

    if event_key is None:
      timestamps = [self._trackers[key].first_timestamp
                    for key in self._trackers]
      return max(timestamp for timestamp in timestamps if timestamp >= 0)
    else:
      return self._trackers[event_key].last_timestamp

Obtain the last timestamp.

Args:
        event_key: the type key of the sought events (e.g., constants.NAN_KEY). If
        None, includes all event type keys.

Returns:
        Last (latest) timestamp of all the events of the given type (or all
        event types if event_key is None).


def ReceiveMessagesRelationalFlows(self, client_id, messages):

    now = time.time()
    unprocessed_msgs = []
    message_handler_requests = []
    dropped_count = 0
    for session_id, msgs in iteritems(
        collection.Group(messages, operator.attrgetter("session_id"))):

      # Remove and handle messages to WellKnownFlows
      leftover_msgs = self.HandleWellKnownFlows(msgs)

      for msg in leftover_msgs:
        if (msg.auth_state != msg.AuthorizationState.AUTHENTICATED and
            msg.session_id != self.unauth_allowed_session_id):
          dropped_count += 1
          continue

        if session_id in queue_manager.session_id_map:
          message_handler_requests.append(
              rdf_objects.MessageHandlerRequest(
                  client_id=msg.source.Basename(),
                  handler_name=queue_manager.session_id_map[session_id],
                  request_id=msg.response_id,
                  request=msg.payload))
        else:
          unprocessed_msgs.append(msg)

    if dropped_count:
      logging.info("Dropped %d unauthenticated messages for %s", dropped_count,
                   client_id)

    if unprocessed_msgs:
      flow_responses = []
      for message in unprocessed_msgs:
        flow_responses.append(
            rdf_flow_objects.FlowResponseForLegacyResponse(message))

      data_store.REL_DB.WriteFlowResponses(flow_responses)

      for msg in unprocessed_msgs:
        if msg.type == rdf_flows.GrrMessage.Type.STATUS:
          stat = rdf_flows.GrrStatus(msg.payload)
          if stat.status == rdf_flows.GrrStatus.ReturnedStatus.CLIENT_KILLED:
            # A client crashed while performing an action, fire an event.
            crash_details = rdf_client.ClientCrash(
                client_id=client_id,
                session_id=msg.session_id,
                backtrace=stat.backtrace,
                crash_message=stat.error_message,
                nanny_status=stat.nanny_status,
                timestamp=rdfvalue.RDFDatetime.Now())
            events.Events.PublishEvent(
                "ClientCrash", crash_details, token=self.token)

    if message_handler_requests:
      data_store.REL_DB.WriteMessageHandlerRequests(message_handler_requests)

    logging.debug("Received %s messages from %s in %s sec", len(messages),
                  client_id,
                  time.time() - now)

Receives and processes messages for flows stored in the relational db.

Args:
        client_id: The client which sent the messages.
        messages: A list of GrrMessage RDFValues.


def search_by_name(cls, name):

        records = aleph.downloadRecords(
            aleph.searchInAleph("aut", name, False, "wau")
        )

        for record in records:
            marc = MARCXMLRecord(record)

            author = cls.parse_author(marc)

            if author:
                yield author

Look for author in NK Aleph authority base by `name`.

Args:
        name (str): Author's name.

Yields:
        obj: :class:`Author` instances.


def check_data_type(self):

        metadata_type = self.column_metadata.get('type')
        if self.type != metadata_type and metadata_type not in self.type:
            raise ValueError('Types of transformer don\'t match')

Check the type of the transformer and column match.

Args:
        column_metadata(dict): Metadata of the column.

    Raises a ValueError if the types don't match


def __init__(self, value):

        super(BinaryParserException, self).__init__()
        self._value = value

Constructor.

Args:
    - `value`: A string description.


def _get_colordata(bs, elements, bs_projection):

        contribs = {}
        if bs_projection and bs_projection.lower() == "elements":
            projections = bs.get_projection_on_elements()

        for spin in (Spin.up, Spin.down):
            if spin in bs.bands:
                contribs[spin] = []
                for band_idx in range(bs.nb_bands):
                    colors = []
                    for k_idx in range(len(bs.kpoints)):
                        if bs_projection and bs_projection.lower() == "elements":
                            c = [0, 0, 0]
                            projs = projections[spin][band_idx][k_idx]
                            # note: squared color interpolations are smoother
                            # see: https://youtu.be/LKnqECcg6Gw
                            projs = dict(
                                [(k, v ** 2) for k, v in projs.items()])
                            total = sum(projs.values())
                            if total > 0:
                                for idx, e in enumerate(elements):
                                    c[idx] = math.sqrt(projs[
                                                           e] / total)  # min is to handle round errors

                            c = [c[1], c[2],
                                 c[0]]  # prefer blue, then red, then green

                        else:
                            c = [0, 0, 0] if spin == Spin.up \
                                else [0, 0,
                                      1]  # black for spin up, blue for spin down

                        colors.append(c)

                    contribs[spin].append(colors)
                contribs[spin] = np.array(contribs[spin])

        return contribs

Get color data, including projected band structures

Args:
        bs: Bandstructure object
        elements: elements (in desired order) for setting to blue, red, green
        bs_projection: None for no projection, "elements" for element projection

    Returns:


def gff3_verifier(entries, line=None):

    regex = r'^[a-zA-Z0-9.:^*$@!+_?-|]+\t.+\t.+\t\d+\t\d+\t' \
            + r'\d*\.?\d*\t[+-.]\t[.0-2]\t.+{0}$'.format(os.linesep)
    delimiter = r'\t'

    for entry in entries:
        try:
            entry_verifier([entry.write()], regex, delimiter)
        except FormatError as error:
            # Format info on what entry error came from
            if line:
                intro = 'Line {0}'.format(str(line))
            elif error.part == 0:
                intro = 'Entry with source {0}'.format(entry.source)
            else:
                intro = 'Entry with Sequence ID {0}'.format(entry.seqid)

            # Generate error
            if error.part == 0:
                msg = '{0} has no Sequence ID'.format(intro)
            elif error.part == 1:
                msg = '{0} has no source'.format(intro)
            elif error.part == 2:
                msg = '{0} has non-numerical characters in type'.format(intro)
            elif error.part == 3:
                msg = '{0} has non-numerical characters in ' \
                      'start position'.format(intro)
            elif error.part == 4:
                msg = '{0} has non-numerical characters in ' \
                      'end position'.format(intro)
            elif error.part == 5:
                msg = '{0} has non-numerical characters in score'.format(intro)
            elif error.part == 6:
                msg = '{0} strand not in [+-.]'.format(intro)
            elif error.part == 7:
                msg = '{0} phase not in [.0-2]'.format(intro)
            elif error.part == 8:
                msg = '{0} has no attributes'.format(intro)
            else:
                msg = 'Unknown Error: Likely a Bug'
            raise FormatError(message=msg)

        if line:
            line += 1

Raises error if invalid GFF3 format detected

Args:
        entries (list): A list of GFF3Entry instances

        line (int): Line number of first entry

Raises:
        FormatError: Error when GFF3 format incorrect with descriptive message


def _should_catch_error(self, error, errors=()):

        caught_errors = (
            errors or
            self.session.driver.invalid_element_errors + (ElementNotFound,))

        return isinstance(error, caught_errors)

Returns whether to catch the given error.

Args:
        error (Exception): The error to consider.
        errors (Tuple[Type[Exception], ...], optional): The exception types that should be
            caught. Defaults to :class:`ElementNotFound` plus any driver-specific invalid
            element errors.

Returns:
        bool: Whether to catch the given error.


def post(self, *messages):

        url = "queues/%s/messages" % self.name

        msgs = [{'body': msg} if isinstance(msg, basestring) else msg
                for msg in messages]
        data = json.dumps({'messages': msgs})

        result = self.client.post(url=url, body=data,
                                  headers={'Content-Type': 'application/json'})

        return result['body']

Executes an HTTP request to create message on the queue.
    Creates queue if not existed.

Args:
    messages -- An array of messages to be added to the queue.


def walk(self, walk_func):

        nodes = self.topological_sort()
        # Reverse so we start with nodes that have no dependencies.
        nodes.reverse()

        for n in nodes:
            walk_func(n)

Walks each node of the graph in reverse topological order.
    This can be used to perform a set of operations, where the next
    operation depends on the previous operation. It's important to note
    that walking happens serially, and is not paralellized.

Args:
        walk_func (:class:`types.FunctionType`): The function to be called
            on each node of the graph.


def summaryDF(date=None, token='', version=''):

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

https://iexcloud.io/docs/api/#stats-historical-summary

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

Returns:
        DataFrame: result


def emit_tree_format(tree, verbose=False):

    if verbose:
        print("Converting: " + repr(tree))
    ret_str = __recursive_formatter(tree)
    return ret_str

Returns a tree representation of a parse tree.

Args:
        tree:           the parse tree whose tree representation is to be generated
        verbose (bool): if True prints the parse tree to be formatted

Returns:
        str:  tree-like representation of the parse tree


def adafactor_decay_rate_adam(beta2):

  t = tf.to_float(tf.train.get_or_create_global_step()) + 1.0
  decay = beta2 * (1.0 - tf.pow(beta2, t - 1.0)) / (1.0 - tf.pow(beta2, t))
  # decay = tf.cond(tf.equal(t, 1.0), lambda: beta2, lambda: decay)
  return decay

Second-moment decay rate like Adam, subsuming the correction factor.

Args:
        beta2: a float between 0 and 1

Returns:
        a scalar


def __init__(self, base_core, input_shape=None, name="skip_connection_core"):

    super(SkipConnectionCore, self).__init__(name=name)
    self._base_core = base_core
    self._input_shape = input_shape

Construct a SkipConnectionCore.

Args:
        base_core: Base RNNCore to wrap.
        input_shape: Shape of the input as tuple, excluding the batch size.
        name: Name of the module.


def __getattr__(self, name):

        if self.has_service_by_name(name):
            return self._service_objects[name]
        return self.__getattribute__(name)

Syntactic sugar to enable direct access of service objects by alias.

Args:
        name: string, the alias a service object was registered under.


def restore(self, state):

        selector = DataStreamSelector.FromString(state.get(u'selector'))
        if self.selector != selector:
            raise ArgumentError("Attempted to restore an InvalidStreamWalker with a different selector",
                                selector=self.selector, serialized_data=state)

        if state.get(u'type') != u'invalid':
            raise ArgumentError("Invalid serialized state for InvalidStreamWalker", serialized_data=state)

Restore the contents of this virtual stream walker.

Args:
        state (dict): The previously serialized state.

Raises:
        ArgumentError: If the serialized state does not have
            a matching selector.


def forum_post_list(self, creator_id=None, creator_name=None,
                        topic_id=None, topic_title_matches=None,
                        topic_category_id=None, body_matches=None):

        params = {
            'search[creator_id]': creator_id,
            'search[creator_name]': creator_name,
            'search[topic_id]': topic_id,
            'search[topic_title_matches]': topic_title_matches,
            'search[topic_category_id]': topic_category_id,
            'search[body_matches]': body_matches
            }
        return self._get('forum_posts.json', params)

Return a list of forum posts.

    Parameters:
        creator_id (int):
        creator_name (str):
        topic_id (int):
        topic_title_matches (str):
        topic_category_id (int): Can be: 0, 1, 2 (General, Tags, Bugs &
                                Features respectively).
        body_matches (str): Can be part of the post content.


def copy_table(self, src, dst):

        # Create table.
        self.create_table_from(dst, src)

        # Copy contents of src to dst.
        self.execute("INSERT INTO {dst} SELECT * FROM {src}"
                     .format(dst=dst, src=src))

        # Commit changes.
        self.commit()

Create a carbon copy of the source table.

Args:
        src (str): The name of the table to copy.
        dst (str): The name of the target duplicate table.

Raises:
        sql.OperationalError: If source table does not exist.


def ParseNetworkConnectivityUsage(
      self, parser_mediator, cache=None, database=None, table=None,
      **unused_kwargs):

    # TODO: consider making ConnectStartTime + ConnectedTime an event.
    self._ParseGUIDTable(
        parser_mediator, cache, database, table,
        self._NETWORK_CONNECTIVITY_USAGE_VALUES_MAP,
        SRUMNetworkConnectivityUsageEventData)

Parses the network connectivity usage monitor table.

Args:
        parser_mediator (ParserMediator): mediates interactions between parsers
        and other components, such as storage and dfvfs.
        cache (Optional[ESEDBCache]): cache, which contains information about
        the identifiers stored in the SruDbIdMapTable table.
        database (Optional[pyesedb.file]): ESE database.
        table (Optional[pyesedb.table]): table.


def add_spin_by_element(self, spins):

        for site in self.sites:
            new_sp = {}
            for sp, occu in site.species.items():
                sym = sp.symbol
                oxi_state = getattr(sp, "oxi_state", None)
                new_sp[Specie(sym, oxidation_state=oxi_state,
                              properties={'spin': spins.get(str(sp), spins.get(sym, None))})] = occu
            site.species = new_sp

Add spin states to a structure.

Args:
        spisn (dict): Dict of spins associated with
        elements or species, e.g. {"Ni":+5} or {"Ni2+":5}


def __init__(self, solution_size, population_size=20):

        super(StandardOptimizer, self).__init__()

        # Set general algorithm paramaters
        self._solution_size = solution_size
        self._population_size = population_size

        # Parameters for metaheuristic optimization
        self._hyperparameters['_population_size'] = {
            'type': 'int',
            'min': 2,
            'max': 1026
        }

Initialize general optimization attributes and bookkeeping

Args:
        solution_size: The number of values in each solution.
        population_size: The number of solutions in every generation.


def markdown_table(data, headers):

    maxx = [max([len(x) for x in column]) for column in zip(*data)]
    maxx = [max(ll) for ll in zip(maxx, [len(x) for x in headers])]
    mask = " | ".join(["%-{0:d}s".format(n) for n in maxx])

    ret = [mask % headers]

    ret.append(" | ".join(["-"*n for n in maxx]))
    for line in data:
        ret.append(mask % line)
    return ret

Creates MarkDown table. Returns list of strings

Args:
        data -- [(cell00, cell01, ...), (cell10, cell11, ...), ...]
        headers -- sequence of strings: (header0, header1, ...)


def check_tweet(tweet, validation_checking=False):

    if "id" not in tweet:
        raise NotATweetError("This text has no 'id' key")

    original_format = is_original_format(tweet)

    if original_format:
        _check_original_format_tweet(tweet, validation_checking=validation_checking)
    else:
        _check_activity_streams_tweet(tweet, validation_checking=validation_checking)

    return original_format

Ensures a tweet is valid and determines the type of format for the tweet.

Args:
        tweet (dict/Tweet): the tweet payload
        validation_checking (bool): check for valid key structure in a tweet.


def create(self, resource, timeout=-1):

        return self._client.create(resource, timeout=timeout, default_values=self.DEFAULT_VALUES)

Creates a scope.

Args:
        resource (dict): Object to create.
        timeout:
            Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation
            in OneView, just stop waiting for its completion.

Returns:
        dict: Created scope.


def zip(self, destination: typing.Union[str, Path] = None, encode: bool = True) -> str:

        if encode:
            self._encode()

        if destination is None:
            destination_path = self.miz_path.parent.joinpath(f'{self.miz_path.stem}_EMIZ.miz')
        else:
            destination_path = elib.path.ensure_file(destination, must_exist=False)

        LOGGER.debug('zipping mission to: %s', destination_path)

        destination_path.write_bytes(dummy_miz)

        with ZipFile(str(destination_path), mode='w', compression=8) as zip_file:

            for root, _, items in os.walk(self.temp_dir.absolute()):
                for item in items:
                    item_abs_path = Path(root, item).absolute()
                    item_rel_path = Path(item_abs_path).relative_to(self.temp_dir)
                    zip_file.write(item_abs_path, arcname=item_rel_path)

        return str(destination_path)

Write mission, dictionary etc. to a MIZ file

Args:
        destination: target MIZ file (if none, defaults to source MIZ + "_EMIZ"

    Returns: destination file


def extract_derivative_feature(feature):

    first_derivative_feature = processing.derivative_extraction(
        feature, DeltaWindows=2)
    second_derivative_feature = processing.derivative_extraction(
        first_derivative_feature, DeltaWindows=2)

    # Creating the future cube for each file
    feature_cube = np.concatenate(
        (feature[:, :, None], first_derivative_feature[:, :, None],
         second_derivative_feature[:, :, None]),
        axis=2)
    return feature_cube

This function extracts temporal derivative features which are
    first and second derivatives.

Args:
    feature (array): The feature vector which its size is: N x M

Returns:
        array: The feature cube vector which contains the static, first and second derivative features of size: N x M x 3


def mkdir_uchroot(dirpath, root="."):

    from benchbuild.utils.uchroot import no_args, uretry

    uchroot = no_args()
    uchroot = uchroot["-E", "-A", "-C", "-w", "/", "-r"]
    uchroot = uchroot[os.path.abspath(root)]
    uretry(uchroot["--", "/bin/mkdir", "-p", dirpath])

Create a file inside a uchroot env.

    You will want to use this when you need to create a file with apropriate
    rights inside a uchroot container with subuid/subgid handling enabled.

Args:
        dirpath:
            The dirpath that should be created. Absolute inside the
            uchroot container.
        root:
            The root PATH of the container filesystem as seen outside of
            the container.


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

        check_type(url, basestring, may_be_none=False)
        check_type(params, dict)

        # Expected response code
        erc = kwargs.pop('erc', EXPECTED_RESPONSE_CODE['GET'])

        response = self.request('GET', url, erc, params=params, **kwargs)
        return extract_and_parse_json(response)

Sends a GET request.

Args:
        url(basestring): The URL of the API endpoint.
        params(dict): The parameters for the HTTP GET request.
        **kwargs:
            erc(int): The expected (success) response code for the request.
            others: Passed on to the requests package.

Raises:
        ApiError: If anything other than the expected response code is
            returned by the Webex Teams API endpoint.


def laid_out_pcoord(self, mesh_axis):

    divisor = list_product(self.shape.to_integer_list[mesh_axis + 1:])
    modulus = self.shape[mesh_axis].size
    def my_fn(pnum):
      return (pnum // divisor) % modulus
    return self.slicewise(my_fn, self.laid_out_pnum())

Returns a LaidOutTensor containing the processor coordinate.

Args:
        mesh_axis: int.

Returns:
        LaidOutTensor where each slice is an integer scalar.


def load(self, fobj, index=None):

        if index is None:
            index = self._get_tab_index()
        page = self.pages[index]

        if fobj is None:
            return

        if not isinstance(fobj, tuple(page.clss_load)):
            raise RuntimeError('Object to load must be in {0!s} (not a {1!s})'.format(
             [x.__name__ for x in page.clss_load], fobj.__class__.__name__))

        page.editor.load(fobj)
        self._update_gui_text_tabs()

Loads given DataFile object. **tolerant with None**

Args:
        fobj: object of one of accepted classes
        index: tab index to load fobj into. If not passed, loads into current tab


def build_batch(cls, size, **kwargs):

        return [cls.build(**kwargs) for _ in range(size)]

Build a batch of instances of the given class, with overriden attrs.

Args:
        size (int): the number of instances to build

Returns:
        object list: the built instances


def select_files(self, what="o"):

        choices = collections.OrderedDict([
            ("i", self.input_file),
            ("o", self.output_file),
            ("f", self.files_file),
            ("j", self.job_file),
            ("l", self.log_file),
            ("e", self.stderr_file),
            ("q", self.qout_file),
        ])

        if what == "all":
            return [getattr(v, "path") for v in choices.values()]

        selected = []
        for c in what:
            try:
                selected.append(getattr(choices[c], "path"))
            except KeyError:
                logger.warning("Wrong keyword %s" % c)

        return selected

Helper function used to select the files of a task.

Args:
        what: string with the list of characters selecting the file type
            Possible choices:
                i ==> input_file,
                o ==> output_file,
                f ==> files_file,
                j ==> job_file,
                l ==> log_file,
                e ==> stderr_file,
                q ==> qout_file,
                all ==> all files.


def gpio_set(self, pins, states):

        if len(pins) != len(states):
            raise ValueError('Length mismatch between pins and states.')

        size = len(pins)
        indices = (ctypes.c_uint8 * size)(*pins)
        states = (ctypes.c_uint8 * size)(*states)
        result_states = (ctypes.c_uint8 * size)()
        result = self._dll.JLINK_EMU_GPIO_SetState(ctypes.byref(indices),
                                                   ctypes.byref(states),
                                                   ctypes.byref(result_states),
                                                   size)
        if result < 0:
            raise errors.JLinkException(result)

        return list(result_states)

Sets the state for one or more user-controllable GPIOs.

    For each of the given pins, sets the the corresponding state based on
    the index.

Args:
        self (JLink): the ``JLink`` instance
        pins (list): list of GPIO indices
        states (list): list of states to set

Returns:
        A list of updated states.

Raises:
        JLinkException: on error.
        ValueError: if ``len(pins) != len(states)``


def __init__(self, scopes=None, service_account_name='default', **kwds):

        # If there is a connectivity issue with the metadata server,
        # detection calls may fail even if we've already successfully
        # identified these scopes in the same execution. However, the
        # available scopes don't change once an instance is created,
        # so there is no reason to perform more than one query.
        self.__service_account_name = service_account_name
        cached_scopes = None
        cache_filename = kwds.get('cache_filename')
        if cache_filename:
            cached_scopes = self._CheckCacheFileForMatch(
                cache_filename, scopes)

        scopes = cached_scopes or self._ScopesFromMetadataServer(scopes)

        if cache_filename and not cached_scopes:
            self._WriteCacheFile(cache_filename, scopes)

        # We check the scopes above, but don't need them again after
        # this point. Newer versions of oauth2client let us drop them
        # here, but since we support older versions as well, we just
        # catch and squelch the warning.
        with warnings.catch_warnings():
            warnings.simplefilter('ignore')
            super(GceAssertionCredentials, self).__init__(scope=scopes, **kwds)

Initializes the credentials instance.

Args:
        scopes: The scopes to get. If None, whatever scopes that are
        available to the instance are used.
        service_account_name: The service account to retrieve the scopes
        from.
        **kwds: Additional keyword args.


def shop(self, index):

        return UserShopFront(self.usr, item.owner, item.id, str(item.price))

Return's the user shop the indexed item is in

    Parameters:
        index (int) -- The item index

    Returns
        UserShopFront - User shop item is in


def add_string(self, data):

        lines = []
        while data:
            match = self._line_end_re.search(data)
            if match is None:
                chunk = data
            else:
                chunk = data[:match.end()]

            data = data[len(chunk):]

            if self._buf and self._buf[-1].endswith(b('\r')) and not chunk.startswith(b('\n')):
                # if we get a carriage return followed by something other than
                # a newline then we assume that we're overwriting the current
                # line (ie. a progress bar)
                #
                # We don't terminate lines that end with a carriage return until
                # we see what's coming next so we can distinguish between a
                # progress bar situation and a Windows line terminator.
                #
                # TODO(adrian): some day these hacks should be replaced with
                # real terminal emulation
                lines.append(self._finish_line())

            self._buf.append(chunk)
            if chunk.endswith(b('\n')):
                lines.append(self._finish_line())

        return lines

Process some data splitting it into complete lines and buffering the rest

Args:
        data: A `str` in Python 2 or `bytes` in Python 3

Returns:
        list of complete lines ending with a carriage return (eg. a progress
        bar) or a newline.


def rotate(self, matrix, tol=1e-3):

        matrix = SquareTensor(matrix)
        if not matrix.is_rotation(tol):
            raise ValueError("Rotation matrix is not valid.")
        sop = SymmOp.from_rotation_and_translation(matrix,
                                                   [0., 0., 0.])
        return self.transform(sop)

Applies a rotation directly, and tests input matrix to ensure a valid
    rotation.

Args:
        matrix (3x3 array-like): rotation matrix to be applied to tensor
        tol (float): tolerance for testing rotation matrix validity


def for_executor(cls, executor: Optional[Executor]) -> 'Subsystem':

        if isinstance(executor, ThreadPoolExecutor):
            return _ThreadingSubsystem(executor)
        elif executor is None:
            return _AsyncioSubsystem()
        else:
            raise TypeError(executor)

Return a subsystem based on the given executor. If ``executor`` is
    None, use :mod:`asyncio`. If ``executor`` is a
    :class:`concurrent.futures.ThreadPoolExecutor`, use :mod:`threading`.

Args:
        executor: The executor in use, if any.


def _updateInferenceStats(self, statistics, objectName=None):

    L6aLearnableCells = self.getL6aLearnableCells()
    L6aSensoryAssociatedCells = self.getL6aSensoryAssociatedCells()
    L6aRepresentations = self.getL6aRepresentations()
    L4Representations = self.getL4Representations()
    L4PredictedCells = self.getL4PredictedCells()
    L2Representation = self.getL2Representations()

    for i in xrange(self.numColumns):
      statistics["L6a SensoryAssociatedCells C" + str(i)].append(
        len(L6aSensoryAssociatedCells[i]))
      statistics["L6a LearnableCells C" + str(i)].append(
        len(L6aLearnableCells[i]))
      statistics["L6a Representation C" + str(i)].append(
        len(L6aRepresentations[i]))
      statistics["L4 Representation C" + str(i)].append(
        len(L4Representations[i]))
      statistics["L4 Predicted C" + str(i)].append(len(L4PredictedCells[i]))
      statistics["L2 Representation C" + str(i)].append(
        len(L2Representation[i]))
      statistics["Full L2 SDR C" + str(i)].append(sorted(
        [int(c) for c in L2Representation[i]]))
      statistics["L4 Apical Segments C" + str(i)].append(len(
        self.L4Regions[i].getSelf()._tm.getActiveApicalSegments()))

      # add true overlap and classification result if objectName was learned
      if objectName in self.learnedObjects:
        objectRepresentation = self.learnedObjects[objectName]
        statistics["Overlap L2 with object C" + str(i)].append(
          len(objectRepresentation[i] & L2Representation[i]))

    if objectName in self.learnedObjects:
      if self.isObjectClassified(objectName, minOverlap=30):
        statistics["Correct classification"].append(1.0)
      else:
        statistics["Correct classification"].append(0.0)

Updates the inference statistics.

    Parameters:
    ----------------------------
    @param  statistics (dict)
            Dictionary in which to write the statistics

    @param  objectName (str)
            Name of the inferred object, if known. Otherwise, set to None.


def probabilistic_collocation(order, dist, subset=.1):

    abscissas, weights = chaospy.quad.collection.golub_welsch(order, dist)

    likelihood = dist.pdf(abscissas)

    alpha = numpy.random.random(len(weights))
    alpha = likelihood > alpha*subset*numpy.max(likelihood)

    abscissas = abscissas.T[alpha].T
    weights = weights[alpha]
    return abscissas, weights

Probabilistic collocation method.

Args:
        order (int, numpy.ndarray) : Quadrature order along each axis.
        dist (Dist) : Distribution to generate samples from.
        subset (float) : Rate of which to removed samples.


def CanonicalPathToLocalPath(path):
  r
  # Account for raw devices
  path = path.replace("/\\", "\\")
  path = path.replace("/", "\\")
  m = re.match(r"\\([a-zA-Z]):(.*)$", path)
  if m:
    path = "%s:\\%s" % (m.group(1), m.group(2).lstrip("\\"))

  return path

r"""Converts the canonical paths as used by GRR to OS specific paths.

    Due to the inconsistencies between handling paths in windows we need to
    convert a path to an OS specific version prior to using it. This function
    should be called just before any OS specific functions.

    Canonical paths on windows have:
        - / instead of \.
        - Begin with /X:// where X is the drive letter.

Args:
        path: A canonical path specification.

Returns:
        A windows specific path.


def __init__(self, config={}):

        self._config = config

        # The child class should override these properties or else the
        # restclient won't work. Reevalute whether to do this as an abstract
        # base class so it doesn't get used by itself.
        self._headers = {}
        self._base_url = ""

        if config.get('session'):
            self._session = requests.Session()
        else:
            self._session = requests

Base class for interacting with RESTful APIs
    Child class MUST have a ._base_url property!

Args:
        config (dict): Arbitrary options that child classes can access


def console_get_alignment(con: tcod.console.Console) -> int:

    return int(lib.TCOD_console_get_alignment(_console(con)))

Return this consoles current alignment mode.

Args:
        con (Console): Any Console instance.

    .. deprecated:: 8.5
        Check :any:`Console.default_alignment` instead.


def sync(coro, timeout=None):

    loop = initloop()
    return asyncio.run_coroutine_threadsafe(coro, loop).result(timeout)

Schedule a coroutine to run on the global loop and return it's result.

Args:
        coro (coroutine): The coroutine instance.

Note:
        This API is thread safe and should only be called by non-loop threads.


def normalize_partial_name(decl):

    if decl.cache.normalized_partial_name is None:
        decl.cache.normalized_partial_name = normalize(decl.partial_name)
    return decl.cache.normalized_partial_name

Cached variant of normalize

Args:
        decl (declaration.declaration_t): the declaration

Returns:
        str: normalized name


def __init__(self, launchdjobs):

    self.launchdjobs = launchdjobs

    self.blacklist_regex = [
        re.compile(r"^0x[a-z0-9]+\.anonymous\..+$"),
        re.compile(r"^0x[a-z0-9]+\.mach_init\.(crash_inspector|Inspector)$"),
    ]

Initialize.

Args:
        launchdjobs: NSCFArray of NSCFDictionarys containing launchd job data from
                the ServiceManagement framework.


def array_to_base64_png(array):

  # TODO(cais): Deal with 3D case.
  # TODO(cais): If there are None values in here, replace them with all NaNs.
  array = np.array(array, dtype=np.float32)
  if len(array.shape) != 2:
    raise ValueError(
        "Expected rank-2 array; received rank-%d array." % len(array.shape))
  if not np.size(array):
    raise ValueError(
        "Cannot encode an empty array (size: %s) as image." % (array.shape,))

  is_infinity = np.isinf(array)
  is_positive = array > 0.0
  is_positive_infinity = np.logical_and(is_infinity, is_positive)
  is_negative_infinity = np.logical_and(is_infinity,
                                        np.logical_not(is_positive))
  is_nan = np.isnan(array)
  finite_indices = np.where(np.logical_and(np.logical_not(is_infinity),
                                           np.logical_not(is_nan)))
  if np.size(finite_indices):
    # Finite subset is not empty.
    minval = np.min(array[finite_indices])
    maxval = np.max(array[finite_indices])
    scaled = np.array((array - minval) / (maxval - minval) * 255,
                      dtype=np.uint8)
    rgb = np.repeat(np.expand_dims(scaled, -1), IMAGE_COLOR_CHANNELS, axis=-1)
  else:
    rgb = np.zeros(array.shape + (IMAGE_COLOR_CHANNELS,), dtype=np.uint8)

  # Color-code pixels that correspond to infinities and nans.
  rgb[is_positive_infinity] = POSITIVE_INFINITY_RGB
  rgb[is_negative_infinity] = NEGATIVE_INFINITY_RGB
  rgb[is_nan] = NAN_RGB

  image_encoded = base64.b64encode(encoder.encode_png(rgb))
  return image_encoded

Convert an array into base64-enoded PNG image.

Args:
        array: A 2D np.ndarray or nested list of items.

Returns:
        A base64-encoded string the image. The image is grayscale if the array is
        2D. The image is RGB color if the image is 3D with lsat dimension equal to
        3.

Raises:
        ValueError: If the input `array` is not rank-2, or if the rank-2 `array` is
        empty.


def validate(self, table: pd.DataFrame, failed_only=False) -> pd.DataFrame:

        series = table[self.name]

        self._check_series_name(series)

        validators = self.validators

        results = pd.DataFrame({validator: series for validator in validators}, index=series.index)

        for name, func in validators.items():
            results[name] = func(results[name])

        results['dtype'] = self._validate_series_dtype(series)

        if self.unique:
            results['unique'] = v.funcs.unique(series)

        if failed_only:
            results = find_failed_rows(results)

        return results

Return a dataframe of validation results for the appropriate series vs the vector of validators.

Args:
        table (pd.DataFrame): A dataframe on which to apply validation logic.
        failed_only (bool): If ``True``: return only the indexes that failed to validate.


def Deserialize(self, reader):

        super(ContractState, self).Deserialize(reader)

        code = FunctionCode()
        code.Deserialize(reader)
        self.Code = code

        self.ContractProperties = reader.ReadUInt8()
        self.Name = reader.ReadVarString(max=252)
        self.CodeVersion = reader.ReadVarString(max=252)
        self.Author = reader.ReadVarString(max=252)
        self.Email = reader.ReadVarString(max=252)
        self.Description = reader.ReadVarString(max=65536)

Deserialize full object.

Args:
        reader (neocore.IO.BinaryReader):


def SetCACertificatesPath(self, ca_certificates_path):

    if not ca_certificates_path:
      return

    if not os.path.exists(ca_certificates_path):
      raise errors.BadConfigOption(
          'No such certificate file: {0:s}.'.format(ca_certificates_path))

    self._ca_certs = ca_certificates_path
    logger.debug('Elasticsearch ca_certs: {0!s}'.format(ca_certificates_path))

Sets the path to the CA certificates.

Args:
        ca_certificates_path (str): path to file containing a list of root
        certificates to trust.

Raises:
        BadConfigOption: if the CA certificates file does not exist.


def _create_outbound_stream(self, config=None):

        if config is None:
            raise ValueError('No stream config to create stream from.')

        name = self._get_stream_name(config)
        stream_handlers = self._get_stream_handlers(config, name)
        stream_input = config.get('input', None)
        stream_output = config.get('output', None)

        if type(stream_output) is int:
            return PortOutputStream(name,
                                    stream_input,
                                    stream_output,
                                    stream_handlers,
                                    zmq_args={'zmq_context': self.broker.context,
                                              'zmq_proxy_xsub_url': self.broker.XSUB_URL,
                                              'zmq_proxy_xpub_url': self.broker.XPUB_URL})
        else:
            if stream_output is not None:
                log.warn("Output of stream {} is not an integer port. "
                         "Stream outputs can only be ports.".format(name))
            return ZMQStream(name,
                             stream_input,
                             stream_handlers,
                             zmq_args={'zmq_context': self.broker.context,
                                       'zmq_proxy_xsub_url': self.broker.XSUB_URL,
                                       'zmq_proxy_xpub_url': self.broker.XPUB_URL})

Creates an outbound stream from its config.

    Params:
        config:       stream configuration as read by ait.config

Returns:
        stream:       a Stream

Raises:
        ValueError:   if any of the required config values are missing


def _OpenFileObject(self, path_spec):

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

    file_object = resolver.Resolver.OpenFileObject(
        path_spec.parent, resolver_context=self._resolver_context)
    qcow_file = pyqcow.file()
    qcow_file.open_file_object(file_object)
    return qcow_file

Opens the file-like object defined by path specification.

Args:
        path_spec (PathSpec): path specification.

Returns:
        pyqcow.file: a file-like object.

Raises:
        PathSpecError: if the path specification is incorrect.


def save_pkl(filename=None, times=None):

    if times is None:
        if not f.root.stopped:
            times = collapse.collapse_times()
        else:
            times = f.root.times
    else:
        if isinstance(times, (list, tuple)):
            for t in times:
                if not isinstance(t, Times):
                    raise TypeError("Expected single Times instance or list/tuple of Times instances for param 'times'.")
        elif not isinstance(times, Times):
            raise TypeError("Expected single Times instance or list/tuple of Times instances for param 'times'.")
    if filename is not None:
        with open(str(filename), 'wb') as file:
            pickle.dump(times, file)
    else:
        return pickle.dumps(times)

Serialize and / or save a Times data object using pickle (cPickle).

Args:
        filename (None, optional): Filename to dump to. If not provided,
            returns serialized object.
        times (None, optional): object to dump.  If non provided, uses
            current root.

Returns:
        pkl: Pickled Times data object, only if no filename provided.

Raises:
        TypeError: If 'times' is not a Times object or a list of tuple of
            them.


def connect(url, prefix=None, **kwargs):

    return connection(url, prefix=get_prefix(prefix), **kwargs)

connect and return a connection instance from url

Args:
        - url (str): xbahn connection url


def create_public_ip(access_token, subscription_id, resource_group, public_ip_name, dns_label,
                     location):

    endpoint = ''.join([get_rm_endpoint(),
                        '/subscriptions/', subscription_id,
                        '/resourceGroups/', resource_group,
                        '/providers/Microsoft.Network/publicIPAddresses/', public_ip_name,
                        '?api-version=', NETWORK_API])
    ip_body = {'location': location}
    properties = {'publicIPAllocationMethod': 'Dynamic'}
    properties['dnsSettings'] = {'domainNameLabel': dns_label}
    ip_body['properties'] = properties
    body = json.dumps(ip_body)
    return do_put(endpoint, body, access_token)

Create a public ip address.

Args:
        access_token (str): A valid Azure authentication token.
        subscription_id (str): Azure subscription id.
        resource_group (str): Azure resource group name.
        public_ip_name (str): Name of the new public ip address resource.
        dns_label (str): DNS label to apply to the IP address.
        location (str): Azure data center location. E.g. westus.

Returns:
        HTTP response. Public IP address JSON body.


def now_playing(self, **kwargs):

        path = self._get_path('now_playing')

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

Get the list of movies playing in theatres. This list refreshes
    every day. The maximum number of items this list will include is 100.

Args:
        page: (optional) Minimum value of 1.  Expected value is an integer.
        language: (optional) ISO 639-1 code.

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


def generate_string(self, initial_logits, initial_state, sequence_length):

    current_logits = initial_logits
    current_state = initial_state

    generated_letters = []
    for _ in range(sequence_length):
      # Sample a character index from distribution.
      char_index = tf.squeeze(tf.multinomial(current_logits, 1))
      char_one_hot = tf.one_hot(char_index, self._output_size, 1.0, 0.0)
      generated_letters.append(char_one_hot)

      # Feed character back into the deep_lstm.
      gen_out_seq, current_state = self._core(
          tf.nn.relu(self._embed_module(char_one_hot)),
          current_state)
      current_logits = self._output_module(gen_out_seq)

    generated_string = tf.stack(generated_letters)

    return generated_string

Builds sub-graph to generate a string, sampled from the model.

Args:
        initial_logits: Starting logits to sample from.
        initial_state: Starting state for the RNN core.
        sequence_length: Number of characters to sample.

Returns:
        A Tensor of characters, with dimensions `[sequence_length, batch_size,
        output_size]`.


def __init__(self, destination, transport):

    self._destination = destination
    self._transport = transport

Create a new ADB stream.

Args:
        destination: String identifier for the destination of this stream.
        transport: AdbStreamTransport to use for reads/writes.


def refresh(self, access_token=None, **kwargs):

        if not self.token_lock.locked():
            with self.token_lock:
                if access_token == self.access_token or access_token is None:
                    if self.developer_token is not None:
                        r = self._httpclient.request(
                            method='POST',
                            url=self.developer_token_url,
                            path='/request_token',
                            headers={
                                'Authorization': 'Bearer {}'.format(
                                    self.developer_token
                                )
                            },
                            timeout=30,
                            raise_for_status=True
                        )

                    elif all(
                        [
                            self.client_id,
                            self.client_secret,
                            self.refresh_token
                        ]
                    ):
                        data = {
                            'client_id': self.client_id,
                            'client_secret': self.client_secret,
                            'refresh_token': self.refresh_token,
                            'grant_type': 'refresh_token'
                        }
                        r = self._httpclient.request(
                            method='POST',
                            url=self.token_url,
                            json=data,
                            path='/api/oauth2/RequestToken',
                            **kwargs
                        )
                    else:
                        raise PartialCredentialsError(
                            "Missing one or more required credentials"
                        )

                    if r:
                        if not r.ok:
                            raise PanCloudError(
                                '%s %s: %s' % (
                                r.status_code, r.reason, r.text)
                            )
                        try:
                            r_json = r.json()
                        except ValueError as e:
                            raise PanCloudError("Invalid JSON: %s" % e)
                        else:
                            if r.json().get(
                                'error_description'
                            ) or r.json().get(
                                'error'
                            ):
                                raise PanCloudError(r.text)
                            self.access_token = r_json.get(
                                'access_token', None
                            )
                            self.jwt_exp = self._decode_exp(
                                self.access_token_)
                            if r_json.get('refresh_token', None):
                                self.refresh_token = \
                                    r_json.get('refresh_token')
                            self.write_credentials()
                        return self.access_token_

Refresh access and refresh tokens.

Args:
        access_token (str): Access token to refresh. Defaults to ``None``.

Returns:
        str: Refreshed access token.


def list_objects(self, path='', relative=False, first_level=False,
                     max_request_entries=None):

        entries = 0
        next_values = []
        max_request_entries_arg = None

        if not relative:
            path = self.relpath(path)

        # From root
        if not path:
            objects = self._list_locators()

        # Sub directory
        else:
            objects = self._list_objects(
                self.get_client_kwargs(path), max_request_entries)

        # Yield file hierarchy
        for obj in objects:
            # Generate first level objects entries
            try:
                name, header, is_directory = obj
            except ValueError:
                # Locators
                name, header = obj
                is_directory = True

            # Start to generate subdirectories content
            if is_directory and not first_level:
                name = next_path = name.rstrip('/') + '/'

                if path:
                    next_path = '/'.join((path.rstrip('/'), name))

                if max_request_entries is not None:
                    max_request_entries_arg = max_request_entries - entries

                next_values.append((
                    name, self._generate_async(self.list_objects(
                        next_path, relative=True,
                        max_request_entries=max_request_entries_arg))))

            entries += 1
            yield name, header
            if entries == max_request_entries:
                return

        for next_name, generator in next_values:
            # Generate other levels objects entries
            for name, header in generator:

                entries += 1
                yield '/'.join((next_name.rstrip('/'), name)), header
                if entries == max_request_entries:
                    return

List objects.

Args:
        path (str): Path or URL.
        relative (bool): Path is relative to current root.
        first_level (bool): It True, returns only first level objects.
            Else, returns full tree.
        max_request_entries (int): If specified, maximum entries returned
            by request.

Returns:
        generator of tuple: object name str, object header dict


def parse_tmhmm_long(tmhmm_results):

    with open(tmhmm_results) as f:
        lines = f.read().splitlines()

    infodict = defaultdict(dict)

    for l in lines:
        if 'Number of predicted TMHs:' in l:
            gene = l.split(' Number')[0].strip('# ')
            infodict[gene]['num_tm_helices'] = int(l.split(': ')[1])

        if 'WARNING' in l:
            log.warning('{}: no TMHMM predictions'.format(l))
            continue

        # TODO: POSSIBLE N-term signal sequence - parse this

        # Look for the lines without #, these are the TM predicted regions
        if '#' not in l:
            stuff = l.split()
            if stuff[1] == 'TMHMM2.0':

                gene = stuff[0]
                region = stuff[2]
                region_start = stuff[3]
                region_end = stuff[4]

                if 'sequence' in infodict[gene]:
                    tm_seq = infodict[gene]['sequence']
                else:
                    tm_seq = ''

                if region == 'outside':
                    info = 'O'
                elif region == 'inside':
                    info = 'I'
                elif region == 'TMhelix':
                    info = 'T'
                else:
                    log.error('{}: unknown region type'.format(info))
                    info = '-'

                for r in range(int(region_start), int(region_end) + 1):
                    tm_seq += info

                infodict[gene]['sequence'] = tm_seq

    return infodict

Parse the 'long' output format of TMHMM and return a dictionary of ``{sequence_ID: TMHMM_prediction}``.

Args:
        tmhmm_results (str): Path to long format TMHMM output.

Returns:
        dict: Dictionary of ``{sequence_ID: TMHMM_prediction}``


def is_coord_subset_pbc(subset, superset, atol=1e-8, mask=None):

    c1 = np.array(subset, dtype=np.float64)
    c2 = np.array(superset, dtype=np.float64)
    if mask is not None:
        m = np.array(mask, dtype=np.int)
    else:
        m = np.zeros((len(subset), len(superset)), dtype=np.int)
    atol = np.zeros(3, dtype=np.float64) + atol
    return cuc.is_coord_subset_pbc(c1, c2, atol, m)

Tests if all fractional coords in subset are contained in superset.

Args:
        subset, superset: List of fractional coords
        atol (float or size 3 array): Tolerance for matching
        mask (boolean array): Mask of matches that are not allowed.
            i.e. if mask[1,2] == True, then subset[1] cannot be matched
            to superset[2]

Returns:
        True if all of subset is in superset.


def _record_blank(self, current, dict_obj):

        if not self.list_blank:
            return
        if self.list_blank not in current:
            self.blank.append(dict_obj)

records the dictionay in the the 'blank' attribute based on the
    'list_blank' path

Args:
    -----
        current: the current dictionay counts
        dict_obj: the original dictionary object


def __init__(self, **kwargs):

        try:
            self.UIStatusMsg = ''
            self.mac = kwargs.get('EUI')
            self.handle = None
            self.AutoDUTEnable = False
            self._is_net = False                  # whether device is through ser2net
            self.logStatus = {'stop':'stop', 'running':'running', 'pauseReq':'pauseReq', 'paused':'paused'}
            self.logThreadStatus = self.logStatus['stop']
            self.connectType = (kwargs.get('Param5')).strip().lower() if kwargs.get('Param5') is not None else 'usb'
            if self.connectType == 'ip':
                self.dutIpv4 = kwargs.get('TelnetIP')
                self.dutPort = kwargs.get('TelnetPort')
                self.port = self.dutIpv4 + ':' + self.dutPort
            else:
                self.port = kwargs.get('SerialPort')
            self.intialize()
        except Exception, e:
            ModuleHelper.WriteIntoDebugLogger('initialize() Error: ' + str(e))

initialize the serial port and default network parameters

Args:
        **kwargs: Arbitrary keyword arguments
                Includes 'EUI' and 'SerialPort'


def from_raw(self, file_names=None, **kwargs):

        # This function only loads one test at a time (but could contain several
        # files). The function from_res() also implements loading several
        # datasets (using list of lists as input).

        if file_names:
            self.file_names = file_names

        if not isinstance(file_names, (list, tuple)):
            self.file_names = [file_names, ]

        # file_type = self.tester
        raw_file_loader = self.loader
        set_number = 0
        test = None
        counter = 0
        self.logger.debug("start iterating through file(s)")
        for f in self.file_names:
            self.logger.debug("loading raw file:")
            self.logger.debug(f"{f}")
            new_tests = raw_file_loader(f, **kwargs)
            if new_tests:
                if test is not None:
                    self.logger.debug("continuing reading files...")
                    _test = self._append(test[set_number], new_tests[set_number])
                    if not _test:
                        self.logger.warning(f"EMPTY TEST: {f}")
                        continue
                    test[set_number] = _test
                    self.logger.debug("added this test - started merging")
                    for j in range(len(new_tests[set_number].raw_data_files)):
                        raw_data_file = new_tests[set_number].raw_data_files[j]
                        file_size = new_tests[set_number].raw_data_files_length[j]
                        test[set_number].raw_data_files.append(raw_data_file)
                        test[set_number].raw_data_files_length.append(file_size)
                        counter += 1
                        if counter > 10:
                            self.logger.debug("ERROR? Too many files to merge")
                            raise ValueError("Too many files to merge - "
                                             "could be a p2-p3 zip thing")
                else:
                    self.logger.debug("getting data from first file")
                    if new_tests[set_number].no_data:
                        self.logger.debug("NO DATA")
                    else:
                        test = new_tests
            else:
                self.logger.debug("NOTHING LOADED")

        self.logger.debug("finished loading the raw-files")

        test_exists = False
        if test:
            if test[0].no_data:
                self.logging.debug("the first dataset (or only dataset) loaded from the raw data file is empty")
            else:
                test_exists = True

        if test_exists:
            if not prms.Reader.sorted_data:
                self.logger.debug("sorting data")
                test[set_number] = self._sort_data(test[set_number])

            self.datasets.append(test[set_number])
        else:
            self.logger.warning("No new datasets added!")
        self.number_of_datasets = len(self.datasets)
        self.status_datasets = self._validate_datasets()
        self._invent_a_name()
        return self

Load a raw data-file.

Args:
        file_names (list of raw-file names): uses CellpyData.file_names if
            None. If the list contains more than one file name, then the
            runs will be merged together.


def es_json(self, role='rdf_class', remove_empty=True, **kwargs):

        def test_idx_status(cls_inst, **kwargs):

            if kwargs.get("force") == True:
                return False
            idx_time = cls_inst.get("kds_esIndexTime", [None])[0]
            mod_time = cls_inst.get("dcterm_modified", [None])[0]
            error_msg = cls_inst.get("kds_esIndexError", [None])[0]
            if (not idx_time) or \
               error_msg or \
               (idx_time and mod_time and idx_time < mod_time):
               return False
            return True

        # if self.__class__.__name__ == 'rdf_type':
        #     pdb.set_trace()
        rtn_obj = {}
        if kwargs.get("depth"):
            kwargs['depth'] += 1
        else:
            kwargs['depth'] = 1
        if role == 'rdf_class':
            if test_idx_status(self, **kwargs):
                return None
            for prop, value in self.items():
                if prop in ['kds_esIndexTime', 'kds_esIndexError']:
                    continue
                new_val = value.es_json()
                rtn_method = get_attr(self[prop], 'kds_esObjectType', [])
                if 'kdr_Array' in rtn_method:
                    rtn_obj[prop] = new_val
                elif (remove_empty and new_val) or not remove_empty:
                    if len(new_val) == 1:
                        rtn_obj[prop] = new_val[0]
                    else:
                        rtn_obj[prop] = new_val
            nested_props = None
        else:
            try:
                nested_props = self.es_defs.get('kds_esNestedProps',
                                                list(self.keys())).copy()
            except AttributeError:
                nested_props = list(self.keys())
            for prop, value in self.items():
                # if prop == 'bf_hasInstance':
                #     pdb.set_trace()
                if prop in ['kds_esIndexTime', 'kds_esIndexError']:
                    continue
                new_val = value.es_json(**kwargs)
                rtn_method = get_attr(self[prop], 'kds_esObjectType', [])
                if 'kdr_Array' in rtn_method:
                    rtn_obj[prop] = new_val
                elif (remove_empty and new_val) or not remove_empty:
                    if len(new_val) == 1:
                        rtn_obj[prop] = new_val[0] \
                                if not isinstance(new_val, dict) \
                                else new_val
                    else:
                        rtn_obj[prop] = new_val
        # if 'bf_Work' in self.hierarchy:
        #     pdb.set_trace()

        rtn_obj = get_es_label(rtn_obj, self)
        rtn_obj = get_es_value(rtn_obj, self)
        rtn_obj = get_es_ids(rtn_obj, self)
        if nested_props:
            nested_props += ['value', 'id', 'uri']
            rtn_obj = {key: value
                       for key, value in rtn_obj.items()
                       if key in nested_props}
        # rml_procs = self.es_defs.get("kds_esRmlProcessor", [])
        # # if role == 'rdf_class':
        # #     pdb.set_trace()
        # rml_procs = [proc for proc in rml_procs
        #              if role == 'rdf_class' or
        #              proc['force']]
        # if rml_procs:
        #     rml_maps = {}
        #     for rml in rml_procs:
        #         proc_kwargs = {rml['subj']: self.subject,
        #                        "dataset": self.dataset}
        #         proc_kwargs.update(rml['proc_kwargs'])
        #         rml_maps[rml['name']] = rml['processor'](**proc_kwargs)
        #     if rml_maps:
        #         rtn_obj['rml_map'] = rml_maps
        rml_maps = self.get_all_rml(role=role)
        if rml_maps:
                rtn_obj['rml_map'] = rml_maps
        # if self.get('bf_contribution'):
        #     pdb.set_trace()
        return rtn_obj

Returns a JSON object of the class for insertion into es

Args:
        role: the role states how the class data should be returned
            depending upon whether it is used as a subject of an object.
            options are kds_esNested or rdf_class
        remove_empty: True removes empty items from es object


def __init__(self, length=None, vendor=None):

        super().__init__(action_type=ActionType.OFPAT_VENDOR, length=length)
        self.vendor = vendor

Create an ActionVendorHeader with the optional parameters below.

Args:
        length (int): Length is a multiple of 8.
        vender (int): Vendor ID with the same form as in VendorHeader.
            Defaults to None.


def namespace_for_prefix(self, prefix):

        try:
            ni = self.__lookup_prefix(prefix)
        except PrefixNotFoundError:
            return None
        else:
            return ni.uri

Get the namespace the given prefix maps to.

Args:
        prefix (str): The prefix

Returns:
        str: The namespace, or None if the prefix isn't mapped to
            anything in this set.


def __init__(self, failfast=False, save_tests=False, report_template=None, report_dir=None,
        log_level="INFO", log_file=None):

        self.exception_stage = "initialize HttpRunner()"
        kwargs = {
            "failfast": failfast,
            "resultclass": report.HtmlTestResult
        }
        self.unittest_runner = unittest.TextTestRunner(**kwargs)
        self.test_loader = unittest.TestLoader()
        self.save_tests = save_tests
        self.report_template = report_template
        self.report_dir = report_dir
        self._summary = None
        if log_file:
            logger.setup_logger(log_level, log_file)

initialize HttpRunner.

Args:
        failfast (bool): stop the test run on the first error or failure.
        save_tests (bool): save loaded/parsed tests to JSON file.
        report_template (str): report template file path, template should be in Jinja2 format.
        report_dir (str): html report save directory.
        log_level (str): logging level.
        log_file (str): log file path.


def mkzip(archive, items, mode="w", save_full_paths=False):

    close = False
    try:
        if not isinstance(archive, zipfile.ZipFile):
            archive = zipfile.ZipFile(archive, mode, allowZip64=True)
            close = True
        logger.info("mkdzip: Creating %s, from: %s", archive.filename, items)
        if isinstance(items, str):
            items = [items]
        for item in items:
            item = os.path.abspath(item)
            basename = os.path.basename(item)
            if os.path.isdir(item):
                for root, directoires, filenames in os.walk(item):
                    for filename in filenames:
                        path = os.path.join(root, filename)
                        if save_full_paths:
                            archive_path = path.encode("utf-8")
                        else:
                            archive_path = os.path.join(
                                basename, path.replace(item, "").strip("\\/")
                            ).encode("utf-8")
                        archive.write(path, archive_path)
            elif os.path.isfile(item):
                if save_full_paths:
                    archive_name = item.encode("utf-8")
                else:
                    archive_name = basename.encode("utf-8")
                archive.write(item, archive_name)  # , zipfile.ZIP_DEFLATED)
        return True
    except Exception as e:
        logger.error("Error occurred during mkzip: %s" % e)
        return False
    finally:
        if close:
            archive.close()

Recursively zip a directory.

Args:
        archive (zipfile.ZipFile or str): ZipFile object add to or path to the
            output zip archive.
        items (str or list of str): Single item or list of items (files and
            directories) to be added to zipfile.
        mode (str): w for create new and write a for append to.
        save_full_paths (bool): Preserve full paths.


def __mul__(self, repeat):

        if not isinstance(repeat, int):
            raise TypeError("Can only multiply a graph with an integer")
        # copy edges
        new_edges = []
        for i in range(repeat):
            for vertex1, vertex2 in self.edges:
                new_edges.append(frozenset([vertex1+i*self.num_vertices, vertex2+i*self.num_vertices]))
        # copy numbers
        new_numbers = np.zeros((repeat, len(self.numbers)), int)
        new_numbers[:] = self.numbers
        new_numbers = new_numbers.ravel()
        # copy orders
        new_orders = np.zeros((repeat, len(self.orders)), int)
        new_orders[:] = self.orders
        new_orders = new_orders.ravel()
        # copy symbols
        if self.symbols is not None:
            new_symbols = self.symbols*repeat
        else:
            new_symbols = None
        return MolecularGraph(new_edges, new_numbers, new_orders, new_symbols)

Construct a graph that repeats this graph a number of times

Args:
    | ``repeat`` -- The number of repetitions.


def __init__(
        self,
        function_approximator,
        batch_size=4,
        map_size=(10, 10),
        memory_num=4,
        repeating_penalty=0.5,
        enemy_num=2,
        enemy_init_dist=5
    ):

        self.__map_arr = self.__create_map(map_size)
        self.__agent_pos = self.START_POS

        self.__enemy_num = enemy_num
        self.__enemy_pos_list = [None] * enemy_num
        self.__enemy_init_dist = enemy_init_dist
        self.__create_enemy(self.__map_arr)

        self.__reward_list = []
        self.__route_memory_list = []
        self.__memory_num = memory_num
        self.__repeating_penalty = repeating_penalty

        self.__batch_size = batch_size

        super().__init__(function_approximator)
        self.__inferencing_flag = False

Init.

Args:
        function_approximator:  is-a `FunctionApproximator`.
        map_size:               Size of map.
        memory_num:             The number of step of agent's memory.
        repeating_penalty:      The value of penalty in the case that agent revisit.
        enemy_num:              The number of enemies.
        enemy_init_dist:        Minimum euclid distance of initial position of agent and enemies.


def _DownloadAuthUrl(self, url, dest_dir):

    dest_file = tempfile.NamedTemporaryFile(dir=dest_dir, delete=False)
    dest_file.close()
    dest = dest_file.name

    self.logger.info(
        'Downloading url from %s to %s using authentication token.', url, dest)

    if not self.token:
      response = self.watcher.GetMetadata(
          self.token_metadata_key, recursive=False, retry=False)

      if not response:
        self.logger.info(
            'Authentication token not found. Attempting unauthenticated '
            'download.')
        return self._DownloadUrl(url, dest_dir)

      self.token = '%s %s' % (
          response.get('token_type', ''), response.get('access_token', ''))

    try:
      request = urlrequest.Request(url)
      request.add_unredirected_header('Metadata-Flavor', 'Google')
      request.add_unredirected_header('Authorization', self.token)
      content = urlrequest.urlopen(request).read().decode('utf-8')
    except (httpclient.HTTPException, socket.error, urlerror.URLError) as e:
      self.logger.warning('Could not download %s. %s.', url, str(e))
      return None

    with open(dest, 'wb') as f:
      f.write(content)

    return dest

Download a Google Storage URL using an authentication token.

    If the token cannot be fetched, fallback to unauthenticated download.

Args:
        url: string, the URL to download.
        dest_dir: string, the path to a directory for storing metadata scripts.

Returns:
        string, the path to the file storing the metadata script.


def full_game_name(short_name):

  camel_game_name = misc_utils.snakecase_to_camelcase(short_name)
  full_name = camel_game_name + ATARI_GAME_MODE
  return full_name

CamelCase game name with mode suffix.

Args:
        short_name: snake_case name without mode e.g "crazy_climber"

Returns:
        full game name e.g. "CrazyClimberNoFrameskip-v4"


def GetPresetsByOperatingSystem(self, operating_system):

    preset_definitions = []
    for preset_definition in self._definitions.values():
      for preset_operating_system in preset_definition.operating_systems:
        if preset_operating_system.IsEquivalent(operating_system):
          preset_definitions.append(preset_definition)

    return preset_definitions

Retrieves preset definitions for a specific operating system.

Args:
        operating_system (OperatingSystemArtifact): an operating system artifact
        attribute container.

Returns:
        list[PresetDefinition]: preset definition that correspond with the
        operating system.


def read_html_file(data_dir, fileroot, encoding=None):

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

    return ftfy.fix_encoding(raw_html).strip()

Read the HTML file corresponding to identifier ``fileroot``
    in the raw HTML directory below the root ``data_dir``.

Args:
        data_dir (str)
        fileroot (str)
        encoding (str)

Returns:
        str


def decstr2int(dec_str, decimals):

    if not isinstance(decimals, int):
        raise TypeError('decimals must be an integer')
    try:
        dollars, cents = dec_str.split('.')
    except ValueError:
        if '.' not in dec_str:
            dollars = dec_str
            cents = '0'
        else:
            raise ValueError('Invalid decimal string')
    else:
        if len(cents) < decimals:
            cents = cents.ljust(decimals, '0')
        elif decimals < 1:
            cents = '0'
        elif len(cents) > decimals:
            cents = cents[:decimals]
    try:
        cents = int(cents)
    except:
        cents = 0
    try:
        return int(int(dollars) * (10 ** decimals)) + cents
    except:
        raise ValueError('Invalid decimal string')

Returns an integer that has the value of the decimal string:
    dec_str*10^decimals

Args:
    dec_str (string) that represents a decimal number
    decimals (int): number of decimals for creating the integer output

Returns:
    (int)

Raises:
    ValueError if dec_string is not a valid decimal string
    TypeError if decimals is not an integer
    Note: values may be truncated (not rounded).


def update(self, data):

        # If the instance was terminated, remove it
        updated = self.set_property('state', data['state'])
        updated |= self.set_property('notes', sorted(data['notes'] or []))
        updated |= self.set_property('last_notice', data['last_notice'])

        if updated:
            self.set_property('last_change', datetime.now())

        return updated

Updates the object information based on live data, if there were any changes made. Any changes will be
    automatically applied to the object, but will not be automatically persisted. You must manually call
    `db.session.add(instance)` on the object.

Args:
        data (:obj:): AWS API Resource object fetched from AWS API

Returns:
        `bool`


def count_stages(self, matrix_name):

        return len(self.data[matrix_name]) if matrix_name in self.data else 0

Number of registered stages for given matrix name.

    Parameters:
        matrix_name (str): name of the matrix

Returns:
        int: number of reported stages for given matrix name.


def is_remote_file_modified(web_file, destination):

    try:
        # check datetime of last modified in file.
        last_mod = web_file.headers.get('last-modified')
        if last_mod:
            web_file_time = time.strptime(
                web_file.headers.get(
                    'last-modified'), '%a, %d %b %Y %H:%M:%S %Z')
        else:
            web_file_time = time.gmtime()

        web_file_size = int(web_file.headers.get('content-length', -1))
        if os.path.exists(destination):
            file_time = time.gmtime(os.path.getmtime(destination))
            file_size = os.path.getsize(destination)
            if file_time >= web_file_time and file_size == web_file_size:
                return False

    except Exception as ex:
        msg = ('Fail checking if remote file is modified default returns TRUE'
               ' - {}'.format(ex))
        logger.debug(msg)

    return True

Check if online file has been modified.

Args:
        :web_file: online file to check.
        :destination: path of the offline file to compare.


def filter(self, *query_filter):

        for query in query_filter:
            self.query.append(query)
        return self

Set the query filter to perform the query with

Args:
        *query_filter: Simplified Query Language filter


def index(self, ref, columns):

        from ambry.orm.exc import NotFoundError

        logger.debug('Creating index for partition.\n    ref: {}, columns: {}'.format(ref, columns))

        connection = self._backend._get_connection()

        try:
            table_or_partition = self._library.partition(ref)
        except NotFoundError:
            table_or_partition = ref

        self._backend.index(connection, table_or_partition, columns)

Create an index on the columns.

Args:
        ref (str): id, vid, name or versioned name of the partition.
        columns (list of str): names of the columns needed indexes.


def __init__(self,
                 unique_identifier=None,
                 data=None):

        super(DecryptResponsePayload, self).__init__(
            enums.Tags.RESPONSE_PAYLOAD
        )

        self._unique_identifier = None
        self._data = None

        self.unique_identifier = unique_identifier
        self.data = data

Construct a Decrypt response payload struct.

Args:
        unique_identifier (string): The ID of the managed object (e.g.,
            a symmetric key) used for decryption. Required for encoding
            and decoding.
        data (bytes): The decrypted data in binary form. Required for
            encoding and decoding.


def Bernoulli(cls,
        mean: 'TensorFluent',
        batch_size: Optional[int] = None) -> Tuple[Distribution, 'TensorFluent']:

        probs = mean.tensor
        dist = tf.distributions.Bernoulli(probs=probs, dtype=tf.bool)
        batch = mean.batch
        if not batch and batch_size is not None:
            t = dist.sample(batch_size)
            batch = True
        else:
            t = dist.sample()
        scope = mean.scope.as_list()
        return (dist, TensorFluent(t, scope, batch=batch))

Returns a TensorFluent for the Bernoulli sampling op with given mean parameter.

Args:
        mean: The mean parameter of the Bernoulli distribution.
        batch_size: The size of the batch (optional).

Returns:
        The Bernoulli distribution and a TensorFluent sample drawn from the distribution.


def WideResnet(num_blocks=3, hidden_size=64, num_output_classes=10,
               mode='train'):

  del mode
  return layers.Serial(
      layers.Conv(hidden_size, (3, 3), padding='SAME'),
      WideResnetGroup(num_blocks, hidden_size),
      WideResnetGroup(num_blocks, hidden_size * 2, (2, 2)),
      WideResnetGroup(num_blocks, hidden_size * 4, (2, 2)), layers.BatchNorm(),
      layers.Relu(), layers.AvgPool(pool_size=(8, 8)), layers.Flatten(),
      layers.Dense(num_output_classes), layers.LogSoftmax())

WideResnet from https://arxiv.org/pdf/1605.07146.pdf.

Args:
        num_blocks: int, number of blocks in a group.
        hidden_size: the size of the first hidden layer (multiplied later).
        num_output_classes: int, number of classes to distinguish.
        mode: is it training or eval.

Returns:
        The WideResnet model with given layer and output sizes.


def invite_by_email(self, email, user, organization, **kwargs):
        # type: (Text, AbstractUser, AbstractBaseOrganization) -> OrganizationInvitationBase

        try:
            invitee = self.user_model.objects.get(email__iexact=email)
        except self.user_model.DoesNotExist:
            invitee = None

        # TODO allow sending just the OrganizationUser instance
        user_invitation = self.invitation_model.objects.create(
            invitee=invitee,
            invitee_identifier=email.lower(),
            invited_by=user,
            organization=organization,
        )
        self.send_invitation(user_invitation)
        return user_invitation

Primary interface method by which one user invites another to join

Args:
        email:
        request:
        **kwargs:

Returns:
        an invitation instance

Raises:
        MultipleObjectsReturned if multiple matching users are found


def get_penalty_model(specification):

    # check that the feasible_configurations are spin
    feasible_configurations = specification.feasible_configurations
    if specification.vartype is dimod.BINARY:
        feasible_configurations = {tuple(2 * v - 1 for v in config): en
                                   for config, en in feasible_configurations.items()}

    # convert ising_quadratic_ranges to the form we expect
    ising_quadratic_ranges = specification.ising_quadratic_ranges
    quadratic_ranges = {(u, v): ising_quadratic_ranges[u][v] for u, v in specification.graph.edges}

    bqm, gap = generate(specification.graph,
                        feasible_configurations,
                        specification.decision_variables,
                        specification.ising_linear_ranges,
                        quadratic_ranges,
                        specification.min_classical_gap,
                        None)  # unspecified smt solver

    try:
        ground = max(feasible_configurations.values())
    except ValueError:
        ground = 0.0  # if empty

    return pm.PenaltyModel.from_specification(specification, bqm, gap, ground)

Factory function for penaltymodel_maxgap.

Args:
        specification (penaltymodel.Specification): The specification
            for the desired penalty model.

Returns:
        :class:`penaltymodel.PenaltyModel`: Penalty model with the given specification.

Raises:
        :class:`penaltymodel.ImpossiblePenaltyModel`: If the penalty cannot be built.

    Parameters:
        priority (int): -100


def save(self, path_info, checksum):

        assert path_info["scheme"] == "local"
        assert checksum is not None

        path = path_info["path"]
        assert os.path.exists(path)

        actual_mtime, actual_size = get_mtime_and_size(path)
        actual_inode = get_inode(path)

        existing_record = self.get_state_record_for_inode(actual_inode)
        if not existing_record:
            self._insert_new_state_record(
                path, actual_inode, actual_mtime, actual_size, checksum
            )
            return

        self._update_state_for_path_changed(
            path, actual_inode, actual_mtime, actual_size, checksum
        )

Save checksum for the specified path info.

Args:
        path_info (dict): path_info to save checksum for.
        checksum (str): checksum to save.


def IsDeletedOrDefault(clean_lines, linenum):

  open_paren = clean_lines.elided[linenum].find('(')
  if open_paren < 0:
    return False
  (close_line, _, close_paren) = CloseExpression(
      clean_lines, linenum, open_paren)
  if close_paren < 0:
    return False
  return Match(r'\s*=\s*(?:delete|default)\b', close_line[close_paren:])

Check if current constructor or operator is deleted or default.

Args:
        clean_lines: A CleansedLines instance containing the file.
        linenum: The number of the line to check.

Returns:
        True if this is a deleted or default constructor.


def get_avatar(from_header, size=64, default="retro"):

    params = OrderedDict([("s", size), ("d", default)])
    query = parse.urlencode(params)
    address = email.utils.parseaddr(from_header)[1]
    value_hash = sha256(address.encode("utf-8")).hexdigest()
    return "https://seccdn.libravatar.org/avatar/{}?{}".format(value_hash, query)

Get the avatar URL from the email's From header.

Args:
        from_header (str): The email's From header. May contain the sender's full name.

Returns:
        str: The URL to that sender's avatar.


def _lease_valid(self, lease):

        if not lease.exist:
            return None

        if lease.has_env:
            return lease.uuid_path
        else:
            self._release(lease)
            return None

Check if the given lease exist and still has a prefix that owns it.
    If the lease exist but its prefix isn't, remove the lease from this
    store.

Args:
        lease (lago.subnet_lease.Lease): Object representation of the
            lease

Returns:
        str or None: If the lease and its prefix exists, return the path
            to the uuid of the prefix, else return None.