code
stringlengths
20
4.93k
docstring
stringlengths
33
1.27k
source
stringclasses
3 values
def custom_apply(self, path: utils.KeyPath, value_spec: pg_typing.ValueSpec, allow_partial: bool, child_transform: Optional[Callable[[utils.KeyPath, pg_typing.Field, Any], Any]]=None) -> Tuple[bool, 'List']: proceed_with_standard_apply = True if self._value_spec: if value_spec and (not value_spec.is_com...
Implement pg.typing.CustomTyping interface. Args: path: KeyPath of current object. value_spec: Origin value spec of the field. allow_partial: Whether allow partial object to be created. child_transform: Function to transform child node values in dict_obj into their final values. Transform function is called on leaf no...
github-repos
def Lookup(self, name): if not self._name2item: self._InitCache() return self._name2item[name]
Convenience function: Look up a given name in the class namespace. Tries to find a method or constant by this name in the class. Args: name: Name to look up. Returns: A Constant or Function instance. Raises: KeyError: if this identifier doesn't exist in this class.
github-repos
def register_validator(flag_name, checker, message='Flag validation failed', flag_values=_flagvalues.FLAGS): v = SingleFlagValidator(flag_name, checker, message) _add_validator(flag_values, v)
Adds a constraint, which will be enforced during program execution. The constraint is validated when flags are initially parsed, and after each change of the corresponding flag's value. Args: flag_name: str, name of the flag to be checked. checker: callable, a function to validate the flag. input - A single positional...
codesearchnet
def copy_raw_block(self): ctable = [] (r, c) = (0, 0) try: for row_index in range(self.start[0], self.end[0]): r = row_index row = [] ctable.append(row) for column_index in range(self.start[1], self.end[1]): c = column_index ...
Copies the block as it was originally specified by start and end into a new table. Returns: A copy of the block with no block transformations.
codesearchnet
def decode_row(line, fields=None): cols = line.rstrip('\n').split(_field_delimiter) cols = list(map(unescape, cols)) if (fields is not None): if (len(cols) != len(fields)): raise ItsdbError('Wrong number of fields: {} != {}'.format(len(cols), len(fields))) for i in range(len(cols...
Decode a raw line from a profile into a list of column values. Decoding involves splitting the line by the field delimiter (`"@"` by default) and unescaping special characters. If *fields* is given, cast the values into the datatype given by their respective Field object. Args: line: a raw line from a [incr tsdb()] p...
codesearchnet
def quantize_flow(flow, max_val=0.02, norm=True): h, w, _ = flow.shape dx = flow[..., 0] dy = flow[..., 1] if norm: dx = dx / w dy = dy / h flow_comps = [ quantize(d, -max_val, max_val, 255, np.uint8) for d in [dx, dy] ] return tuple(flow_comps)
Quantize flow to [0, 255]. After this step, the size of flow will be much smaller, and can be dumped as jpeg images. Args: flow (ndarray): (h, w, 2) array of optical flow. max_val (float): Maximum value of flow, values beyond [-max_val, max_val] will be truncated. norm (bool): Whether to divide flow values by image w...
juraj-google-style
def fpn_map_rois_to_levels(boxes): sqrtarea = tf.sqrt(tf_area(boxes)) level = tf.cast(tf.floor((4 + (tf.log(((sqrtarea * (1.0 / 224)) + 1e-06)) * (1.0 / np.log(2))))), tf.int32) level_ids = [tf.where((level <= 2)), tf.where(tf.equal(level, 3)), tf.where(tf.equal(level, 4)), tf.where((level >= 5))] level...
Assign boxes to level 2~5. Args: boxes (nx4): Returns: [tf.Tensor]: 4 tensors for level 2-5. Each tensor is a vector of indices of boxes in its level. [tf.Tensor]: 4 tensors, the gathered boxes in each level. Be careful that the returned tensor could be empty.
codesearchnet
def nb_ll(data, P, R): genes, cells = data.shape clusters = P.shape[1] lls = np.zeros((cells, clusters)) for c in range(clusters): P_c = P[:,c].reshape((genes, 1)) R_c = R[:,c].reshape((genes, 1)) ll = gammaln(R_c + data) - gammaln(R_c) ll += data...
Returns the negative binomial log-likelihood of the data. Args: data (array): genes x cells P (array): NB success probability param - genes x clusters R (array): NB stopping param - genes x clusters Returns: cells x clusters array of log-likelihoods
juraj-google-style
def set_style(self, column, style): column_idx = None while len(self.headers) > len(self.__style_list): self.__style_list.append(None) if isinstance(column, six.integer_types): column_idx = column elif isinstance(column, six.string_types): ...
Set |Style| for a specific column. Args: column (|int| or |str|): Column specifier. column index or header name correlated with the column. style (|Style|): Style value to be set to the column. Raises: ValueError: If the column specifier is invalid.
juraj-google-style
def run_without_tensor_float_32(description: str) -> Callable[[Callable[..., Any]], Callable[..., None]]: def decorator(f: Callable[..., Any]) -> Callable[..., None]: @functools.wraps(f) def decorated(*args, **kwargs): allowed = config.tensor_float_32_execution_enabled() tr...
Execute test with TensorFloat-32 disabled. While almost every real-world deep learning model runs fine with TensorFloat-32, many tests use assertAllClose or similar methods. TensorFloat-32 matmuls typically will cause such methods to fail with the default tolerances. Args: description: A description used for document...
github-repos
def _find_longest_parent_path(path_set, path): while (path not in path_set): if (not path): return None path = os.path.dirname(path) return path
Finds the longest "parent-path" of 'path' in 'path_set'. This function takes and returns "path-like" strings which are strings made of strings separated by os.sep. No file access is performed here, so these strings need not correspond to actual files in some file-system.. This function returns the longest ancestor pat...
codesearchnet
def profile(self, num): baseuri = self._BASE_URI + "company/{}".format(num) res = self.session.get(baseuri) self.handle_http_error(res) return res
Search for company profile by company number. Args: num (str): Company number to search on.
juraj-google-style
def from_json(cls, data): required_keys = ('name', 'day_type', 'location', 'dry_bulb_condition', 'humidity_condition', 'wind_condition', 'sky_condition') for key in required_keys: assert key in data, 'Required key "{}" is missing!'.format(key) retur...
Create a Design Day from a dictionary. Args: data = { "name": string, "day_type": string, "location": ladybug Location schema, "dry_bulb_condition": ladybug DryBulbCondition schema, "humidity_condition": ladybug HumidityCondition schema, "wind_condition": ladybug WindCondition schema, "sky_condition": ladybug SkyCondi...
juraj-google-style
def request_stop(self, ex=None): with self._lock: ex = self._filter_exception(ex) if self._joined: if isinstance(ex, tuple): _, ex_instance, _ = ex raise ex_instance elif ex is not None: _, ex_instance, _ = sys.exc_info() ...
Request that the threads stop. After this is called, calls to `should_stop()` will return `True`. Note: If an exception is being passed in, in must be in the context of handling the exception (i.e. `try: ... except Exception as ex: ...`) and not a newly created one. Args: ex: Optional `Exception`, or Python `exc_inf...
github-repos
def _on_channel_close(self, channel, reply_code_or_reason, reply_text=None): if isinstance(reply_code_or_reason, pika_errs.ChannelClosed): reply_code = reply_code_or_reason.reply_code reply_text = reply_code_or_reason.reply_text elif isinstance(reply_code_or_reason, int)...
Callback invoked when the channel is closed. Args: channel (pika.channel.Channel): The channel that got closed. reply_code_or_reason (int|Exception): The reason why the channel was closed. In older versions of pika, this is the AMQP code. reply_text (str): The human-readable reason for the channel's closure (only in o...
juraj-google-style
def Current(): return Architecture._MACHINE_TO_ARCHITECTURE.get(platform.machine().lower())
Determines the current system architecture. Returns: ArchitectureTuple, One of the Architecture constants or None if it cannot be determined.
github-repos
def loadnetcdf(filename, copy=True): filename = str(Path(filename).expanduser()) if copy: dataarray = xr.open_dataarray(filename).copy() else: dataarray = xr.open_dataarray(filename, chunks={}) if (dataarray.name is None): dataarray.name = filename.rstrip('.nc') for (key, val...
Load a dataarray from a NetCDF file. Args: filename (str): Filename (*.nc). copy (bool): If True, dataarray is copied in memory. Default is True. Returns: dataarray (xarray.DataArray): Loaded dataarray.
codesearchnet
def _find_docstring_line_for_no_body(self, start): tracked = sorted(list(self._tokenized_triple_quotes.keys())) for i in tracked: if (min(start, i) == start): return i return None
Find the docstring associated with a definition with no body in the node. In these cases, the provided start and end line number for that element are the same, so we must get the docstring based on the sequential position of known docstrings. Args: start: the row where the class / function starts. Returns: int: the ...
codesearchnet
def get(self, key=None): if key: key = ub_to_str(key) if settings.ENABLE_CACHING: return self.get_from_cache(key) or self.set_to_cache(self._get_from_riak(key)) else: return self._get_from_riak(key) else: self._e...
If key is not None, tries to get obj from cache first. If not found, tries to get from riak and sets to cache. If key is None, then execute solr query and checks result. Returns obj data and key tuple or raises exception ObjectDoesNotExist or MultipleObjectsReturned. Args: key(str): obj key Return: (tuple): obj data ...
juraj-google-style
def serialize_to_normalized_compact_json(py_obj): return json.dumps( py_obj, sort_keys=True, separators=(',', ':'), cls=ToJsonCompatibleTypes )
Serialize a native object to normalized, compact JSON. The JSON string is normalized by sorting any dictionary keys. It will be on a single line without whitespace between elements. Args: py_obj: object Any object that can be represented in JSON. Some types, such as datetimes are automatically converted to strings. ...
juraj-google-style
def id_pools_vsn_ranges(self): if (not self.__id_pools_vsn_ranges): self.__id_pools_vsn_ranges = IdPoolsRanges('vsn', self.__connection) return self.__id_pools_vsn_ranges
Gets the IdPoolsRanges API Client for VSN Ranges. Returns: IdPoolsRanges:
codesearchnet
def percent_point(self, U): self.check_fit() return scipy.optimize.brentq(self._brentq_cdf(U), -1000.0, 1000.0)
Given a cdf value, returns a value in original space. Args: U(numpy.array): cdf values in [0,1] Returns: numpy.array: value in original space
juraj-google-style
def attribute(self, attribute_id, action='GET', params=None): if params is None: params = {} if not self.can_update(): self._tcex.handle_error(910, [self.type]) if action == 'GET': return self.tc_requests.get_attribute( self.api_type,...
Gets the attribute from a Group/Indicator or Victim Args: action: params: attribute_id: Returns: attribute json
juraj-google-style
def makeDoubleLinked(dom, parent=None): dom.parent = parent for child in dom.childs: child.parent = dom makeDoubleLinked(child, dom)
Standard output from `dhtmlparser` is single-linked tree. This will make it double-linked. Args: dom (obj): :class:`.HTMLElement` instance. parent (obj, default None): Don't use this, it is used in recursive call.
codesearchnet
def clone(self, to_namespace, to_name): r = fapi.clone_workspace(self.namespace, self.name, to_namespace, to_name, self.api_url) fapi._check_response_code(r, 201) return Workspace(to_namespace, to_name, self.api_url)
Clone this workspace. Args: to_namespace (str): Target workspace namespace to_name (str): Target workspace name
juraj-google-style
def project_surface(surface, angle=DEFAULT_ANGLE): z_coef = np.sin(np.radians(angle)) y_coef = np.cos(np.radians(angle)) (surface_height, surface_width) = surface.shape slope = np.tile(np.linspace(0.0, 1.0, surface_height), [surface_width, 1]).T return ((slope * y_coef) + (surface * z_coef))
Returns the height of the surface when projected at the given angle. Args: surface (surface): the surface to project angle (float): the angle at which to project the surface Returns: surface: A projected surface.
codesearchnet
def extract_paths(self, paths, ignore_nopath): try: if self._has_tar_and_gzip(): self._extract_paths_tar_gz(paths, ignore_nopath) else: self._extract_paths_scp(paths, ignore_nopath) except (ssh.LagoSSHTimeoutException, LagoVMNotRunningErro...
Extract the given paths from the domain Args: paths(list of str): paths to extract ignore_nopath(boolean): if True will ignore none existing paths. Returns: None Raises: :exc:`~lago.plugins.vm.ExtractPathNoPathError`: if a none existing path was found on the VM, and ``ignore_nopath`` is True. :exc:`~lago.plugins.vm.Ext...
juraj-google-style
def check_or_generate_pyi(options) -> AnalysisResult: loader = load_pytd.create_loader(options) compiler_error = None other_error_info = '' src = '' try: src = read_source_file(options.input, options.open_function) if options.check: ctx = check_py(src=src, options=options...
Returns results from running pytype. Args: options: config.Options object. Returns: An AnalysisResult.
github-repos
def reports_progress(reporter): def decorator(func): @wraps(func) def wrapper(*args, **kwargs): with progress_reporter(reporter): return func(*args, **kwargs) return wrapper return decorator
A decorator factory to mark functions which report progress. Args: reporter: A zero-argument callable to report progress. The callable provided should have the means to both retrieve and display current progress information.
codesearchnet
def get_hash(self, handle): handle = os.path.expanduser(os.path.expandvars(handle)) with open(self._prefixed('%s.hash' % handle)) as f: return f.read()
Returns the associated hash for the given handle, the hash file must exist (``handle + '.hash'``). Args: handle (str): Path to the template to get the hash from Returns: str: Hash for the given handle
juraj-google-style
def decode(self, spec, encoded_value): raise NotImplementedError(f'{type(self).__name__}.decode')
Decodes `value` from a batchable tensor encoding. Args: spec: The TypeSpec for the result value. If encoded values with spec `s` were batched, then `spec` should be `s.batch(batch_size)`; or if encoded values with spec `s` were unbatched, then `spec` should be `s.unbatch()`. encoded_value: A nest of values returned b...
github-repos
def download_patric_genomes(self, ids, force_rerun=False): ids = ssbio.utils.force_list(ids) counter = 0 log.info('Downloading sequences from PATRIC...') for patric_id in tqdm(ids): f = ssbio.databases.patric.download_coding_sequences(patric_id=patric_id, seqtype='protein', outdir=self.sequences...
Download genome files from PATRIC given a list of PATRIC genome IDs and load them as strains. Args: ids (str, list): PATRIC ID or list of PATRIC IDs force_rerun (bool): If genome files should be downloaded again even if they exist
codesearchnet
def to_string(cls, error_code): if error_code == cls.EMU_NO_CONNECTION: return 'No connection to emulator.' elif error_code == cls.EMU_COMM_ERROR: return 'Emulator connection error.' elif error_code == cls.DLL_NOT_OPEN: return 'DLL has not been opened...
Returns the string message for the given ``error_code``. Args: cls (JlinkGlobalErrors): the ``JLinkGlobalErrors`` class error_code (int): error code to convert Returns: An error string corresponding to the error code. Raises: ValueError: if the error code is invalid.
juraj-google-style
def _get_upload_cmd(self, mirror=False): if mirror: dest_uri = self.s3_mirror_uri else: dest_uri = self.s3_version_uri cmd = 'aws s3 sync {} {} --delete --exact-timestamps --profile {}'.format(self.artifact_path, dest_uri, self.env) return cmd
Generate the S3 CLI upload command Args: mirror (bool): If true, uses a flat directory structure instead of nesting under a version. Returns: str: The full CLI command to run.
codesearchnet
def info(self, server_id): result = self._storage[server_id].info() result['id'] = server_id return result
return dicionary object with info about server Args: server_id - server identity
juraj-google-style
def unreferenced_vert(script): if script.ml_version == '1.3.4BETA': filter_xml = ' <filter name="Remove Unreferenced Vertex"/>\n' else: filter_xml = ' <filter name="Remove Unreferenced Vertices"/>\n' util.write_filter(script, filter_xml) return None
Check for every vertex on the mesh: if it is NOT referenced by a face, removes it. Args: script: the FilterScript object or script filename to write the filter to. Layer stack: No impacts MeshLab versions: 2016.12 1.3.4BETA
juraj-google-style
def avg_branch_length(self, terminal=True, internal=True): if (not isinstance(terminal, bool)): raise TypeError('terminal must be a bool') if (not isinstance(internal, bool)): raise TypeError('internal must be a bool') if ((not internal) and (not terminal)): raise RuntimeError('Must ...
Compute the average length of the selected branches of this ``Tree``. Edges with length ``None`` will be treated as 0-length Args: ``terminal`` (``bool``): ``True`` to include terminal branches, otherwise ``False`` ``internal`` (``bool``): ``True`` to include internal branches, otherwise ``False`` Returns: The avera...
codesearchnet
def _ReadElementSequenceDataTypeDefinition(self, definitions_registry, definition_values, data_type_definition_class, definition_name, supported_definition_values): unsupported_definition_values = set(definition_values.keys()).difference(supported_definition_values) if unsupported_definition_values: err...
Reads an element sequence data type definition. Args: definitions_registry (DataTypeDefinitionsRegistry): data type definitions registry. definition_values (dict[str, object]): definition values. data_type_definition_class (str): data type definition class. definition_name (str): name of the definition. supported_defi...
codesearchnet
def read(self, istream, kmip_version=enums.KMIPVersion.KMIP_1_0): super(ApplicationSpecificInformation, self).read(istream, kmip_version=kmip_version) tstream = BytearrayStream(istream.read(self.length)) self.application_namespace.read(tstream, kmip_version=kmip_version) self.application_data.read(tstre...
Read the data encoding the ApplicationSpecificInformation object and decode it into its constituent parts. Args: istream (Stream): A data stream containing encoded object data, supporting a read method; usually a BytearrayStream object. kmip_version (KMIPVersion): An enumeration defining the KMIP version with which th...
codesearchnet
def effect_emd(d1, d2): return sum((abs((marginal_zero(d1, i) - marginal_zero(d2, i))) for i in range(d1.ndim)))
Compute the EMD between two effect repertoires. Because the nodes are independent, the EMD between effect repertoires is equal to the sum of the EMDs between the marginal distributions of each node, and the EMD between marginal distribution for a node is the absolute difference in the probabilities that the node is OF...
codesearchnet
def _datetime_from_json(value, field): if _not_null(value, field): if "." in value: return datetime.datetime.strptime(value, _RFC3339_MICROS_NO_ZULU) else: return datetime.datetime.strptime(value, _RFC3339_NO_FRACTION) else: return N...
Coerce 'value' to a datetime, if set or not nullable. Args: value (str): The timestamp. field (.SchemaField): The field corresponding to the value. Returns: Optional[datetime.datetime]: The parsed datetime object from ``value`` if the ``field`` is not null (otherwise it is :data:`None`).
juraj-google-style
def _create_and_save_vocab_table_lookup_qat_model_tf1(self, output_path: str, tags: Collection[str], signature_def_key: str) -> Tuple[Mapping[str, core.Tensor], Mapping[str, core.Tensor]]: with session.Session(graph=ops.Graph()) as sess: input_vocabs_placeholder, lookup_tensor, output_tensor = self._create_...
Creates and saves a simple QAT model that uses a vocab table. Args: output_path: Path to the directory to save the created model. tags: Set of strings that identifies the saved meta graph. signature_def_key: Name of the SignatureDef. Used to identify the SignatureDef within the meta graph. Returns: inputs: A mapping ...
github-repos
def StreamMedia(self, callback=None, finish_callback=None, additional_headers=None): return self.__StreamMedia( callback=callback, finish_callback=finish_callback, additional_headers=additional_headers, use_chunks=False)
Send this resumable upload in a single request. Args: callback: Progress callback function with inputs (http_wrapper.Response, transfer.Upload) finish_callback: Final callback function with inputs (http_wrapper.Response, transfer.Upload) additional_headers: Dict of headers to include with the upload http_wrapper.Reque...
juraj-google-style
class PerceiverClassificationPostprocessor(nn.Module): def __init__(self, config: PerceiverConfig, in_channels: int) -> None: super().__init__() self.classifier = nn.Linear(in_channels, config.num_labels) def forward(self, inputs, pos: Optional[torch.Tensor]=None, modality_sizes=None) -> torch...
Classification postprocessing for Perceiver. Can be used to convert the decoder output to classification logits. Args: config ([*PerceiverConfig*]): Model configuration. in_channels (`int`): Number of channels in the input.
github-repos
def register_magics(store_name='_ampl_cells', ampl_object=None): from IPython.core.magic import Magics, magics_class, cell_magic, line_magic @magics_class class StoreAMPL(Magics): def __init__(self, shell=None, **kwargs): Magics.__init__(self, shell=shell, **kwargs) self._s...
Register jupyter notebook magics ``%%ampl`` and ``%%ampl_eval``. Args: store_name: Name of the store where ``%%ampl cells`` will be stored. ampl_object: Object used to evaluate ``%%ampl_eval`` cells.
codesearchnet
def _get_loss_object(self, loss): if loss is None: return None loss = losses_mod.get(loss) if not isinstance(loss, losses_mod.Loss): loss_name = get_custom_object_name(loss) if loss_name is None: raise ValueError('Loss should be a callable, found: {}'.format(loss)) ...
Returns a `Loss` object. Converts the user-supplied loss to a `Loss` object. Also allows `SUM_OVER_BATCH_SIZE` reduction to be used for this loss. Args: loss: A string, function, or `Loss` object. Returns: A `Loss` object.
github-repos
def interact_GxG(pheno, snps1, snps2=None, K=None, covs=None): if (K is None): K = SP.eye(N) N = snps1.shape[0] if (snps2 is None): snps2 = snps1 return interact_GxE(snps=snps1, pheno=pheno, env=snps2, covs=covs, K=K)
Epistasis test between two sets of SNPs Args: pheno: [N x 1] SP.array of 1 phenotype for N individuals snps1: [N x S1] SP.array of S1 SNPs for N individuals snps2: [N x S2] SP.array of S2 SNPs for N individuals K: [N x N] SP.array of LMM-covariance/kinship koefficients (optional) If not provided, then linear r...
codesearchnet
def dtime(sdat, tstart=None, tend=None): tseries = sdat.tseries_between(tstart, tend) time = tseries['t'].values return ((time[1:] - time[:(- 1)]), time[:(- 1)])
Time increment dt. Compute dt as a function of time. Args: sdat (:class:`~stagpy.stagyydata.StagyyData`): a StagyyData instance. tstart (float): time at which the computation should start. Use the beginning of the time series data if set to None. tend (float): time at which the computation should end. Use the end of ...
codesearchnet
def order_verification(self, institute, case, user, link, variant): LOG.info('Creating event for ordering validation for variant {0}'.format(variant['display_name'])) updated_variant = self.variant_collection.find_one_and_update({'_id': variant['_id']}, {'$set': {'sanger_ordered': True}}, return_document=pymong...
Create an event for a variant verification for a variant and an event for a variant verification for a case Arguments: institute (dict): A Institute object case (dict): Case object user (dict): A User object link (str): The url to be used in the event variant (dict): A variant object Returns: updated_variant(dict)
codesearchnet
def merge(self, ref_name: str): if self.is_dirty(): LOGGER.error('repository is dirty; cannot merge: %s', ref_name) sys.exit((- 1)) LOGGER.info('merging ref: "%s" into branch: %s', ref_name, self.get_current_branch()) self.repo.git.merge(ref_name)
Merges two refs Args: ref_name: ref to merge in the current one
codesearchnet
def push_file(self, source, dest_dir): local_dest = dest_dir + '/' + os.path.basename(source) if os.path.dirname(source) != dest_dir: try: shutil.copyfile(source, local_dest) os.chmod(local_dest, 0o777) except OSError as e: ...
If the source files dirpath is the same as dest_dir, a copy is not necessary, and nothing is done. Else a copy is made. Args: - source (string) : Path to the source file - dest_dir (string) : Path to the directory to which the files is to be copied Returns: - destination_path (String) : Absolute path of the destinati...
juraj-google-style
def get_concept(self, conceptId, lang='en'): url = urljoin((self.concept_service + '/'), conceptId) (res, status_code) = self.get(url, params={'lang': lang}) if (status_code != 200): logger.debug('Fetch concept failed.') return (self.decode(res), status_code)
Fetch the concept from the Knowledge base Args: id (str): The concept id to be fetched, it can be Wikipedia page id or Wikiedata id. Returns: dict, int: A dict containing the concept information; an integer representing the response code.
codesearchnet
def get(self, key): self._create_file_if_none_exists() with open(self.filename, 'rb') as file_object: cache_pickle = pickle.load(file_object) val = cache_pickle.get(key, None) return val
Gets a value by a key. Args: key (str): Key to retrieve the value. Returns: Retrieved value.
codesearchnet
def draw_points(self, *points): point_array = ffi.new('SDL_Point[]', len(points)) for i, p in enumerate(points): point_array[i] = p._ptr[0] check_int_err(lib.SDL_RenderDrawPoints(self._ptr, point_array, len(points)))
Draw multiple points on the current rendering target. Args: *points (Point): The points to draw. Raises: SDLError: If an error is encountered.
juraj-google-style
def _hash_sequence(self, sighash_type, anyone_can_pay): if anyone_can_pay or sighash_type == shared.SIGHASH_SINGLE: return b'\x00' * 32 else: sequences = ByteData() for tx_in in self.tx_ins: sequences += ...
BIP143 hashSequence implementation Args: sighash_type (int): SIGHASH_SINGLE or SIGHASH_ALL anyone_can_pay (bool): true if ANYONECANPAY should be set Returns: (bytes): the hashSequence, a 32 byte hash
juraj-google-style
def _load_tmp_fact(filepath): from hamster_lib import Fact try: with open(filepath, 'rb') as fobj: fact = pickle.load(fobj) except IOError: fact = False else: if (not isinstance(fact, Fact)): raise TypeError(_("Something went wrong. It seems our pickled fi...
Load an 'ongoing fact' from a given location. Args: filepath: Full path to the tmpfile location. Returns: hamster_lib.Fact: ``Fact`` representing the 'ongoing fact'. Returns ``False`` if no file was found. Raises: TypeError: If for some reason our stored instance is no instance of ``hamster_lib.Fact``.
codesearchnet
def validate(request: Union[Dict, List], schema: dict) -> Union[Dict, List]: jsonschema_validate(request, schema) return request
Wraps jsonschema.validate, returning the same object passed in. Args: request: The deserialized-from-json request. schema: The jsonschema schema to validate against. Raises: jsonschema.ValidationError
juraj-google-style
def as_dataframe(self, max_rows=None): max_rows = (len(self._timeseries_list) if (max_rows is None) else max_rows) headers = [{'resource': ts.resource._asdict(), 'metric': ts.metric._asdict()} for ts in self._timeseries_list[:max_rows]] if (not headers): return pandas.DataFrame() dataframe = pan...
Creates a pandas dataframe from the query metadata. Args: max_rows: The maximum number of timeseries metadata to return. If None, return all. Returns: A pandas dataframe containing the resource type, resource labels and metric labels. Each row in this dataframe corresponds to the metadata from one time series.
codesearchnet
def load_user_config(vcs): config_path = os.path.join(vcs.path, 'eci.yaml') if not os.path.exists(config_path): raise ConfigNotFoundError with open(config_path, 'r') as f: try: config = yaml.safe_load(f) except yaml.YAMLError: raise ConfigFormatError ...
Load the user config Args: vcs (easyci.vcs.base.Vcs) - the vcs object for the current project Returns: dict - the config Raises: ConfigFormatError ConfigNotFoundError
juraj-google-style
def test_encode_with_non_root_fhir_path_constraint_succeeds(self, fhir_path_expression: str, expected_sql_expression: str, expected_fhir_path_sql_expression: str, expected_fields_referenced: List[str]): self.maxDiff = None constraint = self.build_constraint(fhir_path_expression=fhir_path_expression) self.as...
Tests that a "transitive constraint" is properly encoded. A "transitive constraint" is a constraint defined relative to a resource elsewhere in the FHIR resource graph than what we're querying against. Args: fhir_path_expression: The FHIRPath expression to encode. expected_sql_expression: The expected generated Stand...
github-repos
def variable_summaries(vars_, groups=None, scope='weights'): groups = (groups or {'all': '.*'}) grouped = collections.defaultdict(list) for var in vars_: for (name, pattern) in groups.items(): if re.match(pattern, var.name): name = re.sub(pattern, name, var.name) ...
Create histogram summaries for the provided variables. Summaries can be grouped via regexes matching variables names. Args: vars_: List of variables to summarize. groups: Mapping of name to regex for grouping summaries. scope: Name scope for this operation. Returns: Summary tensor.
codesearchnet
def from_filenames(filenames, transformations=None, primitive=True, extend_collection=False): allcifs = [] for fname in filenames: with open(fname, "r") as f: allcifs.append(f.read()) return CifTransmuter("\n".join(allcifs), transforma...
Generates a TransformedStructureCollection from a cif, possibly containing multiple structures. Args: filenames: List of strings of the cif files transformations: New transformations to be applied to all structures primitive: Same meaning as in __init__. extend_collection: Same meaning as in __init__.
juraj-google-style
def extract(self, destination, format='csv', csv_delimiter=None, csv_header=True, compress=False): job = self.extract_async(destination, format=format, csv_delimiter=csv_delimiter, csv_header=csv_header, compress=compress) if (job is not None): job.wait() return job
Exports the table to GCS; blocks until complete. Args: destination: the destination URI(s). Can be a single URI or a list. format: the format to use for the exported data; one of 'csv', 'json', or 'avro' (default 'csv'). csv_delimiter: for CSV exports, the field delimiter to use. Defaults to ',' csv_header: for CSV ex...
codesearchnet
def add_chain_ids(self, chains): chains = ssbio.utils.force_list(chains) for c in chains: if self.chains.has_id(c): log.debug('{}: chain already present'.format(c)) else: chain_prop = ChainProp(ident=c, pdb_parent=self.id) self.chains.append(chain_prop) ...
Add chains by ID into the chains attribute Args: chains (str, list): Chain ID or list of IDs
codesearchnet
async def _handle_set_typing_notification(self, set_typing_notification): conv_id = set_typing_notification.conversation_id.id res = parsers.parse_typing_status_message(set_typing_notification) await self.on_typing.fire(res) try: conv = await self._get_or_fetch_conve...
Receive SetTypingNotification and update the conversation. Args: set_typing_notification: hangouts_pb2.SetTypingNotification instance
juraj-google-style
def _parse_example_raw(serialized, names, params, name): if params.num_features == 0: raise ValueError('Must provide at least one feature key.') with ops.name_scope(name, 'ParseExample', [serialized, names]): names = [] if names is None else names serialized = ops.convert_to_tensor(seria...
Parses `Example` protos. Args: serialized: A vector (1-D Tensor) of strings, a batch of binary serialized `Example` protos. names: A vector (1-D Tensor) of strings (optional), the names of the serialized protos. params: A `ParseOpParams` containing the parameters for the parse op. name: A name for this operation (opti...
github-repos
def add_comment(self, comment): if not comment: return self.__comments[comment.name] = comment self.comment_added_signal(self, comment)
Add a comment to the database. Args: comment (hotdoc.core.Comment): comment to add
juraj-google-style
def _pack_images(images, rows, cols): shape = onp.shape(images) width, height, depth = shape[-3:] images = onp.reshape(images, (-1, width, height, depth)) batch = onp.shape(images)[0] rows = onp.minimum(rows, batch) cols = onp.minimum(batch images = images[:rows * cols] images = onp.reshape(images, ...
Helper utility to make a tiled field of images from numpy arrays. Args: images: Image tensor in shape [N, W, H, C]. rows: Number of images per row in tiled image. cols: Number of images per column in tiled image. Returns: A tiled image of shape [W * rows, H * cols, C]. Truncates incomplete rows.
juraj-google-style
def export_to_dir(network, export_dir): package_path = ding0.__path__[0] network.export_to_csv_folder(os.path.join(package_path, 'output', 'debug', 'grid', ...
Exports PyPSA network as CSV files to directory Args: network: pypsa.Network export_dir: str Sub-directory in output/debug/grid/ where csv Files of PyPSA network are exported to.
juraj-google-style
def hashed(field_name, percent, fields=None, count=0): if field_name is None: raise Exception('Hash field must be specified') def _hashed_sampling(sql): projection = Sampling._create_projection(fields) sql = 'SELECT %s FROM (%s) WHERE MOD(ABS(FARM_FINGERPRINT(CAST(%s AS STRING))), 100) <...
Provides a sampling strategy based on hashing and selecting a percentage of data. Args: field_name: the name of the field to hash. percent: the percentage of the resulting hashes to select. fields: an optional list of field names to retrieve. count: optional maximum count of rows to pick. Returns: A sampling function ...
juraj-google-style
def create_detector(self, detector): resp = self._post(self._u(self._DETECTOR_ENDPOINT_SUFFIX), data=detector) resp.raise_for_status() return resp.json()
Creates a new detector. Args: detector (object): the detector model object. Will be serialized as JSON. Returns: dictionary of the response (created detector model).
juraj-google-style
def dummy_inputs(self): input_ids = tf.constant(DUMMY_INPUTS, dtype=tf.int32) batch_size, seq_len = input_ids.shape VISION_DUMMY_INPUTS = tf.random.uniform(shape=(batch_size, self.config.vision_config.num_channels, self.config.vision_config.image_size, self.config.vision_config.image_size), dtype=tf.float32...
Dummy inputs to build the network. Returns: `Dict[str, tf.Tensor]`: The dummy inputs.
github-repos
def __init__(self, shape, layout_rules): self._shape = convert_to_shape(shape) self._layout_rules = convert_to_layout_rules(layout_rules)
Creates a mesh implementation. Args: shape: Shape. layout_rules: LayoutRules.
juraj-google-style
def MapByteStream(self, byte_stream, byte_offset=0, **kwargs): byte_stream = super(StringMap, self).MapByteStream( byte_stream, byte_offset=byte_offset, **kwargs) if self._HasElementsTerminator(): elements_terminator = self._data_type_definition.elements_terminator elemen...
Maps the data type on a byte stream. Args: byte_stream (bytes): byte stream. byte_offset (Optional[int]): offset into the byte stream where to start. Returns: str: mapped values. Raises: MappingError: if the data type definition cannot be mapped on the byte stream.
juraj-google-style
def _get_profile_data_generator(self): node_to_traceback = defaultdict(list) node_to_op_type = defaultdict(str) for op in self._graph.get_operations(): node_to_traceback[op.name] = op.traceback node_to_op_type[op.name] = op.type def profile_data_generator(device_step_stats): for...
Get function that generates `ProfileDatum` objects. Returns: A function that generates `ProfileDatum` objects.
github-repos
def ones(shape, dtype=None): return backend.numpy.ones(shape, dtype=dtype)
Return a new tensor of given shape and type, filled with ones. Args: shape: Shape of the new tensor. dtype: Desired data type of the tensor. Returns: Tensor of ones with the given shape and dtype.
github-repos
def add_get_parameters(url, parameters, percent_encode=True): url_parts = list(parse.urlparse(url)) query = dict(parse.parse_qs(url_parts[4])) query.update(parameters) if percent_encode: url_parts[4] = parse.urlencode(query) else: url_parts[4] = "&".join([key + "=" + value for ...
Utility function to add GET parameters to an existing URL. Args: parameters A dictionary of the parameters that should be added. percent_encode Whether the query parameters should be percent encoded. Returns: The updated URL.
juraj-google-style
def _FindKeys(self, key, names, matches): for (name, subkey) in iter(key.items()): if (name in names): matches.append((name, subkey)) if isinstance(subkey, dict): self._FindKeys(subkey, names, matches)
Searches the plist key hierarchy for keys with matching names. If a match is found a tuple of the key name and value is added to the matches list. Args: key (dict[str, object]): plist key. names (list[str]): names of the keys to match. matches (list[str]): keys with matching names.
codesearchnet
def __init__(self, pattern, flags=0): self.regex = re.compile(pattern, flags=flags)
Initialize. Args: # pattern is the regular expression to search for pattern: str # flags passed to re.compile function as the second argument flags: int
juraj-google-style
def write(self, output_buffer, kmip_version=enums.KMIPVersion.KMIP_1_0): local_buffer = utils.BytearrayStream() if self._unique_identifier: self._unique_identifier.write(local_buffer, kmip_version=kmip_version) else: raise exceptions.InvalidField('The GetAttributeList response payload is mis...
Write the data encoding the GetAttributeList response payload to a stream. Args: output_buffer (stream): A data stream in which to encode object data, supporting a write method; usually a BytearrayStream object. kmip_version (KMIPVersion): An enumeration defining the KMIP version with which the object will be encoded....
codesearchnet
def _construct_graph(self, vertex_dict, edge_dict, default_vertex_attrs, default_edge_attrs): with self._lock: self._graph = pydot.Dot() if default_vertex_attrs: self._graph.set_node_defaults(**default_vertex_attrs) if default_edge_attrs: self._graph.set_edge_defaults...
Constructs the pydot.Dot object for the pipeline graph. Args: vertex_dict: (Dict[str, Dict[str, str]]) maps vertex names to attributes edge_dict: (Dict[(str, str), Dict[str, str]]) maps vertex name pairs to attributes default_vertex_attrs: (Dict[str, str]) a dict of attributes default_edge_attrs: (Dict[str, str]) a di...
github-repos
def vectorize(self, token_list): sentence_list = [token_list] test_observed_arr = self.__setup_dataset(sentence_list, self.__token_master_list) pred_arr = self.__controller.inference(test_observed_arr) return self.__controller.get_feature_points()
Tokenize token list. Args: token_list: The list of tokens.. Returns: [vector of token, vector of token, vector of token, ...]
juraj-google-style
def tournament_selection(population, fitnesses, num_competitors=2, diversity_weight=0.0): if (diversity_weight <= 0.0): fitness_pop = zip(fitnesses, population) return [max(random.sample(fitness_pop, num_competitors))[1] for _ in range(len(population))] else: indices = range(len(populati...
Create a list of parents with tournament selection. Args: population: A list of solutions. fitnesses: A list of fitness values corresponding to solutions in population. num_competitors: Number of solutions to compare every round. Best solution among competitors is selected. diversity_weight: Weight of diversity metric...
codesearchnet
def __init__(self, sess, watch_fn=None, thread_name_filter=None, pass_through_operrors=False): BaseDebugWrapperSession.__init__(self, sess, thread_name_filter=thread_name_filter, pass_through_operrors=pass_through_operrors) self._watch_fn = None if watch_fn is not None: if not callable(watch_fn): ...
Constructor of NonInteractiveDebugWrapperSession. Args: sess: The TensorFlow `Session` object being wrapped. watch_fn: (`Callable`) A Callable that maps the fetches and feeds of a debugged `Session.run()` call to `WatchOptions.` * Args: * `fetches`: the fetches to the `Session.run()` call. * `feeds`: the feeds to the ...
github-repos
def write_to_file(self, file_path): with gfile.Open(file_path, 'w') as f: for line in self._lines: f.write(line + '\n')
Write the object itself to file, in a plain format. The font_attr_segs and annotations are ignored. Args: file_path: (str) path of the file to write to.
github-repos
def call(command, collect_missing=False, silent=True): r return (_execCommand if silent else execCommand)(shlex.split(command), collect_missing)
r"""Calls a task, as if it were called from the command line. Args: command (str): A route followed by params (as if it were entered in the shell). collect_missing (bool): Collects any missing argument for the command through the shell. Defaults to False. Returns: The return value of the called command.
juraj-google-style
def ParsePageVisitedRow( self, parser_mediator, query, row, cache=None, database=None, **unused_kwargs): query_hash = hash(query) from_visit = self._GetRowValue(query_hash, row, 'from_visit') hidden = self._GetRowValue(query_hash, row, 'hidden') rev_host = self._GetRowValue(query_hash,...
Parses a page visited row. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. query (str): query that created the row. row (sqlite3.Row): row. cache (Optional[SQLiteCache]): cache. database (Optional[SQLiteDatabase]): database.
juraj-google-style
def load_parameters(self, path): nn.load_parameters(path) for v in self.get_modules(): if not isinstance(v, tuple): continue prefix, module = v for k, v in module.__dict__.items(): if not isinstance(v, nn.Variable): ...
Load parameters from a file with the specified format. Args: path : path or file object
juraj-google-style
def _get_hash(self, file_obj): size = 0 hash_buider = self.hash_builder() for piece in self._get_file_iterator(file_obj): hash_buider.update(piece) size += len(piece) file_obj.seek(0) return ('%s_%x' % (hash_buider.hexdigest(), size))
Compute hash for the `file_obj`. Attr: file_obj (obj): File-like object with ``.write()`` and ``.seek()``. Returns: str: Hexdigest of the hash.
codesearchnet
class PerceiverClassificationDecoder(PerceiverAbstractDecoder): def __init__(self, config, **decoder_kwargs): super().__init__() self.num_labels = config.num_labels self.decoder = PerceiverBasicDecoder(config, output_num_channels=self.num_labels, output_index_dims=1, **decoder_kwargs) ...
Cross-attention based classification decoder. Light-weight wrapper of [`PerceiverBasicDecoder`] for logit output. Will turn the output of the Perceiver encoder which is of shape (batch_size, num_latents, d_latents) to a tensor of shape (batch_size, num_labels). The queries are of shape (batch_size, 1, num_labels). Arg...
github-repos
def mark_done(task_id): task = Task.get_by_id(task_id) if (task is None): raise ValueError(('Task with id %d does not exist' % task_id)) task.done = True task.put()
Marks a task as done. Args: task_id: The integer id of the task to update. Raises: ValueError: if the requested task doesn't exist.
codesearchnet
def scan_directory(self, dirname, exclude_exts=(), exclude_fnames=()): for (i, ext) in enumerate(exclude_exts): if (not ext.strip().startswith('.')): exclude_exts[i] = ('.' + ext.strip()) paths = [] for fname in os.listdir(dirname): (root, ext) = os.path.splitext(fname) p...
Analyze the files contained in directory dirname. Args: dirname: directory path exclude_exts: list of file extensions that should be skipped. exclude_fnames: list of file names that should be skipped. Returns: List of pseudopotential objects.
codesearchnet
def indicators(self, indicator_type=None, filters=None, params=None): indicator = self._tcex.ti.indicator(indicator_type) for i in self.tc_requests.indicators_from_tag( indicator, self.name, filters=filters, params=params ): yield i
Gets all indicators from a tag. Args: params: filters: indicator_type:
juraj-google-style
def use_test_undeclared_outputs_dir(self): return self.is_flag_on(FLAG_NAME_USE_TEST_UNDECLARED_OUTPUTS_DIR)
Decides the output directory of the report and trace files. Args: None. Returns: True if the output files should be written to the test-undeclared-outputs-directory defined via an env variable.
github-repos
def VFSMultiOpen(pathspecs, progress_callback=None): precondition.AssertIterableType(pathspecs, rdf_paths.PathSpec) vfs_open = functools.partial(VFSOpen, progress_callback=progress_callback) return context.MultiContext(map(vfs_open, pathspecs))
Opens multiple files specified by given path-specs. See documentation for `VFSOpen` for more information. Args: pathspecs: A list of pathspec instances of files to open. progress_callback: A callback function to call to notify about progress Returns: A context manager yielding file-like objects.
codesearchnet
def jax_gather(params, indices, batch_dims=2): def _jax_gather(params, indices): return params[indices] for _ in range(batch_dims): _jax_gather = jax.vmap(_jax_gather, in_axes=(0, 0)) return _jax_gather(params, indices)
Gather the indices from params correctly (equivalent to tf.gather but with modifications) Args: params: (bsz, n_heads, num_blocks, block_size, head_dim) indices: (<num_blocks, 1)
github-repos
def save(self, path): self.clip.write_videofile(path, audio_fps=self.clip.audio.fps)
Save source video to file. Args: path (str): Filename to save to. Notes: Saves entire source video to file, not just currently selected frames.
codesearchnet
def read(self, istream, kmip_version=enums.KMIPVersion.KMIP_1_0): super(BigInteger, self).read(istream, kmip_version=kmip_version) if (self.length % 8): raise exceptions.InvalidPrimitiveLength('invalid big integer length read; expected: multiple of 8, observed: {0}'.format(self.length)) sign = 1 ...
Read the encoding of the BigInteger from the input stream. Args: istream (stream): A buffer containing the encoded bytes of the value of a BigInteger. Usually a BytearrayStream object. Required. kmip_version (KMIPVersion): An enumeration defining the KMIP version with which the object will be decoded. Optional, defaul...
codesearchnet
def parse_args(test: ArgList=None) -> argparse.Namespace: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('encoded_train_data', help='File path for the encoded training data.') parser.add_argument('-o', '--output', help=f'Output file path for the learned weights. (default: {DEFAULT...
Parses commandline arguments. Args: test (typing.Optional[typing.List[str]], optional): Commandline args for testing. Defaults to None. Returns: argparse.Namespace: Parsed data of args.
github-repos
def _VerifyValues(self, input_sizes=None, filter_sizes=None, strides=None, dilations=None, padding=None, data_format_src='NHWC', data_format_dst='NHWC', expected=None, op_name='Conv2D'): total_size_1 = np.prod(input_sizes) total_size_2 = np.prod(filter_sizes) x1 = np.arange(1, total_size_1 + 1, dtype=np.flo...
Tests that tf.nn.conv2d produces the expected value. Args: input_sizes: Input tensor dimensions in [batch, input_rows, input_cols, input_depth]. filter_sizes: Filter tensor dimensions in [kernel_rows, kernel_cols, input_depth, output_depth]. strides: Strides. dilations: RHS dilations. padding: Padding type. data_forma...
github-repos