def parse_ensembl_gene_request(result):

    LOG.info("Parsing genes from request")

    for index, row in result.iterrows():
        # print(index, row)
        ensembl_info = {}

        # Pandas represents missing data with nan which is a float
        if type(row['hgnc_symbol']) is float:
            # Skip genes without hgnc information
            continue

        ensembl_info['chrom'] = row['chromosome_name']
        ensembl_info['gene_start'] = int(row['start_position'])
        ensembl_info['gene_end'] = int(row['end_position'])
        ensembl_info['ensembl_gene_id'] = row['ensembl_gene_id']
        ensembl_info['hgnc_symbol'] = row['hgnc_symbol']

        hgnc_id = row['hgnc_id']

        if type(hgnc_id) is float:
            hgnc_id = int(hgnc_id)
        else:
            hgnc_id = int(hgnc_id.split(':')[-1])

        ensembl_info['hgnc_id'] = hgnc_id

        yield ensembl_info

Parse a dataframe with ensembl gene information

Args:
        res(pandas.DataFrame)

Yields:
        gene_info(dict)


def _table_viewer(table, rows_per_page=25, fields=None):

  # TODO(gram): rework this to use google.datalab.utils.commands.chart_html

  if not table.exists():
    raise Exception('Table %s does not exist' % table.full_name)

  if not table.is_listable():
    return "Done"

  _HTML_TEMPLATE = u

  if fields is None:
    fields = google.datalab.utils.commands.get_field_list(fields, table.schema)
  div_id = google.datalab.utils.commands.Html.next_id()
  meta_count = ('rows: %d' % table.length) if table.length >= 0 else ''
  meta_name = table.full_name if table.job is None else ('job: %s' % table.job.id)
  if table.job:
    if table.job.cache_hit:
      meta_cost = 'cached'
    else:
      bytes = bigquery._query_stats.QueryStats._size_formatter(table.job.bytes_processed)
      meta_cost = '%s processed' % bytes
    meta_time = 'time: %.1fs' % table.job.total_time
  else:
    meta_cost = ''
    meta_time = ''

  data, total_count = google.datalab.utils.commands.get_data(table, fields, first_row=0,
                                                             count=rows_per_page)

  if total_count < 0:
    # The table doesn't have a length metadata property but may still be small if we fetched less
    # rows than we asked for.
    fetched_count = len(data['rows'])
    if fetched_count < rows_per_page:
      total_count = fetched_count

  chart = 'table' if 0 <= total_count <= rows_per_page else 'paged_table'
  meta_entries = [meta_count, meta_time, meta_cost, meta_name]
  meta_data = '(%s)' % (', '.join([entry for entry in meta_entries if len(entry)]))

  return _HTML_TEMPLATE.format(div_id=div_id,
                               static_table=google.datalab.utils.commands.HtmlBuilder
                               .render_chart_data(data),
                               meta_data=meta_data,
                               chart_style=chart,
                               source_index=google.datalab.utils.commands
                               .get_data_source_index(table.full_name),
                               fields=','.join(fields),
                               total_rows=total_count,
                               rows_per_page=rows_per_page,
                               data=json.dumps(data, cls=google.datalab.utils.JSONEncoder))

Return a table viewer.

    This includes a static rendering of the first page of the table, that gets replaced
    by the charting code in environments where Javascript is executable and BQ is available.

Args:
    table: the table to view.
    rows_per_page: how many rows to display at one time.
    fields: an array of field names to display; default is None which uses the full schema.

Returns:
    A string containing the HTML for the table viewer.


def broadcast(self, gossip_message, message_type, exclude=None):

        with self._lock:
            if exclude is None:
                exclude = []
            for connection_id in self._peers.copy():
                if connection_id not in exclude and \
                        self._network.is_connection_handshake_complete(
                            connection_id):
                    self.send(
                        message_type,
                        gossip_message.SerializeToString(),
                        connection_id,
                        one_way=True)

Broadcast gossip messages.

    Broadcast the message to all peers unless they are in the excluded
    list.

Args:
        gossip_message: The message to be broadcast.
        message_type: Type of the message.
        exclude: A list of connection_ids that should be excluded from this
            broadcast.


def from_statements(
        cls, sts: List[Influence], assign_default_polarities: bool = True
    ):

        _dict = {}
        for s in sts:
            if assign_default_polarities:
                for delta in deltas(s):
                    if delta["polarity"] is None:
                        delta["polarity"] = 1
            concepts = nameTuple(s)

            # Excluding self-loops for now:
            if concepts[0] != concepts[1]:
                if all(
                    map(exists, (delta["polarity"] for delta in deltas(s)))
                ):
                    if concepts in _dict:
                        _dict[concepts].append(s)
                    else:
                        _dict[concepts] = [s]

        edges = [
            (*concepts, {"InfluenceStatements": statements})
            for concepts, statements in _dict.items()
        ]
        return cls(edges)

Construct an AnalysisGraph object from a list of INDRA statements.
    Unknown polarities are set to positive by default.

Args:
        sts: A list of INDRA Statements

Returns:
        An AnalysisGraph instance constructed from a list of INDRA
        statements.


def get_num_days_required(offset, period='d', perc_required=0.90):

    x = pd.to_datetime('2010-01-01')
    delta = x - (x - offset)
    # convert to 'trading days' - rough guestimate
    days = delta.days * 0.69

    if period == 'd':
        req = days * perc_required
    elif period == 'm':
        req = (days / 20) * perc_required
    elif period == 'y':
        req = (days / 252) * perc_required
    else:
        raise NotImplementedError(
            'period not supported. Supported periods are d, m, y')

    return req

Estimates the number of days required to assume that data is OK.

    Helper function used to determine if there are enough "good" data
    days over a given period.

Args:
        * offset (DateOffset): Offset (lookback) period.
        * period (str): Period string.
        * perc_required (float): percentage of number of days
            expected required.


def erase(self):

        try:
            # This has to be in a try-catch, as the device may not be in a
            # state where it can halt, but we still want to try and erase.
            if not self.halted():
                self.halt()
        except errors.JLinkException:
            # Can't halt, so just continue to erasing.
            pass

        res = self._dll.JLINK_EraseChip()
        if res < 0:
            raise errors.JLinkEraseException(res)

        return res

Erases the flash contents of the device.

    This erases the flash memory of the target device.  If this method
    fails, the device may be left in an inoperable state.

Args:
        self (JLink): the ``JLink`` instance

Returns:
        Number of bytes erased.


def write(self, data):

    start_time = time.time()
    self._get_write_buffer().write(data)
    ctx = context.get()
    operation.counters.Increment(COUNTER_IO_WRITE_BYTES, len(data))(ctx)
    operation.counters.Increment(
        COUNTER_IO_WRITE_MSEC, int((time.time() - start_time) * 1000))(ctx)

Write data to the GoogleCloudStorage file.

Args:
        data: string containing the data to be written.


def get_ilo_sso_url(self, ip=None):

        uri = "{}/iloSsoUrl".format(self.data["uri"])

        if ip:
            uri = "{}?ip={}".format(uri, ip)

        return self._helper.do_get(uri)

Retrieves the URL to launch a Single Sign-On (SSO) session for the iLO web interface. If the server hardware is
    unsupported, the resulting URL will not use SSO and the iLO web interface will prompt for credentials.
    This is not supported on G7/iLO3 or earlier servers.

Args:
        ip: IP address or host name of the server's iLO management processor

Returns:
        URL


def BuildServiceStub(self, cls):

    def _ServiceStubInit(stub, rpc_channel):
      stub.rpc_channel = rpc_channel
    self.cls = cls
    cls.__init__ = _ServiceStubInit
    for method in self.descriptor.methods:
      setattr(cls, method.name, self._GenerateStubMethod(method))

Constructs the stub class.

Args:
        cls: The class that will be constructed.


def _UpdateUserGroups(self, user, groups):

    groups = ','.join(groups)
    self.logger.debug('Updating user %s with groups %s.', user, groups)
    command = self.usermod_cmd.format(user=user, groups=groups)
    try:
      subprocess.check_call(command.split(' '))
    except subprocess.CalledProcessError as e:
      self.logger.warning('Could not update user %s. %s.', user, str(e))
      return False
    else:
      self.logger.debug('Updated user account %s.', user)
      return True

Update group membership for a Linux user.

Args:
        user: string, the name of the Linux user account.
        groups: list, the group names to add the user as a member.

Returns:
        bool, True if user update succeeded.


def __init__(self, wrapper):

        self._wrapper = wrapper
        self.make_request = self._wrapper.request_parking

Initialization of the API module.

Args:
        wrapper (Wrapper): Object that performs the requests to endpoints.


def is_transcript_available(video_id, language_code=None):

    filter_attrs = {'video__edx_video_id': video_id}
    if language_code:
        filter_attrs['language_code'] = language_code

    transcript_set = VideoTranscript.objects.filter(**filter_attrs)
    return transcript_set.exists()

Returns whether the transcripts are available for a video.

Args:
        video_id: it can be an edx_video_id or an external_id extracted from external sources in a video component.
        language_code: it will the language code of the requested transcript.


def vgg13(pretrained=False, **kwargs):

    if pretrained:
        kwargs['init_weights'] = False
    model = VGG(make_layers(cfg['B']), **kwargs)
    if pretrained:
        model.load_state_dict(model_zoo.load_url(model_urls['vgg13']))
    return model

VGG 13-layer model (configuration "B")

Args:
        pretrained (bool): If True, returns a model pre-trained on ImageNet


def to_representation(self, instance):

        updated_program = copy.deepcopy(instance)
        enterprise_customer_catalog = self.context['enterprise_customer_catalog']
        updated_program['enrollment_url'] = enterprise_customer_catalog.get_program_enrollment_url(
            updated_program['uuid']
        )
        for course in updated_program['courses']:
            course['enrollment_url'] = enterprise_customer_catalog.get_course_enrollment_url(course['key'])
            for course_run in course['course_runs']:
                course_run['enrollment_url'] = enterprise_customer_catalog.get_course_run_enrollment_url(
                    course_run['key']
                )
        return updated_program

Return the updated program data dictionary.

Args:
        instance (dict): The program data.

Returns:
        dict: The updated program data.


def combine(self, x):

    depth = tf.shape(x)[-1]
    x *= tf.expand_dims(self._nonpadding, -1)
    ret = tf.unsorted_segment_sum(
        x, self._flat_indices, num_segments=self._batch * self._length)
    ret = tf.reshape(ret, [self._batch, self._length, depth])
    return ret

Return the output from the experts.

    When one example goes to multiple experts, the outputs are summed.

Args:
        x: a Tensor with shape [batch, num_experts, expert_capacity, depth]

Returns:
        a `Tensor` with shape `[batch, length, depth]


def main_only_quicksetup_rootlogger(level: int = logging.DEBUG,
                                    with_process_id: bool = False,
                                    with_thread_id: bool = False) -> None:

    # Nasty. Only call from "if __name__ == '__main__'" clauses!
    rootlogger = logging.getLogger()
    configure_logger_for_colour(rootlogger, level, remove_existing=True,
                                with_process_id=with_process_id,
                                with_thread_id=with_thread_id)

Quick function to set up the root logger for colour.

    Should ONLY be called from the ``if __name__ == 'main'`` script;
    see https://docs.python.org/3.4/howto/logging.html#library-config.

Args:
        level: log level to set
        with_process_id: include the process ID in the logger's name?
        with_thread_id: include the thread ID in the logger's name?


def start_vm(access_token, subscription_id, resource_group, vm_name):

    endpoint = ''.join([get_rm_endpoint(),
                        '/subscriptions/', subscription_id,
                        '/resourceGroups/', resource_group,
                        '/providers/Microsoft.Compute/virtualMachines/',
                        vm_name,
                        '/start',
                        '?api-version=', COMP_API])
    return do_post(endpoint, '', access_token)

Start a virtual machine.

Args:
        access_token (str): A valid Azure authentication token.
        subscription_id (str): Azure subscription id.
        resource_group (str): Azure resource group name.
        vm_name (str): Name of the virtual machine.

Returns:
        HTTP response.


def create_model(self, ModelName, PrimaryContainer, *args, **kwargs):  # pylint: disable=unused-argument

        LocalSagemakerClient._models[ModelName] = _LocalModel(ModelName, PrimaryContainer)

Create a Local Model Object

Args:
        ModelName (str): the Model Name
        PrimaryContainer (dict): a SageMaker primary container definition


def deleted(self, main_type, sub_type, deleted_since, owner=None, filters=None, params=None):

        params = params or {}

        if filters and filters.filters:
            params['filters'] = filters.filters_string
        if owner:
            params['owner'] = owner
        if deleted_since:
            params['deleteSince'] = deleted_since

        if not sub_type:
            url = '/v2/{}/deleted'.format(main_type)
        else:
            url = '/v2/{}/{}/deleted'.format(main_type, sub_type)

        return self.tcex.session.get(url, params=params)

Args:
    owner:
    filters:
    main_type:
    sub_type:
    deleted_since:
    params:

    Return:


def normalize_version(version):

    rv = []
    for x in version.split("."):
        try:
            rv.append(int(x))
        except ValueError:
            for y in re.split("([0-9]+)", x):
                if y == '':
                    continue
                try:
                    rv.append(int(y))
                except ValueError:
                    rv.append(y)
    return rv

Helper function to normalize version.
    Returns a comparable object.

Args:
        version (str) version, e.g. "0.1.0"


def build_chunk(oscillators):

    step_random_processes(oscillators)
    subchunks = []
    for osc in oscillators:
        osc.amplitude.step_amp()
        osc_chunk = osc.get_samples(config.CHUNK_SIZE)
        if osc_chunk is not None:
            subchunks.append(osc_chunk)
    if len(subchunks):
        new_chunk = sum(subchunks)
    else:
        new_chunk = numpy.zeros(config.CHUNK_SIZE)
    # If we exceed the maximum amplitude, handle it gracefully
    chunk_amplitude = amplitude.find_amplitude(new_chunk)
    if chunk_amplitude > config.MAX_AMPLITUDE:
        # Normalize the amplitude chunk to mitigate immediate clipping
        new_chunk = amplitude.normalize_amplitude(new_chunk,
                                                  config.MAX_AMPLITUDE)
        # Pick some of the offending oscillators (and some random others)
        # and lower their drift targets
        avg_amp = (sum(osc.amplitude.value for osc in oscillators) /
                   len(oscillators))
        for osc in oscillators:
            if (osc.amplitude.value > avg_amp and rand.prob_bool(0.1) or
                    rand.prob_bool(0.01)):
                osc.amplitude.drift_target = rand.weighted_rand(
                    [(-5, 1), (0, 10)])
                osc.amplitude.change_rate = rand.weighted_rand(
                    osc.amplitude.change_rate_weights)
    return new_chunk.astype(config.SAMPLE_DATA_TYPE).tostring()

Build an audio chunk and progress the oscillator states.

Args:
        oscillators (list): A list of oscillator.Oscillator objects
            to build chunks from

Returns:
        str: a string of audio sample bytes ready to be written to a wave file


def get_by_block(self, block_number):

        blocklist_snapshot = self.db.prefixed_db(NotificationPrefix.PREFIX_BLOCK).snapshot()
        block_bytes = block_number.to_bytes(4, 'little')
        results = []
        for val in blocklist_snapshot.iterator(prefix=block_bytes, include_key=False):
            event = SmartContractEvent.FromByteArray(val)
            results.append(event)

        return results

Look up notifications for a block

Args:
        block_number (int): height of block to search for notifications

Returns:
        list: a list of notifications


def info(self, collector_id):

        cid = self.collector_id
        if collector_id:
            cid = collector_id

        url = '{0}/{1}'.format(self.url, cid)
        request = requests.get(url, auth=self.auth)
        return request.json()

Return a dict of collector.

Args:
        collector_id (int): id of collector (optional)


def if_sqlserver_disable_constraints(session: SqlASession,
                                     tablename: str) -> None:
      # noqa
    engine = get_engine_from_session(session)
    if is_sqlserver(engine):
        quoted_tablename = quote_identifier(tablename, engine)
        session.execute(
            "ALTER TABLE {} NOCHECK CONSTRAINT all".format(
                quoted_tablename))
        yield
        session.execute(
            "ALTER TABLE {} WITH CHECK CHECK CONSTRAINT all".format(
                quoted_tablename))
    else:
        yield

If we're running under SQL Server, disable constraint checking for the
    specified table while the resource is held.

Args:
        session: SQLAlchemy :class:`Session`
        tablename: table name

    See
    https://stackoverflow.com/questions/123558/sql-server-2005-t-sql-to-temporarily-disable-a-trigger


def is_dsub_operation(op):

  if not is_pipeline(op):
    return False

  for name in ['dsub-version', 'job-id', 'job-name', 'user-id']:
    if not get_label(op, name):
      return False

  return True

Determine if a pipelines operation is a dsub request.

    We don't have a rigorous way to identify an operation as being submitted
    by dsub. Our best option is to check for certain fields that have always
    been part of dsub operations.

    - labels: job-id, job-name, and user-id have always existed. The dsub-version
            label has always existed for the google-v2 provider.

Args:
        op: a pipelines operation.

Returns:
        Boolean, true if the pipeline run was generated by dsub.


def get_equivalent_kpoints(self, index):

        # if the kpoint has no label it can"t have a repetition along the band
        # structure line object

        if self.kpoints[index].label is None:
            return [index]

        list_index_kpoints = []
        for i in range(len(self.kpoints)):
            if self.kpoints[i].label == self.kpoints[index].label:
                list_index_kpoints.append(i)

        return list_index_kpoints

Returns the list of kpoint indices equivalent (meaning they are the
    same frac coords) to the given one.

Args:
        index: the kpoint index

Returns:
        a list of equivalent indices

    TODO: now it uses the label we might want to use coordinates instead
    (in case there was a mislabel)


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

        local_buffer = utils.BytearrayStream()

        if self._unique_identifier:
            self._unique_identifier.write(
                local_buffer,
                kmip_version=kmip_version
            )
        else:
            raise exceptions.InvalidField(
                "The GetAttributes response payload is missing the unique "
                "identifier field."
            )

        if kmip_version < enums.KMIPVersion.KMIP_2_0:
            for attribute in self._attributes:
                attribute.write(local_buffer, kmip_version=kmip_version)
        else:
            if self._attributes:
                # TODO (ph) Add a new utility to avoid using TemplateAttributes
                template_attribute = objects.TemplateAttribute(
                    attributes=self.attributes
                )
                attributes = objects.convert_template_attribute_to_attributes(
                    template_attribute
                )
                attributes.write(local_buffer, kmip_version=kmip_version)
            else:
                raise exceptions.InvalidField(
                    "The GetAttributes response payload is missing the "
                    "attributes list."
                )

        self.length = local_buffer.length()
        super(GetAttributesResponsePayload, self).write(
            output_buffer,
            kmip_version=kmip_version
        )
        output_buffer.write(local_buffer.buffer)

Write the data encoding the GetAttributes response payload to a
    stream.

Args:
        output_buffer (stream): A data stream in which to encode object
            data, supporting a write method; usually a BytearrayStream
            object.
        kmip_version (KMIPVersion): An enumeration defining the KMIP
            version with which the object will be encoded. Optional,
            defaults to KMIP 1.0.


def device_set(self, device):

		if device['id'].startswith('0x'):
			self.device_id = device['id'][2:]
		elif device['id'].startswith('ios:'):
			self.device_id = device['id'].replace(':', '')
		else:
			self.device_id = device['id']

Set device used by :class:`MobileClient` instance.

    Parameters:
    device (dict): A device dict as returned by :meth:`devices`.


def unpack_rpc_payload(resp_format, payload):

    code = _create_argcode(resp_format, payload)
    return struct.unpack(code, payload)

Unpack an RPC payload according to resp_format.

Args:
        resp_format (str): a struct format code (without the <) for the
            parameter format for this RPC.  This format code may include the final
            character V, which means that it expects a variable length bytearray.
        payload (bytes): The binary payload that should be unpacked.

Returns:
        list: A list of the unpacked payload items.


def get_factors_iterative2(n):

    ans, stack, x = [], [], 2
    while True:
        if x > n // x:
            if not stack:
                return ans
            ans.append(stack + [n])
            x = stack.pop()
            n *= x
            x += 1
        elif n % x == 0:
            stack.append(x)
            n //= x
        else:
            x += 1

[summary]
    analog as above

Args:
        n {[int]} -- [description]

Returns:
        [list of lists] -- [all factors of n]


def _Matches(path, pattern_list):

  # Note: This code does not scale to large pattern_list sizes.
  return any(fnmatch.fnmatchcase(path, pattern) for pattern in pattern_list)

Returns true if path matches any patten found in pattern_list.

Args:
        path: A dot separated path to a package, class, method or variable
        pattern_list: A list of wildcard patterns

Returns:
        True if path matches any wildcard found in pattern_list.


def GetHasher(cls, hasher_name):

    hasher_name = hasher_name.lower()
    if hasher_name not in cls._hasher_classes:
      raise KeyError(
          'hasher class not set for name: {0:s}.'.format(hasher_name))

    hasher_class = cls._hasher_classes[hasher_name]
    return hasher_class()

Retrieves an instance of a specific hasher.

Args:
        hasher_name (str): the name of the hasher to retrieve.

Returns:
        BaseHasher: hasher.

Raises:
        KeyError: if hasher class is not set for the corresponding name.


def __init__(self, alts_list):

        self.alts = alts_list
        self.alts_set = set(alts_list)
        self.m = len(alts_list)
        if len(self.alts) != len(self.alts_set):
            raise ValueError("Alternatives must not contain duplicates")
        self.alts_to_ranks = None # Maps alternatives to ranking (projective)
        self.ranks_to_alts = None

Description:
    Initializes the aggregator with the set of alternatives
    and the number of candidates
    Parameters:
    alts_list: the set of integer alternatives (a.k.a candidates)


def url_to_fn(url):

    url = url.replace("http://", "").replace("https://", "")
    url = url.split("?")[0]

    return url.replace("%", "_").replace("/", "_")

Convert `url` to filename used to download the datasets.

    ``http://kitakitsune.org/xe`` -> ``kitakitsune.org_xe``.

Args:
        url (str): URL of the resource.

Returns:
        str: Normalized URL.


def setup(app):

    for name, (default, rebuild, _) in ref.CONFIG_VALUES.iteritems():
        app.add_config_value(name, default, rebuild)

    app.add_directive('javaimport', ref.JavarefImportDirective)
    app.add_role('javaref', ref.JavarefRole(app))

    app.connect('builder-inited', initialize_env)
    app.connect('env-purge-doc', ref.purge_imports)
    app.connect('env-merge-info', ref.merge_imports)
    app.connect('build-finished', ref.cleanup)

Register the extension with Sphinx.

Args:
        app: The Sphinx application.


def __init__(self, choices=None, validator=None, **kwargs):

    self.choices = choices
    subvalidator = validator or String()
    self.validator = List(validator=subvalidator)

    # Check the choices match the validator
    for choice in self.choices:
      subvalidator.Validate(choice)
    super(MultiChoice, self).__init__(**kwargs)

Create a multichoice object and validate choices.

Args:
        choices: list of available choices
        validator: validator to use for each of the list *items* the validator for
                the top level is a list.
        **kwargs: passed through to parent class.


def consult_robots_txt(self, request: HTTPRequest) -> bool:

        if not self._robots_txt_checker:
            return True

        result = yield from self._robots_txt_checker.can_fetch(request)
        return result

Consult by fetching robots.txt as needed.

Args:
        request: The request to be made
            to get the file.

Returns:
        True if can fetch

    Coroutine


def from_json(cls, data):

        required_keys = ('location', 'design_days')
        for key in required_keys:
            assert key in data, 'Required key "{}" is missing!'.format(key)

        return cls(Location.from_json(data['location']),
                   [DesignDay.from_json(des_day) for des_day in data['design_days']])

Create a DDY from a dictionary.

Args:
        data = {
        "location": ladybug Location schema,
        "design_days": [] // list of ladybug DesignDay schemas}


def execute_command(self, command):

        logger.debug('Executing commands:\n %s' % command)

        err_msg = 'Something happened when executing some commands on device'

        chan = self.ssh.get_transport().open_session()
        chan.settimeout(5)

        chan.exec_command(command)

        error_chan = chan.makefile_stderr()
        output_chan = chan.makefile()

        error = ''
        output = ''
        for e in error_chan.read():
            error = error + self._read_wrapper(e)
        for o in output_chan.read():
            output = output + self._read_wrapper(o)

        if len(error) > 0:
            msg = '%s %s:\n%s\n%s' % (err_msg, self.ssh.get_host_keys().keys()[0], command, error)
            logger.error(msg)
            raise exceptions.CommandExecutionException(msg)

        regex = re.compile('Command fail')
        if len(regex.findall(output)) > 0:
            msg = '%s %s:\n%s\n%s' % (err_msg, self.ssh.get_host_keys().keys()[0], command, output)
            logger.error(msg)
            raise exceptions.CommandExecutionException(msg)

        output = output.splitlines()

        # We look for the prompt and remove it
        i = 0
        for line in output:
            current_line = line.split('#')

            if len(current_line) > 1:
                output[i] = current_line[1]
            else:
                output[i] = current_line[0]
            i += 1

        return output[:-1]

This method will execute the commands on the device without as if you were just connected to it (it will not
    enter into any vdom). This method is not recommended unless you are 100% sure of what you are doing.

Args:
        * **command** (str) -- Command to execute.

Returns:
        A list of strings containing the output.

Raises:
        exceptions.CommandExecutionException -- If it detects any problem with the command.


def insort_event_right(self, event, lo=0, hi=None):

    if lo < 0:
      raise ValueError('lo must be non-negative')
    if hi is None:
      hi = len(self.queue)
    while lo < hi:
      mid = (lo + hi) // 2
      if event[0] < self.queue[mid][0]:
        hi = mid
      else:
        lo = mid + 1
    self.queue.insert(lo, event)

Insert event in queue, and keep it sorted assuming queue is sorted.

    If event is already in queue, insert it to the right of the rightmost
    event (to keep FIFO order).

    Optional args lo (default 0) and hi (default len(a)) bound the
    slice of a to be searched.

Args:
        event: a (time in sec since unix epoch, callback, args, kwds) tuple.


def rouge_l_fscore(predictions, labels, **unused_kwargs):

  outputs = tf.to_int32(tf.argmax(predictions, axis=-1))
  # Convert the outputs and labels to a [batch_size, input_length] tensor.
  outputs = tf.squeeze(outputs, axis=[-1, -2])
  labels = tf.squeeze(labels, axis=[-1, -2])
  rouge_l_f_score = tf.py_func(rouge_l_sentence_level, (outputs, labels),
                               tf.float32)
  return rouge_l_f_score, tf.constant(1.0)

ROUGE scores computation between labels and predictions.

    This is an approximate ROUGE scoring method since we do not glue word pieces
    or decode the ids and tokenize the output.

Args:
        predictions: tensor, model predictions
        labels: tensor, gold output.

Returns:
        rouge_l_fscore: approx rouge-l f1 score.


def setNetworkName(self, networkName='GRL'):

        print '%s call setNetworkName' % self.port
        print networkName
        try:
            cmd = 'networkname %s' % networkName
            datasetCmd = 'dataset networkname %s' % networkName
            self.hasActiveDatasetToCommit = True
            return self.__sendCommand(cmd)[0] == 'Done' and self.__sendCommand(datasetCmd)[0] == 'Done'
        except Exception, e:
            ModuleHelper.WriteIntoDebugLogger("setNetworkName() Error: " + str(e))

set Thread Network name

Args:
        networkName: the networkname string to be set

Returns:
        True: successful to set the Thread Networkname
        False: fail to set the Thread Networkname


def save(self, sess, save_path, timestep=None):

        if self._saver is None:
            raise TensorForceError("register_saver_ops should be called before save")
        return self._saver.save(
            sess=sess,
            save_path=save_path,
            global_step=timestep,
            write_meta_graph=False,
            write_state=True,  # Do we need this?
        )

Saves this component's managed variables.

Args:
        sess: The session for which to save the managed variables.
        save_path: The path to save data to.
        timestep: Optional, the timestep to append to the file name.

Returns:
        Checkpoint path where the model was saved.


def SubtractFromBalance(self, assetId, fixed8_val):

        found = False
        for key, balance in self.Balances.items():
            if key == assetId:
                self.Balances[assetId] = self.Balances[assetId] - fixed8_val
                found = True
        if not found:
            self.Balances[assetId] = fixed8_val * Fixed8(-1)

Subtract amount to the specified balance.

Args:
        assetId (UInt256):
        fixed8_val (Fixed8): amount to add.


def get_default_connection_info(self, provider_name):

        provider = self._provider_client.get_by_name(provider_name)
        if provider:
            return provider['defaultConnectionInfo']
        else:
            return {}

Gets default connection info for a specific provider.

Args:
        provider_name: Name of the provider.

Returns:
        dict: Default connection information.


def _find_current_phase(self, global_step):

    epoch_size = sum(phase.steps for phase in self._phases)
    epoch = int(global_step // epoch_size)
    steps_in = global_step % epoch_size
    for phase in self._phases:
      if steps_in < phase.steps:
        return phase, epoch, steps_in
      steps_in -= phase.steps

Determine the current phase based on the global step.

    This ensures continuing the correct phase after restoring checkoints.

Args:
        global_step: The global number of steps performed across all phases.

Returns:
        Tuple of phase object, epoch number, and phase steps within the epoch.


def _safe_get(self, revision, key):

        if self.has_revision(revision):
            return self.raw_answers[revision].get(key)
        else:
            return None

Get an answer data (vote or rationale) by revision

Args:
        revision (int): the revision number for student answer, could be
            0 (original) or 1 (revised)
        key (str); key for retrieve answer data, could be VOTE_KEY or
            RATIONALE_KEY

Returns:
        the answer data or None if revision doesn't exists


def parse(self, data, extent, desc_tag):
        # type: (bytes, int, UDFTag) -> None

        if self._initialized:
            raise pycdlibexception.PyCdlibInternalError('UDF Partition Volume Descriptor already initialized')

        (tag_unused, self.vol_desc_seqnum, self.part_flags, self.part_num,
         part_contents, part_contents_use, self.access_type,
         self.part_start_location, self.part_length, impl_ident,
         self.implementation_use, reserved_unused) = struct.unpack_from(self.FMT, data, 0)

        self.desc_tag = desc_tag

        self.part_contents = UDFEntityID()
        self.part_contents.parse(part_contents)
        if self.part_contents.identifier[:6] != b'+NSR02':
            raise pycdlibexception.PyCdlibInvalidISO("Partition Contents Identifier not '+NSR02'")

        self.impl_ident = UDFEntityID()
        self.impl_ident.parse(impl_ident)

        self.part_contents_use = UDFPartitionHeaderDescriptor()
        self.part_contents_use.parse(part_contents_use)

        self.orig_extent_loc = extent

        self._initialized = True

Parse the passed in data into a UDF Partition Volume Descriptor.

    Parameters:
    data - The data to parse.
    extent - The extent that this descriptor currently lives at.
    desc_tag - A UDFTag object that represents the Descriptor Tag.

Returns:
    Nothing.


def to_hg_scheme_url(cls, url):

        regexes = cls._get_url_scheme_regexes()
        for scheme_key, pattern, regex in regexes:
            match = regex.match(url)
            if match is not None:
                groups = match.groups()
                if len(groups) == 2:
                    return u''.join(
                        scheme_key,
                        '://',
                        pattern.replace('{1}', groups[0]),
                        groups[1])
                elif len(groups) == 1:
                    return u''.join(
                        scheme_key,
                        '://',
                        pattern,
                        groups[0])

Convert a URL to local mercurial URL schemes

Args:
        url (str): URL to map to local mercurial URL schemes

    example::

        # schemes.gh = git://github.com/
        >> remote_url = git://github.com/westurner/dotfiles'
        >> to_hg_scheme_url(remote_url)
        << gh://westurner/dotfiles


def transpose(self, name=None, activate_final=None):

    if name is None:
      name = self.module_name + "_transpose"
    if activate_final is None:
      activate_final = self.activate_final
    output_sizes = [lambda l=layer: l.input_shape[1] for layer in self._layers]
    output_sizes.reverse()
    return MLP(
        name=name,
        output_sizes=output_sizes,
        activation=self.activation,
        activate_final=activate_final,
        initializers=self.initializers,
        partitioners=self.partitioners,
        regularizers=self.regularizers,
        use_bias=self.use_bias,
        use_dropout=self.use_dropout)

Returns transposed `MLP`.

Args:
        name: Optional string specifying the name of the transposed module. The
        default name is constructed by appending "_transpose"
        to `self.module_name`.
        activate_final: Optional boolean determining if the activation and batch
        normalization, if turned on, are applied to the final layer.

Returns:
        Matching transposed `MLP` module.


def d_grade_ipix(ipix, nside_in, nside_out, nest=False):

    if nside_in==nside_out: return ipix
    if not (nside_in > nside_out):
        raise ValueError("nside_out must be less than nside_in")

    return hp.vec2pix(nside_out, *hp.pix2vec(nside_in, ipix, nest), nest=nest)

Return the indices of the super-pixels which contain each of the
    sub-pixels (nside_in > nside_out).

    Parameters:
    -----------
    ipix      : index of the input subpixels
    nside_in  : nside of the input subpix
    nside_out : nside of the desired superpixels

Returns:
    --------
    ipix_out  : superpixels for each subpixel


def get_updates(
        self,
        display_all_distributions=False,
        verbose=False
    ):  # pragma: no cover

        if verbose:
            logging.basicConfig(
                stream=sys.stdout,
                level=logging.INFO,
                format='%(message)s',
            )
            logging.info('Checking installed packages for updates...')

        updates = self._get_environment_updates(
            display_all_distributions=display_all_distributions
        )

        if updates:
            for update in updates:
                logging.info(update)

        if updates and self._csv_file_name:
            self.write_updates_to_csv(updates)

        if updates and self._new_config:
            self.write_new_config(updates)

        return updates

When called, get the environment updates and write updates to a CSV
    file and if a new config has been provided, write a new configuration
    file.

Args:
        display_all_distributions (bool): Return distribution even if it is
            up-to-date.
        verbose (bool): If ``True``, log to terminal to terminal.


def GetFileSystem(self, path_spec):

    identifier = self._GetFileSystemCacheIdentifier(path_spec)
    return self._file_system_cache.GetObject(identifier)

Retrieves a file system object defined by path specification.

Args:
        path_spec (PathSpec): path specification.

Returns:
        FileSystem: a file system object or None if not cached.


def __sendCommand(self, cmd):

        logging.info('%s: sendCommand[%s]', self.port, cmd)
        if self.logThreadStatus == self.logStatus['running']:
            self.logThreadStatus = self.logStatus['pauseReq']
            while self.logThreadStatus != self.logStatus['paused'] and self.logThreadStatus != self.logStatus['stop']:
                pass

        ssh_stdin = None
        ssh_stdout = None
        ssh_stderr = None
        try:
            # command retransmit times
            retry_times = 3
            while retry_times > 0:
                retry_times -= 1
                try:
                    if self._is_net:
                        ssh_stdin, ssh_stdout, ssh_stderr = self.handle.exec_command(cmd)
                    else:
                        self._sendline(cmd)
                        self._expect(cmd)
                except Exception as e:
                    logging.exception('%s: failed to send command[%s]: %s', self.port, cmd, str(e))
                    if retry_times == 0:
                        raise
                else:
                    break

            line = None
            response = []
            retry_times = 20
            stdout_lines = []
            stderr_lines = []
            if self._is_net:
                stdout_lines = ssh_stdout.readlines()
                stderr_lines = ssh_stderr.readlines()
                if stderr_lines:
                    for stderr_line in stderr_lines:
                        if re.search(r'Not\s+Found|failed\s+with\s+error', stderr_line.strip(), re.M | re.I):
                            print "Command failed:" + stderr_line
                            return 'Fail'
                        print "Got line: " + stderr_line
                        logging.info('%s: the read line is[%s]', self.port, stderr_line)
                        response.append(str(stderr_line.strip()))
                elif stdout_lines:
                    for stdout_line in stdout_lines:
                        logging.info('%s: the read line is[%s]', self.port, stdout_line)
                        if re.search(r'Not\s+Found|failed\s+with\s+error', stdout_line.strip(), re.M | re.I):
                            print "Command failed"
                            return 'Fail'
                        print "Got line: " + stdout_line
                        logging.info('%s: send command[%s] done!', self.port, cmd)
                        response.append(str(stdout_line.strip()))
                response.append(WPAN_CARRIER_PROMPT)
                return response
            else:
                while retry_times > 0:
                    line = self._readline()
                    print "read line: %s" % line
                    logging.info('%s: the read line is[%s]', self.port, line)
                    if line:
                        response.append(line)
                        if re.match(WPAN_CARRIER_PROMPT, line):
                            break
                        elif re.search(r'Not\s+Found|failed\s+with\s+error', line, re.M | re.I):
                            print "Command failed"
                            return 'Fail'

                    retry_times -= 1
                    time.sleep(0.1)

                if retry_times == 0:
                    raise Exception('%s: failed to find end of response' % self.port)
                logging.info('%s: send command[%s] done!', self.port, cmd)
                return response
        except Exception, e:
            ModuleHelper.WriteIntoDebugLogger('sendCommand() Error: ' + str(e))
            raise

send specific command to reference unit over serial port

Args:
        cmd: OpenThread_WpanCtl command string

Returns:
        Fail: Failed to send the command to reference unit and parse it
        Value: successfully retrieve the desired value from reference unit
        Error: some errors occur, indicates by the followed specific error number


def service_configuration_check(config):

    ipv4_enabled = config.getboolean('daemon', 'ipv4')
    ipv6_enabled = config.getboolean('daemon', 'ipv6')
    services = config.sections()
    # we don't need it during sanity check for services check
    services.remove('daemon')
    ip_prefixes = []

    for service in services:
        for option, getter in SERVICE_OPTIONS_TYPE.items():
            try:
                getattr(config, getter)(service, option)
            except configparser.NoOptionError as error:
                if option not in SERVICE_OPTIONAL_OPTIONS:
                    raise ValueError(error)
            except configparser.Error as error:
                raise ValueError(error)
            except ValueError as exc:
                msg = ("invalid data for '{opt}' option in service check "
                       "{name}: {err}"
                       .format(opt=option, name=service, err=exc))
                raise ValueError(msg)

        if (config.get(service, 'on_disabled') != 'withdraw' and
                config.get(service, 'on_disabled') != 'advertise'):
            msg = ("'on_disabled' option has invalid value ({val}) for "
                   "service check {name}, 'on_disabled option should be set "
                   "either to 'withdraw' or to 'advertise'"
                   .format(name=service,
                           val=config.get(service, 'on_disabled')))
            raise ValueError(msg)

        ip_prefixes.append(config.get(service, 'ip_prefix'))

        if not valid_ip_prefix(config.get(service, 'ip_prefix')):
            msg = ("invalid value ({val}) for 'ip_prefix' option in service "
                   "check {name}. It should be an IP PREFIX in form of "
                   "ip/prefixlen."
                   .format(name=service, val=config.get(service, 'ip_prefix')))
            raise ValueError(msg)

        _ip_prefix = ipaddress.ip_network(config.get(service, 'ip_prefix'))
        if not ipv6_enabled and _ip_prefix.version == 6:
            raise ValueError("IPv6 support is disabled in "
                             "anycast-healthchecker while there is an IPv6 "
                             "prefix configured for {name} service check"
                             .format(name=service))
        if not ipv4_enabled and _ip_prefix.version == 4:
            raise ValueError("IPv4 support is disabled in "
                             "anycast-healthchecker while there is an IPv4 "
                             "prefix configured for {name} service check"
                             .format(name=service))

        cmd = shlex.split(config.get(service, 'check_cmd'))
        try:
            proc = subprocess.Popen(cmd)
            proc.kill()
        except (OSError, subprocess.SubprocessError) as exc:
            msg = ("failed to run check command '{cmd}' for service check "
                   "{name}: {err}"
                   .format(name=service,
                           cmd=config.get(service, 'check_cmd'),
                           err=exc))
            raise ValueError(msg)

    occurrences_of_ip_prefixes = Counter(ip_prefixes)
    for ip_prefix, counter in occurrences_of_ip_prefixes.items():
        if counter > 1:
            raise ValueError("{ip} is used by {c} service checks"
                             .format(ip=ip_prefix, c=counter))

Perform a sanity check against options for each service check.

Args:
        config (obj): A configparser object which holds our configuration.

Returns:
        None if all sanity checks are successfully passed otherwise raises a
        ValueError exception.


def main(params=None):

    if params == None:
        parser = getParser()
        args = parser.parse_args(params)
    else:
        args = params

    print(general.title(banner.text))

    extraWords = args.extra_words

    try:
        if args.name == None and args.surname1 == None and args.surname2 == None and args.city == None and args.country == None and args.year == None:
            print("\nCollecting information about the profile")
            print("----------------------------------------\n")

            args.name = raw_input(general.emphasis("Insert a name: ".ljust(35, " "))).replace(' ','')
            args.surname1 = raw_input(general.emphasis("Insert the first surname: ".ljust(35, " "))).replace(' ','')
            args.surname2 = raw_input(general.emphasis("Insert the second surname: ".ljust(35, " "))).replace(' ','')
            args.year = raw_input(general.emphasis("Insert a year (e. g.: birthyear): ".ljust(35, " "))).replace(' ','')
            args.city = raw_input(general.emphasis("Insert a city: ".ljust(35, " "))).replace(' ','')
            args.country = raw_input(general.emphasis("Insert a country: ".ljust(35, " "))).replace(' ','')

            if args.extra_words == []:
                print("\nAdditional transformations to be added")
                print("--------------------------------------\n")
                inputText = raw_input(general.emphasis("Extra words to add (',' separated): ".ljust(35, " "))).replace(' ','')
                extraWords += inputText.lower().split(',')
    except KeyboardInterrupt:
        print("\n\nThe user manually aborted the program. Exiting...")
        sys.exit(2)

    lista=[]

    print("\nInput data:")
    print("-----------\n")
    if args.name != "":
        print("Name: ".ljust(20, " ") + args.name)
    if args.surname1 != "":
        print("First Surname: ".ljust(20, " ") + args.surname1)
    if args.surname2 != "":
        print("Second Surname: ".ljust(20, " ") + args.surname2)
    if args.year != "":
        print("Year: ".ljust(20, " ") + args.year)
    if args.city != "":
        print("City: ".ljust(20, " ") + args.city)
    if args.country != "":
        print("Country: ".ljust(20, " ") + args.country)

    aliases = generate(
        name=args.name,
        surname1=args.surname1,
        surname2=args.surname2,
        city=args.city,
        country=args.country,
        year=args.year,
        useNumbers=args.numbers,
        useCommonWords=args.common_words,
        useLeet=args.leet,
        useLocales=args.locales,
        extraWords=extraWords
    )

    print("Writing the results onto the file:\n\t" + general.emphasis(args.outputFile))

    oF=open(args.outputFile, "w")
    for l in aliases:
        oF.write(l+"\n")
    oF.close()

    # Urging users to place an issue on Github...
    print(banner.footer)

Main function to launch alias_generator.

Args:
    -----
        params: A list with the parameters as grabbed by the terminal. It is
            None when this is called by an entry_point. If it is called by osrf
            the data is already parsed.


def _entry_allocated_bitmap(self, entry_number):

    index, offset = divmod(entry_number, 8)
    return bool(self._bitmap[index] & (1 << offset))

Checks if a particular index is allocated.

Args:
        entry_number (int): Index to verify

Returns:
        bool: True if it is allocated, False otherwise.


def random_init_mapping(candidate_mapping):

    # if needed, a fixed seed could be passed here to generate same random (to help debugging)
    random.seed()
    matched_dict = {}
    result = []
    for c in candidate_mapping:
        candidates = list(c)
        if not candidates:
            # -1 indicates no possible mapping
            result.append(-1)
            continue
        found = False
        while candidates:
            # randomly generate an index in [0, length of candidates)
            rid = random.randint(0, len(candidates) - 1)
            candidate = candidates[rid]
            # check if it has already been matched
            if candidate in matched_dict:
                candidates.pop(rid)
            else:
                matched_dict[candidate] = 1
                result.append(candidate)
                found = True
                break
        if not found:
            result.append(-1)
    return result

Generate a random node mapping.

Args:
        candidate_mapping: candidate_mapping: candidate node match list

Returns:
        randomly-generated node mapping between two AMRs


def get_parameter_names(self, include_frozen=False):

        if include_frozen:
            return self.parameter_names
        return tuple(p
                     for p, f in zip(self.parameter_names, self.unfrozen_mask)
                     if f)

Get a list of the parameter names

Args:
        include_frozen (Optional[bool]): Should the frozen parameters be
            included in the returned value? (default: ``False``)


def sign(self, message):

        message = _helpers._to_bytes(message, encoding='utf-8')
        return rsa.pkcs1.sign(message, self._key, 'SHA-256')

Signs a message.

Args:
        message: bytes, Message to be signed.

Returns:
        string, The signature of the message for the given key.


def filter_by_hoys(self, hoys):

        _moys = tuple(int(hour * 60) for hour in hoys)
        return self.filter_by_moys(_moys)

Filter the Data Collection based on an analysis period.

Args:
        hoys: A List of hours of the year 0..8759

Returns:
        A new Data Collection with filtered data


def actnorm_3d(name, x, logscale_factor=3.):

  with tf.variable_scope(name, reuse=tf.AUTO_REUSE):
    x = tf.unstack(x, axis=1)
    x_normed = []
    for ind, x_step in enumerate(x):
      x_step, _ = actnorm("actnorm_%d" % ind, x_step,
                          logscale_factor=logscale_factor)
      x_normed.append(x_step)
    return tf.stack(x_normed, axis=1), None

Applies actnorm to each time-step independently.

    There are a total of 2*n_channels*n_steps parameters learnt.

Args:
        name: variable scope.
        x: 5-D Tensor, (NTHWC)
        logscale_factor: Increases the learning rate of the scale by
                    logscale_factor.

Returns:
        x: 5-D Tensor, (NTHWC) with the per-timestep, per-channel normalization.


def rmod(self, other, axis="columns", level=None, fill_value=None):

        return self._binary_op(
            "rmod", other, axis=axis, level=level, fill_value=fill_value
        )

Mod this DataFrame against another DataFrame/Series/scalar.

Args:
        other: The object to use to apply the div against this.
        axis: The axis to div over.
        level: The Multilevel index level to apply div over.
        fill_value: The value to fill NaNs with.

Returns:
        A new DataFrame with the rdiv applied.


def _get_fans(shape):
    r
    if len(shape) == 2:
        fan_in = shape[0]
        fan_out = shape[1]
    elif len(shape) == 4 or len(shape) == 5:
        # assuming convolution kernels (2D or 3D).
        kernel_size = np.prod(shape[:2])
        fan_in = shape[-2] * kernel_size
        fan_out = shape[-1] * kernel_size
    else:
        # no specific assumptions
        fan_in = np.sqrt(np.prod(shape))
        fan_out = np.sqrt(np.prod(shape))
    return fan_in, fan_out

r"""Returns the size of input dimension and output dimension, given `shape`.

Args:
        shape: A list of integers.

Returns:
        fan_in: An int. The value of input dimension.
        fan_out: An int. The value of output dimension.


def optional(self, value = None):

		# If there's no value, this is a getter
		if value is None:
			return this._optional

		# Else, set the flag
		else:
			this._optional = value and True or False

Optional

    Getter/Setter method for optional flag

Args:
    value (bool): If set, the method is a setter

Returns:
    bool | None


def sort_dependencies(self, image, dependencies=None):

        if dependencies is None:
            dependencies = OrderedDict()  # using this as an ordered set - not storing any values

        if image in dependencies:
            return

        requires = self.ymldefs[image].get('requires', [])

        for dep in requires:
            self.sort_dependencies(dep, dependencies)

        dependencies[image] = None
        return dependencies.keys()

Topologically sort the docker commands by their requirements

Note:
        Circular "requires" dependencies are assumed to have already been checked in
        get_external_base_image, they are not checked here

Args:
        image (str): process this docker image's dependencies
        dependencies (OrderedDict): running cache of sorted dependencies (ordered dict)

Returns:
        List[str]: list of dependencies a topologically-sorted build order


def _label_path_from_index(self, index):

        label_file = os.path.join(self.label_dir, index + self.label_extension)
        assert os.path.exists(label_file), 'Path does not exist: {}'.format(label_file)
        return label_file

given image index, find out annotation path

    Parameters:
    ----------
    index: int
        index of a specific image

Returns:
    ----------
    full path of annotation file


def __init__(self, linter_name, path, msg, line_nr=None, col=None):

        # Set all attributes in the constructor for convenience.
        # pylint: disable=too-many-arguments
        if line_nr:
            line_nr = int(line_nr)
        if col:
            col = int(col)
        self._linter_name = linter_name
        self.path = path
        self.line_nr = line_nr
        self.msg = msg
        self.col = col

Optionally set all attributes.

Args:
        path (str): Relative file path.
        line (int): Line number.
        msg (str): Explanation of what is wrong.
        col (int): Column where the problem begins.


def _get(self, url, params=None):

        if not params:
            params = {}

        params.update({'login': self.login, 'key': self.key})

        response_json = requests.get(self.api_url + url, params).json()

        return self._process_response(response_json)

Used by every other method, it makes a GET request with the given params.

Args:
        url (str): relative path of a specific service (account_info, ...).
        params (:obj:`dict`, optional): contains parameters to be sent in the GET request.

Returns:
        dict: results of the response of the GET request.


def wv45(msg):

    d = hex2bin(data(msg))
    if d[12] == '0':
        return None

    ws = bin2int(d[13:15])
    return ws

Wake vortex.

Args:
        msg (String): 28 bytes hexadecimal message string

Returns:
        int: Wake vortex level. 0=NIL, 1=Light, 2=Moderate, 3=Severe


def additive_coupling(name, x, mid_channels=512, reverse=False,
                      activation="relu", dropout=0.0):

  with tf.variable_scope(name, reuse=tf.AUTO_REUSE):
    output_channels = common_layers.shape_list(x)[-1] // 2
    x1, x2 = tf.split(x, num_or_size_splits=2, axis=-1)

    z1 = x1
    shift = conv_stack("nn", x1, mid_channels, output_channels=output_channels,
                       activation=activation, dropout=dropout)

    if not reverse:
      z2 = x2 + shift
    else:
      z2 = x2 - shift
    return tf.concat([z1, z2], axis=3), 0.0

Reversible additive coupling layer.

Args:
        name: variable scope.
        x: 4-D Tensor, shape=(NHWC).
        mid_channels: number of channels in the coupling layer.
        reverse: Forward or reverse operation.
        activation: "relu" or "gatu"
        dropout: default, 0.0

Returns:
        output: 4-D Tensor, shape=(NHWC)
        objective: 0.0


def read(self, filename, binary_mode=False, size=None, offset=None):

        s3 = boto3.resource("s3")
        bucket, path = self.bucket_and_path(filename)
        args = {}
        endpoint = 0
        if size is not None or offset is not None:
            if offset is None:
                offset = 0
            endpoint = '' if size is None else (offset + size)
            args['Range'] = 'bytes={}-{}'.format(offset, endpoint)
        try:
            stream = s3.Object(bucket, path).get(**args)['Body'].read()
        except botocore.exceptions.ClientError as exc:
            if exc.response['Error']['Code'] == '416':
                if size is not None:
                    # Asked for too much, so request just to the end. Do this
                    # in a second request so we don't check length in all cases.
                    client = boto3.client("s3")
                    obj = client.head_object(Bucket=bucket, Key=path)
                    len = obj['ContentLength']
                    endpoint = min(len, offset + size)
                if offset == endpoint:
                    # Asked for no bytes, so just return empty
                    stream = b''
                else:
                    args['Range'] = 'bytes={}-{}'.format(offset, endpoint)
                    stream = s3.Object(bucket, path).get(**args)['Body'].read()
            else:
                raise
        if binary_mode:
            return bytes(stream)
        else:
            return stream.decode('utf-8')

Reads contents of a file to a string.

Args:
        filename: string, a path
        binary_mode: bool, read as binary if True, otherwise text
        size: int, number of bytes or characters to read, otherwise
            read all the contents of the file from the offset
        offset: int, offset into file to read from, otherwise read
            from the very beginning

Returns:
        Subset of the contents of the file as a string or bytes.


def get_sites_in_sphere(self, pt, r):

        neighbors = []
        for site in self._sites:
            dist = site.distance_from_point(pt)
            if dist <= r:
                neighbors.append((site, dist))
        return neighbors

Find all sites within a sphere from a point.

Args:
        pt (3x1 array): Cartesian coordinates of center of sphere.
        r (float): Radius of sphere.

Returns:
        [(site, dist) ...] since most of the time, subsequent processing
        requires the distance.


def save(self, filename):

        handle = open(filename, 'wb')
        handle.write(P_LAY % self._code())
        handle.close()

Saves pipeline as a Python source code file.

Args:
        - filename(``path``) Path to save the pipeline source code.


def __parse_entry(entry_line):

    if entry_line.startswith("!"):
        entry_line = sub(r"!\w*?_", '', entry_line)
    else:
        entry_line = entry_line.strip()[1:]
    try:
        entry_type, entry_name = [i.strip() for i in entry_line.split("=", 1)]
    except ValueError:
        entry_type = [i.strip() for i in entry_line.split("=", 1)][0]
        entry_name = ''
    return entry_type, entry_name

Parse the SOFT file entry name line that starts with '^', '!' or '#'.

Args:
        entry_line (:obj:`str`): Line from SOFT  to be parsed.

Returns:
        :obj:`2-tuple`: Type of entry, value of entry.


def generate_csr(private_key_bytes, subject_name, fqdn_list):

    return (
        cryptography.x509.CertificateSigningRequestBuilder()
        .subject_name(subject_name)
        .add_extension(
            extension=cryptography.x509.SubjectAlternativeName(
                [cryptography.x509.DNSName(v) for v in fqdn_list]
            ),
            critical=False,
        )
        .sign(
            private_key=private_key_bytes,
            algorithm=cryptography.hazmat.primitives.hashes.SHA256(),
            backend=cryptography.hazmat.backends.default_backend(),
        )
    )

Generate a Certificate Signing Request (CSR).

Args:
        private_key_bytes: bytes
            Private key with which the CSR will be signed.

        subject_name: str
            Certificate Subject Name

        fqdn_list:
            List of Fully Qualified Domain Names (FQDN) and/or IP addresses for which
            this certificate will provide authentication.

            E.g.: ['my.membernode.org', '1.2.3.4']


def _get_target_encoder(self, x, y):

        assert len(x) == len(y)

        # NaN cannot be used as a key for dict. So replace it with a random integer
        df = pd.DataFrame({y.name: y, x.name: x.fillna(NAN_INT)})
        return df.groupby(x.name)[y.name].mean().to_dict()

Return a mapping from categories to average target values.

Args:
        x (pandas.Series): a categorical column to encode.
        y (pandas.Series): the target column

Returns:
        target_encoder (dict): mapping from categories to average target values


def getsize(self, path):

        try:
            file_obj = self.filesystem.resolve(path)
            if (self.filesystem.ends_with_path_separator(path) and
                    S_IFMT(file_obj.st_mode) != S_IFDIR):
                error_nr = (errno.EINVAL if self.filesystem.is_windows_fs
                            else errno.ENOTDIR)
                self.filesystem.raise_os_error(error_nr, path)
            return file_obj.st_size
        except IOError as exc:
            raise os.error(exc.errno, exc.strerror)

Return the file object size in bytes.

Args:
        path:  path to the file object.

Returns:
        file size in bytes.


def __init__(self, tokenizer=None, trie=None):

        pyee.EventEmitter.__init__(self)
        self.tokenizer = tokenizer or EnglishTokenizer()
        self.trie = trie or Trie()
        self.regular_expressions_entities = []
        self._regex_strings = set()
        self.tagger = EntityTagger(self.trie, self.tokenizer, self.regular_expressions_entities)
        self.intent_parsers = []

Initialize the IntentDeterminationEngine

Args:
        tokenizer(tokenizer) : tokenizer used to break up spoken text
            example EnglishTokenizer()
        trie(Trie): tree of matches to Entites


def CallDhclient(
    interfaces, logger, dhclient_script=None):

  logger.info('Enabling the Ethernet interfaces %s.', interfaces)

  dhclient_command = ['dhclient']

  if dhclient_script and os.path.exists(dhclient_script):
    dhclient_command += ['-sf', dhclient_script]

  try:
    subprocess.check_call(dhclient_command + ['-x'] + interfaces)
    subprocess.check_call(dhclient_command + interfaces)
  except subprocess.CalledProcessError:
    logger.warning('Could not enable interfaces %s.', interfaces)

Configure the network interfaces using dhclient.

Args:
        interfaces: list of string, the output device names to enable.
        logger: logger object, used to write to SysLog and serial port.
        dhclient_script: string, the path to a dhclient script used by dhclient.


def get_consensus_module(module_name):

        module_package = module_name
        if module_name == 'genesis':
            module_package = (
                'sawtooth_validator.journal.consensus.genesis.'
                'genesis_consensus'
            )
        elif module_name == 'devmode':
            module_package = (
                'sawtooth_validator.journal.consensus.dev_mode.'
                'dev_mode_consensus'
            )

        try:
            return importlib.import_module(module_package)
        except ImportError:
            raise UnknownConsensusModuleError(
                'Consensus module "{}" does not exist.'.format(module_name))

Returns a consensus module by name.

Args:
        module_name (str): The name of the module to load.

Returns:
        module: The consensus module.

Raises:
        UnknownConsensusModuleError: Raised if the given module_name does
            not correspond to a consensus implementation.


def assert_visible(self, selector, testid=None, **kwargs):

        self.info_log(
            "Assert visible selector(%s) testid(%s)" % (selector, testid)
        )

        highlight = kwargs.get(
            'highlight',
            BROME_CONFIG['highlight']['highlight_on_assertion_success']
        )
        self.debug_log("effective highlight: %s" % highlight)

        wait_until_visible = kwargs.get(
            'wait_until_visible',
            BROME_CONFIG['proxy_driver']['wait_until_visible_before_assert_visible']  # noqa
        )
        self.debug_log("effective wait_until_visible: %s" % wait_until_visible)

        if wait_until_visible:
            self.wait_until_visible(selector, raise_exception=False)

        element = self.find(
            selector,
            raise_exception=False,
            wait_until_visible=False,
            wait_until_present=False
        )
        if element and element.is_displayed(raise_exception=False):
            if highlight:
                element.highlight(
                    style=BROME_CONFIG['highlight']['style_on_assertion_success']  # noqa
                )
            if testid is not None:
                self.create_test_result(testid, True)

            return True
        else:
            if testid is not None:
                self.create_test_result(testid, False)

            return False

Assert that the element is visible in the dom

Args:
        selector (str): the selector used to find the element
        testid (str): the test_id or a str

    Kwargs:
        wait_until_visible (bool)
        highlight (bool)

Returns:
        bool: True is the assertion succeed; False otherwise.


def MakeSuiteFromHist(hist, name=None):

    if name is None:
        name = hist.name

    # make a copy of the dictionary
    d = dict(hist.GetDict())
    return MakeSuiteFromDict(d, name)

Makes a normalized suite from a Hist object.

Args:
        hist: Hist object
        name: string name

Returns:
        Suite object


def get_resource_url(cls, resource, base_url):

        if resource.Meta.resource_name:
            url = '{}/{}'.format(base_url, resource.Meta.resource_name)
        else:
            p = inflect.engine()
            plural_name = p.plural(resource.Meta.name.lower())
            url = '{}/{}'.format(base_url, plural_name)
        return cls._parse_url_and_validate(url)

Construct the URL for talking to this resource.

    i.e.:

    http://myapi.com/api/resource

    Note that this is NOT the method for calling individual instances i.e.

    http://myapi.com/api/resource/1

Args:
        resource: The resource class instance
        base_url: The Base URL of this API service.

Returns:
        resource_url: The URL for this resource


def uint8sc(im):

    im = np.asarray(im)
    immin = im.min()
    immax = im.max()
    imrange = immax - immin
    return cv2.convertScaleAbs(im - immin, alpha=255 / imrange)

Scale the image to uint8

    Parameters:
    -----------
    im: 2d array
        The image

Returns:
    --------
    im: 2d array (dtype uint8)
        The scaled image to uint8


def delete(self, uri, force=False, timeout=-1, custom_headers=None):

        if force:
            uri += '?force=True'

        logger.debug("Delete resource (uri = %s)" % (str(uri)))

        task, body = self._connection.delete(uri, custom_headers=custom_headers)

        if not task:
            # 204 NO CONTENT
            # Successful return from a synchronous delete operation.
            return True

        task = self._task_monitor.wait_for_task(task, timeout=timeout)

        return task

Deletes current resource.

Args:
        force: Flag to delete the resource forcefully, default is False.
        timeout: Timeout in seconds.
        custom_headers: Allows to set custom http headers.


def restore(self, state):

        self._clear()
        self._parseUserInfo({'labels': state['labels']})
        self._parseNodes(state['nodes'])
        self._keep_version = state['keep_version']

Unserialize saved note data.

Args:
        state (dict): Serialized state to load.


def __init__(self, url_formatter, mapsources):

        super().__init__(url_formatter)
        self.map_folders = {
            root: {
                "folders": folders,
                "maps": maps
            } for root, folders, maps in walk_mapsources(mapsources)
        }
        self.add_maps(parent=self.kml_doc)

Create a KML master document.

Args:
        mapsources (list of MapSource):


def get_variables(scope=None, suffix=None):

  candidates = tf.get_collection(MODEL_VARIABLES, scope)[:]
  if suffix is not None:
    candidates = [var for var in candidates if var.op.name.endswith(suffix)]
  return candidates

Gets the list of variables, filtered by scope and/or suffix.

Args:
        scope: an optional scope for filtering the variables to return.
        suffix: an optional suffix for filtering the variables to return.

Returns:
        a copied list of variables with scope and suffix.


def search(self, search_phrase, limit=None):

        query, query_params = self._make_query_from_terms(search_phrase, limit=limit)

        self._parsed_query = (str(query), query_params)

        assert isinstance(query, TextClause)

        datasets = {}

        def make_result(vid=None, b_score=0, p_score=0):
            res = DatasetSearchResult()
            res.b_score = b_score
            res.p_score = p_score
            res.partitions = set()
            res.vid = vid
            return res

        if query_params:
            results = self.execute(query, **query_params)

            for result in results:
                vid, dataset_score = result

                datasets[vid] = make_result(vid, b_score=dataset_score)

        logger.debug('Extending datasets with partitions.')

        for partition in self.backend.partition_index.search(search_phrase):

            if partition.dataset_vid not in datasets:
                datasets[partition.dataset_vid] = make_result(partition.dataset_vid)

            datasets[partition.dataset_vid].p_score += partition.score
            datasets[partition.dataset_vid].partitions.add(partition)

        return list(datasets.values())

Finds datasets by search phrase.

Args:
        search_phrase (str or unicode):
        limit (int, optional): how many results to return. None means without limit.

Returns:
        list of DatasetSearchResult instances.


def compose(*funcs):

    if not funcs:
        return lambda *args: args[0] if args else None

    if len(funcs) == 1:
        return funcs[0]

    last = funcs[-1]
    rest = funcs[0:-1]
    return lambda *args: reduce(lambda ax, func: func(ax),
                                reversed(rest), last(*args))

chained function composition wrapper

    creates function f, where f(x) = arg0(arg1(arg2(...argN(x))))

    if *funcs is empty, an identity function is returned.

Args:
        *funcs: list of functions to chain

Returns:
        a new function composed of chained calls to *args


def transform_string_replace(source, needle, haystack, name=None):

    with ops.name_scope(name, "TransformStringReplace", [source]):
        source = convert_to_tensor_or_sparse_tensor(source, dtype=tf.string)
        if isinstance(source, tf.SparseTensor):
            result = tf.SparseTensor(
                indices=source.indices,
                values=ops_module.transform_string_replace(source.values, needle, haystack),
                dense_shape=source.dense_shape
            )
        else:
            result = ops_module.transform_string_replace(source, needle, haystack)

    return result

Replace all substrings from `needle` to corresponding strings in `haystack` with source.

Args:
        source: `Tensor` or `SparseTensor` of any shape, source strings for replacing.
        needle: List of strings to search in source
        haystack: List of strings to replace with. Should have same length as `needle`.
        name: A name for the operation (optional).

Returns:
        `Tensor` or `SparseTensor` of same shape and size as input.


def DeleteRecords(cls, ids, token):

    with data_store.DB.GetMutationPool() as mutation_pool:
      mutation_pool.QueueDeleteRecords(ids)

Delete records identified by ids.

Args:
        ids: A list of ids provided by ClaimRecords.
        token: The database access token to delete with.

Raises:
        LockError: If the queue is not locked.


def join_dags(self, names=None):

        return self._client.send(
            Request(
                action='join_dags',
                payload={'names': names}
            )
        ).success

Wait for the specified dags to terminate.

    This function blocks until the specified dags terminate. If no dags are specified
    wait for all dags of the workflow, except the dag of the task calling this signal,
    to terminate.

Args:
        names (list): The names of the dags that have to terminate.

Returns:
        bool: True if all the signal was sent successfully.


def AddSerializedFile(self, serialized_file_desc_proto):

    # pylint: disable=g-import-not-at-top
    from google.protobuf import descriptor_pb2
    file_desc_proto = descriptor_pb2.FileDescriptorProto.FromString(
        serialized_file_desc_proto)
    self.Add(file_desc_proto)

Adds the FileDescriptorProto and its types to this pool.

Args:
        serialized_file_desc_proto: A bytes string, serialization of the
        FileDescriptorProto to add.


def _comparison_functions(cls, partial=False):

        def prerelease_cmp(a, b):

            if a and b:
                return identifier_list_cmp(a, b)
            elif a:
                # Versions with prerelease field have lower precedence
                return -1
            elif b:
                return 1
            else:
                return 0

        def build_cmp(a, b):

            if a == b:
                return 0
            else:
                return NotImplemented

        def make_optional(orig_cmp_fun):

            @functools.wraps(orig_cmp_fun)
            def alt_cmp_fun(a, b):
                if a is None or b is None:
                    return 0
                return orig_cmp_fun(a, b)

            return alt_cmp_fun

        if partial:
            return [
                base_cmp,  # Major is still mandatory
                make_optional(base_cmp),
                make_optional(base_cmp),
                make_optional(prerelease_cmp),
                make_optional(build_cmp),
            ]
        else:
            return [
                base_cmp,
                base_cmp,
                base_cmp,
                prerelease_cmp,
                build_cmp,
            ]

Retrieve comparison methods to apply on version components.

    This is a private API.

Args:
        partial (bool): whether to provide 'partial' or 'strict' matching.

Returns:
        5-tuple of cmp-like functions.


def _create_controller_info_record(self, controller_module_name):

        module = self._controller_modules[controller_module_name]
        controller_info = None
        try:
            controller_info = module.get_info(
                copy.copy(self._controller_objects[controller_module_name]))
        except AttributeError:
            logging.warning('No optional debug info found for controller '
                            '%s. To provide it, implement `get_info`.',
                            controller_module_name)
        try:
            yaml.dump(controller_info)
        except TypeError:
            logging.warning('The info of controller %s in class "%s" is not '
                            'YAML serializable! Coercing it to string.',
                            controller_module_name, self._class_name)
            controller_info = str(controller_info)
        return records.ControllerInfoRecord(
            self._class_name, module.MOBLY_CONTROLLER_CONFIG_NAME,
            controller_info)

Creates controller info record for a particular controller type.

    Info is retrieved from all the controller objects spawned from the
    specified module, using the controller module's `get_info` function.

Args:
        controller_module_name: string, the name of the controller module
            to retrieve info from.

Returns:
        A records.ControllerInfoRecord object.


def populate_settings_dir(force: bool = False) -> bool:

    res = False
    if _default_settings_path == _settings_path:
        return res

    for src in list(_default_settings_path.glob('**/*.json')):
        dest = _settings_path / src.relative_to(_default_settings_path)
        if not force and dest.exists():
            continue
        res = True
        dest.parent.mkdir(parents=True, exist_ok=True)
        shutil.copy(src, dest)
    return res

Populate settings directory with default settings files

Args:
        force: if ``True``, replace existing settings files with default ones

Returns:
        ``True`` if any files were copied and ``False`` otherwise


def upload_marcxml(self, marcxml, mode):

        if mode not in ["-i", "-r", "-c", "-a", "-ir"]:
            raise NameError, "Incorrect mode " + str(mode)

        # Are we running locally? If so, submit directly
        if self.local:
            (code, marcxml_filepath) = tempfile.mkstemp(prefix="upload_%s" % \
                                                        time.strftime("%Y%m%d_%H%M%S_",
                                                                      time.localtime()))
            marcxml_file_d = os.fdopen(code, "w")
            marcxml_file_d.write(marcxml)
            marcxml_file_d.close()
            return task_low_level_submission("bibupload", "", mode, marcxml_filepath)
        else:
            params = urllib.urlencode({'file': marcxml,
                                        'mode': mode})
            ## We don't use self.browser as batchuploader is protected by IP
            opener = urllib2.build_opener()
            opener.addheaders = [('User-Agent', CFG_USER_AGENT)]
            return opener.open(self.server_url + "/batchuploader/robotupload", params,)

Uploads a record to the server

    Parameters:
        marcxml - *str* the XML to upload.
        mode - *str* the mode to use for the upload.
                "-i" insert new records
                "-r" replace existing records
                "-c" correct fields of records
                "-a" append fields to records
                "-ir" insert record or replace if it exists


def __init__(self, cookie_identifier):

    data_type = '{0:s}:{1:s}'.format(self.DATA_TYPE, cookie_identifier)

    super(GoogleAnalyticsEventData, self).__init__(data_type=data_type)
    self.cookie_name = None
    self.domain_hash = None
    self.pages_viewed = None
    self.sessions = None
    self.sources = None
    self.url = None
    self.visitor_id = None

Initializes event data.

Args:
        cookie_identifier (str): unique identifier of the cookie.


def union(self, other):

        operation = bool.__or__
        self.cross_product(other, operation)
        return self

Constructs an unminimized DFA recognizing the union of the languages of two given DFAs.

Args:
        other (DFA): The other DFA that will be used
                    for the union operation

Returns:
        DFA: The resulting DFA


def __init__(self, dir=dir, size=10000, upstream=None, **kwargs):

        from ambry.dbexceptions import ConfigurationError

        super(FsLimitedCache, self).__init__(dir, upstream=upstream, **kwargs)

        self._size = size
        self.maxsize = int(size) * 1048578  # size in MB

        self.readonly = False
        self.usreadonly = False
        self._database = None

        self.use_db = True

        if not os.path.isdir(self.cache_dir):
            os.makedirs(self.cache_dir)

        if not os.path.isdir(self.cache_dir):
            raise ConfigurationError(
                "Cache dir '{}' is not valid".format(
                    self.cache_dir))

Init a new FileSystem Cache

Args:
        cache_dir
        maxsize. Maximum size of the cache, in GB


def __init__(self, channel):

    self.MemberAdd = channel.unary_unary(
        '/etcdserverpb.Cluster/MemberAdd',
        request_serializer=rpc__pb2.MemberAddRequest.SerializeToString,
        response_deserializer=rpc__pb2.MemberAddResponse.FromString,
        )
    self.MemberRemove = channel.unary_unary(
        '/etcdserverpb.Cluster/MemberRemove',
        request_serializer=rpc__pb2.MemberRemoveRequest.SerializeToString,
        response_deserializer=rpc__pb2.MemberRemoveResponse.FromString,
        )
    self.MemberUpdate = channel.unary_unary(
        '/etcdserverpb.Cluster/MemberUpdate',
        request_serializer=rpc__pb2.MemberUpdateRequest.SerializeToString,
        response_deserializer=rpc__pb2.MemberUpdateResponse.FromString,
        )
    self.MemberList = channel.unary_unary(
        '/etcdserverpb.Cluster/MemberList',
        request_serializer=rpc__pb2.MemberListRequest.SerializeToString,
        response_deserializer=rpc__pb2.MemberListResponse.FromString,
        )

Constructor.

Args:
        channel: A grpc.Channel.


def make_tstore_conn(params, **kwargs):

    log.setLevel(params.get('log_level', __LOG_LEVEL__))
    log.debug("\n%s", params)
    params.update(kwargs)
    try:
        vendor = RdfwConnections['triplestore'][params.get('vendor')]
    except KeyError:
        vendor = RdfwConnections['triplestore']['blazegraph']
    conn = vendor(**params)
    return conn

Returns a triplestore connection

Args:
        attr_name: The name the connection will be assigned in the
            config manager
        params: The paramaters of the connection

    kwargs:
        log_level: logging level to use


def _calculateCrcString(inputstring):

    _checkString(inputstring, description='input CRC string')

    # Preload a 16-bit register with ones
    register = 0xFFFF

    for char in inputstring:
        register = (register >> 8) ^ _CRC16TABLE[(register ^ ord(char)) & 0xFF]

    return _numToTwoByteString(register, LsbFirst=True)

Calculate CRC-16 for Modbus.

Args:
        inputstring (str): An arbitrary-length message (without the CRC).

Returns:
        A two-byte CRC string, where the least significant byte is first.


def __init__(self, name, context=None):

    super(Job, self).__init__(name)
    if context is None:
      context = datalab.Context.default()
    self._context = context
    self._api = discovery.build('ml', 'v1', credentials=self._context.credentials)
    if not name.startswith('projects/'):
      name = 'projects/' + self._context.project_id + '/jobs/' + name
    self._name = name
    self._refresh_state()

Initializes an instance of a CloudML Job.

Args:
        name: the name of the job. It can be an operation full name
        ("projects/[project_id]/jobs/[operation_name]") or just [operation_name].
        context: an optional Context object providing project_id and credentials.


def insert_arguments_into_query(compilation_result, arguments):

    _ensure_arguments_are_provided(compilation_result.input_metadata, arguments)

    if compilation_result.language == MATCH_LANGUAGE:
        return insert_arguments_into_match_query(compilation_result, arguments)
    elif compilation_result.language == GREMLIN_LANGUAGE:
        return insert_arguments_into_gremlin_query(compilation_result, arguments)
    elif compilation_result.language == SQL_LANGUAGE:
        return insert_arguments_into_sql_query(compilation_result, arguments)
    else:
        raise AssertionError(u'Unrecognized language in compilation result: '
                             u'{}'.format(compilation_result))

Insert the arguments into the compiled GraphQL query to form a complete query.

Args:
        compilation_result: a CompilationResult object derived from the GraphQL compiler
        arguments: dict, mapping argument name to its value, for every parameter the query expects.

Returns:
        string, a query in the appropriate output language, with inserted argument data


def _faster_to_representation(self, instance):

        ret = {}
        fields = self._readable_fields

        is_fast = isinstance(instance, prefetch.FastObject)
        id_fields = self._readable_id_fields

        for field in fields:
            attribute = None

            # we exclude dynamic fields here because the proper fastquery
            # dereferencing happens in the `get_attribute` method now
            if (
                is_fast and
                not isinstance(
                    field,
                    (DynamicGenericRelationField, DynamicRelationField)
                )
            ):
                if field in id_fields and field.source not in instance:
                    # TODO - make better.
                    attribute = instance.get(field.source + '_id')
                    ret[field.field_name] = attribute
                    continue
                else:
                    try:
                        attribute = instance[field.source]
                    except KeyError:
                        # slower, but does more stuff
                        # Also, some temp debugging
                        if hasattr(instance, field.source):
                            attribute = getattr(instance, field.source)
                        else:
                            # Fall back on DRF behavior
                            attribute = field.get_attribute(instance)
                            print(
                                'Missing %s from %s' % (
                                    field.field_name,
                                    self.__class__.__name__
                                )
                            )
            else:
                try:
                    attribute = field.get_attribute(instance)
                except SkipField:
                    continue

            if attribute is None:
                # We skip `to_representation` for `None` values so that
                # fields do not have to explicitly deal with that case.
                ret[field.field_name] = None
            else:
                ret[field.field_name] = field.to_representation(attribute)

        return ret

Modified to_representation with optimizations.

    1) Returns a plain old dict as opposed to OrderedDict.
        (Constructing ordered dict is ~100x slower than `{}`.)
    2) Ensure we use a cached list of fields
        (this optimization exists in DRF 3.2 but not 3.1)

Args:
        instance: a model instance or data object

Returns:
        Dict of primitive datatypes.


def FetchBlobsForSignedBinary(
    binary_urn,
    token = None
):

  if _ShouldUseLegacyDatastore():
    try:
      aff4_stream = aff4.FACTORY.Open(
          binary_urn, aff4_type=collects.GRRSignedBlob, mode="r", token=token)
    except aff4.InstantiationError:
      raise SignedBinaryNotFoundError(binary_urn)
    timestamp = aff4_stream.Get(aff4_stream.Schema.TYPE).age
    return (blob for blob in aff4_stream), timestamp
  else:
    try:
      references, timestamp = data_store.REL_DB.ReadSignedBinaryReferences(
          _SignedBinaryIDFromURN(binary_urn))
    except db.UnknownSignedBinaryError:
      raise SignedBinaryNotFoundError(binary_urn)
    blob_ids = [r.blob_id for r in references.items]
    raw_blobs = (data_store.BLOBS.ReadBlob(blob_id) for blob_id in blob_ids)
    blobs = (
        rdf_crypto.SignedBlob.FromSerializedString(raw_blob)
        for raw_blob in raw_blobs)
    return blobs, timestamp

Retrieves blobs for the given binary from the datastore.

Args:
        binary_urn: RDFURN that uniquely identifies the binary.
        token: ACL token to use with the legacy (non-relational) datastore.

Returns:
        A tuple containing an iterator for all the binary's blobs and an
        RDFDatetime representing when the binary's contents were saved
        to the datastore.

Raises:
        SignedBinaryNotFoundError: If no signed binary with the given URN exists.


def __init__(self, job_context, shard_state):

    self.job_context = job_context
    self.id = shard_state.shard_id
    self.number = shard_state.shard_number
    self.attempt = shard_state.retries + 1
    self._state = shard_state

Init.

    The signature of __init__ is subject to change.

    Read only properties:
        job_context: JobContext object.
        id: str. of format job_id-shard_number.
        number: int. shard number. 0 indexed.
        attempt: int. The current attempt at executing this shard.
        Starting at 1.

Args:
        job_context: map_job.JobConfig.
        shard_state: model.ShardState.


def coordinate_tensor(shape, axis):

  if axis < 0:
    axis = tf.size(shape) + axis  # Convert to positive for the one_hot indice

  r = tf.range(shape[axis])
  r_shape = tf.one_hot(
      axis, tf.size(shape), on_value=-1, off_value=1, dtype=tf.int32)
  return tf.zeros(shape, dtype=tf.int32) + tf.reshape(r, r_shape)

Return a tensor with given shape containing coordinate along given axis.

Args:
        shape: a Tensor representing the shape of the output Tensor
        axis: an integer

Returns:
        A tensor with shape shape and type tf.int32, where each elements its
        coordinate along the given axis.


def GreaterThan(self, value):

    self._awql = self._CreateSingleValueCondition(value, '>')
    return self._query_builder

Sets the type of the WHERE clause as "greater than".

Args:
        value: The value to be used in the WHERE condition.

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


def post_pipeline(self, pipeline):

        url = "{0}/pipelines".format(API_URL)

        if isinstance(pipeline, str):
            pipeline_json = pipeline
        else:
            pipeline_json = json.dumps(pipeline)

        pipeline_dict = json.loads(pipeline_json)

        self.log.debug('Pipeline JSON:\n%s', pipeline_json)

        pipeline_response = requests.post(
            url, data=pipeline_json, headers=self.header, verify=GATE_CA_BUNDLE, cert=GATE_CLIENT_CERT)

        self.log.debug('Pipeline creation response:\n%s', pipeline_response.text)

        if not pipeline_response.ok:
            raise SpinnakerPipelineCreationFailed('Pipeline for {0}: {1}'.format(self.app_name,
                                                                                pipeline_response.json()))

        self.log.info('Successfully created "%s" pipeline in application "%s".', pipeline_dict['name'],
                      pipeline_dict['application'])

Send Pipeline JSON to Spinnaker.

Args:
        pipeline (json): json of the pipeline to be created in Spinnaker


def cardinal(self, to):

        return sum(1 for _ in filter(
            lambda d: not d.external and d.target in to, self.dependencies))

Return the number of dependencies of this module to the given node.

Args:
        to (Package/Module): the target node.

Returns:
        int: number of dependencies.


def merge_all_models_into_first_model(biop_structure):

    from string import ascii_uppercase
    idx = 1
    first_model = biop_structure[0]

    for m in biop_structure.get_models():
        # Don't duplicate the original model
        if first_model.id == m.id:
            continue
        for c in m.get_chains():
            c.id = ascii_uppercase[idx]
            first_model.add(c)
        idx += 1

Merge all existing models into a Structure's first_model attribute.

    This directly modifies the Biopython Structure object. Chains IDs will start from A and increment for each new
    chain (model that is converted).

Args:
        biop_structure (Structure): Structure with multiple models that should be merged


def incoming_edges(self, node):

        edges = self.edges()
        in_edges = []
        for out_node, in_node in edges:
            if node is in_node:
                in_edges.append((out_node, in_node))
        return tuple(in_edges)

Returns a ``tuple`` of incoming edges for a **node object**.

Args:
        - node(``object``) **node object** present in the graph to be queried
        for incoming edges.


def _log_submission(submission, student_item):

    logger.info(
        u"Created submission uuid={submission_uuid} for "
        u"(course_id={course_id}, item_id={item_id}, "
        u"anonymous_student_id={anonymous_student_id})"
        .format(
            submission_uuid=submission["uuid"],
            course_id=student_item["course_id"],
            item_id=student_item["item_id"],
            anonymous_student_id=student_item["student_id"]
        )
    )

Log the creation of a submission.

Args:
        submission (dict): The serialized submission model.
        student_item (dict): The serialized student item model.

Returns:
        None


def _add_string_to_commastring(self, field, string):
        # type: (str, str) -> bool

        if string in self._get_stringlist_from_commastring(field):
            return False
        strings = '%s,%s' % (self.data.get(field, ''), string)
        if strings[0] == ',':
            strings = strings[1:]
        self.data[field] = strings
        return True

Add a string to a comma separated list of strings

Args:
        field (str): Field containing comma separated list
        string (str): String to add

Returns:
        bool: True if string added or False if string already present


def synthesize(self, duration, tick_frequency):

        sr = self.samplerate.samples_per_second
        # create a short, tick sound
        tick = np.random.uniform(low=-1., high=1., size=int(sr * .1))
        tick *= np.linspace(1, 0, len(tick))
        # create silence
        samples = np.zeros(int(sr * (duration / Seconds(1))))
        ticks_per_second = Seconds(1) / tick_frequency
        # introduce periodic ticking sound
        step = int(sr // ticks_per_second)
        for i in range(0, len(samples), step):
            size = len(samples[i:i + len(tick)])
            samples[i:i + len(tick)] += tick[:size]
        return AudioSamples(samples, self.samplerate)

Synthesize periodic "ticks", generated from white noise and an envelope

Args:
        duration (numpy.timedelta64): The total duration of the sound to be
            synthesized
        tick_frequency (numpy.timedelta64): The frequency of the ticking
            sound


def to_df(self, **kwargs):

        return pd.read_sql(sql=self.statement, con=self.session.bind, **kwargs)

[pandas.read_sql]

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

Returns:
        [pd.DataFrame or generate] -- [description]


def __init__(self, values, mode='rgb', alpha=1.0, wref=_DEFAULT_WREF):

    if not(isinstance(values, tuple)):
      raise TypeError('values must be a tuple')

    if mode=='rgb':
      self.__rgb = values
      self.__hsl = Color.RgbToHsl(*values)
    elif mode=='hsl':
      self.__hsl = values
      self.__rgb = Color.HslToRgb(*values)
    else:
      raise ValueError('Invalid color mode: ' + mode)

    self.__a = alpha
    self.__wref = wref

Instantiate a new grapefruit.Color object.

    Parameters:
        :values:
        The values of this color, in the specified representation.
        :mode:
        The representation mode used for values.
        :alpha:
        the alpha value (transparency) of this color.
        :wref:
        The whitepoint reference, default is 2° D65.


def __init__(self, protocol):

        self._protocol = protocol
        self._current_consumer = self._HEADER
        self._message = None
        self._buf_header = None

Configure a Receiver with a specific Bokeh protocol version.

Args:
        protocol (Protocol) :
            A Bokeh protocol object to use to assemble collected message
            fragments.


def __init__(self, idx, name="select_input"):

    super(SelectInput, self).__init__(name=name)
    self._check_type(idx)
    self._idx = idx

Module constructor.

Args:
        idx: Indexes of the tensors to select. If `idx` is an integer, then
        a `Tensor` is returned. If `idx` is a (nested) list/tuple, then a
        (nested) tuple of `Tensor` is returned.
        name: Name of the module.

Raises:
        TypeError: If `idx` is not an list, tuple or integer.