def set_json(self, reason='', new_page=False):

        compressed_json = json.dumps(self._compress_json(self.cached_json))

        if len(compressed_json) > self.max_page_size:
            raise OverflowError(
                'Usernotes page is too large (>{0} characters)'.
                format(self.max_page_size)
            )

        if new_page:
            self.subreddit.wiki.create(
                self.page_name,
                compressed_json,
                reason
            )
            # Set the page as hidden and available to moderators only
            self.subreddit.wiki[self.page_name].mod.update(False, permlevel=2)
        else:
            self.subreddit.wiki[self.page_name].edit(
                compressed_json,
                reason
            )

Send the JSON from the cache to the usernotes wiki page.

Args:
        reason: the change reason that will be posted to the wiki changelog
            (str)

Raises:
        OverflowError if the new JSON data is greater than max_page_size


def word_error_rate(ref: Sequence[T], hyp: Sequence[T]) -> float:

    if len(ref) == 0:
        raise EmptyReferenceException(
            "Cannot calculating word error rate against a length 0 "\
            "reference sequence.")

    distance = min_edit_distance(ref, hyp)
    return 100 * float(distance) / len(ref)

Calculate the word error rate of a sequence against a reference.

Args:
        ref: The gold-standard reference sequence
        hyp: The hypothesis to be evaluated against the reference.

Returns:
        The word error rate of the supplied hypothesis with respect to the
        reference string.

Raises:
        persephone.exceptions.EmptyReferenceException: If the length of the reference sequence is 0.


def jobUpdateResults(self, jobID, results):

    with ConnectionFactory.get() as conn:
      query = 'UPDATE %s SET _eng_last_update_time=UTC_TIMESTAMP(), ' \
              '              results=%%s ' \
              '          WHERE job_id=%%s' % (self.jobsTableName,)
      conn.cursor.execute(query, [results, jobID])

Update the results string and last-update-time fields of a model.

    Parameters:
    ----------------------------------------------------------------
    jobID:      job ID of model to modify
    results:    new results (json dict string)


def filter_parts(cls, part_info):
        # type: (Type[T], PartInfo) -> Dict[str, List[T]]

        filtered = OrderedDict()
        for part_name, info_list in part_info.items():
            if info_list is None or isinstance(info_list, Exception):
                continue
            info_list = [i for i in info_list if isinstance(i, cls)]
            if info_list:
                filtered[part_name] = info_list
        return filtered

Filter the part_info dict looking for instances of our class

Args:
        part_info (dict): {part_name: [Info] or None} as returned from
            Controller.run_hook()

Returns:
        dict: {part_name: [info]} where info is a subclass of cls


def get_replicas(self, service_id: str) -> str:

        # Initialising empty list
        replicas = []

        # Raise an exception if we are not a manager
        if not self._manager:
            raise RuntimeError('Only the Swarm manager node can retrieve '
                               'replication level of the service')

        service_tasks = self._client.services.get(service_id).tasks()
        for task in service_tasks:
            if task['Status']['State'] == "running":
                replicas.append(task)
        return len(replicas)

Get the replication level of a service.

Args:
        service_id (str): docker swarm service id

Returns:
        str, replication level of the service


def reopen_encoded(fileobj, mode='r', fallback_encoding=None):

    encoding = determine_encoding(fileobj.name, fallback_encoding)
    fileobj.close()
    return open(fileobj.name, mode, encoding=encoding)

Makes sure that a file was opened with some valid encoding.

Args:
        fileobj (file): The file-object.
        mode (str, optional): The mode in which to re-open the file.
        fallback_encoding (str, optional): The encoding in which to re-open
            the file if it does not specify an encoding itself.

Returns:
        file: The re-opened file.


def parse(self, rrstr):
        # type: (bytes) -> int

        if self._initialized:
            raise pycdlibexception.PyCdlibInternalError('PX record already initialized!')

        (su_len, su_entry_version_unused, posix_file_mode_le, posix_file_mode_be,
         posix_file_links_le, posix_file_links_be, posix_file_user_id_le,
         posix_file_user_id_be, posix_file_group_id_le,
         posix_file_group_id_be) = struct.unpack_from('=BBLLLLLLLL', rrstr[:38], 2)

        # We assume that the caller has already checked the su_entry_version,
        # so we don't bother.

        if posix_file_mode_le != utils.swab_32bit(posix_file_mode_be):
            raise pycdlibexception.PyCdlibInvalidISO('PX record big and little-endian file mode do not agree')

        if posix_file_links_le != utils.swab_32bit(posix_file_links_be):
            raise pycdlibexception.PyCdlibInvalidISO('PX record big and little-endian file links do not agree')

        if posix_file_user_id_le != utils.swab_32bit(posix_file_user_id_be):
            raise pycdlibexception.PyCdlibInvalidISO('PX record big and little-endian file user ID do not agree')

        if posix_file_group_id_le != utils.swab_32bit(posix_file_group_id_be):
            raise pycdlibexception.PyCdlibInvalidISO('PX record big and little-endian file group ID do not agree')

        # In Rock Ridge 1.09 and 1.10, there is no serial number so the su_len
        # is 36, while in Rock Ridge 1.12, there is an 8-byte serial number so
        # su_len is 44.
        if su_len == 36:
            posix_file_serial_number_le = 0
        elif su_len == 44:
            (posix_file_serial_number_le,
             posix_file_serial_number_be) = struct.unpack_from('=LL',
                                                               rrstr[:44], 36)
            if posix_file_serial_number_le != utils.swab_32bit(posix_file_serial_number_be):
                raise pycdlibexception.PyCdlibInvalidISO('PX record big and little-endian file serial number do not agree')
        else:
            raise pycdlibexception.PyCdlibInvalidISO('Invalid length on Rock Ridge PX record')

        self.posix_file_mode = posix_file_mode_le
        self.posix_file_links = posix_file_links_le
        self.posix_user_id = posix_file_user_id_le
        self.posix_group_id = posix_file_group_id_le
        self.posix_serial_number = posix_file_serial_number_le

        self._initialized = True

        return su_len

Parse a Rock Ridge POSIX File Attributes record out of a string.

    Parameters:
    rrstr - The string to parse the record out of.

Returns:
    A string representing the RR version, either 1.09 or 1.12.


def get_all_aminames(i_info):

    for i in i_info:
        try:
            # pylint: disable=maybe-no-member
            i_info[i]['aminame'] = EC2R.Image(i_info[i]['ami']).name
        except AttributeError:
            i_info[i]['aminame'] = "Unknown"
    return i_info

Get Image_Name for each instance in i_info.

Args:
        i_info (dict): information on instances and details.

Returns:
        i_info (dict): i_info is returned with the aminame
                    added for each instance.


def move_spines(ax, sides, dists):

    for side, dist in zip(sides, dists):
        ax.spines[side].set_position(("axes", dist))
    return ax

Move the entire spine relative to the figure.

    Parameters:
        ax: axes to operate on
        sides: list of sides to move. Sides: top, left, bottom, right
        dists: list of float distances to move. Should match sides in length.

Example:
    move_spines(ax, sides=['left', 'bottom'], dists=[-0.02, 0.1])


def __call__(self, *x_batch, **kwargs) -> Union[List, np.ndarray]:

        with self.graph.as_default():
            K.set_session(self.sess)
            return self._net.predict_on_batch(x_batch, **kwargs)

Predicts answers on batch elements.

Args:
        instance: a batch to predict answers on


def MakeSimpleProtoClass(fields, full_name=None, pool=None):

  factory = message_factory.MessageFactory(pool=pool)

  if full_name is not None:
    try:
      proto_cls = _GetMessageFromFactory(factory, full_name)
      return proto_cls
    except KeyError:
      # The factory's DescriptorPool doesn't know about this class yet.
      pass

  # Get a list of (name, field_type) tuples from the fields dict. If fields was
  # an OrderedDict we keep the order, but otherwise we sort the field to ensure
  # consistent ordering.
  field_items = fields.items()
  if not isinstance(fields, OrderedDict):
    field_items = sorted(field_items)

  # Use a consistent file name that is unlikely to conflict with any imported
  # proto files.
  fields_hash = hashlib.sha1()
  for f_name, f_type in field_items:
    fields_hash.update(f_name.encode('utf-8'))
    fields_hash.update(str(f_type).encode('utf-8'))
  proto_file_name = fields_hash.hexdigest() + '.proto'

  # If the proto is anonymous, use the same hash to name it.
  if full_name is None:
    full_name = ('net.proto2.python.public.proto_builder.AnonymousProto_' +
                 fields_hash.hexdigest())
    try:
      proto_cls = _GetMessageFromFactory(factory, full_name)
      return proto_cls
    except KeyError:
      # The factory's DescriptorPool doesn't know about this class yet.
      pass

  # This is the first time we see this proto: add a new descriptor to the pool.
  factory.pool.Add(
      _MakeFileDescriptorProto(proto_file_name, full_name, field_items))
  return _GetMessageFromFactory(factory, full_name)

Create a Protobuf class whose fields are basic types.

    Note: this doesn't validate field names!

Args:
        fields: dict of {name: field_type} mappings for each field in the proto. If
        this is an OrderedDict the order will be maintained, otherwise the
        fields will be sorted by name.
        full_name: optional str, the fully-qualified name of the proto type.
        pool: optional DescriptorPool instance.

Returns:
        a class, the new protobuf class with a FileDescriptor.


def RemoveTask(self, task):

    with self._lock:
      if task.identifier not in self._tasks_abandoned:
        raise KeyError('Task {0:s} was not abandoned.'.format(task.identifier))

      if not task.has_retry:
        raise KeyError(
            'Will not remove a task {0:s} without retry task.'.format(
                task.identifier))

      del self._tasks_abandoned[task.identifier]

      logger.debug('Removed task {0:s}.'.format(task.identifier))

Removes an abandoned task.

Args:
        task (Task): task.

Raises:
        KeyError: if the task was not abandoned or the task was abandoned and
        was not retried.


def tinsel(to_patch, module_name, decorator=mock_decorator):

    def fn_decorator(function):
        def wrapper(*args, **kwargs):
            with patch(to_patch, decorator):
                m = importlib.import_module(module_name)
                reload(m)
                function(*args, **kwargs)

            reload(m)
        return wrapper
    return fn_decorator

Decorator for simple in-place decorator mocking for tests

Args:
        to_patch: the string path of the function to patch
        module_name: complete string path of the module to reload
        decorator (optional): replacement decorator. By default a pass-through
            will be used.

Returns:
        A wrapped test function, during the context of execution the specified
        path is patched.


def _redis_watcher(state):

    conf = state.app.config

    r = redis.client.StrictRedis(
        host=conf.get('WAFFLE_REDIS_HOST', 'localhost'),
        port=conf.get('WAFFLE_REDIS_PORT', 6379))

    sub = r.pubsub(ignore_subscribe_messages=True)
    sub.subscribe(conf.get('WAFFLE_REDIS_CHANNEL', 'waffleconf'))

    while True:
        for msg in sub.listen():
            # Skip non-messages
            if not msg['type'] == 'message':
                continue

            tstamp = float(msg['data'])

            # Compare timestamps and update config if needed
            if tstamp > state._tstamp:
                state.update_conf()
                state._tstamp = tstamp

Listen to redis channel for a configuration update notifications.

Args:
        state (_WaffleState): Object that contains reference to app and its
            configstore.


def remove_attribute(self, attribute: str) -> None:

        attr_index = self.__attr_index(attribute)
        if attr_index is not None:
            self.yaml_node.value.pop(attr_index)

Remove an attribute from the node.

    Use only if is_mapping() returns True.

Args:
        attribute: The name of the attribute to remove.


def __init__(self, server, port, project_key=None,
                 run_asyncore_thread=True):

        self.server = server
        self.port = port

        super(ZEOWrapper, self).__init__(
            project_key=project_key,
            run_asyncore_thread=run_asyncore_thread,
        )

Initialize the object.

Args:
        conf_path (str): See :attr:`conf_path`.
        project_key (str, default None): See :attr:`project_key`. If not
            set, the root of the database is used (this may cause
            performace issues).
        run_asyncore_thread (bool, default True): Run external asyncore
            thread, which handles connections to database? Default True.


def get_variant(variant_handle, context=None):

    if isinstance(variant_handle, dict):
        variant_handle = ResourceHandle.from_dict(variant_handle)

    variant_resource = package_repository_manager.get_resource_from_handle(variant_handle)
    variant = Variant(variant_resource, context=context)
    return variant

Create a variant given its handle (or serialized dict equivalent)

Args:
        variant_handle (`ResourceHandle` or dict): Resource handle, or
            equivalent serialized dict representation from
            ResourceHandle.to_dict
        context (`ResolvedContext`): The context this variant is associated
            with, if any.

Returns:
        `Variant`.


def directional_poisson_ratio(self, n, m, tol=1e-8):

        n, m = get_uvec(n), get_uvec(m)
        if not np.abs(np.dot(n, m)) < tol:
            raise ValueError("n and m must be orthogonal")
        v = self.compliance_tensor.einsum_sequence([n]*2 + [m]*2)
        v *= -1 / self.compliance_tensor.einsum_sequence([n]*4)
        return v

Calculates the poisson ratio for a specific direction
    relative to a second, orthogonal direction

Args:
        n (3-d vector): principal direction
        m (3-d vector): secondary direction orthogonal to n
        tol (float): tolerance for testing of orthogonality


def write_failure_file(failure_msg):  # type: (str) -> None

    file_path = os.path.join(_env.output_dir, 'failure')
    write_file(file_path, failure_msg)

Create a file 'failure' if training fails after all algorithm output (for example, logging) completes,
    the failure description should be written to this file. In a DescribeTrainingJob response, Amazon SageMaker
    returns the first 1024 characters from this file as FailureReason.
    See: https://docs.aws.amazon.com/sagemaker/latest/dg/your-algorithms-training-algo.html

Args:
        failure_msg: The description of failure


def get_learning_rate(self, iter):

        lr = self.scheduler.get_learning_rate(iter)
        if iter < self.warmup_iter:
            lr *= (iter + 1) * 1.0 / self.warmup_iter
        return lr

Get learning rate with exponential decay based on current iteration.

Args:
        iter (int): Current iteration (starting with 0).

Returns:
        float: Learning rate


def _AddHeader(self, fp):

    text = textwrap.wrap(
        textwrap.dedent(self.config_header), break_on_hyphens=False)
    fp.write('\n'.join(['# ' + line for line in text]))
    fp.write('\n\n')

Create a file header in the config.

Args:
        fp: int, a file pointer for writing the header.


def run(self, input_dir, output_file_path):

    logging.info('Running defense %s', self.submission_id)
    tmp_run_dir = self.temp_copy_extracted_submission()
    output_dir = os.path.dirname(output_file_path)
    output_filename = os.path.basename(output_file_path)
    cmd = ['--network=none',
           '-m=24g',
           '--cpus=3.75',
           '-v', '{0}:/input_images:ro'.format(input_dir),
           '-v', '{0}:/output_data'.format(output_dir),
           '-v', '{0}:/code'.format(tmp_run_dir),
           '-w', '/code',
           self.container_name,
           './' + self.entry_point,
           '/input_images',
           '/output_data/' + output_filename]
    elapsed_time_sec = self.run_with_time_limit(cmd)
    sudo_remove_dirtree(tmp_run_dir)
    return elapsed_time_sec

Runs defense inside Docker.

Args:
        input_dir: directory with input (adversarial images).
        output_file_path: path of the output file.

Returns:
        how long it took to run submission in seconds


def get_cached_or_new(url, new=False):

    garbage_collection()

    old_req = DATABASE.get(url)

    if old_req and not new:
        return old_req

    if not (url.startswith("http://") or url.startswith("https://")):
        raise ValueError("Invalid URL `%s`!" % url)

    req = RequestInfo(url=url)
    DATABASE[url] = req

    return req

Look into the database and return :class:`RequestInfo` if the `url` was
    already analyzed, or create and return new instance, if not.

    If the `new` is set to True, always create new instance.

Args:
        url (str): URL of the analyzed resource.
        new (bool, default False): Force new instance?

Returns:
        obj: :class:`RequestInfo` instance.


def Copy(From, To):

    from benchbuild.utils.cmd import cp
    cp("-ar", "--reflink=auto", From, To)

Small copy wrapper.

Args:
        From (str): Path to the SOURCE.
        To (str): Path to the TARGET.


def port(self, check=False):

        if not self.__ports:  # refresh ports if sequence is empty
            self.refresh()

        try:
            port = self.__ports.pop()
            if check:
                while not self.__check_port(port):
                    self.release_port(port)
                    port = self.__ports.pop()
        except (IndexError, KeyError):
            raise IndexError("Could not find a free port,\nclosed ports: {closed}".format(closed=self.__closed))
        self.__closed.add(port)
        return port

return next opened port

Args:
        check - check is port realy free


def read(self, file_des, num_bytes):

        file_handle = self.filesystem.get_open_file(file_des)
        file_handle.raw_io = True
        return file_handle.read(num_bytes)

Read number of bytes from a file descriptor, returns bytes read.

Args:
        file_des: An integer file descriptor for the file object requested.
        num_bytes: Number of bytes to read from file.

Returns:
        Bytes read from file.

Raises:
        OSError: bad file descriptor.
        TypeError: if file descriptor is not an integer.


def get_data_for_sensors(macs=[], search_duratio_sec=5, bt_device=''):

        log.info('Get latest data for sensors. Stop with Ctrl+C.')
        log.info('Stops automatically in %ss', search_duratio_sec)
        log.info('MACs: %s', macs)

        datas = dict()

        for new_data in RuuviTagSensor._get_ruuvitag_datas(macs, search_duratio_sec, bt_device=bt_device):
            datas[new_data[0]] = new_data[1]

        return datas

Get lates data for sensors in the MAC's list.

Args:
        macs (array): MAC addresses
        search_duratio_sec (int): Search duration in seconds. Default 5
        bt_device (string): Bluetooth device id

Returns:
        dict: MAC and state of found sensors


def add_menu_item(self, command, title):

        m_item = Gtk.MenuItem()
        m_item.set_label(title)
        m_item.connect('activate', command)
        self.menu.append(m_item)
        self.menu.show_all()

Add mouse right click menu item.

Args:
        command (callable): function that will be called after left mouse click on title
        title (str): label that will be shown in menu


def iter_train_batches(self, max_yield=999):

        for ev, sample_batch in self._augment_with_replay(
                self.sample_tasks.completed_prefetch(
                    blocking_wait=True, max_yield=max_yield)):
            sample_batch.decompress_if_needed()
            self.batch_buffer.append(sample_batch)
            if sum(b.count
                   for b in self.batch_buffer) >= self.train_batch_size:
                train_batch = self.batch_buffer[0].concat_samples(
                    self.batch_buffer)
                yield train_batch
                self.batch_buffer = []

            # If the batch was replayed, skip the update below.
            if ev is None:
                continue

            # Put in replay buffer if enabled
            if self.replay_buffer_num_slots > 0:
                if len(self.replay_batches) < self.replay_buffer_num_slots:
                    self.replay_batches.append(sample_batch)
                else:
                    self.replay_batches[self.replay_index] = sample_batch
                    self.replay_index += 1
                    self.replay_index %= self.replay_buffer_num_slots

            ev.set_weights.remote(self.broadcasted_weights)
            self.num_weight_syncs += 1
            self.num_sent_since_broadcast += 1

            # Kick off another sample request
            self.sample_tasks.add(ev, ev.sample.remote())

Iterate over train batches.

Args:
        max_yield (int): Max number of batches to iterate over in this
            cycle. Setting this avoids iter_train_batches returning too
            much data at once.


def plot(self, freq=None, figsize=(15, 5), title=None,
             logy=False, **kwargs):

        if title is None:
            title = self._get_default_plot_title(
                freq, 'Equity Progression')

        ser = self._get_series(freq).rebase()
        return ser.plot(figsize=figsize, logy=logy,
                        title=title, **kwargs)

Helper function for plotting the series.

Args:
        * freq (str): Data frequency used for display purposes.
            Refer to pandas docs for valid freq strings.
        * figsize ((x,y)): figure size
        * title (str): Title if default not appropriate
        * logy (bool): log-scale for y axis
        * kwargs: passed to pandas' plot method


def in_array_list(array_list, a, tol=1e-5):

    if len(array_list) == 0:
        return False
    axes = tuple(range(1, a.ndim + 1))
    if not tol:
        return np.any(np.all(np.equal(array_list, a[None, :]), axes))
    else:
        return np.any(np.sum(np.abs(array_list - a[None, :]), axes) < tol)

Extremely efficient nd-array comparison using numpy's broadcasting. This
    function checks if a particular array a, is present in a list of arrays.
    It works for arrays of any size, e.g., even matrix searches.

Args:
        array_list ([array]): A list of arrays to compare to.
        a (array): The test array for comparison.
        tol (float): The tolerance. Defaults to 1e-5. If 0, an exact match is
            done.

Returns:
        (bool)


def on_hello(self, message):

        logger.info("Got a hello")
        self.identify(self.token)
        self.heartbeat_thread = Heartbeat(self.ws,
                                          message['d']['heartbeat_interval'])
        self.heartbeat_thread.start()
        return

Runs on a hello event from websocket connection

Args:
        message (dict): Full message from Discord websocket connection"


def DeregisterHelper(cls, analyzer_helper):

    if analyzer_helper.type_indicator not in cls._analyzer_helpers:
      raise KeyError(
          'Analyzer helper object not set for type indicator: {0:s}.'.format(
              analyzer_helper.type_indicator))

    analyzer_helper = cls._analyzer_helpers[analyzer_helper.type_indicator]

    cls._FlushCache(analyzer_helper.format_categories)

    del cls._analyzer_helpers[analyzer_helper.type_indicator]

Deregisters a format analyzer helper.

Args:
        analyzer_helper (AnalyzerHelper): analyzer helper.

Raises:
        KeyError: if analyzer helper object is not set for the corresponding
        type indicator.


def register_macro(name: str, func: Callable, allow_overwrite: bool = False) -> None:

        if hasattr(Circuit, name):
            if allow_overwrite:
                warnings.warn(f"Circuit has attribute `{name}`.")
            else:
                raise ValueError(f"Circuit has attribute `{name}`.")
        if name.startswith("run_with_"):
            if allow_overwrite:
                warnings.warn(f"Gate name `{name}` may conflict with run of backend.")
            else:
                raise ValueError(f"Gate name `{name}` shall not start with 'run_with_'.")
        if not allow_overwrite:
            if name in GATE_SET:
                raise ValueError(f"Gate '{name}' is already exists in gate set.")
            if name in GLOBAL_MACROS:
                raise ValueError(f"Macro '{name}' is already exists.")
        GLOBAL_MACROS[name] = func

Register new macro to Circuit.

Args:
        name (str): The name of macro.
        func (callable): The function to be called.
        allow_overwrite (bool, optional): If True, allow to overwrite the existing macro.
            Otherwise, raise the ValueError.

Raises:
        ValueError: The name is duplicated with existing macro, gate or method.
            When `allow_overwrite=True`, this error is not raised.


def _AddSerializedEvent(self, event):

    identifier = identifiers.SQLTableIdentifier(
        self._CONTAINER_TYPE_EVENT,
        self._serialized_event_heap.number_of_events + 1)
    event.SetIdentifier(identifier)

    serialized_data = self._SerializeAttributeContainer(event)

    self._serialized_event_heap.PushEvent(event.timestamp, serialized_data)

    if self._serialized_event_heap.data_size > self._maximum_buffer_size:
      self._WriteSerializedAttributeContainerList(self._CONTAINER_TYPE_EVENT)

Adds an serialized event.

Args:
        event (EventObject): event.

Raises:
        IOError: if the event cannot be serialized.
        OSError: if the event cannot be serialized.


def write_tabular(obj, filepath):

    _, fn, ext = splitext2(filepath)
    if ext == '.h5':
        _write_tabular_h5(obj, filepath)
    elif ext == '.pkl':
        _write_tabular_pickle(obj, filepath)
    else:
        raise NotImplementedError

Write tabular object in HDF5 or pickle format

Args:
        obj (array or DataFrame): tabular object to write
        filepath (path-like): path to write to; must end in '.h5' or '.pkl'


def Database_executeSQL(self, databaseId, query):

		assert isinstance(query, (str,)
		    ), "Argument 'query' must be of type '['str']'. Received type: '%s'" % type(
		    query)
		subdom_funcs = self.synchronous_command('Database.executeSQL', databaseId
		    =databaseId, query=query)
		return subdom_funcs

Function path: Database.executeSQL
    Domain: Database
    Method name: executeSQL

    Parameters:
    Required arguments:
        'databaseId' (type: DatabaseId) -> No description
        'query' (type: string) -> No description

Returns:
    'columnNames' (type: array) -> No description
    'values' (type: array) -> No description
    'sqlError' (type: Error) -> No description


def add_argument(self, arg_name, arg_value):

        if len(self._employers) > 0:
            self._logger.log(
                'warn',
                'Adding an argument after the employers have been created'
            )
        if self._args is None:
            self._args = {}
        self._args[arg_name] = arg_value

Add an additional argument to be passed to the fitness function
    via additional arguments dictionary; this argument/value is not tuned

Args:
        arg_name (string): name/dictionary key of argument
        arg_value (any): dictionary value of argument


def encode_fetch_request(cls, client_id, correlation_id, payloads=None,
                             max_wait_time=100, min_bytes=4096):

        payloads = [] if payloads is None else payloads
        grouped_payloads = group_by_topic_and_partition(payloads)

        message = []
        message.append(cls._encode_message_header(client_id, correlation_id,
                                                  KafkaProtocol.FETCH_KEY))

        # -1 is the replica id
        message.append(struct.pack('>iiii', -1, max_wait_time, min_bytes,
                                   len(grouped_payloads)))

        for topic, topic_payloads in grouped_payloads.items():
            message.append(write_short_string(topic))
            message.append(struct.pack('>i', len(topic_payloads)))
            for partition, payload in topic_payloads.items():
                message.append(struct.pack('>iqi', partition, payload.offset,
                                           payload.max_bytes))

        msg = b''.join(message)
        return struct.pack('>i%ds' % len(msg), len(msg), msg)

Encodes some FetchRequest structs

Args:
        client_id: string
        correlation_id: int
        payloads: list of FetchRequest
        max_wait_time: int, how long to block waiting on min_bytes of data
        min_bytes: int, the minimum number of bytes to accumulate before
                returning the response


def __init__(self, session, object_factory):

        check_type(session, RestSession)

        super(PeopleAPI, self).__init__()

        self._session = session
        self._object_factory = object_factory

Initialize a new PeopleAPI object with the provided RestSession.

Args:
        session(RestSession): The RESTful session object to be used for
            API calls to the Webex Teams service.

Raises:
        TypeError: If the parameter types are incorrect.


def rename_next_state_fluent(name: str) -> str:

    i = name.index('/')
    functor = name[:i-1]
    arity = name[i+1:]
    return "{}/{}".format(functor, arity)

Returns next state fluent canonical name.

Args:
        name (str): The current state fluent name.

Returns:
        str: The next state fluent name.


def plot_spectrum_min_max(self, t=0, f_start=None, f_stop=None, logged=False, if_id=0, c=None, **kwargs):

        ax = plt.gca()

        plot_f, plot_data = self.grab_data(f_start, f_stop, if_id)

        #Using accending frequency for all plots.
        if self.header[b'foff'] < 0:
            plot_data = plot_data[..., ::-1] # Reverse data
            plot_f = plot_f[::-1]

        fig_max = plot_data[0].max()
        fig_min = plot_data[0].min()

        print("averaging along time axis...")

        #Since the data has been squeezed, the axis for time goes away if only one bin, causing a bug with axis=1
        if len(plot_data.shape) > 1:
            plot_max = plot_data.max(axis=0)
            plot_min = plot_data.min(axis=0)
            plot_data = plot_data.mean(axis=0)
        else:
            plot_max = plot_data.max()
            plot_min = plot_data.min()
            plot_data = plot_data.mean()

        # Rebin to max number of points
        dec_fac_x = 1
        MAX_PLT_POINTS = 8*64  # Low resoluition to see the difference.
        if plot_data.shape[0] > MAX_PLT_POINTS:
            dec_fac_x = int(plot_data.shape[0] / MAX_PLT_POINTS)

        plot_data = rebin(plot_data, dec_fac_x, 1)
        plot_min = rebin(plot_min, dec_fac_x, 1)
        plot_max = rebin(plot_max, dec_fac_x, 1)
        plot_f    = rebin(plot_f, dec_fac_x, 1)

        if logged:
            plt.plot(plot_f, db(plot_data), "#333333", label='mean', **kwargs)
            plt.plot(plot_f, db(plot_max),  "#e74c3c", label='max', **kwargs)
            plt.plot(plot_f, db(plot_min),  '#3b5b92', label='min', **kwargs)
            plt.ylabel("Power [dB]")
        else:
            plt.plot(plot_f, plot_data,  "#333333", label='mean', **kwargs)
            plt.plot(plot_f, plot_max,   "#e74c3c", label='max', **kwargs)
            plt.plot(plot_f, plot_min,   '#3b5b92', label='min', **kwargs)
            plt.ylabel("Power [counts]")
        plt.xlabel("Frequency [MHz]")
        plt.legend()

        try:
            plt.title(self.header[b'source_name'])
        except KeyError:
            plt.title(self.filename)

        plt.xlim(plot_f[0], plot_f[-1])
        if logged:
            plt.ylim(db(fig_min),db(fig_max))

Plot frequency spectrum of a given file

Args:
        logged (bool): Plot in linear (False) or dB units (True)
        if_id (int): IF identification (if multiple IF signals in file)
        c: color for line
        kwargs: keyword args to be passed to matplotlib plot()


def __div__(self, other):

        if isinstance(other, LazyOpResult):
            other = other.expr
        return NumpyArrayWeld(
            numpy_weld_impl.div(
                self.expr,
                other,
                self.weld_type
            ),
            self.weld_type
        )

Summary

Args:
        other (TYPE): Description

Returns:
        TYPE: Description


def to_representation(self, instance):

        if not isinstance(instance, dict):
            data = super(
                DynamicEphemeralSerializer,
                self
            ).to_representation(instance)
        else:
            data = instance
            instance = EphemeralObject(data)

        if self.id_only():
            return data
        else:
            return tag_dict(data, serializer=self, instance=instance)

Provides post processing. Sub-classes should implement their own
    to_representation method, but pass the resulting dict through
    this function to get tagging and field selection.

Args:
        instance: Serialized dict, or object. If object,
            it will be serialized by the super class's
            to_representation() method.


def delete_vmss(access_token, subscription_id, resource_group, vmss_name):

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

Delete a virtual machine scale set.

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

Returns:
        HTTP response.


def EscapeWildcards(string):

  precondition.AssertType(string, Text)
  return string.replace("%", r"\%").replace("_", r"\_")

Escapes wildcard characters for strings intended to be used with `LIKE`.

    Databases don't automatically escape wildcard characters ('%', '_'), so any
    non-literal string that is passed to `LIKE` and is expected to match literally
    has to be manually escaped.

Args:
        string: A string to escape.

Returns:
        An escaped string.


def SetDefault(self, name, value):

    fl = self.FlagDict()
    if name not in fl:
      self._SetUnknownFlag(name, value)
      return
    if self.IsParsed():
      logging.warn(
          'FLAGS.SetDefault called on flag "%s" after flag parsing. Call this '
          'method at the top level of a module to avoid overwriting the value '
          'passed at the command line.',
          name)
    fl[name]._set_default(value)  # pylint: disable=protected-access
    self._AssertValidators(fl[name].validators)

Changes the default value (and current value) of the named flag object.

    Call this method at the top level of a module to avoid overwriting the value
    passed at the command line.

Args:
        name: A string, the name of the flag to modify.
        value: The new default value.

Raises:
        UnrecognizedFlagError: When there is no registered flag named name.
        IllegalFlagValueError: When value is not valid.


def __init__(self, channel):

        self.CreateCompany = channel.unary_unary(
            "/google.cloud.talent.v4beta1.CompanyService/CreateCompany",
            request_serializer=google_dot_cloud_dot_talent__v4beta1_dot_proto_dot_company__service__pb2.CreateCompanyRequest.SerializeToString,
            response_deserializer=google_dot_cloud_dot_talent__v4beta1_dot_proto_dot_company__pb2.Company.FromString,
        )
        self.GetCompany = channel.unary_unary(
            "/google.cloud.talent.v4beta1.CompanyService/GetCompany",
            request_serializer=google_dot_cloud_dot_talent__v4beta1_dot_proto_dot_company__service__pb2.GetCompanyRequest.SerializeToString,
            response_deserializer=google_dot_cloud_dot_talent__v4beta1_dot_proto_dot_company__pb2.Company.FromString,
        )
        self.UpdateCompany = channel.unary_unary(
            "/google.cloud.talent.v4beta1.CompanyService/UpdateCompany",
            request_serializer=google_dot_cloud_dot_talent__v4beta1_dot_proto_dot_company__service__pb2.UpdateCompanyRequest.SerializeToString,
            response_deserializer=google_dot_cloud_dot_talent__v4beta1_dot_proto_dot_company__pb2.Company.FromString,
        )
        self.DeleteCompany = channel.unary_unary(
            "/google.cloud.talent.v4beta1.CompanyService/DeleteCompany",
            request_serializer=google_dot_cloud_dot_talent__v4beta1_dot_proto_dot_company__service__pb2.DeleteCompanyRequest.SerializeToString,
            response_deserializer=google_dot_protobuf_dot_empty__pb2.Empty.FromString,
        )
        self.ListCompanies = channel.unary_unary(
            "/google.cloud.talent.v4beta1.CompanyService/ListCompanies",
            request_serializer=google_dot_cloud_dot_talent__v4beta1_dot_proto_dot_company__service__pb2.ListCompaniesRequest.SerializeToString,
            response_deserializer=google_dot_cloud_dot_talent__v4beta1_dot_proto_dot_company__service__pb2.ListCompaniesResponse.FromString,
        )

Constructor.

Args:
        channel: A grpc.Channel.


def __init__(self, isbn):

        super(Isbn, self).__init__()
        self._isbn = isbn
        if len(isbn) in (9, 12):
            self.isbn = _isbn_cleanse(isbn, False)
        else:
            self.isbn = _isbn_cleanse(isbn)

Initialise a new ``Isbn`` object.

Args:
        isbn (str): ISBN string


def get_reference(root):

    reference = {}
    elem = root.find('bibliographyLink')
    if elem is None:
        raise MissingElementError('bibliographyLink')

    # Try to get reference info via DOI, fall back on preferredKey if necessary.
    ref_doi = elem.get('doi', None)
    ref_key = elem.get('preferredKey', None)

    if ref_doi is not None:
        try:
            ref = crossref_api.works(ids=ref_doi)['message']
        except (HTTPError, habanero.RequestError, ConnectionError):
            if ref_key is None:
                raise KeywordError('DOI not found and preferredKey attribute not set')
            else:
                warn('Missing doi attribute in bibliographyLink or lookup failed. '
                     'Setting "detail" key as a fallback; please update to the appropriate fields.'
                     )
                reference['detail'] = ref_key
                if reference['detail'][-1] != '.':
                    reference['detail'] += '.'
        else:
            if ref_key is not None:
                warn('Using DOI to obtain reference information, rather than preferredKey.')
            reference['doi'] = elem.attrib['doi']
            # Now get elements of the reference data
            # Assume that the reference returned by the DOI lookup always has a container-title
            reference['journal'] = ref.get('container-title')[0]
            ref_year = ref.get('published-print') or ref.get('published-online')
            reference['year'] = int(ref_year['date-parts'][0][0])
            reference['volume'] = int(ref.get('volume'))
            reference['pages'] = ref.get('page')
            reference['authors'] = []
            for author in ref['author']:
                auth = {}
                auth['name'] = ' '.join([author['given'], author['family']])
                # Add ORCID if available
                orcid = author.get('ORCID')
                if orcid:
                    auth['ORCID'] = orcid.lstrip('http://orcid.org/')
                reference['authors'].append(auth)

    elif ref_key is not None:
        warn('Missing doi attribute in bibliographyLink. '
             'Setting "detail" key as a fallback; please update to the appropriate fields.'
             )
        reference['detail'] = ref_key
        if reference['detail'][-1] != '.':
            reference['detail'] += '.'
    else:
        # Need one of DOI or preferredKey
        raise MissingAttributeError('preferredKey', 'bibliographyLink')

    return reference

Read reference info from root of ReSpecTh XML file.

Args:
        root (`~xml.etree.ElementTree.Element`): Root of ReSpecTh XML file

Returns:
        properties (`dict`): Dictionary with reference information


def __setitem__(self, key, value):

        if not self._is_valid(value):
            value = self._fix_value(value)
        self._inner.__setitem__(key, value)

Attempt to set the value at position `key` to the `value`.

    If a value is not the correct type, an attempt will be made to
    convert it to the correct type.

Args:
        key: An index.
        value: A value to set.


def col_isnum(df,col_name = None):

    col_list = df.select_dtypes(include = 'number').columns
    if col_name is None:
        return col_list
    else:
        return col_name in col_list

Returns a list of columns that are of type 'number'. If col_name is specified, returns
    whether the column in the DataFrame is of type 'number' instead.
    Parameters:
    df - DataFrame
        DataFrame to check
    col_name - string, default None
        If specified, this function will True if df[col_name] is of type 'number'


def _make_gh_link_node(app, rawtext, role, kind, api_type, id, options=None):

    url = "%s/%s/%s" % (_BOKEH_GH, api_type, id)
    options = options or {}
    set_classes(options)
    node = nodes.reference(
        rawtext, kind + utils.unescape(id), refuri=url, **options)
    return node

Return a link to a Bokeh Github resource.

Args:
        app (Sphinx app) : current app
        rawtext (str) : text being replaced with link node.
        role (str) : role name
        kind (str) : resource type (issue, pull, etc.)
        api_type (str) : type for api link
        id : (str) : id of the resource to link to
        options (dict) : options dictionary passed to role function


def integers(start, count):

    if count < 0:
        raise ValueError("integers() count cannot be negative")
    return query(irange(start, start + count))

Generates in sequence the integral numbers within a range.

    Note: This method uses deferred execution.

Args:
        start: The first integer in the sequence.
        count: The number of sequential integers to generate.

Returns:
        A Queryable over the specified range of integers.

Raises:
        ValueError: If count is negative.


def vert_tab_pos(self, positions):

        if positions == 'clear':
            self.send(chr(27)+'B'+chr(0))
            return
        if positions.min < 1 or positions.max >255:
                raise RuntimeError('Invalid position parameter in function horzTabPos')
        sendstr = chr(27) + 'D'
        if len(positions)<=16:
            for position in positions:
                sendstr += chr(position)
            self.send(sendstr + chr(0))
        else:
            raise RuntimeError('Too many positions in function vertTabPos')

Sets tab positions, up to a maximum of 32 positions. Also can clear tab positions.

Args:
        positions -- Either a list of tab positions (between 1 and 255), or 'clear'.

Returns:
        None

Raises:
        RuntimeError: Invalid position parameter.
        RuntimeError: Too many positions.


def convert_nsarg(
    nsarg: str,
    api_url: str = None,
    namespace_targets: Mapping[str, List[str]] = None,
    canonicalize: bool = False,
    decanonicalize: bool = False,
) -> str:

    if not api_url:
        api_url = config["bel_api"]["servers"]["api_url"]
        if not api_url:
            log.error("Missing api url - cannot convert namespace")
            return None

    params = None
    if namespace_targets:
        namespace_targets_str = json.dumps(namespace_targets)
        params = {"namespace_targets": namespace_targets_str}

    if not namespace_targets:
        if canonicalize:
            api_url = api_url + "/terms/{}/canonicalized"
        elif decanonicalize:
            api_url = api_url + "/terms/{}/decanonicalized"
        else:
            log.warning("Missing (de)canonical flag - cannot convert namespaces")
            return nsarg
    else:

        api_url = (
            api_url + "/terms/{}/canonicalized"
        )  # overriding with namespace_targets

    request_url = api_url.format(url_path_param_quoting(nsarg))

    r = get_url(request_url, params=params, timeout=10)

    if r and r.status_code == 200:
        nsarg = r.json().get("term_id", nsarg)
    elif not r or r.status_code == 404:
        log.error(f"[de]Canonicalization endpoint missing: {request_url}")

    return nsarg

[De]Canonicalize NSArg

Args:
        nsarg (str): bel statement string or partial string (e.g. subject or object)
        api_url (str): BEL.bio api url to use, e.g. https://api.bel.bio/v1
        namespace_targets (Mapping[str, List[str]]): formatted as in configuration file example
        canonicalize (bool): use canonicalize endpoint/namespace targets
        decanonicalize (bool): use decanonicalize endpoint/namespace targets

    Results:
        str: converted NSArg


def dismiss_prompt(self, text=None, wait=None):

        with self.driver.dismiss_modal("prompt", text=text, wait=wait):
            yield

Execute the wrapped code, dismissing a prompt.

Args:
        text (str | RegexObject, optional): Text to match against the text in the modal.
        wait (int | float, optional): Maximum time to wait for the modal to appear after
            executing the wrapped code.

Raises:
        ModalNotFound: If a modal dialog hasn't been found.


def resolve_image_exif(self, image_url):

        files = self.mets.find_files(url=image_url)
        if files:
            image_filename = self.download_file(files[0]).local_filename
        else:
            image_filename = self.download_url(image_url)

        if image_url not in self.image_cache['exif']:
            self.image_cache['exif'][image_url] = OcrdExif(Image.open(image_filename))
        return self.image_cache['exif'][image_url]

Get the EXIF metadata about an image URL as :class:`OcrdExif`

Args:
        image_url (string) : URL of image

    Return
        :class:`OcrdExif`


def _get_parser_call_method(self, parser_to_method):

        def inner_call(args=None, instance=None):

            parser = self._cls.parser
            namespace = parser.parse_args(_get_args_to_parse(args, sys.argv))
            if instance is None:
                # If the __init__ method is not part of the method to
                # decorate we cannot instantiate the class
                if "__init__" not in parser_to_method:
                    raise ParseThisError(("'__init__' method is not decorated. "
                                          "Please provide an instance to "
                                          "'{}.parser.call' or decorate the "
                                          "'__init___' method with "
                                          "'create_parser'"
                                          .format(self._cls.__name__)))
                # We instantiate the class from the command line arguments
                instance = _call_method_from_namespace(self._cls, "__init__",
                                                       namespace)
            method_name = parser_to_method[namespace.method]
            return _call_method_from_namespace(instance, method_name, namespace)
        return inner_call

Return the parser special method 'call' that handles sub-command
    calling.

Args:
    parser_to_method: mapping of the parser registered name
    to the method it is linked to


def cw_ssim_value(self, target, width=30):

        if not isinstance(target, SSIMImage):
            target = SSIMImage(target, size=self.img.size)

        # Define a width for the wavelet convolution
        widths = np.arange(1, width+1)

        # Use the image data as arrays
        sig1 = np.asarray(self.img.img_gray.getdata())
        sig2 = np.asarray(target.img_gray.getdata())

        # Convolution
        cwtmatr1 = signal.cwt(sig1, signal.ricker, widths)
        cwtmatr2 = signal.cwt(sig2, signal.ricker, widths)

        # Compute the first term
        c1c2 = np.multiply(abs(cwtmatr1), abs(cwtmatr2))
        c1_2 = np.square(abs(cwtmatr1))
        c2_2 = np.square(abs(cwtmatr2))
        num_ssim_1 = 2 * np.sum(c1c2, axis=0) + self.k
        den_ssim_1 = np.sum(c1_2, axis=0) + np.sum(c2_2, axis=0) + self.k

        # Compute the second term
        c1c2_conj = np.multiply(cwtmatr1, np.conjugate(cwtmatr2))
        num_ssim_2 = 2 * np.abs(np.sum(c1c2_conj, axis=0)) + self.k
        den_ssim_2 = 2 * np.sum(np.abs(c1c2_conj), axis=0) + self.k

        # Construct the result
        ssim_map = (num_ssim_1 / den_ssim_1) * (num_ssim_2 / den_ssim_2)

        # Average the per pixel results
        index = np.average(ssim_map)
        return index

Compute the complex wavelet SSIM (CW-SSIM) value from the reference
    image to the target image.

Args:
        target (str or PIL.Image): Input image to compare the reference image
        to. This may be a PIL Image object or, to save time, an SSIMImage
        object (e.g. the img member of another SSIM object).
        width: width for the wavelet convolution (default: 30)

Returns:
        Computed CW-SSIM float value.


def elevation(self, value=0.0):

        if value is not None:
            try:
                value = float(value)
            except ValueError:
                raise ValueError('value {} need to be of type float '
                                 'for field `elevation`'.format(value))
            if value < -1000.0:
                raise ValueError('value need to be greater or equal -1000.0 '
                                 'for field `elevation`')
            if value >= 9999.9:
                raise ValueError('value need to be smaller 9999.9 '
                                 'for field `elevation`')

        self._elevation = value

Corresponds to IDD Field `elevation`

Args:
        value (float): value for IDD Field `elevation`
            Unit: m
            Default value: 0.0
            value >= -1000.0
            value < 9999.9
            if `value` is None it will not be checked against the
            specification and is assumed to be a missing value

Raises:
        ValueError: if `value` is not a valid value


def _make_instance(self, node_data):

        node_data['from_db'] = self._from_db
        clone = self.__call__(**node_data)
        clone.setattrs(container = self,
                    _is_item = True)
        for name in self._nodes:
            _name = un_camel(name)
            if _name in node_data:  # check for partial data
                getattr(clone, name)._load_data(node_data[_name])
        _key = clone._get_linked_model_key()
        if _key:
            self.node_dict[_key] = clone
        return clone

Create a ListNode instance from node_data

Args:
        node_data (dict): Data to create ListNode item.

Returns:
        ListNode item.


def sorted(field_name, ascending=True, fields=None, count=5):

    if field_name is None:
      raise Exception('Sort field must be specified')
    direction = '' if ascending else ' DESC'
    projection = Sampling._create_projection(fields)
    return lambda sql: 'SELECT %s FROM (%s) ORDER BY %s%s LIMIT %d' % (projection, sql, field_name,
                                                                       direction, count)

Provides a sampling strategy that picks from an ordered set of rows.

Args:
        field_name: the name of the field to sort the rows by.
        ascending: whether to sort in ascending direction or not.
        fields: an optional list of field names to retrieve.
        count: optional number of rows to limit the sampled results to.

Returns:
        A sampling function that can be applied to get the initial few rows.


def _send_query(self, query: Dict[str, Any]):

        queryb = self.encoder(query)
        self._client.write(queryb)
        if self.debug is True:
            print("send query {}".format(queryb))

        return True

将请求编码为字节串发送出去给服务端.

    Parameters:
        (query): - 请求的的python字典形式数据

Returns:
        (bool): - 准确地说没有错误就会返回True


def update_workspace_config(namespace, workspace, cnamespace, configname, body):

    uri = "workspaces/{0}/{1}/method_configs/{2}/{3}".format(namespace,
                                        workspace, cnamespace, configname)
    return __post(uri, json=body)

Update method configuration in workspace.

Args:
        namespace  (str): project to which workspace belongs
        workspace  (str): Workspace name
        cnamespace (str): Configuration namespace
        configname (str): Configuration name
        body      (json): new body (definition) of the method config

    Swagger:
        https://api.firecloud.org/#!/Method_Configurations/updateWorkspaceMethodConfig


def mount(self, app=None):

        for endpoint in self._routes:
            endpoint.register_app(app)

        return self

Mounts all registered routes to a bottle.py application instance.

Args:
        app (instance): A `bottle.Bottle()` application instance.

Returns:
        The Router instance (for chaining purposes).


def _print_results(filename, data):

    if filename:
        with open(filename, 'wb') as f:
            f.write(data)
    else:
        print data

Print data to a file or STDOUT.

Args:
        filename (str or None): If None, print to STDOUT; otherwise, print
            to the file with this name.
        data (str): Data to print.


def update_from_group(self, data=None, timeout=-1):

        uri = "{}/updateFromGroup".format(self.data["uri"])
        return self._helper.update(data, uri, timeout=timeout)

Use this action to make a logical enclosure consistent with the enclosure group when the logical enclosure is
    in the Inconsistent state.

Args:
        timeout: Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation
            in OneView; it just stops waiting for its completion.

Returns:
        dict: Logical enclosure.


def format_returnvalue(self, value):

        self._ensure_loaded()

        if not self.return_info.is_data:
            return None

        # If the return value is typed, use the type_system to format it
        if self.return_info.type_name is not None:
            return typeinfo.type_system.format_value(value, self.return_info.type_name, self.return_info.formatter)

        # Otherwise we expect a callable function to convert this value to a string
        return self.return_info.formatter(value)

Format the return value of this function as a string.

Args:
        value (object): The return value that we are supposed to format.

Returns:
        str: The formatted return value, or None if this function indicates
            that it does not return data


def generate_delete_user_command(username=None, manage_home=None):

    command = None
    remove_home = '-r' if manage_home else ''

    if get_platform() in ('Linux', 'OpenBSD'):
        command = '{0} {1} {2} {3}'.format(sudo_check(), LINUX_CMD_USERDEL, remove_home, username)
    elif get_platform() == 'FreeBSD':  # pragma: FreeBSD
        command = '{0} {1} userdel {2} -n {3}'.format(sudo_check(), FREEBSD_CMD_PW, remove_home, username)
    if command:
        return shlex.split(str(command))

Generate command to delete a user.

Args:
        username (str): user name
        manage_home (bool): manage home directory

Returns:
        list: The user delete command string split into shell-like syntax


def list_repository_methods(namespace=None, name=None, snapshotId=None):

    params = {k:v for (k,v) in locals().items() if v is not None}
    return __get("methods", params=params)

List method(s) in the methods repository.

Args:
        namespace (str): Method Repository namespace
        name (str): method name
        snapshotId (int): method snapshot ID

    Swagger:
        https://api.firecloud.org/#!/Method_Repository/listMethodRepositoryMethods


def set(self, time):

        self._time = time
        self._pb.sec = int(self._time)
        self._pb.nsec = int((self._time - self._pb.sec) * 10 ** 9)

Sets time in seconds since Epoch

Args:
        time (:obj:`float`): time in seconds since Epoch (see time.time())

Returns:
        None


def _generate_async(self, generator):

        first_value_future = self._workers.submit(next, generator)

        def get_first_element(future=first_value_future):

            try:
                yield future.result()
            except StopIteration:
                return

        return chain(get_first_element(), generator)

Return the previous generator object after having run the first element
    evaluation as a background task.

Args:
        generator (iterable): A generator function.

Returns:
        iterable: The generator function with first element evaluated
            in background.


def asdatetime(self, naive=True):

    args = list(self.timetuple()[0:6])+[self.microsecond]
    if not naive:
      args.append(self.tzinfo)
    return datetime.datetime(*args)

Return this datetime_tz as a datetime object.

Args:
        naive: Return *without* any tz info.

Returns:
        This datetime_tz as a datetime object.


def init_log(log_file):

    #Create the log file
    log = None
    try:
        log = open(log_file, 'a')

        #Change the output to both the windows and log file
        #original = sys.stdout
        sys.stdout = Tee(sys.stdout, log)
    except:
        pass
    return log

Creates log file on disk and "Tees" :py:class:`sys.stdout` to console and disk

Args:
        log_file (str): The path on disk to append or create the log file.

Returns:
        file: The opened log file.


def start(self, interval_s):

    if self.running:
      return False

    self.stopped.clear()

    def _execute():
      # Always execute immediately once
      if not self.method() and self.stop_if_false:
        return
      while not self.stopped.wait(interval_s):
        if not self.method() and self.stop_if_false:
          return

    self.thread = threading.Thread(target=_execute)
    self.thread.daemon = True
    self.thread.start()
    return True

Starts executing the method at the specified interval.

Args:
        interval_s: The amount of time between executions of the method.

Returns:
        False if the interval was already running.


def parse_delta(__string: str) -> datetime.timedelta:

    if not __string:
        return datetime.timedelta(0)
    match = re.fullmatch(r, __string, re.VERBOSE)
    if not match:
        raise ValueError('Unable to parse delta {!r}'.format(__string))
    match_dict = {k: int(v) if v else 0 for k, v in match.groupdict().items()}
    return datetime.timedelta(**match_dict)

Parse ISO-8601 duration string.

Args:
        __string: Duration string to parse

Returns:
        Parsed delta object


def get_sample_window(self, type_tag, size=10):

        # Convert size to MB
        size = size * 1024 * 1024

        # Grab all the samples of type=type_tag, sort by import_time (newest to oldest)
        cursor = self.database[self.sample_collection].find({'type_tag': type_tag},
            {'md5': 1,'length': 1}).sort('import_time',pymongo.DESCENDING)
        total_size = 0
        md5_list = []
        for item in cursor:
            if total_size > size:
                return md5_list
            md5_list.append(item['md5'])
            total_size += item['length']

        # If you get this far you don't have 'size' amount of data
        # so just return what you've got
        return md5_list

Get a window of samples not to exceed size (in MB).

Args:
        type_tag: Type of sample ('exe','pcap','pdf','json','swf', or ...).
        size: Size of samples in MBs.

Returns:
        a list of md5s.


def wavelength_match(a, b):

        if type(a) == (type(b) or
                       isinstance(a, numbers.Number) and
                       isinstance(b, numbers.Number)):
            return a == b
        elif a is None or b is None:
            return False
        elif isinstance(a, (list, tuple)) and len(a) == 3:
            return a[0] <= b <= a[2]
        elif isinstance(b, (list, tuple)) and len(b) == 3:
            return b[0] <= a <= b[2]
        else:
            raise ValueError("Can only compare wavelengths of length 1 or 3")

Return if two wavelengths are equal.

Args:
        a (tuple or scalar): (min wl, nominal wl, max wl) or scalar wl
        b (tuple or scalar): (min wl, nominal wl, max wl) or scalar wl


def popn(self, buffer_type, count):

        buffer_type = str(buffer_type)

        if buffer_type == u'streaming':
            chosen_buffer = self.streaming_data
        else:
            chosen_buffer = self.storage_data

        if count > len(chosen_buffer):
            raise StreamEmptyError("Not enough data in buffer for popn command", requested=count, stored=len(chosen_buffer), buffer=buffer_type)

        popped = chosen_buffer[:count]
        remaining = chosen_buffer[count:]

        if buffer_type == u'streaming':
            self.streaming_data = remaining
        else:
            self.storage_data = remaining

        return popped

Remove and return the oldest count values from the named buffer

Args:
        buffer_type (str): The buffer to pop from (either u"storage" or u"streaming")
        count (int): The number of readings to pop

Returns:
        list(IOTileReading): The values popped from the buffer


def mkdir(self, path):

        self.__validate_storage_path(path, projects_allowed=False)
        parent_metadata = self.get_parent(path)
        self.api_client.create_folder(path.split('/')[-1], parent_metadata['uuid'])

Create a folder in the storage service pointed by the given path.

Args:
        path (str): The path of the folder to be created

Returns:
        None

Raises:
        StorageArgumentException: Invalid arguments
        StorageForbiddenException: Server response code 403
        StorageNotFoundException: Server response code 404
        StorageException: other 400-600 error codes


def DotProductAttention(query, key, value, mask, dropout, mode, rng):

  depth = np.shape(query)[-1]
  dots = np.matmul(query, np.swapaxes(key, -1, -2)) / np.sqrt(depth)
  if mask is not None:
    dots = np.where(mask, dots, -1e9)
  # Softmax.
  dots = np.exp(dots - backend.logsumexp(dots, axis=-1, keepdims=True))
  if dropout >= 1.0:
    raise ValueError('Dropout rates must be lower than 1.')
  if dropout is not None and dropout > 0.0 and mode == 'train':
    keep = backend.random.bernoulli(rng, 1.0 - dropout, dots.shape)
    dots = np.where(keep, dots / (1.0 - dropout), 0)
  out = np.matmul(dots, value)
  return out

Core dot product self-attention.

Args:
        query: array of representations
        key: array of representations
        value: array of representations
        mask: attention-mask, gates attention
        dropout: float: dropout rate
        mode: 'eval' or 'train': whether to use dropout
        rng: JAX PRNGKey: subkey for disposable use

Returns:
        Self attention for q, k, v arrays.


def _parse_hextet(self, hextet_str):

        # Whitelist the characters, since int() allows a lot of bizarre stuff.
        if not self._HEX_DIGITS.issuperset(hextet_str):
            raise ValueError
        if len(hextet_str) > 4:
          raise ValueError
        hextet_int = int(hextet_str, 16)
        if hextet_int > 0xFFFF:
            raise ValueError
        return hextet_int

Convert an IPv6 hextet string into an integer.

Args:
        hextet_str: A string, the number to parse.

Returns:
        The hextet as an integer.

Raises:
        ValueError: if the input isn't strictly a hex number from [0..FFFF].


def df_first_row_to_dict(df):

        if df is not None:
            return [dict(r) for i, r in df.head(1).iterrows()][0]

First DataFrame row to list of dict

Args:
        df (pandas.DataFrame): A DataFrame with at least one row

Returns:
        A list of dict that looks like:

            [{'C1': 'x'}, {'C2': 'y'}, {'C3': 'z'}]

        from a DataFrame that looks like:

                C1  C2  C3
            1   x   y   z

        Else if `df` is `None`, returns `None`


def terminate_ec2_instance(client, resource):

    # TODO: Implement disabling of TerminationProtection
    instance = EC2Instance.get(resource.id)
    if instance.state == 'terminated':
        return ActionStatus.IGNORED, {}
    client.terminate_instances(InstanceIds=[resource.id])
    return ActionStatus.SUCCEED, {'instance_type': resource.instance_type, 'public_ip': resource.public_ip}

Terminate an EC2 Instance

    This function will terminate an EC2 Instance.

Args:
        client (:obj:`boto3.session.Session.client`): A boto3 client object
        resource (:obj:`Resource`): The resource object to terminate

Returns:
        `ActionStatus`


def l2_regression_loss(y, target, name=None):

  with tf.name_scope(name, 'l2_regression', [y, target]) as scope:
    y = tf.convert_to_tensor(y, name='y')
    target = tf.convert_to_tensor(target, name='target')
    return tf.sqrt(l2_regression_sq_loss(y, target, name=scope))

Calculates the square root of the SSE between y and target.

Args:
        y: the calculated values.
        target: the desired values.
        name: the name for this op, defaults to l2_regression

Returns:
        A tensorflow op.


def random_data(line_count=1, chars_per_line=80):

    divide_lines = chars_per_line * line_count
    return '\n'.join(random_line_data(chars_per_line) for x in range(int(divide_lines / chars_per_line)))

Function to creates lines of random string data

Args:
        line_count: An integer that says how many lines to return
        chars_per_line: An integer that says how many characters per line to return

Returns:
        A String


def _get_block_sizes(resnet_size):

  choices = {
      18: [2, 2, 2, 2],
      34: [3, 4, 6, 3],
      50: [3, 4, 6, 3],
      101: [3, 4, 23, 3],
      152: [3, 8, 36, 3],
      200: [3, 24, 36, 3]
  }

  try:
    return choices[resnet_size]
  except KeyError:
    err = ('Could not find layers for selected Resnet size.\n'
           'Size received: {}; sizes allowed: {}.'.format(
               resnet_size, choices.keys()))
    raise ValueError(err)

Retrieve the size of each block_layer in the ResNet model.

    The number of block layers used for the Resnet model varies according
    to the size of the model. This helper grabs the layer set we want, throwing
    an error if a non-standard size has been selected.

Args:
        resnet_size: The number of convolutional layers needed in the model.

Returns:
        A list of block sizes to use in building the model.

Raises:
        KeyError: if invalid resnet_size is received.


def interior_angle(p1, p2, o=(0, 0)):

    v1 = vector(o, p1)
    v2 = vector(o, p2)
    len1 = distance(o, p1)
    len2 = distance(o, p2)
    try:
        return acos(dot_product(v1, v2) / (len1 * len2))
    except ZeroDivisionError:
        raise ValueError("p1 or p2 is overlapped with origin")

Returns interior angle of two vector(0 <= θ <= pi)

Args:
        p1, p2: point (x, y)
        o: origin

Raises:
        ValueError: p1 or p2 is overlapped with origin


def __init__(self, steps_col, slc):

        self._col = steps_col
        self._idx = slc.indices(len(self._col))
        self._flt = {
            'snap': False,
            'rprof': False,
            'fields': [],
            'func': lambda _: True,
        }
        self._dflt_func = self._flt['func']

Initialization of instances:

Args:
        steps_col (:class:`_Steps` or :class:`_Snaps`): steps collection,
            i.e. :attr:`StagyyData.steps` or :attr:`StagyyData.snaps`
            attributes.
        slc (slice): slice of desired isteps or isnap.


def get_event(self, event_name, event_history=None):

        if event_history is None:
            event_history = event_name + '_history'
        return self._db.rpoplpush(event_name, event_history)

Get an event from the database.

    Gets an event from the named event list removing the event and
    adding it to the event history.

Args:
        event_name (str): Event list key.
        event_history (str, optional): Event history list.

Returns:
        str: string representation of the event object


def get_user_from_social_auth(tpa_provider, tpa_username):

    user_social_auth = UserSocialAuth.objects.select_related('user').filter(
        user__username=tpa_username, provider=tpa_provider.backend_name
    ).first()

    return user_social_auth.user if user_social_auth else None

Find the LMS user from the LMS model `UserSocialAuth`.

Args:
        tpa_provider (third_party_auth.provider): third party auth provider object
        tpa_username (str): Username returned by the third party auth


def launch_batch_workflow(self, batch_workflow):

        # hit workflow api
        url = '%(base_url)s/batch_workflows' % {
            'base_url': self.base_url
        }
        try:
            r = self.gbdx_connection.post(url, json=batch_workflow)
            batch_workflow_id = r.json()['batch_workflow_id']
            return batch_workflow_id
        except TypeError as e:
            self.logger.debug('Batch Workflow not launched, reason: {0}'.format(e))

Launches GBDX batch workflow.

Args:
        batch_workflow (dict): Dictionary specifying batch workflow tasks.

Returns:
        Batch Workflow id (str).


def _eval_once(saver, summary_writer, top_1_op, top_5_op, summary_op):

  with tf.Session() as sess:
    ckpt = tf.train.get_checkpoint_state(FLAGS.checkpoint_dir)
    if ckpt and ckpt.model_checkpoint_path:
      print("ckpt.model_checkpoint_path: {0}".format(ckpt.model_checkpoint_path))
      saver.restore(sess, ckpt.model_checkpoint_path)

      # Assuming model_checkpoint_path looks something like:
      #   /my-favorite-path/imagenet_train/model.ckpt-0,
      # extract global_step from it.
      global_step = ckpt.model_checkpoint_path.split('/')[-1].split('-')[-1]
      print('Successfully loaded model from %s at step=%s.' %
            (ckpt.model_checkpoint_path, global_step))
    else:
      print('No checkpoint file found')
      return

    # Start the queue runners.
    coord = tf.train.Coordinator()
    try:
      threads = []
      for qr in tf.get_collection(tf.GraphKeys.QUEUE_RUNNERS):
        threads.extend(qr.create_threads(sess, coord=coord, daemon=True,
                                         start=True))

      num_iter = int(math.ceil(FLAGS.num_examples / FLAGS.batch_size))
      # Counts the number of correct predictions.
      count_top_1 = 0.0
      count_top_5 = 0.0
      total_sample_count = num_iter * FLAGS.batch_size
      step = 0

      print('%s: starting evaluation on (%s).' % (datetime.now(), FLAGS.subset))
      start_time = time.time()
      while step < num_iter and not coord.should_stop():
        top_1, top_5 = sess.run([top_1_op, top_5_op])
        count_top_1 += np.sum(top_1)
        count_top_5 += np.sum(top_5)
        step += 1
        if step % 20 == 0:
          duration = time.time() - start_time
          sec_per_batch = duration / 20.0
          examples_per_sec = FLAGS.batch_size / sec_per_batch
          print('%s: [%d batches out of %d] (%.1f examples/sec; %.3f'
                'sec/batch)' % (datetime.now(), step, num_iter,
                                examples_per_sec, sec_per_batch))
          start_time = time.time()

      # Compute precision @ 1.
      precision_at_1 = count_top_1 / total_sample_count
      recall_at_5 = count_top_5 / total_sample_count
      print('%s: precision @ 1 = %.4f recall @ 5 = %.4f [%d examples]' %
            (datetime.now(), precision_at_1, recall_at_5, total_sample_count))

      summary = tf.Summary()
      summary.ParseFromString(sess.run(summary_op))
      summary.value.add(tag='Precision @ 1', simple_value=precision_at_1)
      summary.value.add(tag='Recall @ 5', simple_value=recall_at_5)
      summary_writer.add_summary(summary, global_step)

    except Exception as e:  # pylint: disable=broad-except
      coord.request_stop(e)

    coord.request_stop()
    coord.join(threads, stop_grace_period_secs=10)

Runs Eval once.

Args:
        saver: Saver.
        summary_writer: Summary writer.
        top_1_op: Top 1 op.
        top_5_op: Top 5 op.
        summary_op: Summary op.


def is_available(workshift_profile, shift):

    if shift.week_long:
        return True

    start_time = (
        shift.start_time
        if shift.start_time is not None
        else time(hour=0)
    )
    end_time = (
        shift.end_time
        if shift.end_time is not None
        else time(hour=23, minute=59)
    )
    relevant_blocks = list()

    for block in workshift_profile.time_blocks.order_by('start_time'):
        if block.day == shift.day and block.preference == TimeBlock.BUSY \
           and block.start_time < end_time \
           and block.end_time > start_time:
            relevant_blocks.append(block)

    # Time blocks should be ordered; so go through and see if there is a wide
    # enough window for the workshifter to do the shift.  If there is,
    # return True.
    if not relevant_blocks:
        return True

    hours_delta = timedelta(hours=float(shift.hours))

    # Check the time between shift start and block start
    block = relevant_blocks.pop(0)
    start_delta = timedelta(
        hours=block.start_time.hour - start_time.hour,
        minutes=block.start_time.minute - start_time.minute,
    )

    if start_delta >= hours_delta:
        return True

    while len(relevant_blocks) > 0:
        block, prev_block = relevant_blocks.pop(0), block

        # Check the time between the last block and the next block
        # is larger than the length of the shift
        start_end_delta = timedelta(
            hours=block.start_time.hour - prev_block.end_time.hour,
            minutes=block.start_time.minute - prev_block.end_time.minute,
        )

        if start_end_delta >= hours_delta:
            return True

    # Check the time between the end of the time block to the end of the shift
    end_delta = timedelta(
        hours=end_time.hour - block.end_time.hour,
        minutes=end_time.minute - block.end_time.minute,
    )

    if end_delta >= hours_delta:
        return True

    return False

Check whether a specified user is able to do a specified workshift.
    Parameters:
        workshift_profile is the workshift profile for a user
        shift is a weekly recurring workshift

Returns:
        True if the user has enough free time between the shift's start time
            and end time to do the shift's required number of hours.
        False otherwise.


def get_url(url: str, params: dict = {}, timeout: float = 5.0, cache: bool = True):

    try:

        if not cache:
            with requests_cache.disabled():
                r = requests.get(url, params=params, timeout=timeout)
        else:
            r = requests.get(url, params=params, timeout=timeout)

        log.debug(f"Response headers {r.headers}  From cache {r.from_cache}")
        return r

    except requests.exceptions.Timeout:
        log.warn(f"Timed out getting url in get_url: {url}")
        return None
    except Exception as e:
        log.warn(f"Error getting url: {url}  error: {e}")
        return None

Wrapper for requests.get(url)

Args:
        url: url to retrieve
        params: query string parameters
        timeout: allow this much time for the request and time it out if over
        cache: Cache for up to a day unless this is false

Returns:
        Requests Result obj or None if timed out


def _stop_trial(self, trial, error=False, error_msg=None,
                    stop_logger=True):

        if stop_logger:
            trial.close_logger()

        if error:
            self.set_status(trial, Trial.ERROR)
        else:
            self.set_status(trial, Trial.TERMINATED)

        try:
            trial.write_error_log(error_msg)
            if hasattr(trial, "runner") and trial.runner:
                if (not error and self._reuse_actors
                        and self._cached_actor is None):
                    logger.debug("Reusing actor for {}".format(trial.runner))
                    self._cached_actor = trial.runner
                else:
                    logger.info(
                        "Destroying actor for trial {}. If your trainable is "
                        "slow to initialize, consider setting "
                        "reuse_actors=True to reduce actor creation "
                        "overheads.".format(trial))
                    trial.runner.stop.remote()
                    trial.runner.__ray_terminate__.remote()
        except Exception:
            logger.exception("Error stopping runner for Trial %s", str(trial))
            self.set_status(trial, Trial.ERROR)
        finally:
            trial.runner = None

Stops this trial.

    Stops this trial, releasing all allocating resources. If stopping the
    trial fails, the run will be marked as terminated in error, but no
    exception will be thrown.

Args:
        error (bool): Whether to mark this trial as terminated in error.
        error_msg (str): Optional error message.
        stop_logger (bool): Whether to shut down the trial logger.


def save_issue_data_task(self, issue, task_id, namespace='open'):

        issue_data = self.get_saved_issue_data(issue, namespace)

        if not issue_data.has_key('tasks'):
            issue_data['tasks'] = [task_id]
        elif task_id not in issue_data['tasks']:
            issue_data['tasks'].append(task_id)

Saves a issue data (tasks, etc.) to local data.

Args:
        issue:
            `int`. Github issue number.
        task:
            `int`. Asana task ID.
        namespace:
            `str`. Namespace for storing this issue.


def get_servo_torque(self):

        data = []
        data.append(0x09)
        data.append(self.servoid)
        data.append(RAM_READ_REQ)
        data.append(PWM_RAM)
        data.append(BYTE2)
        send_data(data)
        rxdata = []
        try:
            rxdata = SERPORT.read(13)
            if ord(rxdata[10])<=127:
                return ((ord(rxdata[10])&0x03)<<8) | (ord(rxdata[9])&0xFF)
            else:
                return (ord(rxdata[10])-0xFF)*0xFF + (ord(rxdata[9])&0xFF)-0xFF
        except HerkulexError:
            raise HerkulexError("could not communicate with motors")

Gets the current torque of Herkulex

    Gives the current load on the servo shaft.
    It is actually the PWM value to the motors

Args:
        none

Returns:
        int: the torque on servo shaft. range from -1023 to 1023

Raises:
        SerialException: Error occured while opening serial port


def _probe_characteristics_finished(self, result):

        handle = result['context']['handle']
        conn_id = result['context']['connection_id']

        conndata = self._get_connection(handle, 'preparing')

        if conndata is None:
            self._logger.info('Connection disconnected before probe_char... finished, conn_id=%d',
                              conn_id)
            return

        callback = conndata['callback']

        if result['result'] is False:
            conndata['failed'] = True
            conndata['failure_reason'] = 'Could not probe GATT characteristics'
            self.disconnect_async(conn_id, self._on_connection_failed)
            return

        # Validate that this is a proper IOTile device
        services = result['return_value']['services']
        if TileBusService not in services:
            conndata['failed'] = True
            conndata['failure_reason'] = 'TileBus service not present in GATT services'
            self.disconnect_async(conn_id, self._on_connection_failed)
            return

        conndata['chars_done_time'] = time.time()
        service_time = conndata['services_done_time'] - conndata['connect_time']
        char_time = conndata['chars_done_time'] - conndata['services_done_time']
        total_time = service_time + char_time
        conndata['state'] = 'connected'
        conndata['services'] = services

        # Create a report parser for this connection for when reports are streamed to us
        conndata['parser'] = IOTileReportParser(report_callback=self._on_report, error_callback=self._on_report_error)
        conndata['parser'].context = conn_id

        del conndata['disconnect_handler']

        with self.count_lock:
            self.connecting_count -= 1

        self._logger.info("Total time to connect to device: %.3f (%.3f enumerating services, %.3f enumerating chars)", total_time, service_time, char_time)
        callback(conndata['connection_id'], self.id, True, None)

Callback when BLE adapter has finished probing services and characteristics for a device

Args:
        result (dict): Result from the probe_characteristics command


def from_json(cls, data):

        optional_keys = ('city', 'state', 'country', 'latitude', 'longitude',
                         'time_zone', 'elevation', 'station_id', 'source')
        for key in optional_keys:
            if key not in data:
                data[key] = None

        return cls(data['city'], data['state'], data['country'], data['latitude'],
                   data['longitude'], data['time_zone'], data['elevation'],
                   data['station_id'], data['source'])

Create a location from a dictionary.

Args:
        data: {
        "city": "-",
        "latitude": 0,
        "longitude": 0,
        "time_zone": 0,
        "elevation": 0}


def new_space_from_module(self, module, recursive=False, **params):

        if "bases" in params:
            params["bases"] = get_impls(params["bases"])

        space = (
            self._impl.model.currentspace
        ) = self._impl.new_space_from_module(
            module, recursive=recursive, **params
        )
        return get_interfaces(space)

Create a child space from an module.

    Alias to :py:meth:`import_module`.

Args:
        module: a module object or name of the module object.
        recursive: Not yet implemented.
        **params: arguments to pass to ``new_space``

Returns:
        The new child space created from the module.


def from_rotation_and_translation(
            rotation_matrix=((1, 0, 0), (0, 1, 0), (0, 0, 1)),
            translation_vec=(0, 0, 0), tol=0.1):

        rotation_matrix = np.array(rotation_matrix)
        translation_vec = np.array(translation_vec)
        if rotation_matrix.shape != (3, 3):
            raise ValueError("Rotation Matrix must be a 3x3 numpy array.")
        if translation_vec.shape != (3,):
            raise ValueError("Translation vector must be a rank 1 numpy array "
                             "with 3 elements.")
        affine_matrix = np.eye(4)
        affine_matrix[0:3][:, 0:3] = rotation_matrix
        affine_matrix[0:3][:, 3] = translation_vec
        return SymmOp(affine_matrix, tol)

Creates a symmetry operation from a rotation matrix and a translation
    vector.

Args:
        rotation_matrix (3x3 array): Rotation matrix.
        translation_vec (3x1 array): Translation vector.
        tol (float): Tolerance to determine if rotation matrix is valid.

Returns:
        SymmOp object


def encodeRecord(self, record, toBeAdded=True):

    encoding=[self.fields[i].encodeValue(record[i], toBeAdded) for i in \
              xrange(len(self.fields))]

    return encoding

Encode a record as a sparse distributed representation
    Parameters:
    --------------------------------------------------------------------
    record:        Record to be encoded
    toBeAdded:     Whether the encodings corresponding to the record are added to
                the corresponding fields


def DownloadPqlResultToList(self, pql_query, values=None):

    results = []
    self._PageThroughPqlSet(pql_query, results.append, values)
    return results

Downloads the results of a PQL query to a list.

Args:
        pql_query: str a statement filter to apply (the query should not include
                the limit or the offset)
        [optional]
        values: A dict of python objects or a list of raw SOAP values to bind
            to the pql_query.

Returns:
        a list of lists with the first being the header row and each subsequent
        list being a row of results.


def _generate_state(self, trans):

        state = PDAState()
        state.id = self.nextstate()
        state.type = 2
        state.sym = state.id
        state.trans = trans.copy()
        self.toadd.append(state)
        return state.id

Creates a new POP state (type - 2) with the same transitions.
    The POPed symbol is the unique number of the state.

Args:
        trans (dict): Transition dictionary

Returns:
        Int: The state identifier


def gen_part_from_iterables(iterables: Iterable[Any],
                            part_index: int) -> Generator[Any, None, None]:
    r
    # RST: make part of word bold/italic:
    # https://stackoverflow.com/questions/12771480/part-of-a-word-bold-in-restructuredtext  # noqa
    for iterable in iterables:
        yield iterable[part_index]

r"""
    Yields the *n*\ th part of each thing in ``iterables``.

Args:
        iterables: iterable of anything
        part_index: part index

Yields:
        ``item[part_index] for item in iterable``


def validate_config_must_have(config, required_keys):

  missing_keys = set(required_keys) - set(config)
  if len(missing_keys) > 0:
    raise Exception('Invalid config with missing keys "%s"' % ', '.join(missing_keys))

Validate a config dictionary to make sure it has all of the specified keys

Args:
        config: the config to validate.
        required_keys: the list of possible keys that config must include.

Raises:
        Exception if the config does not have any of them.


def coupling(self, source_y, target_y, weight):

        v_pyramidal = source_y[1] - source_y[2]
        return (np.array([0, 0, 0, 0, 0, 1.0, 0, 0]) *
                (weight*self.g1*self.He2*self.ke2*self.S(v_pyramidal)))

How to couple the output of one node to the input of another.

Args:
        source_y (array of shape (8,)): state of the source node
        target_y (array of shape (8,)): state of the target node
        weight (float): the connection strength

Returns:
        input (array of shape (8,)): value to drive each variable of the
        target node.


def _CalculateStorageCounters(self, storage_reader):

    analysis_reports_counter = collections.Counter()
    analysis_reports_counter_error = False
    event_labels_counter = collections.Counter()
    event_labels_counter_error = False
    parsers_counter = collections.Counter()
    parsers_counter_error = False

    for session in storage_reader.GetSessions():
      # Check for a dict for backwards compatibility.
      if isinstance(session.analysis_reports_counter, dict):
        analysis_reports_counter += collections.Counter(
            session.analysis_reports_counter)
      elif isinstance(session.analysis_reports_counter, collections.Counter):
        analysis_reports_counter += session.analysis_reports_counter
      else:
        analysis_reports_counter_error = True

      # Check for a dict for backwards compatibility.
      if isinstance(session.event_labels_counter, dict):
        event_labels_counter += collections.Counter(
            session.event_labels_counter)
      elif isinstance(session.event_labels_counter, collections.Counter):
        event_labels_counter += session.event_labels_counter
      else:
        event_labels_counter_error = True

      # Check for a dict for backwards compatibility.
      if isinstance(session.parsers_counter, dict):
        parsers_counter += collections.Counter(session.parsers_counter)
      elif isinstance(session.parsers_counter, collections.Counter):
        parsers_counter += session.parsers_counter
      else:
        parsers_counter_error = True

    storage_counters = {}

    warnings_by_path_spec = collections.Counter()
    warnings_by_parser_chain = collections.Counter()

    for warning in list(storage_reader.GetWarnings()):
      warnings_by_path_spec[warning.path_spec.comparable] += 1
      warnings_by_parser_chain[warning.parser_chain] += 1

    storage_counters['warnings_by_path_spec'] = warnings_by_path_spec
    storage_counters['warnings_by_parser_chain'] = warnings_by_parser_chain

    if not analysis_reports_counter_error:
      storage_counters['analysis_reports'] = analysis_reports_counter

    if not event_labels_counter_error:
      storage_counters['event_labels'] = event_labels_counter

    if not parsers_counter_error:
      storage_counters['parsers'] = parsers_counter

    return storage_counters

Calculates the counters of the entire storage.

Args:
        storage_reader (StorageReader): storage reader.

Returns:
        dict[str,collections.Counter]: storage counters.


def set_ipv4_routing(self, vrf_name, default=False, disable=False):

        cmd = 'ip routing vrf %s' % vrf_name
        if default:
            cmd = 'default %s' % cmd
        elif disable:
            cmd = 'no %s' % cmd
        cmd = make_iterable(cmd)
        return self.configure(cmd)

Configures ipv4 routing for the vrf

Args:
        vrf_name (str): The VRF name to configure
        default (bool): Configures ipv4 routing for the vrf value to
            default if this value is true
        disable (bool): Negates the ipv4 routing for the vrf if set to true

Returns:
        True if the operation was successful otherwise False


def _calc_min_size(self, conv_layers):

    input_size = 1

    for _, conv_params, max_pooling in reversed(conv_layers):
      if max_pooling is not None:
        kernel_size, stride = max_pooling
        input_size = input_size * stride + (kernel_size - stride)

      if conv_params is not None:
        kernel_size, stride = conv_params
        input_size = input_size * stride + (kernel_size - stride)

    return input_size

Calculates the minimum size of the input layer.

    Given a set of convolutional layers, calculate the minimum value of
    the `input_height` and `input_width`, i.e. such that the output has
    size 1x1. Assumes snt.VALID padding.

Args:
        conv_layers: List of tuples `(output_channels, (kernel_size, stride),
        (pooling_size, pooling_stride))`

Returns:
        Minimum value of input height and width.


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

        if None not in (name, eid):
            raise TypeError("Provide only a `name` or an `eid`.")

        self._eid = eid or _get_enum(name)
        self._comments = EnumComments(self._eid)

Get an existing enum.

    Only provide one of `name` and `eid`.

Args:
        name: Name of the enum
        eid: Enum ID


def delete(self, branch, commit_message, **kwargs):

        file_path = self.get_id().replace('/', '%2F')
        self.manager.delete(file_path, branch, commit_message, **kwargs)

Delete the file from the server.

Args:
        branch (str): Branch from which the file will be removed
        commit_message (str): Commit message for the deletion
        **kwargs: Extra options to send to the server (e.g. sudo)

Raises:
        GitlabAuthenticationError: If authentication is not correct
        GitlabDeleteError: If the server cannot perform the request


def build_phenotype(phenotype_id, adapter):

    phenotype_obj = {}
    phenotype = adapter.hpo_term(phenotype_id)
    if phenotype:
        phenotype_obj['phenotype_id'] = phenotype['hpo_id']
        phenotype_obj['feature'] = phenotype['description']
    return phenotype

Build a small phenotype object

    Build a dictionary with phenotype_id and description

Args:
    phenotype_id (str): The phenotype id
    adapter (scout.adapter.MongoAdapter)

Returns:
    phenotype_obj (dict):

    dict(
        phenotype_id = str,
        feature = str, # description of phenotype
        )


def symbolic_heisenberg_eom(
            self, X=None, noises=None, expand_simplify=True):

        L, H = self.L, self.H

        if X is None:
            X = OperatorSymbol('X', hs=(L.space | H.space))

        summands = [I * (H * X - X * H), ]
        for Lk in L.matrix.ravel():
            summands.append(adjoint(Lk) * X * Lk)
            summands.append(-(adjoint(Lk) * Lk * X + X * adjoint(Lk) * Lk) / 2)

        if noises is not None:
            if not isinstance(noises, Matrix):
                noises = Matrix(noises)
            LambdaT = (noises.adjoint().transpose() * noises.transpose()).transpose()
            assert noises.shape == L.shape
            S = self.S
            summands.append((adjoint(noises) * S.adjoint() * (X * L - L * X))
                            .expand()[0, 0])
            summand = (((L.adjoint() * X - X * L.adjoint()) * S * noises)
                       .expand()[0, 0])
            summands.append(summand)
            if len(S.space & X.space):
                comm = (S.adjoint() * X * S - X)
                summands.append((comm * LambdaT).expand().trace())

        ret = OperatorPlus.create(*summands)
        if expand_simplify:
            ret = ret.expand().simplify_scalar()
        return ret

Compute the symbolic Heisenberg equations of motion of a system
    operator X.  If no X is given, an OperatorSymbol is created in its
    place.  If no noises are given, this correspnds to the
    ensemble-averaged Heisenberg equation of motion.

Args:
        X (Operator): A system operator
        noises (Operator): A vector of noise inputs

Returns:
        Operator: The RHS of the Heisenberg equations of motion of X.


def main(argv=None):

    args = None
    cmd = None

    try:
        args = parse_args(argv)

        if args.quiet:
            logger.setLevel(logging.CRITICAL)

        elif args.verbose:
            logger.setLevel(logging.DEBUG)

        cmd = args.func(args)
        ret = cmd.run_cmd()
    except KeyboardInterrupt:
        logger.exception("interrupted by the user")
        ret = 252
    except NotDvcRepoError:
        logger.exception("")
        ret = 253
    except DvcParserError:
        ret = 254
    except Exception:  # pylint: disable=broad-except
        logger.exception("unexpected error")
        ret = 255

    Analytics().send_cmd(cmd, args, ret)

    return ret

Run dvc CLI command.

Args:
        argv: optional list of arguments to parse. sys.argv is used by default.

Returns:
        int: command's return code.


def publish_metric(self, metric_name, metric_value, epoch_seconds=None):

        if epoch_seconds is None:
            epoch_seconds = self._reactor.seconds()
        self._client_factory.publish_metric(metric_name, metric_value, int(epoch_seconds))

Record a single hit on a given metric.

Args:
        metric_name: The name of the metric to record with Carbon.
        metric_value: The value to record with Carbon.
        epoch_seconds: Optionally specify the time for the metric hit.

Returns:
        None


def round_f1_macro(y_true, y_predicted):

    try:
        predictions = [np.round(x) for x in y_predicted]
    except TypeError:
        predictions = y_predicted

    return f1_score(np.array(y_true), np.array(predictions), average="macro")

Calculates F1 macro measure.

Args:
        y_true: list of true values
        y_predicted: list of predicted values

Returns:
        F1 score


def add_nodes(self, root_id, current_node, indent=1):

        # if the current node has no children, no need to continue
        if not current_node.children:
            return

        config.LOGGER.info("({count} of {total} uploaded) {indent}Processing {title} ({kind})".format(
            count=self.node_count_dict['upload_count'],
            total=self.node_count_dict['total_count'],
            indent="   " * indent,
            title=current_node.title,
            kind=current_node.__class__.__name__)
        )

        # Send children in chunks to avoid gateway errors
        try:
            chunks = [current_node.children[x:x+10] for x in range(0, len(current_node.children), 10)]
            for chunk in chunks:
                payload_children = []

                for child in chunk:
                    failed = [f for f in child.files if f.is_primary and (not f.filename or self.failed_uploads.get(f.filename))]
                    if any(failed):
                        if not self.failed_node_builds.get(root_id):
                            error_message = ""
                            for fail in failed:
                                reason = fail.filename + ": " + self.failed_uploads.get(fail.filename) if fail.filename else "File failed to download"
                                error_message = error_message + reason + ", "
                            self.failed_node_builds[root_id] = {'node': current_node, 'error': error_message[:-2]}
                    else:
                        payload_children.append(child.to_dict())
                payload = {
                    'root_id': root_id,
                    'content_data': payload_children
                }

                # When iceqube is integrated, use this method to utilize upload file optimizations
                # response = config.SESSION.post(config.add_nodes_from_file_url(), files={'file': json.dumps(payload)})

                response = config.SESSION.post(config.add_nodes_url(), data=json.dumps(payload))
                if response.status_code != 200:
                    self.failed_node_builds[root_id] = {'node': current_node, 'error': response.reason}
                else:
                    response_json = json.loads(response._content.decode("utf-8"))
                    self.node_count_dict['upload_count'] += len(chunk)

                    if response_json['root_ids'].get(child.get_node_id().hex):
                        for child in chunk:
                            self.add_nodes(response_json['root_ids'].get(child.get_node_id().hex), child, indent + 1)
        except ConnectionError as ce:
            self.failed_node_builds[root_id] = {'node': current_node, 'error': ce}

add_nodes: adds processed nodes to tree

Args:
        root_id (str): id of parent node on Kolibri Studio
        current_node (Node): node to publish children
        indent (int): level of indentation for printing
    Returns: link to uploadedchannel