def getStreamNetworkAsGeoJson(self, session, withNodes=True):

        features_list = []

        # Assemble link features
        for link in self.streamLinks:
            link_geoJson = link.getAsGeoJson(session)

            if link_geoJson:
                link_geometry = json.loads(link.getAsGeoJson(session))

                link_properties = {"link_number": link.linkNumber,
                                   "type": link.type,
                                   "num_elements": link.numElements,
                                   "dx": link.dx,
                                   "erode": link.erode,
                                   "subsurface": link.subsurface}

                link_feature = {"type": "Feature",
                                "geometry": link_geometry,
                                "properties": link_properties,
                                "id": link.id}

                features_list.append(link_feature)

            # Assemble node features
            if withNodes:
                for node in link.nodes:
                    node_geoJson = node.getAsGeoJson(session)

                    if node_geoJson:
                        node_geometry = json.loads(node_geoJson)

                    node_properties = {"link_number": link.linkNumber,
                                       "node_number": node.nodeNumber,
                                       "elevation": node.elevation}

                    node_feature = {"type": "Feature",
                                    "geometry": node_geometry,
                                    "properties": node_properties,
                                    "id": node.id}

                    features_list.append(node_feature)

        feature_collection = {"type": "FeatureCollection",
                              "features": features_list}

        return json.dumps(feature_collection)

Retrieve the stream network geometry in GeoJSON format.

Args:
        session (:mod:`sqlalchemy.orm.session.Session`): SQLAlchemy session object bound to PostGIS enabled database
        withNodes (bool, optional): Include nodes. Defaults to False.

Returns:
        str: GeoJSON string.


def clean(exclude):
    # type: (bool, List[str]) -> None

    pretend = context.get('pretend', False)
    exclude = list(exclude) + conf.get('clean.exclude', [])
    clean_patterns = conf.get('clean.patterns', [
        '*__pycache__*',
        '*.py[cod]',
        '*.swp',
    ])

    num_files = 0
    with util.timed_block() as t:
        files = fs.filtered_walk(conf.proj_path(), clean_patterns, exclude)
        for path in files:
            try:
                num_files += 1

                if not isdir(path):
                    log.info('  <91>[file] <90>{}', path)
                    not pretend and os.remove(path)
                else:
                    log.info('  <91>[dir]  <90>{}', path)
                    not pretend and rmtree(path)

            except OSError:
                log.info("<33>Failed to remove <90>{}", path)

    if pretend:
        msg = "Would delete <33>{}<32> files. Took <33>{}<32>s"
    else:
        msg = "Deleted <33>{}<32> files in <33>{}<32>s"

    log.info(msg.format(num_files, t.elapsed_s))

Remove all unnecessary files.

Args:
        pretend (bool):
            If set to **True**, do not delete any files, just show what would be
            deleted.
        exclude (list[str]):
            A list of path patterns to exclude from deletion.


def wtime_to_minutes(time_string):

    hours, mins, seconds = time_string.split(':')
    total_mins = int(hours) * 60 + int(mins)
    if total_mins < 1:
        logger.warning("Time string '{}' parsed to {} minutes, less than 1".format(time_string, total_mins))
    return total_mins

wtime_to_minutes

    Convert standard wallclock time string to minutes.

Args:
        - Time_string in HH:MM:SS format

Returns:
        (int) minutes


def DOMDebugger_setInstrumentationBreakpoint(self, eventName):

		assert isinstance(eventName, (str,)
		    ), "Argument 'eventName' must be of type '['str']'. Received type: '%s'" % type(
		    eventName)
		subdom_funcs = self.synchronous_command(
		    'DOMDebugger.setInstrumentationBreakpoint', eventName=eventName)
		return subdom_funcs

Function path: DOMDebugger.setInstrumentationBreakpoint
    Domain: DOMDebugger
    Method name: setInstrumentationBreakpoint

    WARNING: This function is marked 'Experimental'!

    Parameters:
    Required arguments:
        'eventName' (type: string) -> Instrumentation name to stop on.
    No return value.

    Description: Sets breakpoint on particular native event.


def __init__(self, path):

    super(FilterFile, self).__init__()
    self._path = path

Initializes a filter file.

Args:
        path (str): path to a file that contains one or more path filters.


def slice(filename, number_tiles=None, col=None, row=None, save=True):

    im = Image.open(filename)
    im_w, im_h = im.size

    columns = 0
    rows = 0
    if not number_tiles is None:
        validate_image(im, number_tiles)
        columns, rows = calc_columns_rows(number_tiles)
        extras = (columns * rows) - number_tiles
    else:
        validate_image_col_row(im, col, row)
        columns = col
        rows = row
        extras = (columns * rows) - number_tiles

    tile_w, tile_h = int(floor(im_w / columns)), int(floor(im_h / rows))

    tiles = []
    number = 1
    for pos_y in range(0, im_h - rows, tile_h): # -rows for rounding error.
        for pos_x in range(0, im_w - columns, tile_w): # as above.
            area = (pos_x, pos_y, pos_x + tile_w, pos_y + tile_h)
            image = im.crop(area)
            position = (int(floor(pos_x / tile_w)) + 1,
                        int(floor(pos_y / tile_h)) + 1)
            coords = (pos_x, pos_y)
            tile = Tile(image, number, position, coords)
            tiles.append(tile)
            number += 1
    if save:
        save_tiles(tiles,
                   prefix=get_basename(filename),
                   directory=os.path.dirname(filename))
    return tuple(tiles)

Split an image into a specified number of tiles.

Args:
        filename (str):  The filename of the image to split.
        number_tiles (int):  The number of tiles required.

    Kwargs:
        save (bool): Whether or not to save tiles to disk.

Returns:
        Tuple of :class:`Tile` instances.


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

        uri = self.URI + "/repair"
        custom_headers = {'Accept-Language': 'en_US'}
        return self._client.create(resource, uri=uri, timeout=timeout, custom_headers=custom_headers)

Removes extra presentations from a specified server profile.

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

Returns:
        dict: Associated storage attachment resource.


def _cursor_pb(cursor_pair):

    if cursor_pair is not None:
        data, before = cursor_pair
        value_pbs = [_helpers.encode_value(value) for value in data]
        return query_pb2.Cursor(values=value_pbs, before=before)

Convert a cursor pair to a protobuf.

    If ``cursor_pair`` is :data:`None`, just returns :data:`None`.

Args:
        cursor_pair (Optional[Tuple[list, bool]]): Two-tuple of

            * a list of field values.
            * a ``before`` flag

Returns:
        Optional[google.cloud.firestore_v1beta1.types.Cursor]: A
        protobuf cursor corresponding to the values.


def _lookup_model(cls, kind, default_model=None):

    modelclass = cls._kind_map.get(kind, default_model)
    if modelclass is None:
      raise KindError(
          "No model class found for kind '%s'. Did you forget to import it?" %
          kind)
    return modelclass

Get the model class for the kind.

Args:
        kind: A string representing the name of the kind to lookup.
        default_model: The model class to use if the kind can't be found.

Returns:
        The model class for the requested kind.

Raises:
        KindError: The kind was not found and no default_model was provided.


def get_artifact_url(context, task_id, path):

    if path.startswith("public/"):
        url = context.queue.buildUrl('getLatestArtifact', task_id, path)
    else:
        url = context.queue.buildSignedUrl(
            'getLatestArtifact', task_id, path,
            # XXX Can set expiration kwarg in (int) seconds from now;
            # defaults to 15min.
        )

    return url

Get a TaskCluster artifact url.

Args:
        context (scriptworker.context.Context): the scriptworker context
        task_id (str): the task id of the task that published the artifact
        path (str): the relative path of the artifact

Returns:
        str: the artifact url

Raises:
        TaskClusterFailure: on failure.


def roots_in_unit_interval(coeffs):
    r
    all_roots = polynomial.polyroots(coeffs)
    # Only keep roots inside or very near to the unit interval.
    all_roots = all_roots[
        (_UNIT_INTERVAL_WIGGLE_START < all_roots.real)
        & (all_roots.real < _UNIT_INTERVAL_WIGGLE_END)
    ]
    # Only keep roots with very small imaginary part. (Really only
    # keep the real parts.)
    real_inds = np.abs(all_roots.imag) < _IMAGINARY_WIGGLE
    return all_roots[real_inds].real

r"""Compute roots of a polynomial in the unit interval.

Args:
        coeffs (numpy.ndarray): A 1D array (size ``d + 1``) of coefficients in
            monomial / power basis.

Returns:
        numpy.ndarray: ``N``-array of real values in :math:`\left[0, 1\right]`.


def parse_conservations(variant):

    conservations = {}

    conservations['gerp'] = parse_conservation(
                                            variant,
                                            'dbNSFP_GERP___RS'
                                        )
    conservations['phast'] = parse_conservation(
                                            variant,
                                            'dbNSFP_phastCons100way_vertebrate'
                                        )
    conservations['phylop'] = parse_conservation(
                                            variant,
                                            'dbNSFP_phyloP100way_vertebrate'
                                        )
    return conservations

Parse the conservation predictors

Args:
        variant(dict): A variant dictionary

Returns:
        conservations(dict): A dictionary with the conservations


def verified(context, collaborator, test, outpath=None):

    written_files = 0
    collaborator = collaborator or 'cust000'
    LOG.info('Exporting verified variants for cust {}'.format(collaborator))

    adapter = context.obj['adapter']
    verified_vars = adapter.verified(institute_id=collaborator)
    LOG.info('FOUND {} verified variants for institute {}'.format(len(verified_vars), collaborator))

    if not verified_vars:
        LOG.warning('There are no verified variants for institute {} in database!'.format(collaborator))
        return None

    document_lines = export_verified_variants(verified_vars)

    today = datetime.datetime.now().strftime('%Y-%m-%d')
    document_name = '.'.join(['verified_variants', collaborator, today]) + '.xlsx'

    # If this was a test and lines are created return success
    if test and document_lines:
        written_files +=1
        LOG.info('Success. Verified variants file contains {} lines'.format(len(document_lines)))
        return written_files

    # create workbook and new sheet
    # set up outfolder
    if not outpath:
        outpath = str(os.getcwd())
    workbook = Workbook(os.path.join(outpath,document_name))
    Report_Sheet = workbook.add_worksheet()

    # Write the column header
    row = 0
    for col,field in enumerate(VERIFIED_VARIANTS_HEADER):
        Report_Sheet.write(row,col,field)

    # Write variant lines, after header (start at line 1)
    for row, line in enumerate(document_lines,1): # each line becomes a row in the document
        for col, field in enumerate(line): # each field in line becomes a cell
            Report_Sheet.write(row,col,field)
    workbook.close()

    if os.path.exists(os.path.join(outpath,document_name)):
        LOG.info('Success. Verified variants file of {} lines was written to disk'. format(len(document_lines)))
        written_files += 1

    return written_files

Export variants which have been verified for an institute
    and write them to an excel file.

Args:
    collaborator(str): institute id
    test(bool): True if the function is called for testing purposes
    outpath(str): path to output file

Returns:
    written_files(int): number of written or simulated files


def load_and_save_resfile(filename, outfile=None, outdir=None, mass=1.00):

    d = CellpyData()

    if not outdir:
        outdir = prms.Paths["cellpydatadir"]

    if not outfile:
        outfile = os.path.basename(filename).split(".")[0] + ".h5"
        outfile = os.path.join(outdir, outfile)

    print("filename:", filename)
    print("outfile:", outfile)
    print("outdir:", outdir)
    print("mass:", mass, "mg")

    d.from_raw(filename)
    d.set_mass(mass)
    d.make_step_table()
    d.make_summary()
    d.save(filename=outfile)
    d.to_csv(datadir=outdir, cycles=True, raw=True, summary=True)
    return outfile

Load a raw data file and save it as cellpy-file.

Args:
        mass (float): active material mass [mg].
        outdir (path): optional, path to directory for saving the hdf5-file.
        outfile (str): optional, name of hdf5-file.
        filename (str): name of the resfile.

Returns:
        out_file_name (str): name of saved file.


def is_valid(self, value):

        if not self.is_array:
            return self._valid(value)

        if isinstance(value, (list, set, tuple)):
            return all([self._valid(item) for item in value])

        return self._valid(value)

Validate value before actual instance setting based on type.

Args:
        value (object): The value object for validation.

Returns:
        True if value validation succeeds else False.


def GetFileEntryByPathSpec(self, path_spec):

    return fvde_file_entry.FVDEFileEntry(
        self._resolver_context, self, path_spec, is_root=True, is_virtual=True)

Retrieves a file entry for a path specification.

Args:
        path_spec (PathSpec): path specification.

Returns:
        FVDEFileEntry: file entry or None.


def delete(self, key):

    key = self._service_key(key)
    self._service_ops['delete'](key)

Removes the object named by `key` in `service`.

Args:
        key: Key naming the object to remove.


def load_obj(fn):

  position = [np.zeros(3, dtype=np.float32)]
  normal = [np.zeros(3, dtype=np.float32)]
  uv = [np.zeros(2, dtype=np.float32)]

  tuple2idx = OrderedDict()
  trinagle_indices = []

  input_file = open(fn) if isinstance(fn, str) else fn
  for line in input_file:
    line = line.strip()
    if not line or line[0] == '#':
      continue
    line = line.split(' ', 1)
    tag = line[0]
    if len(line) > 1:
      line = line[1]
    else:
      line = ''
    if tag == 'v':
      position.append(np.fromstring(line, sep=' '))
    elif tag == 'vt':
      uv.append(np.fromstring(line, sep=' '))
    elif tag == 'vn':
      normal.append(np.fromstring(line, sep=' '))
    elif tag == 'f':
      output_face_indices = []
      for chunk in line.split():
        # tuple order: pos_idx, uv_idx, normal_idx
        vt = _parse_vertex_tuple(chunk)
        if vt not in tuple2idx:  # create a new output vertex?
          tuple2idx[vt] = len(tuple2idx)
        output_face_indices.append(tuple2idx[vt])
      # generate face triangles
      for i in range(1, len(output_face_indices)-1):
        for vi in [0, i, i+1]:
          trinagle_indices.append(output_face_indices[vi])

  outputs = {}
  outputs['face'] = np.int32(trinagle_indices)
  pos_idx, uv_idx, normal_idx = np.int32(list(tuple2idx)).T
  if np.any(pos_idx):
    outputs['position'] = _unify_rows(position)[pos_idx]
  if np.any(uv_idx):
    outputs['uv'] = _unify_rows(uv)[uv_idx]
  if np.any(normal_idx):
    outputs['normal'] = _unify_rows(normal)[normal_idx]
  return outputs

Load 3d mesh form .obj' file.

Args:
        fn: Input file name or file-like object.

Returns:
        dictionary with the following keys (some of which may be missing):
        position: np.float32, (n, 3) array, vertex positions
        uv: np.float32, (n, 2) array, vertex uv coordinates
        normal: np.float32, (n, 3) array, vertex uv normals
        face: np.int32, (k*3,) traingular face indices


def isworkday(self, date):

        date = parsefun(date)
        return self.weekdaymap[date.weekday()].isworkday

Check if a given date is a work date, ignoring holidays.

Args:
        date (date, datetime or str): Date to be checked.

Returns:
        bool: True if the date is a work date, False otherwise.


def __init__(self, envs, blocking):

    self._envs = envs
    self._blocking = blocking
    observ_space = self._envs[0].observation_space
    if not all(env.observation_space == observ_space for env in self._envs):
      raise ValueError('All environments must use the same observation space.')
    action_space = self._envs[0].action_space
    if not all(env.action_space == action_space for env in self._envs):
      raise ValueError('All environments must use the same observation space.')

Combine multiple environments to step them in batch.

    To step environments in parallel, environments must support a
    `blocking=False` argument to their step and reset functions that makes them
    return callables instead to receive the result at a later time.

Args:
        envs: List of environments.
        blocking: Step environments after another rather than in parallel.

Raises:
        ValueError: Environments have different observation or action spaces.


def _resolve_path(obj, path=None):

        if path:
            for attr_name in path.split('__'):
                obj = getattr(obj, attr_name)
        return obj

Resolve django-like path eg. object2__object3 for object

Args:
        obj: The object the view is displaying.
        path (str, optional): Description

Returns:
        A oject at end of resolved path


def getDiskSpace(self, file_path, upload_path = '', overwrite = False):

        self.checkAccount()

        url = nurls['checkUpload']

        file_size = os.stat(file_path).st_size
        file_name = os.path.basename(file_path)

        now = datetime.datetime.now().isoformat()

        data = {'userid': self.user_id,
                'useridx': self.useridx,
                'getlastmodified': now,
                'dstresource': upload_path + file_name,
                'overwrite': overwrite,
                'uploadsize': file_size,
               }
        r = self.session.post(nurls['getDiskSpace'], data = data)

        return resultManager(r.text)

getDiskSpace

Args:
        file_path: Full path for a file you want to checkUpload
        upload_path: Ndrive path where you want to upload file
            ex) /Picture/

Returns:
        True: Possible to upload a file with a given file_size
        False: Impossible to upload a file with a given file_size


def backend_monitor(backend):

    if not isinstance(backend, IBMQBackend):
        raise QiskitError('Input variable is not of type IBMQBackend.')
    config = backend.configuration().to_dict()
    status = backend.status().to_dict()
    config_dict = {**status, **config}
    if not config['simulator']:
        props = backend.properties().to_dict()

    print(backend.name())
    print('='*len(backend.name()))
    print('Configuration')
    print('-'*13)
    offset = '    '

    upper_list = ['n_qubits', 'operational',
                  'status_msg', 'pending_jobs',
                  'basis_gates', 'local', 'simulator']

    lower_list = list(set(config_dict.keys()).difference(upper_list))
    # Remove gates because they are in a different tab
    lower_list.remove('gates')
    for item in upper_list+lower_list:
        print(offset+item+':', config_dict[item])

    # Stop here if simulator
    if config['simulator']:
        return

    print()
    qubit_header = 'Qubits [Name / Freq / T1 / T2 / U1 err / U2 err / U3 err / Readout err]'
    print(qubit_header)
    print('-'*len(qubit_header))

    sep = ' / '
    for qub in range(len(props['qubits'])):
        name = 'Q%s' % qub
        qubit_data = props['qubits'][qub]
        gate_data = props['gates'][3*qub:3*qub+3]
        t1_info = qubit_data[0]
        t2_info = qubit_data[1]
        freq_info = qubit_data[2]
        readout_info = qubit_data[3]

        freq = str(round(freq_info['value'], 5))+' '+freq_info['unit']
        T1 = str(round(t1_info['value'],  # pylint: disable=invalid-name
                       5))+' ' + t1_info['unit']
        T2 = str(round(t2_info['value'],  # pylint: disable=invalid-name
                       5))+' ' + t2_info['unit']
        # pylint: disable=invalid-name
        U1 = str(round(gate_data[0]['parameters'][0]['value'], 5))
        # pylint: disable=invalid-name
        U2 = str(round(gate_data[1]['parameters'][0]['value'], 5))
        # pylint: disable=invalid-name
        U3 = str(round(gate_data[2]['parameters'][0]['value'], 5))

        readout_error = str(round(readout_info['value'], 5))

        qstr = sep.join([name, freq, T1, T2, U1, U2, U3, readout_error])
        print(offset+qstr)

    print()
    multi_qubit_gates = props['gates'][3*config['n_qubits']:]
    multi_header = 'Multi-Qubit Gates [Name / Type / Gate Error]'
    print(multi_header)
    print('-'*len(multi_header))

    for gate in multi_qubit_gates:
        name = gate['name']
        ttype = gate['gate']
        error = str(round(gate['parameters'][0]['value'], 5))
        mstr = sep.join([name, ttype, error])
        print(offset+mstr)

Monitor a single IBMQ backend.

Args:
        backend (IBMQBackend): Backend to monitor.

Raises:
        QiskitError: Input is not a IBMQ backend.


def calculate_expiration(self, token):

        if not token:
            return None
        now = datetime.utcnow()
        time_to_live = self.config["expiration"]
        if "exp" not in token:
            return now + timedelta(seconds=time_to_live)
        elif self.config["refresh"]:
            exp = datetime.utcfromtimestamp(token["exp"])
            # 0.5: reduce refresh frequent
            if exp - now < timedelta(seconds=0.5 * time_to_live):
                return now + timedelta(seconds=time_to_live)
        return None

Calculate token expiration

    return expiration if the token need to set expiration or refresh,
    otherwise return None.

Args:
        token (dict): a decoded token


def itersplit(s, sep=None):

    if not s:
        yield s
        return
    exp = re.compile(r'\s+' if sep is None else re.escape(sep))
    pos = 0
    while True:
        m = exp.search(s, pos)
        if not m:
            if pos < len(s) or sep is not None:
                yield s[pos:]
            break
        if pos < m.start() or sep is not None:
            yield s[pos:m.start()]
        pos = m.end()

Split a string by ``sep`` and yield chunks

Args:
        s (str-type): string to split
        sep (str-type): delimiter to split by

Yields:
        generator of strings: chunks of string s


def InitFromAff4Object(self, aff4_obj):

    attr_blacklist = []  # We use this to show attributes only once.

    self.types = []
    for aff4_cls in aff4_obj.__class__.__mro__:
      if not hasattr(aff4_cls, "SchemaCls"):
        continue

      type_repr = ApiAff4ObjectType().InitFromAff4Object(
          aff4_obj, aff4_cls, attr_blacklist)

      if type_repr.attributes:
        self.types.append(type_repr)

      # Add all attribute names from this type representation to the
      # blacklist to not add them to the result again.
      attr_blacklist.extend([attr.name for attr in type_repr.attributes])

    return self

Initializes the current instance from an Aff4Object.

    Iterates the inheritance hierarchy of the given Aff4Object and adds a
    ApiAff4ObjectType for each class found in the hierarchy.

Args:
        aff4_obj: An Aff4Object as source for the initialization.

Returns:
        A reference to the current instance.


def _PromptUserForAPFSVolumeIdentifiers(
      self, volume_system, volume_identifiers):

    print_header = True
    while True:
      if print_header:
        self._PrintAPFSVolumeIdentifiersOverview(
            volume_system, volume_identifiers)

        print_header = False

      lines = self._textwrapper.wrap(self._USER_PROMPT_APFS)
      self._output_writer.Write('\n'.join(lines))
      self._output_writer.Write('\n\nVolume identifiers: ')

      try:
        selected_volumes = self._ReadSelectedVolumes(
            volume_system, prefix='apfs')
        if (not selected_volumes or
            not set(selected_volumes).difference(volume_identifiers)):
          break
      except ValueError:
        pass

      self._output_writer.Write('\n')

      lines = self._textwrapper.wrap(
          'Unsupported volume identifier(s), please try again or abort with '
          'Ctrl^C.')
      self._output_writer.Write('\n'.join(lines))
      self._output_writer.Write('\n\n')

    return selected_volumes

Prompts the user to provide APFS volume identifiers.

Args:
        volume_system (dfvfs.APFSVolumeSystem): volume system.
        volume_identifiers (list[str]): volume identifiers including prefix.

Returns:
        list[str]: selected volume identifiers including prefix or None.


def gosper(seqs, f=None, start=None, key=lambda x: x):

    tab = []
    for c, value in enumerate(seqs[0], start=1):
        yield value
        try:
            e = tab.index(key(value))
            raise CycleDetected(
                period=c - ((((c >> e) - 1) | 1) << e))
        except ValueError:
            try:
                tab[(c ^ (c - 1)).bit_length() - 1] = key(value)
            except IndexError:
                tab.append(value)

Gosper's cycle detector

    See help(cycle_detector) for more context.

Args:
        sequence: A sequence to detect cyles in.

        f, start: Function and starting state for finite state machine

Yields:
        Values yielded by sequence_a if it terminates, undefined if a
        cycle is found.

Raises:
        CycleFound if exception is found.  Unlike Floyd and Brent's,
        Gosper's can only detect period of a cycle.  It cannot
        compute the first position


def _select_mgmt_networks(self, conf):

        nets = conf['nets']
        mgmts = sorted(
            [
                name for name, net in nets.iteritems()
                if net.get('management') is True
            ]
        )

        if len(mgmts) == 0:
            mgmt_name = sorted((nets.keys()))[0]
            LOGGER.debug(
                'No management network configured, selecting network %s',
                mgmt_name
            )
            nets[mgmt_name]['management'] = True
            mgmts.append(mgmt_name)

        for mgmt_name in mgmts:
            if nets[mgmt_name].get('dns_domain_name', None) is None:
                nets[mgmt_name]['dns_domain_name'] = 'lago.local'

        return mgmts

Select management networks. If no management network is found, it will
    mark the first network found by sorted the network lists. Also adding
    default DNS domain, if none is set.

Args:
        conf(spec): spec


def forum_post_undelete(self, post_id):

        return self._get('forum_posts/{0}/undelete.json'.format(post_id),
                         method='POST', auth=True)

Undelete a specific forum post (Requires login)(Moderator+)(UNTESTED).

    Parameters:
        post_id (int): Forum post id.


def __init__(self, transport, maxdata, remote_banner):

    try:
      self.systemtype, self.serial, self.banner = remote_banner.split(':', 2)
    except ValueError:
      raise usb_exceptions.AdbProtocolError('Received malformed banner %s',
                                            remote_banner)
    self.transport = transport
    self.maxdata = maxdata
    self._last_id_used = 0
    self._reader_lock = threading.Lock()
    self._open_lock = threading.Lock()
    # Maps local_id: AdbStreamTransport object for the relevant stream.
    self._stream_transport_map = {}
    self._stream_transport_map_lock = threading.RLock()

Create an ADB connection to a device.

Args:
        transport: AdbTransportAdapter to use for reading/writing AdbMessages
        maxdata: Max data size the remote endpoint will accept.
        remote_banner: Banner received from the remote endpoint.


def joinCommissioned(self, strPSKd='threadjpaketest', waitTime=20):

        print '%s call joinCommissioned' % self.port
        self.__sendCommand('ifconfig up')
        cmd = 'joiner start %s %s' %(strPSKd, self.provisioningUrl)
        print cmd
        if self.__sendCommand(cmd)[0] == "Done":
            maxDuration = 150 # seconds
            self.joinCommissionedStatus = self.joinStatus['ongoing']

            if self.logThreadStatus == self.logStatus['stop']:
                self.logThread = ThreadRunner.run(target=self.__readCommissioningLogs, args=(maxDuration,))

            t_end = time.time() + maxDuration
            while time.time() < t_end:
                if self.joinCommissionedStatus == self.joinStatus['succeed']:
                    break
                elif self.joinCommissionedStatus == self.joinStatus['failed']:
                    return False

                time.sleep(1)

            self.__sendCommand('thread start')
            time.sleep(30)
            return True
        else:
            return False

start joiner

Args:
        strPSKd: Joiner's PSKd

Returns:
        True: successful to start joiner
        False: fail to start joiner


def add_curves_from_lasio(self, l, remap=None, funcs=None):

        params = {}
        for field, (sect, code) in LAS_FIELDS['data'].items():
            params[field] = utils.lasio_get(l,
                                            sect,
                                            code,
                                            remap=remap,
                                            funcs=funcs)

        curves = {c.mnemonic: Curve.from_lasio_curve(c, **params)
                  for c in l.curves}

        # This will clobber anything with the same key!
        self.data.update(curves)

        return None

Given a LAS file, add curves from it to the current well instance.
    Essentially just wraps ``add_curves_from_lasio()``.

Args:
        fname (str): The path of the LAS file to read curves from.
        remap (dict): Optional. A dict of 'old': 'new' LAS field names.
        funcs (dict): Optional. A dict of 'las field': function() for
            implementing a transform before loading. Can be a lambda.

Returns:
        None. Works in place.


def get_version_string(version):

    version_len = len(version)
    if version_len == 3:
        version_string = '%d.%d.%d' % version
    elif version_len == 4:
        version_string = '%d.%d.%d-%s' % version
    else:
        raise Exception(
            'Version tuple is non-semver-compliant {} length!'.format(version_len)
        )
    return version_string

Translate a version tuple into a string.

    Specify the __version__ as a tuple for more precise comparisons, and
    translate it to __version_string__ for when that's needed.

    This function exists primarily for easier unit testing.

Args:
        version (Tuple[int, int, int, str]): three ints and an optional string.

Returns:
        version_string (str): the tuple translated into a string per semver.org


def list_insights_components(access_token, subscription_id, resource_group):

    endpoint = ''.join([get_rm_endpoint(),
                        '/subscriptions/', subscription_id,
                        '/resourceGroups/', resource_group,
                        '/providers/microsoft.insights/',
                        '/components?api-version=', INSIGHTS_COMPONENTS_API])
    return do_get(endpoint, access_token)

List the Microsoft Insights components in a resource group.

Args:
        access_token (str): A valid Azure authentication token.
        subscription_id (str): Azure subscription id.
        resource_group (str): Azure resource group name.

Returns:
        HTTP response. JSON body of components.


def delete_group_maintainer(self, grp_name, user):

        self.service.delete_group_maintainer(
            grp_name, user, self.url_prefix, self.auth, self.session,
            self.session_send_opts)

Delete the given user to the named group.

    Both group and user must already exist for this to succeed.

Args:
        name (string): Name of group.
        user (string): User to add to group.

Raises:
        requests.HTTPError on failure.


def wrap_inference_results(inference_result_proto):

  inference_proto = inference_pb2.InferenceResult()
  if isinstance(inference_result_proto,
                classification_pb2.ClassificationResponse):
    inference_proto.classification_result.CopyFrom(
        inference_result_proto.result)
  elif isinstance(inference_result_proto, regression_pb2.RegressionResponse):
    inference_proto.regression_result.CopyFrom(inference_result_proto.result)
  return inference_proto

Returns packaged inference results from the provided proto.

Args:
        inference_result_proto: The classification or regression response proto.

Returns:
        An InferenceResult proto with the result from the response.


def __init__(self, message=None, orig_exc=None, context=None):

        self.orig_exc = orig_exc
        if message is not None:
            self.error_message = message
        elif orig_exc is not None:
            # derive the error message from the original exception
            self.error_message = "%s" % orig_exc

        self.context = context or StatikErrorContext()
        if not isinstance(self.context, StatikErrorContext):
            raise TypeError("Statik error context must be of type StatikErrorContext")

Constructor.

Args:
        message: An optional message to override the predefined error message.
        orig_exc: The original exception from which this error was generated.
        context: An optional ErrorContext instance to provide additional information during
            error rendering.


def build(cls, seqs: Iterable[int], uid: bool = False) -> 'SequenceSet':

        seqs_list = sorted(set(seqs))
        groups: List[Union[int, Tuple[int, int]]] = []
        group: Union[int, Tuple[int, int]] = seqs_list[0]
        for i in range(1, len(seqs_list)):
            group_i = seqs_list[i]
            if isinstance(group, int):
                if group_i == group + 1:
                    group = (group, group_i)
                else:
                    groups.append(group)
                    group = group_i
            elif isinstance(group, tuple):
                if group_i == group[1] + 1:
                    group = (group[0], group_i)
                else:
                    groups.append(group)
                    group = group_i
        groups.append(group)
        return SequenceSet(groups, uid)

Build a new sequence set that contains the given values using as
    few groups as possible.

Args:
        seqs: The sequence values to build.
        uid: True if the sequences refer to message UIDs.


def dependency_of_fetches(fetches, op):

    try:
        from tensorflow.python.client.session import _FetchHandler as FetchHandler
        # use the graph of the op, so that this function can be called without being under a default graph
        handler = FetchHandler(op.graph, fetches, {})
        targets = tuple(handler.fetches() + handler.targets())
    except ImportError:
        if isinstance(fetches, list):
            targets = tuple(fetches)
        elif isinstance(fetches, dict):
            raise ValueError("Don't know how to parse dictionary to fetch list! "
                             "This is a bug of tensorpack.")
        else:
            targets = (fetches, )
    return dependency_of_targets(targets, op)

Check that op is in the subgraph induced by the dependencies of fetches.
    fetches may have more general structure.

Args:
        fetches: An argument to `sess.run`. Nested structure will affect performance.
        op (tf.Operation or tf.Tensor):

Returns:
        bool: True if any of `fetches` depend on `op`.


def get_user_roles(self, user):

        return self.service.get_user_roles(
            user, self.url_prefix, self.auth, self.session, self.session_send_opts)

Get roles associated with the given user.

Args:
        user (string): User name.

Returns:
        (list): List of roles that user has.

Raises:
        requests.HTTPError on failure.


def add_gene_panel(self, panel_obj):

        panel_name = panel_obj['panel_name']
        panel_version = panel_obj['version']
        display_name = panel_obj.get('display_name', panel_name)

        if self.gene_panel(panel_name, panel_version):
            raise IntegrityError("Panel {0} with version {1} already"
                                 " exist in database".format(panel_name, panel_version))
        LOG.info("loading panel {0}, version {1} to database".format(
            display_name, panel_version
        ))
        result = self.panel_collection.insert_one(panel_obj)
        LOG.debug("Panel saved")
        return result.inserted_id

Add a gene panel to the database

Args:
        panel_obj(dict)


def rating(self, value):

        if not self.can_update():
            self._tcex.handle_error(910, [self.type])
        request_data = {'rating': value}
        return self.tc_requests.update(
            self.api_type, self.api_sub_type, self.unique_id, request_data, owner=self.owner
        )

Updates the Indicators rating

Args:
        value:


def write_config_file(self, parsed_namespace, output_file_paths, exit_after=False):

        for output_file_path in output_file_paths:
            # validate the output file path
            try:
                with open(output_file_path, "w") as output_file:
                    pass
            except IOError as e:
                raise ValueError("Couldn't open %s for writing: %s" % (
                    output_file_path, e))
        if output_file_paths:
            # generate the config file contents
            config_items = self.get_items_for_config_file_output(
                self._source_to_settings, parsed_namespace)
            file_contents = self._config_file_parser.serialize(config_items)
            for output_file_path in output_file_paths:
                with open(output_file_path, "w") as output_file:
                    output_file.write(file_contents)
            message = "Wrote config file to " + ", ".join(output_file_paths)
            if exit_after:
                self.exit(0, message)
            else:
                print(message)

Write the given settings to output files.

Args:
        parsed_namespace: namespace object created within parse_known_args()
        output_file_paths: any number of file paths to write the config to
        exit_after: whether to exit the program after writing the config files


def exceptions(error_is_fatal=True, error_messages=None):

    def exception_decorator(func):
        nonlocal error_messages

        @functools.wraps(func)
        def exc_wrapper(*args, **kwargs):
            nonlocal error_messages
            try:
                result = func(*args, **kwargs)
            except sa.exc.SQLAlchemyError as err:
                result = None
                details = None
                err_type = err.__class__
                if error_messages and err_type in error_messages:
                    details = error_messages[err_type]
                if details:
                    LOG.error(details)
                LOG.error("For developers: (%s) %s", err.__class__, str(err))
                if error_is_fatal:
                    sys.exit("Abort, SQL operation failed.")
                if not ui.ask(
                        "I can continue at your own risk, do you want that?"):
                    raise err
            return result

        return exc_wrapper

    return exception_decorator

Handle SQLAlchemy exceptions in a sane way.

Args:
        func: An arbitrary function to wrap.
        error_is_fatal: Should we exit the program on exception?
        reraise: Should we reraise the exception, after logging? Only makes sense
            if error_is_fatal is False.
        error_messages: A dictionary that assigns an exception class to a
            customized error message.


def new(self, ext_id, ext_des, ext_src):
        # type: (bytes, bytes, bytes) -> None

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

        self.ext_id = ext_id
        self.ext_des = ext_des
        self.ext_src = ext_src
        self.ext_ver = 1

        self._initialized = True

Create a new Rock Ridge Extensions Reference record.

    Parameters:
    ext_id - The extension identifier to use.
    ext_des - The extension descriptor to use.
    ext_src - The extension specification source to use.

Returns:
    Nothing.


def find(self, username):

        filter = ['(uid={})'.format(username)]
        results = self.client.search(filter)

        if len(results) < 1:
            raise ldap_tools.exceptions.NoUserFound(
                'User ({}) not found'.format(username))
            return  # pragma: no cover
        elif len(results) > 1:
            raise ldap_tools.exceptions.TooManyResults(
                'Multiple users found. Please narrow your search.')
            return  # pragma: no cover
        else:
            return results

Find user with given username.

Args:
        username Username of the user to search for

Raises:
        ldap_tools.exceptions.NoUserFound: No users returned by LDAP
        ldap_tools.exceptions.TooManyResults:
            Multiple users returned by LDAP


def list_street_poi_parking(self, **kwargs):

        # Endpoint parameters
        url_args = {
            'language': util.language_code(kwargs.get('lang')),
            'address': kwargs.get('address', '')
        }

        # Request
        result = self.make_request('list_street_poi_parking', url_args)

        if not util.check_result(result):
            return False, result.get('message', 'UNKNOWN ERROR')

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

Obtain a list of addresses and POIs.

    This endpoint uses an address to perform the search

Args:
        lang (str): Language code (*es* or *en*).
        address (str): Address in which to perform the search.

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


def account_id(self, value):

    if type(value) is not str:
      raise TypeError("commit value must be string")
    self._account_id = value

Sets the current account id

Args:
        value: current account id (string)

Returns:
        None


def firmware_outdated(self):

        datefmt = ' %b %d %Y %H:%M:%S'

        compat_date = self.compatible_firmware_version.split('compiled')[1]
        compat_date = datetime.datetime.strptime(compat_date, datefmt)

        fw_date = self.firmware_version.split('compiled')[1]
        fw_date = datetime.datetime.strptime(fw_date, datefmt)
        return (compat_date > fw_date)

Returns whether the J-Link's firmware version is older than the one
    that the DLL is compatible with.

Note:
        This is not the same as calling ``not jlink.firmware_newer()``.

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

Returns:
        ``True`` if the J-Link's firmware is older than the one supported by
        the DLL, otherwise ``False``.


def write_block(self, block_, body):

    self.write('for ; πF.State() >= 0; πF.PopCheckpoint() {')
    with self.indent_block():
      self.write('switch πF.State() {')
      self.write('case 0:')
      for checkpoint in block_.checkpoints:
        self.write_tmpl('case $state: goto Label$state', state=checkpoint)
      self.write('default: panic("unexpected function state")')
      self.write('}')
      # Assume that body is aligned with goto labels.
      with self.indent_block(-1):
        self.write(body)
    self.write('}')

Outputs the boilerplate necessary for code blocks like functions.

Args:
        block_: The Block object representing the code block.
        body: String containing Go code making up the body of the code block.


def select_action(self, next_action_arr, next_q_arr):

        key_arr = self.select_action_key(next_action_arr, next_q_arr)
        return next_action_arr[key_arr], next_q_arr[key_arr]

Select action by Q(state, action).

Args:
        next_action_arr:        `np.ndarray` of actions.
        next_q_arr:             `np.ndarray` of Q-Values.

    Retruns:
        Tuple(`np.ndarray` of action., Q-Value)


def NewFromJSON(data):

        if data.get('shakes', None):
            shakes = [Shake.NewFromJSON(shk) for shk in data.get('shakes')]
        else:
            shakes = None

        return User(
            id=data.get('id', None),
            name=data.get('name', None),
            profile_image_url=data.get('profile_image_url', None),
            about=data.get('about', None),
            website=data.get('website', None),
            shakes=shakes)

Create a new User instance from a JSON dict.

Args:
        data (dict): JSON dictionary representing a user.

Returns:
        A User instance.


def ClientCertFromCSR(cls, csr):

    builder = x509.CertificateBuilder()
    # Use the client CN for a cert serial_id. This will ensure we do
    # not have clashing cert id.
    common_name = csr.GetCN()
    serial = int(common_name.split(".")[1], 16)
    builder = builder.serial_number(serial)
    builder = builder.subject_name(
        x509.Name(
            [x509.NameAttribute(oid.NameOID.COMMON_NAME, str(common_name))]))

    now = rdfvalue.RDFDatetime.Now()
    now_plus_year = now + rdfvalue.Duration("52w")
    builder = builder.not_valid_after(now_plus_year.AsDatetime())
    now_minus_ten = now - rdfvalue.Duration("10s")
    builder = builder.not_valid_before(now_minus_ten.AsDatetime())
    # TODO(user): dependency loop with
    # grr/core/grr_response_core/config/client.py.
    # pylint: disable=protected-access
    ca_cert = config_lib._CONFIG["CA.certificate"]
    # pylint: enable=protected-access
    builder = builder.issuer_name(ca_cert.GetIssuer())
    builder = builder.public_key(csr.GetPublicKey().GetRawPublicKey())

    # TODO(user): dependency loop with
    # grr/core/grr_response_core/config/client.py.
    # pylint: disable=protected-access
    ca_key = config_lib._CONFIG["PrivateKeys.ca_key"]
    # pylint: enable=protected-access

    return RDFX509Cert(
        builder.sign(
            private_key=ca_key.GetRawPrivateKey(),
            algorithm=hashes.SHA256(),
            backend=openssl.backend))

Creates a new cert for the given common name.

Args:
        csr: A CertificateSigningRequest.

Returns:
        The signed cert.


def connect_socket(root_dir):

    # Get config directory where the daemon socket is located
    config_dir = os.path.join(root_dir, '.config/pueue')

    # Create Socket and exit with 1, if socket can't be created
    try:
        client = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
        socket_path = os.path.join(config_dir, 'pueue.sock')
        if os.path.exists(socket_path):
            client.connect(socket_path)
        else:
            print("Socket doesn't exist")
            raise Exception
    except:
        print("Error connecting to socket. Make sure the daemon is running")
        sys.exit(1)
    return client

Connect to a daemon's socket.

Args:
        root_dir (str): The directory that used as root by the daemon.

Returns:
        socket.socket: A socket that is connected to the daemon.


def load_filename(self, filename, index=None):

        filename = str(filename)  # QString protection
        if index is None:
            index = self._get_tab_index()
        page = self.pages[index]

        # Maybe this is set on purpose before loading attempt to leave new load_dir set (?)
        self.load_dir, _ = os.path.split(filename)

        clss = page.clss_load
        if len(clss) == 1:
            # If there is only one class to handle the file, will load it in a way that eventual
            # load errors will raise
            f = clss[0]()
            f.load(filename)
        else:
            # At the moment, the multi-class alternative will not display particular error information
            # if the file does not load
            f = f311.load_with_classes(filename, page.clss_load)
            if f is None:
                raise RuntimeError("Could not load '{0!s}'".format(filename))

        self.load(f, index)

Loads file given filename

Args:
        filename:
        index: tab index to load file into. If not passed, loads into current tab


def keep_artifacts(self, **kwargs):

        path = '%s/%s/artifacts/keep' % (self.manager.path, self.get_id())
        self.manager.gitlab.http_post(path)

Prevent artifacts from being deleted when expiration is set.

Args:
        **kwargs: Extra options to send to the server (e.g. sudo)

Raises:
        GitlabAuthenticationError: If authentication is not correct
        GitlabCreateError: If the request could not be performed


def __init__(self, reactants, products):

        self._input_reactants = reactants
        self._input_products = products
        self._all_comp = reactants + products

        els = set()
        for c in self.all_comp:
            els.update(c.elements)
        els = sorted(els)

        # Solving:
        #          | 0  R |
        # [ x y ]  |      |  =  [ 1 .. 1 0 .. 0]
        #          | C  P |
        # x, y are the coefficients of the reactants and products
        # R, P the matrices of the element compositions of the reactants
        # and products
        # C is a constraint matrix that chooses which compositions to normalize to

        # try just normalizing to just the first product
        rp_mat = np.array([[c[el] for el in els] for c in self._all_comp])
        f_mat = np.concatenate([np.zeros((len(rp_mat), 1)), rp_mat], axis=1)
        f_mat[len(reactants), 0] = 1  # set normalization by the first product
        b = np.zeros(len(els) + 1)
        b[0] = 1
        coeffs, res, _, s = np.linalg.lstsq(f_mat.T, b, rcond=None)

        # for whatever reason the rank returned by lstsq isn't always correct
        # seems to be a problem with low-rank M but inconsistent system
        # M x = b.
        # the singular values seem ok, so checking based on those
        if sum(np.abs(s) > 1e-12) == len(f_mat):
            if res.size > 0 and res[0] > self.TOLERANCE ** 2:
                raise ReactionError("Reaction cannot be balanced.")
            else:
                ok = True
        else:
            # underdetermined, add product constraints to make non-singular
            ok = False
            n_constr = len(rp_mat) - np.linalg.matrix_rank(rp_mat)
            f_mat = np.concatenate([np.zeros((len(rp_mat), n_constr)),
                                    rp_mat], axis=1)
            b = np.zeros(f_mat.shape[1])
            b[:n_constr] = 1

            # try setting C to all n_constr combinations of products
            for inds in itertools.combinations(range(len(reactants),
                                                     len(f_mat)),
                                               n_constr):
                f_mat[:, :n_constr] = 0
                for j, i in enumerate(inds):
                    f_mat[i, j] = 1
                # try a solution
                coeffs, res, _, s = np.linalg.lstsq(f_mat.T, b, rcond=None)
                if sum(np.abs(s) > 1e-12) == len(self._all_comp) and \
                        (res.size == 0 or res[0] < self.TOLERANCE ** 2):
                    ok = True
                    break

        if not ok:
            r_mat = np.array([[c[el] for el in els] for c in reactants])
            reactants_underdetermined = (
                np.linalg.lstsq(r_mat.T, np.zeros(len(els)), rcond=None)[2]
                != len(reactants))
            if reactants_underdetermined:
                raise ReactionError("Reaction cannot be balanced. "
                                    "Reactants are underdetermined.")
            raise ReactionError("Reaction cannot be balanced. "
                                "Unknown error, please report.")

        self._els = els
        self._coeffs = coeffs

Reactants and products to be specified as list of
    pymatgen.core.structure.Composition.  e.g., [comp1, comp2]

Args:
        reactants ([Composition]): List of reactants.
        products ([Composition]): List of products.


def listen(self, orb, listeners):

        if isinstance(listeners, Listener):
            listeners = [listeners]

        orb.event = None
        results = []
        for listener in listeners:
            if listener.check(orb):
                results.append(self._bisect(listener.prev, orb, listener))

            # Saving of the current value for the next iteration
            listener.prev = orb
        return sorted(results, key=lambda x: x.date)

This method allows to loop over the listeners and trigger the :py:meth:`_bisect` method
    in case a watched parameter has its state changed.

Args:
        orb (Orbit): The current state of the orbit
        listeners (iterable): List of Listener objects

Returns:
        list of Orbit: Orbits corresponding to events, sorted by dates


def execute(self, action):

        self.logger.debug('Executing action: %s', action)

        reward = self.wrapped.execute(action)
        if reward:
            self.total_reward += reward
        self.steps += 1

        self.logger.debug('Reward received on this step: %.5f',
                          reward or 0)
        self.logger.debug('Average reward per step: %.5f',
                          self.total_reward / self.steps)

        return reward

Execute the indicated action within the environment and
    return the resulting immediate reward dictated by the reward
    program.

    Usage:
        immediate_reward = scenario.execute(selected_action)

Args:
        action: The action to be executed within the current situation.

Returns:
        A float, the reward received for the action that was executed,
        or None if no reward is offered.


def copy(source, destination):

    if os.path.isdir(source):
        return __copytree(source, destination)
    else:
        return __copyfile2(source, destination)

Copy file or directory.

Args:
        source (str): Source file or directory
        destination (str): Destination file or directory (where to copy).

Returns:
        bool: True if the operation is successful, False otherwise.


def place_line(self,
                   device: 'cirq.google.XmonDevice',
                   length: int) -> GridQubitLineTuple:

        seqs = AnnealSequenceSearch(device, self.seed).search(self.trace_func)
        return GridQubitLineTuple.best_of(seqs, length)

Runs line sequence search.

Args:
        device: Chip description.
        length: Required line length.

Returns:
        List of linear sequences on the chip found by simulated annealing
        method.


def require_attribute(self, attribute: str, typ: Type = _Any) -> None:

        attr_nodes = [
            value_node for key_node, value_node in self.yaml_node.value
            if key_node.value == attribute
        ]
        if len(attr_nodes) == 0:
            raise RecognitionError(
                ('{}{}Missing required attribute {}').format(
                    self.yaml_node.start_mark, os.linesep, attribute))
        attr_node = attr_nodes[0]

        if typ != _Any:
            recognized_types, message = self.__recognizer.recognize(
                attr_node, cast(Type, typ))
            if len(recognized_types) == 0:
                raise RecognitionError(message)

Require an attribute on the node to exist.

    If `typ` is given, the attribute must have this type.

Args:
        attribute: The name of the attribute / mapping key.
        typ: The type the attribute must have.


def __init__(self):

        self._local_id = str(uuid4())
        self._creation_date = None
        self._last_updated_date = None
        self._id = None
        self._owner = None
        self._parent_id = None
        self._parent_type = None
        self._parent = None
        self._is_dirty = False

        self._attribute_errors = dict()
        self._attributes = dict()

        self.expose_attribute(local_name='id', remote_name=BambouConfig.get_id_remote_name(), attribute_type=BambouConfig.get_id_type(), is_identifier=True)
        self.expose_attribute(local_name='parent_id', remote_name='parentID', attribute_type=str)
        self.expose_attribute(local_name='parent_type', remote_name='parentType', attribute_type=str)
        self.expose_attribute(local_name='creation_date', remote_name='creationDate', attribute_type=float, is_editable=False)
        self.expose_attribute(local_name='last_updated_date', remote_name='lastUpdatedDate', attribute_type=float, is_editable=False)
        self.expose_attribute(local_name='owner', attribute_type=str, is_readonly=True)

        self._fetchers_registry = dict()

Initializes the object with general information

Args:
        creation_date: float representing time since epoch
        id: identifier of the object
        local_id: internal identifier of the object
        owner: string representing the owner
        parent_id: identifier of the object's parent
        parent_type: type of the parent


def _compute_nfps_uniform(cum_counts, sizes):

    nfps = np.zeros((len(sizes), len(sizes)))
    # All u an l are inclusive bounds for intervals.
    # Compute p = 1, the NFPs
    for l in range(len(sizes)):
        for u in range(l, len(sizes)):
            nfps[l, u] = _compute_nfp_uniform(l, u, cum_counts, sizes)
    return nfps

Computes the matrix of expected false positives for all possible
    sub-intervals of the complete domain of set sizes, assuming uniform
    distribution of set_sizes within each sub-intervals.

Args:
        cum_counts: the complete cummulative distribution of set sizes.
        sizes: the complete domain of set sizes.

    Return (np.array): the 2-D array of expected number of false positives
        for every pair of [l, u] interval, where l is axis-0 and u is
        axis-1.


def copy_sizes(self, othervd):
        # type: (PrimaryOrSupplementaryVD) -> None

        if not self._initialized:
            raise pycdlibexception.PyCdlibInternalError('This Volume Descriptor is not yet initialized')

        self.space_size = othervd.space_size
        self.path_tbl_size = othervd.path_tbl_size
        self.path_table_num_extents = othervd.path_table_num_extents

Copy the path_tbl_size, path_table_num_extents, and space_size from
    another volume descriptor.

    Parameters:
    othervd - The other volume descriptor to copy from.

Returns:
    Nothing.


def adb_cmd(self, command, **kwargs):

        kwargs['timeout'] = kwargs.get('timeout', self._adb_shell_timeout)
        if isinstance(command, list) or isinstance(command, tuple):
            return self.adb_device.run_cmd(*list(command), **kwargs)
        return self.adb_device.run_cmd(command, **kwargs)

Run adb command, for example: adb(['pull', '/data/local/tmp/a.png'])

Args:
        command: string or list of string

Returns:
        command output


def create(self, *args, **kwargs):

        data = self.get_data('floating_ips/',
                             type=POST,
                             params={'droplet_id': self.droplet_id})

        if data:
            self.ip = data['floating_ip']['ip']
            self.region = data['floating_ip']['region']

        return self

Creates a FloatingIP and assigns it to a Droplet.

    Note: Every argument and parameter given to this method will be
    assigned to the object.

Args:
        droplet_id: int - droplet id


def run_board(args):

    init_config(args)

    # backend service, should import after django settings initialized
    from backend.collector import CollectorService

    service = CollectorService(
        args.logdir,
        args.reload_interval,
        standalone=False,
        log_level=args.log_level)
    service.run()

    # frontend service
    logger.info("Try to start automlboard on port %s\n" % args.port)
    command = [
        os.path.join(root_path, "manage.py"), "runserver",
        "0.0.0.0:%s" % args.port, "--noreload"
    ]
    execute_from_command_line(command)

Run main entry for AutoMLBoard.

Args:
        args: args parsed from command line


def mark_all_as_done(self, **kwargs):

        result = self.gitlab.http_post('/todos/mark_as_done', **kwargs)
        try:
            return int(result)
        except ValueError:
            return 0

Mark all the todos as done.

Args:
        **kwargs: Extra options to send to the server (e.g. sudo)

Raises:
        GitlabAuthenticationError: If authentication is not correct
        GitlabTodoError: If the server failed to perform the request

Returns:
        int: The number of todos maked done


def forward(self, input):

        sl,bs = input.size()
        if bs!=self.bs:
            self.bs=bs
            self.reset()
        with set_grad_enabled(self.training):
            emb = self.encoder_with_dropout(input, dropout=self.dropoute if self.training else 0)
            emb = self.dropouti(emb)
            raw_output = emb
            new_hidden,raw_outputs,outputs = [],[],[]
            for l, (rnn,drop) in enumerate(zip(self.rnns, self.dropouths)):
                current_input = raw_output
                with warnings.catch_warnings():
                    warnings.simplefilter("ignore")
                    raw_output, new_h = rnn(raw_output, self.hidden[l])
                new_hidden.append(new_h)
                raw_outputs.append(raw_output)
                if l != self.n_layers - 1: raw_output = drop(raw_output)
                outputs.append(raw_output)

            self.hidden = repackage_var(new_hidden)
        return raw_outputs, outputs

Invoked during the forward propagation of the RNN_Encoder module.

Args:
        input (Tensor): input of shape (sentence length x batch_size)

Returns:
        raw_outputs (tuple(list (Tensor), list(Tensor)): list of tensors evaluated from each RNN layer without using
        dropouth, list of tensors evaluated from each RNN layer using dropouth,


def write_file(self, filepath, filename=None, directory=None):

        arcname = None
        if filename or directory:
            directory = directory.rstrip("/") + "/" if directory else ""
            filename = filename or os.path.basename(filepath)
            arcname = "{}{}".format(directory, filename)
        self._copy_to_zipfile(filepath, arcname=arcname)
        return arcname or filepath

write_file: Write local file to zip

Args:
        filepath: (str) location to local file
        directory: (str) directory in zipfile to write file to (optional)
    Returns: path to file in zip

    Note: filepath must be a relative path


def encode_offset_commit_request(cls, group, payloads):

        return kafka.protocol.commit.OffsetCommitRequest[0](
            consumer_group=group,
            topics=[(
                topic,
                [(
                    partition,
                    payload.offset,
                    payload.metadata)
                for partition, payload in six.iteritems(topic_payloads)])
            for topic, topic_payloads in six.iteritems(group_by_topic_and_partition(payloads))])

Encode an OffsetCommitRequest struct

Args:
        group: string, the consumer group you are committing offsets for
        payloads: list of OffsetCommitRequestPayload


def get_package_from_string(txt, paths=None):

    o = VersionedObject(txt)
    return get_package(o.name, o.version, paths=paths)

Get a package given a string.

Args:
        txt (str): String such as 'foo', 'bah-1.3'.
        paths (list of str, optional): paths to search for package, defaults
            to `config.packages_path`.

Returns:
        `Package` instance, or None if no package was found.


def get_sendback(self, uuid, key):

        def send_back_callback(data):
            self.sendResponse(
                serializers.serialize(data),
                uuid,
                key
            )

        return send_back_callback

Return function for sending progress messages back to original caller.

Args:
        uuid (str): UUID of the received message.
        key (str): Routing key.

Returns:
        fn reference: Reference to function which takes only one data \
                    argument.


def from_string(cls, text, comments="#", error="warn"):

        cache = []
        for line in text.splitlines():

            # If the line is empty or begins with a comment mark, we skip it.
            if not line.strip() or line.startswith(comments):
                continue

            # The startswith conditions include a blank space in order to not take into account
            # lines containing only a COSPAR ID, which happens when an object is detected but the
            # JSpOc doesn't know what is the source yet.
            if line.startswith('1 '):
                cache.append(line)
            elif line.startswith('2 '):
                cache.append(line)
                try:
                    yield cls("\n".join(cache))
                except ValueError as e:
                    if error in ('raise', 'warn'):
                        if error == "raise":
                            raise
                        else:
                            log.warning(str(e))

                cache = []
            else:
                # In the 3LE format, the first line (numbered 0, or unnumbered) contains the name
                # of the satellite
                # In the TLE format, this line doesn't exists.
                cache = [line]

Generator of TLEs from a string

Args:
        text (str): A text containing many TLEs
        comments (str): If a line starts with this character, it is ignored
        error (str): How to handle errors while parsing the text. Could be
            'raise', 'warn' or 'ignore'.

Yields:
        Tle:


def validate(cls, mapper_spec):

    if mapper_spec.input_reader_class() != cls:
      raise BadReaderParamsError("Input reader class mismatch")
    params = _get_params(mapper_spec)
    if cls.ENTITY_KIND_PARAM not in params:
      raise BadReaderParamsError("Missing mapper parameter 'entity_kind'")
    if cls.BATCH_SIZE_PARAM in params:
      try:
        batch_size = int(params[cls.BATCH_SIZE_PARAM])
        if batch_size < 1:
          raise BadReaderParamsError("Bad batch size: %s" % batch_size)
      except ValueError, e:
        raise BadReaderParamsError("Bad batch size: %s" % e)
    if cls.NAMESPACE_PARAM in params:
      if not isinstance(params[cls.NAMESPACE_PARAM],
                        (str, unicode, type(None))):
        raise BadReaderParamsError(
            "Expected a single namespace string")
    if cls.NAMESPACES_PARAM in params:
      raise BadReaderParamsError("Multiple namespaces are no longer supported")
    if cls.FILTERS_PARAM in params:
      filters = params[cls.FILTERS_PARAM]
      if not isinstance(filters, list):
        raise BadReaderParamsError("Expected list for filters parameter")
      for f in filters:
        if not isinstance(f, (tuple, list)):
          raise BadReaderParamsError("Filter should be a tuple or list: %s", f)
        if len(f) != 3:
          raise BadReaderParamsError("Filter should be a 3-tuple: %s", f)
        if not isinstance(f[0], basestring):
          raise BadReaderParamsError("First element should be string: %s", f)
        if f[1] != "=":
          raise BadReaderParamsError(
              "Only equality filters are supported: %s", f)

Validates mapper spec and all mapper parameters.

Args:
        mapper_spec: The MapperSpec for this InputReader.

Raises:
        BadReaderParamsError: required parameters are missing or invalid.


def stream_matching(self, address, name):

        matching = [x for x in self.entries if x.valid and x.target.matches(address, name)]

        rpc_list = []
        for var in matching:
            rpc_list.extend(var.generate_rpcs(address))

        return rpc_list

Return the RPCs needed to stream matching config variables to the given tile.

    This function will return a list of tuples suitable for passing to
    EmulatedDevice.deferred_rpc.

Args:
        address (int): The address of the tile that we wish to stream to
        name (str or bytes): The 6 character name of the target tile.

Returns:
        list of tuple: The list of RPCs to send to stream these variables to a tile.


def __init__(self, key_wrapping_data=None):

        super(Key, self).__init__()

        self.cryptographic_algorithm = None
        self.cryptographic_length = None
        self.key_format_type = None
        self.key_wrapping_data = key_wrapping_data

        # All remaining attributes are not considered part of the public API
        # and are subject to change.
        self._cryptographic_parameters = list()

        # The following attributes are placeholders for attributes that are
        # unsupported by kmip.core
        self._usage_limits = None

Create a Key object.

Args:
        key_wrapping_data(dict): A dictionary containing key wrapping data
            settings, describing how the key value has been wrapped.
            Optional, defaults to None.


def Lookup(self, name):

        if name == '@':
            return self.stack[-1].context

        parts = name.split('.')
        value = self._LookUpStack(parts[0])

        # Now do simple lookups of the rest of the parts
        for part in parts[1:]:
            try:
                value = value[part]
            except (KeyError, TypeError):  # TypeError for non-dictionaries
                return self._Undefined(part)

        return value

Get the value associated with a name in the current context.

    The current context could be an dictionary in a list, or a dictionary
    outside a list.

Args:
        name: name to lookup, e.g. 'foo' or 'foo.bar.baz'

Returns:
        The value, or self.undefined_str

Raises:
        UndefinedVariable if self.undefined_str is not set


def bruteVersionStr(self, valu):

        try:
            valu, info = self.core.model.type('it:semver').norm(valu)
            subs = info.get('subs')
            return valu, subs
        except s_exc.BadTypeValu:
            # Try doing version part extraction by noming through the string
            subs = s_version.parseVersionParts(valu)
            if subs is None:
                raise s_exc.BadTypeValu(valu=valu, name='bruteVersionStr',
                                        mesg='Unable to brute force version parts out of the string')
            if subs:
                valu = s_version.packVersion(subs.get('major'),
                                             subs.get('minor', 0),
                                             subs.get('patch', 0))
                return valu, subs

Brute force the version out of a string.

Args:
        valu (str): String to attempt to get version information for.

Note:
        This first attempts to parse strings using the it:semver normalization
        before attempting to extract version parts out of the string.

Returns:
        int, dict: The system normalized version integer and a subs dictionary.


def upload_dict(s3_conn, s3_prefix, data_to_sync):

    bucket_name, prefix = split_s3_path(s3_prefix)
    bucket = s3_conn.get_bucket(bucket_name)

    for key, value in data_to_sync.items():
        full_name = '{}/{}.json'.format(prefix, key)
        s3_key = boto.s3.key.Key(
            bucket=bucket,
            name=full_name
        )
        logging.info('uploading key %s', full_name)
        s3_key.set_contents_from_string(json.dumps(value))

Syncs a dictionary to an S3 bucket, serializing each value in the
    dictionary as a JSON file with the key as its name.

Args:
        s3_conn: (boto.s3.connection) an s3 connection
        s3_prefix: (str) the destination prefix
        data_to_sync: (dict)


def jobs_get(self, job_id, project_id=None):

    if project_id is None:
      project_id = self._project_id
    url = Api._ENDPOINT + (Api._JOBS_PATH % (project_id, job_id))
    return datalab.utils.Http.request(url, credentials=self._credentials)

Issues a request to retrieve information about a job.

Args:
        job_id: the id of the job
        project_id: the project id to use to fetch the results; use None for the default project.

Returns:
        A parsed result object.

Raises:
        Exception if there is an error performing the operation.


def __init__(self, name, min_val, max_val):

        self.name = name
        self.min_val = min_val
        self.max_val = max_val
        if type(min_val) != type(max_val):
            raise ValueError('Supplied min_val is not the same type as\
                             supplied max_val: {}, {}'.format(
                                 type(min_val),
                                 type(max_val))
                             )
        self.dtype = type(min_val + max_val)
        if self.dtype not in SUPPORTED_DTYPES:
            raise ValueError('Unsupported data type: use {}'
                             .format(SUPPORTED_DTYPES))

Parameter object

Args:
        name (str): name of the parameter
        min_val (int or float): minimum allowed value for the parameter
        max_val (int or float): maximum allowed value for the parameter


def json_to_url(json, symbol):

    start = json[0]['date']
    end = json[-1]['date']
    diff = end - start

    # Get period by a ratio from calculated period to valid periods
    # Ratio closest to 1 is the period
    # Valid values: 300, 900, 1800, 7200, 14400, 86400
    periods = [300, 900, 1800, 7200, 14400, 86400]

    diffs = {}
    for p in periods:
        diffs[p] = abs(1 - (p / (diff / len(json)))) # Get ratio

    period = min(diffs, key=diffs.get) # Find closest period

    url = ('https://poloniex.com/public?command'
           '=returnChartData&currencyPair={0}&start={1}'
           '&end={2}&period={3}').format(symbol, start, end, period)
    return url

Converts a JSON to a URL by the Poloniex API

Args:
        json: JSON data as a list of dict dates, where the keys are
            the raw market statistics.
        symbol: String of currency pair, like a ticker symbol.

Returns:
        String URL to Poloniex API representing the given JSON.


def tf_step(self, x, iteration, conjugate, residual, squared_residual):

        x, next_iteration, conjugate, residual, squared_residual = super(ConjugateGradient, self).tf_step(
            x, iteration, conjugate, residual, squared_residual
        )

        # Ac := A * c_t
        A_conjugate = self.fn_x(conjugate)

        # TODO: reference?
        if self.damping > 0.0:
            A_conjugate = [A_conj + self.damping * conj for A_conj, conj in zip(A_conjugate, conjugate)]

        # cAc := c_t^T * Ac
        conjugate_A_conjugate = tf.add_n(
            inputs=[tf.reduce_sum(input_tensor=(conj * A_conj)) for conj, A_conj in zip(conjugate, A_conjugate)]
        )

        # \alpha := r_t^2 / cAc
        alpha = squared_residual / tf.maximum(x=conjugate_A_conjugate, y=util.epsilon)

        # x_{t+1} := x_t + \alpha * c_t
        next_x = [t + alpha * conj for t, conj in zip(x, conjugate)]

        # r_{t+1} := r_t - \alpha * Ac
        next_residual = [res - alpha * A_conj for res, A_conj in zip(residual, A_conjugate)]

        # r_{t+1}^2 := r_{t+1}^T * r_{t+1}
        next_squared_residual = tf.add_n(inputs=[tf.reduce_sum(input_tensor=(res * res)) for res in next_residual])

        # \beta = r_{t+1}^2 / r_t^2
        beta = next_squared_residual / tf.maximum(x=squared_residual, y=util.epsilon)

        # c_{t+1} := r_{t+1} + \beta * c_t
        next_conjugate = [res + beta * conj for res, conj in zip(next_residual, conjugate)]

        return next_x, next_iteration, next_conjugate, next_residual, next_squared_residual

Iteration loop body of the conjugate gradient algorithm.

Args:
        x: Current solution estimate $x_t$.
        iteration: Current iteration counter $t$.
        conjugate: Current conjugate $c_t$.
        residual: Current residual $r_t$.
        squared_residual: Current squared residual $r_t^2$.

Returns:
        Updated arguments for next iteration.


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

    super(EnumerationValue, self).__init__()
    self.aliases = aliases or []
    self.description = description
    self.name = name
    self.number = number

Initializes an enumeration value.

Args:
        name (str): name.
        number (int): number.
        aliases (Optional[list[str]]): aliases.
        description (Optional[str]): description.


def repl_member_add(self, params):

        repl_config = self.config
        member_id = max([member['_id'] for member in repl_config['members']]) + 1
        member_config = self.member_create(params, member_id)
        repl_config['members'].append(member_config)
        if not self.repl_update(repl_config):
            self.member_del(member_id, reconfig=True)
            raise ReplicaSetError("Could not add member to ReplicaSet.")
        return member_id

create new mongod instances and add it to the replica set.

Args:
        params - mongod params
    return True if operation success otherwise False


def load_pascal(image_set, year, devkit_path, shuffle=False):

    image_set = [y.strip() for y in image_set.split(',')]
    assert image_set, "No image_set specified"
    year = [y.strip() for y in year.split(',')]
    assert year, "No year specified"

    # make sure (# sets == # years)
    if len(image_set) > 1 and len(year) == 1:
        year = year * len(image_set)
    if len(image_set) == 1 and len(year) > 1:
        image_set = image_set * len(year)
    assert len(image_set) == len(year), "Number of sets and year mismatch"

    imdbs = []
    for s, y in zip(image_set, year):
        imdbs.append(PascalVoc(s, y, devkit_path, shuffle, is_train=True))
    if len(imdbs) > 1:
        return ConcatDB(imdbs, shuffle)
    else:
        return imdbs[0]

wrapper function for loading pascal voc dataset

    Parameters:
    ----------
    image_set : str
        train, trainval...
    year : str
        2007, 2012 or combinations splitted by comma
    devkit_path : str
        root directory of dataset
    shuffle : bool
        whether to shuffle initial list

Returns:
    ----------
    Imdb


def Deserialize(self, reader):

        self.Magic = reader.ReadUInt32()
        self.Command = reader.ReadFixedString(12).decode('utf-8')
        self.Length = reader.ReadUInt32()

        if self.Length > self.PayloadMaxSizeInt:
            raise Exception("invalid format- payload too large")

        self.Checksum = reader.ReadUInt32()
        self.Payload = reader.ReadBytes(self.Length)

        checksum = Message.GetChecksum(self.Payload)

        if checksum != self.Checksum:
            raise ChecksumException("checksum mismatch")

Deserialize full object.

Args:
        reader (neo.IO.BinaryReader):


def record_little_endian(self):
        # type: () -> bytes

        if not self._initialized:
            raise pycdlibexception.PyCdlibInternalError('Path Table Record not yet initialized')

        return self._record(self.extent_location, self.parent_directory_num)

A method to generate a string representing the little endian version of
    this Path Table Record.

    Parameters:
    None.

Returns:
    A string representing the little endian version of this Path Table Record.


def _NormalizedVolumeIdentifiers(
      self, volume_system, volume_identifiers, prefix='v'):

    normalized_volume_identifiers = []
    for volume_identifier in volume_identifiers:
      if isinstance(volume_identifier, int):
        volume_identifier = '{0:s}{1:d}'.format(prefix, volume_identifier)

      elif not volume_identifier.startswith(prefix):
        try:
          volume_identifier = int(volume_identifier, 10)
          volume_identifier = '{0:s}{1:d}'.format(prefix, volume_identifier)
        except (TypeError, ValueError):
          pass

      try:
        volume = volume_system.GetVolumeByIdentifier(volume_identifier)
      except KeyError:
        volume = None

      if not volume:
        raise errors.ScannerError(
            'Volume missing for identifier: {0:s}.'.format(volume_identifier))

      normalized_volume_identifiers.append(volume_identifier)

    return normalized_volume_identifiers

Normalizes volume identifiers.

Args:
        volume_system (VolumeSystem): volume system.
        volume_identifiers (list[int|str]): allowed volume identifiers, formatted
        as an integer or string with prefix.
        prefix (Optional[str]): volume identifier prefix.

Returns:
        list[str]: volume identifiers with prefix.

Raises:
        ScannerError: if the volume identifier is not supported or no volume
        could be found that corresponds with the identifier.


def play(self, wav=None, data=None, rate=16000, channels=1, width=2, block=True, spectrum=None):

        if wav:
            f = wave.open(wav, 'rb')
            rate = f.getframerate()
            channels = f.getnchannels()
            width = f.getsampwidth()

            def gen(w):
                d = w.readframes(CHUNK_SIZE)
                while d:
                    yield d
                    d = w.readframes(CHUNK_SIZE)
                w.close()

            data = gen(f)

        self.stop_event.clear()
        if block:
            self._play(data, rate, channels, width, spectrum)
        else:
            thread = threading.Thread(target=self._play, args=(data, rate, channels, width, spectrum))
            thread.start()

play wav file or raw audio (string or generator)

Args:
        wav: wav file path
        data: raw audio data, str or iterator
        rate: sample rate, only for raw audio
        channels: channel number, only for raw data
        width: raw audio data width, 16 bit is 2, only for raw data
        block: if true, block until audio is played.
        spectrum: if true, use a spectrum analyzer thread to analyze data


def read_from_hdx(identifier, configuration=None):
        # type: (str, Optional[Configuration]) -> Optional['ResourceView']

        resourceview = ResourceView(configuration=configuration)
        result = resourceview._load_from_hdx('resource view', identifier)
        if result:
            return resourceview
        return None

Reads the resource view given by identifier from HDX and returns ResourceView object

Args:
        identifier (str): Identifier of resource view
        configuration (Optional[Configuration]): HDX configuration. Defaults to global configuration.

Returns:
        Optional[ResourceView]: ResourceView object if successful read, None if not


def create_group(self, name):

        self.service.create_group(
            name, self.url_prefix, self.auth, self.session,
            self.session_send_opts)

Create a new group.

Args:
        name (string): Name of the group to create.

Raises:
        requests.HTTPError on failure.


def WriteValuesToJSONFile(self, state, values):

    value_counters = {}
    max_post_size = config.CONFIG["BigQuery.max_file_post_size"]
    for value in values:
      class_name = value.__class__.__name__
      output_tracker, created = self._GetTempOutputFileHandles(class_name)

      # If our output stream is getting huge we should flush everything now and
      # set up new output files. Only start checking when we are getting within
      # range of the limit because we need to flush the stream to check the
      # size. Start counting at 0 so we check each file the first time.
      value_counters[class_name] = value_counters.get(class_name, -1) + 1
      if not value_counters[class_name] % max_post_size // 1000:

        # Flush our temp gzip handle so we can stat it to see how big it is.
        output_tracker.gzip_filehandle.flush()
        if os.path.getsize(output_tracker.gzip_filehandle.name) > max_post_size:
          # Flush what we have and get new temp output handles.
          self.Flush(state)
          value_counters[class_name] = 0
          output_tracker, created = self._GetTempOutputFileHandles(class_name)

      if not output_tracker.schema:
        output_tracker.schema = self.RDFValueToBigQuerySchema(value)

      if created:
        # Omit the leading newline for the first entry in the file.
        self._WriteJSONValue(output_tracker.gzip_filehandle, value)
      else:
        self._WriteJSONValue(
            output_tracker.gzip_filehandle, value, delimiter="\n")

    for output_tracker in itervalues(self.temp_output_trackers):
      output_tracker.gzip_filehandle.flush()

Write newline separated JSON dicts for each value.

    We write each dict separately so we don't have to hold all of the output
    streams in memory. We open and close the JSON array manually with [].

Args:
        state: rdf_protodict.AttributedDict with the plugin's state.
        values: RDF values to export.


def remove_role(self, databaseName, roleName, collectionName=None):

        role = {"databaseName" : databaseName,
                "roleName" : roleName}

        if collectionName:
            role["collectionName"] = collectionName

        if role in self.roles:
            self.roles.remove(role)

Remove one role

Args:
        databaseName (str): Database Name
        roleName (RoleSpecs): role

    Keyword Args:
        collectionName (str): Collection


def process_alias_export_namespace(namespace):

    namespace.export_path = os.path.abspath(namespace.export_path)
    if os.path.isfile(namespace.export_path):
        raise CLIError(FILE_ALREADY_EXISTS_ERROR.format(namespace.export_path))

    export_path_dir = os.path.dirname(namespace.export_path)
    if not os.path.isdir(export_path_dir):
        os.makedirs(export_path_dir)

    if os.path.isdir(namespace.export_path):
        namespace.export_path = os.path.join(namespace.export_path, ALIAS_FILE_NAME)

Validate input arguments when the user invokes 'az alias export'.

Args:
        namespace: argparse namespace object.


def _project_TH2(self, hist: Hist) -> Any:

        if len(self.projection_axes) != 1:
            raise ValueError(len(self.projection_axes), "Invalid number of axes")

        #logger.debug(f"self.projection_axes[0].axis: {self.projection_axes[0].axis}, axis range name: {self.projection_axes[0].name}, axis_type: {self.projection_axes[0].axis_type}")
        # NOTE: We cannot use TH3.ProjectionZ(...) because it has different semantics than ProjectionX
        #       and ProjectionY. In particular, it doesn't respect the axis limits of axis onto which it
        #       is projected.  So we have to separate the projection by histogram type as opposed to axis
        #       length.
        projection_func_map = {
            TH1AxisType.x_axis.value: hist.ProjectionX,
            TH1AxisType.y_axis.value: hist.ProjectionY
        }

        # Determine the axis_type value
        # Use try here instead of checking for a particular type to protect against type changes (say
        # in the enum)
        try:
            # Try to extract the value from an enum
            axis_type = self.projection_axes[0].axis_type.value
        except ValueError:
            # Seems that we received an int, so just use that value
            axis_type = self.axis_type  # type: ignore

        projection_func = projection_func_map[axis_type]

        # Do the actual projection
        logger.info(f"Projecting onto axis range {self.projection_axes[0].name} from hist {hist.GetName()}")
        projected_hist = projection_func()

        return projected_hist

Perform the actual TH2 -> TH1 projection.

    This projection can only be to 1D.

Args:
        hist (ROOT.TH2): Histogram from which the projections should be performed.

Returns:
        ROOT.TH1: The projected histogram.


def cleandata(inputlist):

    output = []
    for e in inputlist:
        new = []
        for f in e:
            if f == "--":
                new.append(None)
            else:
                new.append(float(f))
        output.append(new)
    return output

Helper function for parse.getdata.
    Remove empty variables, convert strings to float

Args:
        inputlist: list
            List of Variables

Returns:
        ouput:
            Cleaned list


def Validate(self, value):

    if value is None:
      return None

    if not isinstance(value, self.rdfclass):
      # Try to coerce the type to the correct rdf_class.
      try:
        r = self.rdfclass()
        r.FromDict(value)
        return r
      except (AttributeError, TypeError, rdfvalue.InitializeError):
        # AttributeError is raised if value contains items that don't
        # belong to the given rdfstruct.
        # TypeError will be raised if value is not a dict-like object.
        raise TypeValueError("Value for arg %s should be an %s" %
                             (self.name, self.rdfclass.__name__))

    return value

Validate the value.

Args:
        value: Value is expected to be a dict-like object that a given RDFStruct
        can be initialized from.

Raises:
        TypeValueError: If the value is not a valid dict-like object that a given
        RDFStruct can be initialized from.

Returns:
        A valid instance of self.rdfclass or None.


def _sync_content_metadata(self, serialized_data):

        url = self.enterprise_configuration.sapsf_base_url + self.global_sap_config.course_api_path
        try:
            status_code, response_body = self._call_post_with_session(url, serialized_data)
        except requests.exceptions.RequestException as exc:
            raise ClientError(
                'SAPSuccessFactorsAPIClient request failed: {error} {message}'.format(
                    error=exc.__class__.__name__,
                    message=str(exc)
                )
            )

        if status_code >= 400:
            raise ClientError(
                'SAPSuccessFactorsAPIClient request failed with status {status_code}: {message}'.format(
                    status_code=status_code,
                    message=response_body
                )
            )

Create/update/delete content metadata records using the SuccessFactors OCN Course Import API endpoint.

Args:
        serialized_data: Serialized JSON string representing a list of content metadata items.

Raises:
        ClientError: If SuccessFactors API call fails.


def bbox_clip(bboxes, img_shape):

    assert bboxes.shape[-1] % 4 == 0
    clipped_bboxes = np.empty_like(bboxes, dtype=bboxes.dtype)
    clipped_bboxes[..., 0::2] = np.maximum(
        np.minimum(bboxes[..., 0::2], img_shape[1] - 1), 0)
    clipped_bboxes[..., 1::2] = np.maximum(
        np.minimum(bboxes[..., 1::2], img_shape[0] - 1), 0)
    return clipped_bboxes

Clip bboxes to fit the image shape.

Args:
        bboxes (ndarray): Shape (..., 4*k)
        img_shape (tuple): (height, width) of the image.

Returns:
        ndarray: Clipped bboxes.


def read(self, vals):

        i = 0
        if len(vals[i]) == 0:
            self.comments_1 = None
        else:
            self.comments_1 = vals[i]
        i += 1

Read values.

Args:
        vals (list): list of strings representing values


def context(name=None):

    def _context(cls):
        annotated(cls, name)
        cls.context = True

        return cls

    return _context

Declare that a class defines a context.

    Contexts are for use with HierarchicalShell for discovering
    and using functionality from the command line.

Args:
        name (str): Optional name for this context if you don't want
            to just use the class name.


def get_poi_types(self, **kwargs):

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

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

        # Parse
        values = result.get('types', [])
        return True, [emtype.PoiType(**a) for a in values]

Obtain POI types.

Args:
        lang (str): Language code (*es* or *en*).

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


def to_qasm(self,
                header: Optional[str] = None,
                precision: int = 10,
                qubit_order: ops.QubitOrderOrList = ops.QubitOrder.DEFAULT,
                ) -> str:

        return str(self._to_qasm_output(header, precision, qubit_order))

Returns QASM equivalent to the circuit.

Args:
        header: A multi-line string that is placed in a comment at the top
            of the QASM. Defaults to a cirq version specifier.
        precision: Number of digits to use when representing numbers.
        qubit_order: Determines how qubits are ordered in the QASM
            register.


def cv_score_mean(self, X, y):

        X, y = self._format_inputs(X, y)

        if self.problem_type.binary_classification:
            kf = StratifiedKFold(
                shuffle=True, random_state=RANDOM_STATE + 3)
        elif self.problem_type.multi_classification:
            self.target_type_transformer.inverse_transform(y)
            transformer = self.target_type_transformer
            kf = StratifiedKFoldMultiClassIndicator(
                transformer, shuffle=True, n_splits=3,
                random_state=RANDOM_STATE + 3)
        elif self.problem_type.regression:
            kf = KFold(shuffle=True, n_splits=3, random_state=RANDOM_STATE + 4)
        else:
            raise NotImplementedError

        scoring = {
            scorer_info.name: scorer_info.scorer
            for scorer_info in self.scorers_info
        }
        cv_results = cross_validate(
            self.estimator, X, y,
            scoring=scoring, cv=kf, return_train_score=False)

        # post-processing
        results = self._process_cv_results(cv_results)
        return results

Compute mean score across cross validation folds.

    Split data and labels into cross validation folds and fit the model for
    each fold. Then, for each scoring type in scorings, compute the score.
    Finally, average the scores across folds. Returns a dictionary mapping
    scoring to score.

Args:
    X (np.array): data
    y (np.array): labels
    scorings (List[str]): scoring types


def GetMessages(self, formatter_mediator, event):

    if self.DATA_TYPE != event.data_type:
      raise errors.WrongFormatter('Unsupported data type: {0:s}.'.format(
          event.data_type))

    event_values = event.CopyToDict()

    file_entry_type = event_values.get('file_entry_type', None)
    if file_entry_type is not None:
      event_values['file_entry_type'] = self._FILE_ENTRY_TYPES.get(
          file_entry_type, 'UNKNOWN')

    # The usage of allocated is deprecated in favor of is_allocated but
    # is kept here to be backwards compatible.
    if (not event_values.get('allocated', False) and
        not event_values.get('is_allocated', False)):
      event_values['unallocated'] = 'unallocated'

    return self._ConditionalFormatMessages(event_values)

Determines the formatted message strings for an event object.

Args:
        formatter_mediator (FormatterMediator): mediates the interactions
        between formatters and other components, such as storage and Windows
        EventLog resources.
        event (EventObject): event.

Returns:
        tuple(str, str): formatted message string and short message string.

Raises:
        WrongFormatter: if the event object cannot be formatted by the formatter.


def _list_like_func(self, func, axis, *args, **kwargs):

        func_prepared = self._prepare_method(
            lambda df: pandas.DataFrame(df.apply(func, axis, *args, **kwargs))
        )
        new_data = self._map_across_full_axis(axis, func_prepared)
        # When the function is list-like, the function names become the index/columns
        new_index = (
            [f if isinstance(f, string_types) else f.__name__ for f in func]
            if axis == 0
            else self.index
        )
        new_columns = (
            [f if isinstance(f, string_types) else f.__name__ for f in func]
            if axis == 1
            else self.columns
        )
        return self.__constructor__(new_data, new_index, new_columns)

Apply list-like function across given axis.

Args:
        func: The function to apply.
        axis: Target axis to apply the function along.

Returns:
        A new PandasQueryCompiler.


def WriteVarString(self, value, encoding="utf-8"):

        if type(value) is str:
            value = value.encode(encoding)

        length = len(value)
        ba = bytearray(value)
        byts = binascii.hexlify(ba)
        string = byts.decode(encoding)
        self.WriteVarInt(length)
        self.WriteBytes(string)

Write a string value to the stream.
    Read more about variable size encoding here: http://docs.neo.org/en-us/node/network-protocol.html#convention

Args:
        value (string): value to write to the stream.
        encoding (str): string encoding format.


def split_leading_dim(tensor, inputs, n_dims=2):

  input_shape_static = inputs.get_shape()
  input_shape_list = input_shape_static.as_list()
  tensor_shape_static = tensor.get_shape()
  tensor_shape_list = tensor_shape_static.as_list()
  if (input_shape_static.is_fully_defined()
      and tensor_shape_static.is_fully_defined()):
    new_shape = input_shape_list[:n_dims] + tensor_shape_list[1:]
    return tf.reshape(tensor, new_shape)

  # Shape can't be inferred statically.
  dims_after_first = tf.shape(tensor)[1:]
  split_sizes = tf.shape(inputs)[:n_dims]
  known_split_sizes = input_shape_list[:n_dims]
  known_dims_after_first = tensor_shape_list[1:]
  output_size = tf.concat([split_sizes, dims_after_first], 0)
  result = tf.reshape(tensor, output_size)
  result.set_shape(known_split_sizes + known_dims_after_first)
  return result

Split the first dimension of a tensor.

Args:
        tensor: Tensor to have its first dimension split.
        inputs: Original reference input to look the dimensions of.
        n_dims: Number of dimensions to split.

Returns:
        The input tensor, with its first dimension split.


def _decontextualise_connection(self, connection):

        ctx = stack.top
        if ctx is not None and connection in ctx.ldap3_manager_connections:
            ctx.ldap3_manager_connections.remove(connection)

Remove a connection from the appcontext.

Args:
        connection (ldap3.Connection): connection to remove from the
            appcontext


def remove(self, email):

        if email in self._collaborators:
            if self._collaborators[email] == ShareRequestValue.Add:
                del self._collaborators[email]
            else:
                self._collaborators[email] = ShareRequestValue.Remove
        self._dirty = True

Remove a Collaborator.

Args:
        str : Collaborator email address.