code
stringlengths
20
4.93k
docstring
stringlengths
33
1.27k
source
stringclasses
3 values
def cacheResult(fn): cache = {} @functools.wraps(fn) def wrapper(*args, **kwargs): key = args + tuple(kwargs.items()) try: if key in cache: return cache[key] except TypeEr...
Method decorator: calculate the value on first access, produce the cached value thereafter. If the function takes arguments, the cache is a dictionary using all arguments as the key. Args: fn (method): function to decorate Returns: method: wrapper function with caching
juraj-google-style
def _FormatPackedIPv6Address(self, packed_ip_address): octet_pairs = zip(packed_ip_address[0::2], packed_ip_address[1::2]) octet_pairs = [octet1 << 8 | octet2 for octet1, octet2 in octet_pairs] return ':'.join([ '{0:04x}'.format(octet_pair) for octet_pair in octet_pairs])
Formats a packed IPv6 address as a human readable string. Args: packed_ip_address (list[int]): packed IPv6 address. Returns: str: human readable IPv6 address.
juraj-google-style
def _gen_ipython_string(func, args, defaults, original_doc): magic_string = ('%s(' % func.__name__) if defaults: default_offset = (len(args) - len(defaults)) else: default_offset = len(args) for (i, value) in enumerate(args): if (i >= default_offset): magic_string += ...
Provides auto-complete hint to ipython. If the first line in a docstring is fn(arg1=, arg2=) then they are added to auto-complete. This cannot be called on an instance method. Args: func: The function that will be modified. args: The arguments that this function takes in order. defaults: The default arguments corres...
codesearchnet
def register_for_auto_class(cls, auto_class='AutoTokenizer'): if not isinstance(auto_class, str): auto_class = auto_class.__name__ import transformers.models.auto as auto_module if not hasattr(auto_module, auto_class): raise ValueError(f'{auto_class} is not a valid auto class.') cls._aut...
Register this class with a given auto class. This should only be used for custom tokenizers as the ones in the library are already mapped with `AutoTokenizer`. Args: auto_class (`str` or `type`, *optional*, defaults to `"AutoTokenizer"`): The auto class to register this new tokenizer with.
github-repos
def pre_verify(method): @wraps(method) def wrapper(self, *args, **kwargs): self._verify_page() return method(self, *args, **kwargs) return wrapper
Decorator that calls self._verify_page() before executing the decorated method Args: method (callable): The method to decorate. Returns: Decorated method
juraj-google-style
def evaluate_extracted_tokens(gold_content, extr_content): if isinstance(gold_content, string_): gold_content = simple_tokenizer(gold_content) if isinstance(extr_content, string_): extr_content = simple_tokenizer(extr_content) gold_set = set(gold_content) extr_set = set(extr_content) ...
Evaluate the similarity between gold-standard and extracted content, typically for a single HTML document, as another way of evaluating the performance of an extractor model. Args: gold_content (str or Sequence[str]): Gold-standard content, either as a string or as an already-tokenized list of tokens. extr_content (st...
codesearchnet
def camelize(word): return ''.join(((w[0].upper() + w[1:]) for w in re.sub('[^A-Z^a-z^0-9^:]+', ' ', word).split(' ')))
Convert a word from lower_with_underscores to CamelCase. Args: word: The string to convert. Returns: The modified string.
codesearchnet
def is_common(schema): if isinstance(schema, StreamSchema): return schema.schema() in _SCHEMA_COMMON if isinstance(schema, CommonSchema): return True if isinstance(schema, basestring): return is_common(StreamSchema(schema)) return False
Is `schema` an common schema. Args: schema: Scheme to test. Returns: bool: ``True`` if schema is a common schema, otherwise ``False``.
juraj-google-style
def get_config(self): return {}
Returns a Python dict of the object config. A constraint config is a Python dictionary (JSON-serializable) that can be used to reinstantiate the same object. Returns: Python dict containing the configuration of the constraint object.
github-repos
def tpu_model_inference_fn(features): def custom_getter(getter, name, *args, **kwargs): with tf.control_dependencies(None): return tf.guarantee_const(getter(name, *args, **kwargs), name=(name + '/GuaranteeConst')) with tf.variable_scope('', custom_getter=custom_getter): t = int(time...
Builds the model graph suitable for running on TPU. It does two things: 1) Mark all weights as constant, which improves TPU inference performance because it prevents the weights being transferred to the TPU every call to Session.run(). 2) Adds constant to the graph with a unique value and marks it as a dependency on t...
codesearchnet
def compose_full_url(pub, uuid_url=False): url = compose_path(pub, uuid_url) if WEB_PORT == 80: return "%s: return "%s:
Compose full url for given `pub`, with protocol, server's address and port. Args: pub (obj): :class:`.DBPublication` instance. uuid_url (bool, default False): Compose URL using UUID. Returns: str: Absolute url of the publication. Raises: PrivatePublicationError: When the `pub` is private publication.
juraj-google-style
def cast(self, dtype: tf.DType) -> 'TensorFluent': if (self.dtype == dtype): return self t = tf.cast(self.tensor, dtype) scope = self.scope.as_list() batch = self.batch return TensorFluent(t, scope, batch=batch)
Returns a TensorFluent for the cast operation with given `dtype`. Args: dtype: The output's data type. Returns: A TensorFluent wrapping the cast operation.
codesearchnet
def match_as_dict(self, film_sl_vectors, substrate_sl_vectors, film_vectors, substrate_vectors, match_area): d = {} d["film_sl_vecs"] = np.asarray(film_sl_vectors) d["sub_sl_vecs"] = np.asarray(substrate_sl_vectors) d["match_area"] = match_area d["film_vecs"] = np.asarra...
Returns dict which contains ZSL match Args: film_miller(array) substrate_miller(array)
juraj-google-style
def mutate(self, dna: pg.DNA, global_state: pg.geno.AttributeDict, step: int=0) -> typing.Union[pg.DNA, List[pg.DNA]]: raise NotImplementedError()
Mutates the DNA at a given step. User should override this method or `mutate_list` method with optional keyword arguments 'global_state' and 'step'. Args: dna: DNA to mutate. global_state: An `AttributeDict` object as the container of global states. step: Number of examples historically proposed, which can be used fo...
github-repos
def migration_exchange(self, *, users: List[str], **kwargs) -> SlackResponse: kwargs.update({'users': users}) return self.api_call('migration.exchange', http_verb='GET', params=kwargs)
For Enterprise Grid workspaces, map local user IDs to global user IDs Args: users (list): A list of user ids, up to 400 per request. e.g. ['W1234567890', 'U2345678901', 'U3456789012']
codesearchnet
def search(self): safeEnvDict = {'freeSearch': self.freeSearch, 'extentSearch': self.extentSearch, 'indexSearch': self.indexSearch} for col in self._dataFrame.columns: safeEnvDict[col] = self._dataFrame[col] try: searchIndex = eval(self._filterString, {'__builtins__': None}, safeEnvDict) ...
Applies the filter to the stored dataframe. A safe environment dictionary will be created, which stores all allowed functions and attributes, which may be used for the filter. If any object in the given `filterString` could not be found in the dictionary, the filter does not apply and returns `False`. Returns: tuple:...
codesearchnet
def generate_state_data(means, weights): x_true = np.dot(means, weights) sample = np.random.poisson(x_true) return sample.astype(float)
Generates data according to the Poisson Convex Mixture Model. Args: means (array): Cell types- genes x clusters weights (array): Cell cluster assignments- clusters x cells Returns: data matrix - genes x cells
codesearchnet
def disasm(code, addr=0, syntax=None, target=None): if (target is None): target = pwnypack.target.target if (syntax is None): if (target.arch is pwnypack.target.Target.Arch.x86): syntax = AsmSyntax.nasm else: syntax = AsmSyntax.att if (syntax is AsmSyntax.nasm...
Disassemble machine readable code into human readable statements. Args: code(bytes): The machine code that is to be disassembled. addr(int): The memory address of the code (used for relative references). syntax(AsmSyntax): The output assembler syntax. This defaults to nasm on x86 architectures, AT&T on all other archi...
codesearchnet
def from_json(cls, data): required_keys = ('hum_type', 'hum_value') optional_keys = {'barometric_pressure': 101325, 'schedule': '', 'wet_bulb_range': ''} for key in required_keys: assert (key in data), 'Required key "{}" is missing!'.format(key) for (key, val) in optional_keys.items(): i...
Create a Humidity Condition from a dictionary. Args: data = { "hum_type": string, "hum_value": float, "barometric_pressure": float, "schedule": string, "wet_bulb_range": string}
codesearchnet
def _get_resized_lm_head_decoder(self, old_lm_head_decoder, new_num_tokens): new_lm_head_decoder = old_lm_head_decoder is_input_output_equals = tf.reduce_any(self._get_word_embedding_weight(self.get_input_embeddings()) == old_lm_head_decoder) if old_lm_head_decoder is not None and (not is_input_output_equal...
Build a resized decoder from the old ones. Increasing the size will add newly initialized vectors at the end. Reducing the size will remove vectors from the end Args: old_lm_head_decoder (`tf.Variable`): Old lm head decoder to be resized. new_num_tokens (`int`, *optional*): New number of tokens in the linear matrix. ...
github-repos
def __init__(self, initializer: tf.keras.initializers.Initializer=tf.keras.initializers.RandomUniform()): super().__init__() self._initializer = initializer
Initializes a VariableDot layer. Args: initializer: A `tf.keras.initializers.Initializer` which specifies how to initialize the values of the parameters.
github-repos
def _standardize_and_copy_config(config): kwargs = config.copy() for k, v in kwargs.items(): if isinstance(v, list): kwargs[k] = tuple(v) return kwargs
Returns a shallow copy of config with lists turned to tuples. Keras serialization uses nest to listify everything. This causes problems with the NumericColumn shape, which becomes unhashable. We could try to solve this on the Keras side, but that would require lots of tracking to avoid changing existing behavior. Inst...
github-repos
def _RunOsLoginNssCache(self): try: return subprocess.call([constants.OSLOGIN_NSS_CACHE_SCRIPT]) except OSError as e: if (e.errno == errno.ENOENT): return None else: raise
Run the OS Login NSS cache binary. Returns: int, the return code from the call, or None if the script is not found.
codesearchnet
def validate(self, nanopub: Mapping[(str, Any)]) -> Tuple[(bool, List[Tuple[(str, str)]])]: (is_valid, messages) = validate_to_schema(nanopub, self.nanopub_schema) if (not is_valid): return messages if (nanopub['nanopub']['type']['name'].upper() == 'BEL'): bel_version = nanopub['nanopub']['t...
Validates using the nanopub schema Args: nanopub (Mapping[str, Any]): nanopub dict Returns: Tuple[bool, List[Tuple[str, str]]]: bool: Is valid? Yes = True, No = False List[Tuple[str, str]]: Validation issues, empty if valid, tuple is ('ERROR|WARNING', msg) e.g. [('WARNING', "Context ID not found")]
codesearchnet
def expand(self, pcoll: beam.PCollection[Chunk]) -> beam.PTransform[Chunk, Any]: write_transform = self.database_config.create_write_transform() return pcoll | write_transform
Creates and applies the database-specific write transform. Args: pcoll: PCollection of Chunks with embeddings to write to the vector database. Each Chunk must have: - An embedding - An ID - Metadata used to filter results as specified by database config Returns: Result of writing to database (implementation specific)...
github-repos
def _set_avg_session_metrics(session_group): assert session_group.sessions, 'SessionGroup cannot be empty.' metric_stats = collections.defaultdict(_MetricStats) for session in session_group.sessions: for metric_value in session.metric_values: metric_name = _MetricIdentifier(group=metric_...
Sets the metrics for the group to be the average of its sessions. The resulting session group metrics consist of the union of metrics across the group's sessions. The value of each session group metric is the average of that metric values across the sessions in the group. The 'step' and 'wall_time_secs' fields of the ...
codesearchnet
def rprint(sep='\n', end='\n', file=sys.stdout, flush=False): try: first_item = (yield) file.write(str(first_item)) if flush: file.flush() while True: item = (yield) file.write(sep) file.write(str(item)) if flush: ...
A coroutine sink which prints received items stdout Args: sep: Optional separator to be printed between received items. end: Optional terminator to be printed after the last item. file: Optional stream to which to print. flush: Optional flag to force flushing after each item.
juraj-google-style
def upload(self, file_path, uri=None, timeout=(- 1)): if (not uri): uri = self._uri upload_file_name = os.path.basename(file_path) (task, entity) = self._connection.post_multipart_with_response_handling(uri, file_path, upload_file_name) if (not task): return entity return self._task_...
Makes a multipart request. Args: file_path: File to upload. uri: A specific URI (optional). 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: Response body.
codesearchnet
def to_grayscale(img, num_output_channels=1): if (not _is_pil_image(img)): raise TypeError('img should be PIL Image. Got {}'.format(type(img))) if (num_output_channels == 1): img = img.convert('L') elif (num_output_channels == 3): img = img.convert('L') np_img = np.array(img,...
Convert image to grayscale version of image. Args: img (PIL Image): Image to be converted to grayscale. Returns: PIL Image: Grayscale version of the image. if num_output_channels = 1 : returned image is single channel if num_output_channels = 3 : returned image is 3 channel with r = g = b
codesearchnet
def usufyToXlsExport(d, fPath): from pyexcel_xls import get_data try: oldData = {'OSRFramework': get_data(fPath)} except: oldData = {'OSRFramework': []} tabularData = _generateTabularData(d, oldData) from pyexcel_xls import save_data save_data(fPath, tabularData)
Workaround to export to a .xls file. Args: ----- d: Data to export. fPath: File path for the output file.
codesearchnet
def stack(list_or_tensor, element_dtype=None, strict=True): if strict: def raise_error(x): raise ValueError('%s must be stackable when strict=True' % x) original_call = raise_error else: original_call = lambda x: x return data_structures.list_stack(list_or_tensor, data_s...
Stacks the input, if it admits the notion of stacking. For example, a list of tensors can be stacked into a larger tensor. This function is similar to tf.stack, but it accepts non-lists and lists of non-tensors as arguments. In the latter case, the function does nothing. Args: list_or_tensor: Any element_dtype: tf.DT...
github-repos
def save(self, path, compressed=True, exist_ok=False): path = os.path.expandvars(os.path.expanduser(path)) if (os.path.isfile(path) and (not exist_ok)): raise OSError(17, os.strerror(17), path) if os.path.isdir(path): path = os.path.join(path, 'out.gdg') if compressed: bytes_writ...
Save the GADDAG to file. Args: path: path to save the GADDAG to. compressed: compress the saved GADDAG using gzip. exist_ok: overwrite existing file at `path`.
codesearchnet
def arg_types(parsed: Parsed, errors: Errors) -> Tuple[Parsed, Errors]: func_pattern = re.compile(r"\s*[a-zA-Z]+\(") nsarg_pattern = re.compile(r"^\s*([A-Z]+):(.*?)\s*$") for span in parsed: if parsed[span]["type"] != "Function" or "parens_span" not in parsed[span]: continue ...
Add argument types to parsed function data structure Args: parsed: function and arg locations in BEL string errors: error messages Returns: (parsed, errors): parsed, arguments with arg types plus error messages
juraj-google-style
def gpu(self: EagerTensorType, gpu_index=0) -> EagerTensorType: return self._copy(context.context(), 'GPU:' + str(gpu_index))
A copy of this Tensor with contents backed by memory on the GPU. Args: gpu_index: Identifies which GPU to place the contents on the returned Tensor in. Returns: A GPU-memory backed Tensor object initialized with the same contents as this Tensor.
github-repos
def _get_password_url(self): password_url = None if (self._settings['user'] or self._settings['authorization']): if self._settings['url']: password_url = self._settings['url'] elif self._settings['base_url']: password_url = self._settings['base_url'] return password_u...
Get URL used for authentication Returns: string: URL
codesearchnet
def get_structure_seqs(self, model): dont_overwrite = [] chains = list(model.get_chains()) for x in chains: if self.chains.has_id(x.id): if self.chains.get_by_id(x.id).seq_record: dont_overwrite.append(x.id) if len(dont_o...
Gather chain sequences and store in their corresponding ``ChainProp`` objects in the ``chains`` attribute. Args: model (Model): Biopython Model object of the structure you would like to parse
juraj-google-style
def _compute_args(self, data=dict(), **kwargs): for name, remote_attribute in self._attributes.items(): default_value = BambouConfig.get_default_attribute_value(self.__class__, name, remote_attribute.attribute_type) setattr(self, name, default_value) if len(data) > 0: ...
Compute the arguments Try to import attributes from data. Otherwise compute kwargs arguments. Args: data: a dict() kwargs: a list of arguments
juraj-google-style
def contextmanager(target: Callable[..., Iterator[_T]]) -> Callable[..., ContextManager[_T]]: context_manager = _contextlib.contextmanager(target) return tf_decorator.make_decorator(target, context_manager, 'contextmanager')
A tf_decorator-aware wrapper for `contextlib.contextmanager`. Usage is identical to `contextlib.contextmanager`. Args: target: A callable to be wrapped in a contextmanager. Returns: A callable that can be used inside of a `with` statement.
github-repos
def __init__(self, given, enum_type, options): super(InvalidEnumValue, self).__init__('Could not parse [{0}] into a valid {1}. Valid values are [{2}]'.format(given, enum_type, ', '.join(options)))
Constructs a new exception. Args: given: str, The given string that could not be parsed. enum_type: str, The human readable name of the enum you were trying to parse. options: list(str), The valid values for this enum.
github-repos
def infer_pyarrow_schema(data): column_data = OrderedDict() for row in data: for key, value in row.items(): column_data.setdefault(key, []).append(value) column_types = OrderedDict([(key, pa.array(value).type) for key, value in column_data.items()]) return pa.schema(list(column_types...
For internal use only; no backwards-compatibility guarantees. Infer PyArrow schema for tabular data. Args: data (List[dict]): A list of dictionaries representing rows in a table. Returns: A PyArrow schema object.
github-repos
def _flatten_location_translations(location_translations): sources_to_process = set(six.iterkeys(location_translations)) def _update_translation(source): 'Return the proper (fully-flattened) translation for the given location.' destination = location_translations[source] if (destination...
If location A translates to B, and B to C, then make A translate directly to C. Args: location_translations: dict of Location -> Location, where the key translates to the value. Mutated in place for efficiency and simplicity of implementation.
codesearchnet
def Reformat(llines, lines=None): final_lines = [] prev_line = None indent_width = style.Get('INDENT_WIDTH') for lline in _SingleOrMergedLines(llines): first_token = lline.first _FormatFirstToken(first_token, lline.depth, prev_line, final_lines) indent_amt = indent_width * lline....
Reformat the logical lines. Arguments: llines: (list of logical_line.LogicalLine) Lines we want to format. lines: (set of int) The lines which can be modified or None if there is no line range restriction. Returns: A string representing the reformatted code.
github-repos
def assembly(self, value): if value == self._defaults['assembly'] and 'assembly' in self._values: del self._values['assembly'] else: self._values['assembly'] = value
The assembly property. Args: value (string). the property value.
juraj-google-style
def make_report_table(fp, title, reports): reports.sort(key=lambda x: x[1]['tflite_converter'], reverse=False) reports.sort(key=lambda x: x[1]['tf'], reverse=True) def result_cell(x, row, col): s = html.escape(repr(x), quote=True) color = ' handler = 'ShowLog(%d, %d)' % (ro...
Make an HTML report of the success/failure reports. Args: fp: File-like object in which to put the html. title: "Title of the zip file this pertains to." reports: a list of conversion attempts. (report_args, report_vals) i.e. ({"shape": [1,2,3], "type": "tf.float32"}, {"tf": "SUCCESS", "tflite_converter": "FAILURE", "...
github-repos
def env(mounts): f_mounts = [m.strip('/') for m in mounts] root = local.path('/') ld_libs = [((root / m) / 'lib') for m in f_mounts] ld_libs.extend([((root / m) / 'lib64') for m in f_mounts]) paths = [((root / m) / 'bin') for m in f_mounts] paths.extend([((root / m) / 'sbin') for m in f_mounts])...
Compute the environment of the change root for the user. Args: mounts: The mountpoints of the current user. Return: paths ld_libs
codesearchnet
def get_point_index(self, point): for (i, segment) in enumerate(self.segments): idx = segment.getPointIndex(point) if (idx != (- 1)): return (i, idx) return ((- 1), (- 1))
Gets of the closest first point Args: point (:obj:`Point`) Returns: (int, int): Segment id and point index in that segment
codesearchnet
def set_default_by_index(self, index): if index >= len(self._datasets): raise DataInvalidIndex('A dataset with index {} does not exist'.format(index)) self._default_index = index
Set the default dataset by its index. After changing the default dataset, all calls without explicitly specifying the dataset by index or alias will be redirected to this dataset. Args: index (int): The index of the dataset that should be made the default. Raises: DataInvalidIndex: If the index does not represent a ...
juraj-google-style
def setup_modules(self, args): def _setup_module_thread(module_description): new_args = utils.import_args_from_dict( module_description['args'], vars(args), self.config) module = self._module_pool[module_description['name']] try: module.setup(**new_args) except...
Performs setup tasks for each module in the module pool. Threads declared modules' setup() functions. Takes CLI arguments into account when replacing recipe parameters for each module. Args: args: Command line arguments that will be used to replace the parameters declared in the recipe.
juraj-google-style
def from_encoder_decoder_configs(cls, encoder_config: PretrainedConfig, decoder_config: PretrainedConfig, **kwargs) -> PretrainedConfig: logger.info('Setting `config.is_decoder=True` and `config.add_cross_attention=True` for decoder_config') decoder_config.is_decoder = True decoder_config.add_cross_attentio...
Instantiate a [`VisionEncoderDecoderConfig`] (or a derived class) from a pre-trained encoder model configuration and decoder model configuration. Returns: [`VisionEncoderDecoderConfig`]: An instance of a configuration object
github-repos
def check_version(self, node_id=None, timeout=2, strict=False): self._lock.acquire() end = (time.time() + timeout) while (time.time() < end): try_node = (node_id or self.least_loaded_node()) if (try_node is None): self._lock.release() raise Errors.NoBrokersAvailable()...
Attempt to guess the version of a Kafka broker. Note: It is possible that this method blocks longer than the specified timeout. This can happen if the entire cluster is down and the client enters a bootstrap backoff sleep. This is only possible if node_id is None. Returns: version tuple, i.e. (0, 10), (0, 9), (0, 8, ...
codesearchnet
def send(self, response): self._connection.connection.set('{}:{}'.format(SIGNAL_REDIS_PREFIX, response.uid), pickle.dumps(response))
Send a response back to the client that issued a request. Args: response (Response): Reference to the response object that should be sent.
codesearchnet
def get_config_parameter_boolean(config: ConfigParser, section: str, param: str, default: bool) -> bool: try: value = config.getboolean(section, param) except (TypeError, ValueError, NoOptionError): ...
Get Boolean parameter from ``configparser`` ``.INI`` file. Args: config: :class:`ConfigParser` object section: section name within config file param: name of parameter within section default: default value Returns: parameter value, or default
juraj-google-style
def is_github_task(task): return any(((task.get('schedulerId') == 'taskcluster-github'), task.get('extra', {}).get('tasks_for', '').startswith('github-'), is_github_url(task.get('metadata', {}).get('source', ''))))
Determine if a task is related to GitHub. This function currently looks into the ``schedulerId``, ``extra.tasks_for``, and ``metadata.source``. Args: task (dict): the task definition to check. Returns: bool: True if a piece of data refers to GitHub
codesearchnet
def __init__(self, base_object=None, query=None): if not query: raise errors.FormatError('Missing query value.') super(WMIQuerySourceType, self).__init__() self.base_object = base_object self.query = query
Initializes a source type. Args: base_object (Optional[str]): WMI base object. query (Optional[str]): WMI query. Raises: FormatError: when query is not set.
juraj-google-style
def save_to_file(self, filename, remap_dim0=None, remap_dim1=None): with open(filename, 'w') as fobj: columns = list(sorted(self._dim1)) for col in columns: fobj.write(',') fobj.write(str((remap_dim1[col] if remap_dim1 else col))) fobj.write('\n') for row in s...
Saves matrix to the file. Args: filename: name of the file where to save matrix remap_dim0: dictionary with mapping row indices to row names which should be saved to file. If none then indices will be used as names. remap_dim1: dictionary with mapping column indices to column names which should be saved to file. If no...
codesearchnet
def __getitem__(self, key): if not isinstance(key, basestring): raise Exception("LRU cache can only be indexed by strings (%s has type %s)" % (str(key), str(type(key)))) if key in self._cache: entry = self._cache[key] entry['last_used'] = datetime.datetime.now() ...
Get an item from the cache. Args: key: a string used as the lookup key. Returns: The cached item, if any. Raises: Exception if the key is not a string. KeyError if the key is not found.
juraj-google-style
def GetEntries( self, parser_mediator, cookie_data=None, url=None, **kwargs): fields = cookie_data.split('.') number_of_fields = len(fields) if number_of_fields > 5: variables = '.'.join(fields[4:]) fields = fields[0:4] fields.append(variables) number_of_fields = len(fiel...
Extracts event objects from the cookie. Args: parser_mediator (ParserMediator): parser mediator. cookie_data (str): cookie data. url (str): URL or path where the cookie got set.
juraj-google-style
def gnuplot(script_name, args_dict={}, data=[], silent=True): gnuplot_command = 'gnuplot' if data: assert ('data' not in args_dict), "Can't use 'data' variable twice." data_temp = _GnuplotDataTemp(*data) args_dict['data'] = data_temp.name if args_dict: gnuplot_command += ' -e...
Call a Gnuplot script, passing it arguments and datasets. Args: scipt_name(str): The name of the Gnuplot script. args_dict(dict): A dictionary of parameters to pass to the script. The `key` is the name of the variable that the `item` will be passed to the Gnuplot script with. data(list): A list of lists containing li...
codesearchnet
def MakeJoint(pmf1, pmf2): joint = Joint() for v1, p1 in pmf1.Items(): for v2, p2 in pmf2.Items(): joint.Set((v1, v2), p1 * p2) return joint
Joint distribution of values from pmf1 and pmf2. Args: pmf1: Pmf object pmf2: Pmf object Returns: Joint pmf of value pairs
juraj-google-style
def case_study_social_link_facebook(value): parsed = parse.urlparse(value.lower()) if not parsed.netloc.endswith('facebook.com'): raise ValidationError(MESSAGE_NOT_FACEBOOK)
Confirms that the social media url is pointed at the correct domain. Args: value (string): The url to check. Raises: django.forms.ValidationError
juraj-google-style
def get_file_path(self, digest): relPath = Fsdb.generate_tree_path(digest, self._conf['depth']) return os.path.join(self.fsdbRoot, relPath)
Retrieve the absolute path to the file with the given digest Args: digest -- digest of the file Returns: String rapresenting the absolute path of the file
codesearchnet
def instrument(self, package, options=None, runner=None, handler=None): if (runner is None): runner = DEFAULT_INSTRUMENTATION_RUNNER if (options is None): options = {} options_list = [] for (option_key, option_value) in options.items(): options_list.append(('-e %s %s' % (option_k...
Runs an instrumentation command on the device. This is a convenience wrapper to avoid parameter formatting. Example: .. code-block:: python device.instrument( 'com.my.package.test', options = { 'class': 'com.my.package.test.TestSuite', }, ) Args: package: string, the package of the instrumentation tests. options: ...
codesearchnet
def _list(self, dir_or_prefix): try: for path, (size, updated) in self._blobstorageIO().list_files(dir_or_prefix, with_metadata=True): yield FileMetadata(path, size, updated) except Exception as e: raise BeamIOError('List operation failed', {dir_or_prefix: e})
List files in a location. Listing is non-recursive (for filesystems that support directories). Args: dir_or_prefix: (string) A directory or location prefix (for filesystems that don't have directories). Returns: Generator of ``FileMetadata`` objects. Raises: ``BeamIOError``: if listing fails, but not if no files were f...
github-repos
def contacts(self, *args, **kwargs): n = Contacts.read_cellframe(self, prune_neighbors=True) if ('measured_regions' in kwargs): n.measured_regions = kwargs['measured_regions'] else: n.measured_regions = self.get_measured_regions() if ('measured_phenotypes' in kwargs): n.measured_...
Use assess the cell-to-cell contacts recorded in the celldataframe Returns: Contacts: returns a class that holds cell-to-cell contact information for whatever phenotypes were in the CellDataFrame before execution.
codesearchnet
def load_config(self, config): for (k, v) in config.items(): if hasattr(self, k): raise DeviceError(self, ('Attribute %s already exists with value %s, cannot set again.' % (k, getattr(self, k)))) setattr(self, k, v)
Add attributes to the AndroidDevice object based on config. Args: config: A dictionary representing the configs. Raises: Error: The config is trying to overwrite an existing attribute.
codesearchnet
def _detect(self): results = [] self.results = [] self.visited_all_paths = {} for contract in self.slither.contracts: for function in contract.functions: if function.is_implemented: uninitialized_storage_variables = [v for v in function.local_variables if (v.is_storag...
Detect uninitialized storage variables Recursively visit the calls Returns: dict: [contract name] = set(storage variable uninitialized)
codesearchnet
def _Execute(statements, context, callback, trace): if trace: trace.exec_depth += 1 for i, statement in enumerate(statements): if isinstance(statement, six.string_types): callback(statement) else: try: func, args...
Execute a bunch of template statements in a ScopedContext. Args: callback: Strings are "written" to this callback function. trace: Trace object, or None This is called in a mutually recursive fashion.
juraj-google-style
def update_variant_compounds(self, variant, variant_objs=None): compound_objs = [] for compound in variant.get('compounds', []): not_loaded = True gene_objs = [] if variant_objs: variant_obj = variant_objs.get(compound['variant']) else: variant_obj = self....
Update compounds for a variant. This will add all the necessary information of a variant on a compound object. Args: variant(scout.models.Variant) variant_objs(dict): A dictionary with _ids as keys and variant objs as values. Returns: compound_objs(list(dict)): A dictionary with updated compound objects.
codesearchnet
def image_needs_building(image): d = docker_client() try: d.images.get(image) except docker.errors.ImageNotFound: pass else: return False return image_needs_pushing(image)
Return whether an image needs building Checks if the image exists (ignores commit range), either locally or on the registry. Args: image (str): the `repository:tag` image to be build. Returns: True: if image needs to be built False: if not (image already exists)
codesearchnet
def set_hostname(hostname=None, deploy=False): if not hostname: raise CommandExecutionError("Hostname option must not be none.") ret = {} query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system...
Set the hostname of the Palo Alto proxy minion. A commit will be required before this is processed. CLI Example: Args: hostname (str): The hostname to set deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' panos.set_hostname newhostn...
juraj-google-style
def create_software_renderer(self, surface): renderer = object.__new__(Renderer) renderer._ptr = self._ptr = check_ptr_err(lib.SDL_CreateSoftwareRenderer(surface._ptr)) return renderer
Create a 2D software rendering context for a surface. Args: surface (Surface): The surface where rendering is done. Returns: Renderer: A 2D software rendering context. Raises: SDLError: If there was an error creating the renderer.
codesearchnet
def delete(self, *args, **kwargs): api = Api() api.authenticate() api.delete_video(self.video_id) return super(Video, self).delete(*args, **kwargs)
Deletes the video from youtube Raises: OperationError
codesearchnet
def SetDecryptedStreamSize(self, decrypted_stream_size): if self._is_open: raise IOError('Already open.') if (decrypted_stream_size < 0): raise ValueError('Invalid decrypted stream size: {0:d} value out of bounds.'.format(decrypted_stream_size)) self._decrypted_stream_size = decrypted_stream...
Sets the decrypted stream size. This function is used to set the decrypted stream size if it can be determined separately. Args: decrypted_stream_size (int): size of the decrypted stream in bytes. Raises: IOError: if the file-like object is already open. OSError: if the file-like object is already open. ValueError: ...
codesearchnet
def range(cls, start=None, stop=None, step=None, inclusive=False): def sign(x): 'Inner function for determining the sign of a float\n ' return ((- 1), 1)[(x >= 0)] if (not step): raise ValueError('Null step') if isinstance(stop, timedelta): stop = (start + stop) ...
Generator of a date range Args: start (Date): stop (Date or datetime.timedelta)! step (timedelta): Keyword Args: inclusive (bool): If ``False``, the stopping date is not included. This is the same behavior as the built-in :py:func:`range`. Yield: Date:
codesearchnet
def _buckets(data, bucket_count=None): import tensorflow.compat.v1 as tf if bucket_count is None: bucket_count = summary_v2.DEFAULT_BUCKET_COUNT with tf.name_scope('buckets', values=[data, bucket_count]), \ tf.control_dependencies([tf.assert_scalar(bucket_count), t...
Create a TensorFlow op to group data into histogram buckets. Arguments: data: A `Tensor` of any shape. Must be castable to `float64`. bucket_count: Optional positive `int` or scalar `int32` `Tensor`. Returns: A `Tensor` of shape `[k, 3]` and type `float64`. The `i`th row is a triple `[left_edge, right_edge, count]` fo...
juraj-google-style
def get_header(vcf_file_path): logger.info("Parsing header of file {0}".format(vcf_file_path)) head = HeaderParser() handle = get_vcf_handle(infile=vcf_file_path) for line in handle: line = line.rstrip() if line.startswith(' if line.startswith(' head...
Parse the header and return a header object Args: vcf_file_path(str): Path to vcf Returns: head: A HeaderParser object
juraj-google-style
def set_tensor_shapes(tensors, shapes): if shapes: tensor_names_to_tensor = {get_tensor_name(tensor): tensor for tensor in tensors} for name, shape in shapes.items(): if name not in tensor_names_to_tensor: raise ValueError("Invalid tensor '{}' found in tensor shapes map."...
Sets Tensor shape for each tensor if the shape is defined. Args: tensors: TensorFlow tensor.Tensor. shapes: Dict of strings representing input tensor names to list of integers representing input shapes (e.g., {"foo": : [1, 16, 16, 3]}). Raises: ValueError: `shapes` contains an invalid tensor. `shapes` contains an inv...
github-repos
def iter_variants(self): for variant in self.repository.iter_variants(self.resource): (yield Variant(variant, context=self.context, parent=self))
Iterate over the variants within this package, in index order. Returns: `Variant` iterator.
codesearchnet
def _on_notification_received(self, success, result, failure_reason): if not success: self._logger.info("Notification received with failure failure_reason=%s", failure_reason) notification_id = (result['connection_handle'], result['attribute_handle']) callback = None ...
Callback function called when a notification has been received. It is executed in the baBLE working thread: should not be blocking. Args: success (bool): A bool indicating that the operation is successful or not result (dict): The notification information - value (bytes): Data notified failure_reason (any): An object ...
juraj-google-style
def ParseRecord(self, parser_mediator, key, structure): if (key != 'log_entry'): raise errors.ParseError('Unable to parse record, unknown structure: {0:s}'.format(key)) event_data = BashHistoryEventData() event_data.command = structure.command date_time = dfdatetime_posix_time.PosixTime(timestam...
Parses a record and produces a Bash history event. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. key (str): name of the parsed structure. structure (pyparsing.ParseResults): elements parsed from the file. Raises: ParseError: when the str...
codesearchnet
def complete(self, default_output=None): if not self.async: raise UnexpectedPipelineError( 'May only call complete() method for asynchronous pipelines.') self._context.fill_slot( self._pipeline_key, self.outputs.default, default_output)
Marks this asynchronous Pipeline as complete. Args: default_output: What value the 'default' output slot should be assigned. Raises: UnexpectedPipelineError if the slot no longer exists or this method was called for a pipeline that is not async.
juraj-google-style
def delete(self, filething=None): self.tags.clear() self.save(filething, padding=lambda x: 0)
delete(filething=None) Args: filething (filething) Raises: mutagen.MutagenError
juraj-google-style
def handleresult(self, r): if r.status_code >= 400 and r.status_code < 500: msg = r.json() raise AuthenticationError(str(msg["code"]) + ": " + msg["msg"] + " (" + msg["ref"] + ")") elif r.status_code > 300: err = None ...
Handles HTTP error codes for the given request Raises: AuthenticationError on the appropriate 4** errors ServerError if the response is not an ok (2**) Arguments: r -- The request result
juraj-google-style
def _ExtractRequestSummaryFields(self, request, error=None): headers = request.headers summary_fields = {'server': request.get_full_url(), 'contentRange': headers['Content-range'], 'contentLength': headers['Content-length']} if error: summary_fields['isError'] = True summary_fields['errorMes...
Extract fields used in the summary logs. Args: request: a urllib2.Request instance configured to make the request. [optional] error: a urllib2.HttpError instance used to retrieve error details. Returns: A dict containing the fields to be output in the summary logs.
codesearchnet
def cap17(msg): allbds = ['05', '06', '07', '08', '09', '0A', '20', '21', '40', '41', '42', '43', '44', '45', '48', '50', '51', '52', '53', '54', '55', '56', '5F', '60', 'NA', 'NA', 'E1', 'E2'] d = hex2bin(data(msg)) idx = [i for (i, v) in enumerate(d[:28]) if (v == '1')] capacity = [('BDS' + allbds[i])...
Extract capacities from BDS 1,7 message Args: msg (String): 28 bytes hexadecimal message string Returns: list: list of suport BDS codes
codesearchnet
def cancel(self, **kwargs): path = '%s/%s/cancel' % (self.manager.path, self.get_id()) self.manager.gitlab.http_post(path)
Cancel the job. Args: **kwargs: Extra options to send to the server (e.g. sudo) Raises: GitlabAuthenticationError: If authentication is not correct GitlabJobCancelError: If the job could not be canceled
juraj-google-style
def put(cls, obj): return PyarrowOnRayFramePartition(ray.put(pyarrow.Table.from_pandas(obj)))
Put an object in the Plasma store and wrap it in this object. Args: obj: The object to be put. Returns: A `RayRemotePartition` object.
codesearchnet
def set_bias(self, bias): self.x_offset += (bias - self._bias) self._bias = bias self._build_cdict()
Adjusts the image bias. Bias determines where the color changes start. At low bias, low intensities (i.e., low pixel values) will have non-zero color differences, while at high bias only high pixel values will have non-zero differences Args: bias: float A number between 0 and 1. Note that upon initialization the co...
juraj-google-style
def set_key(self, structure_prefix, key_line): self._empty = False key_value = self._remove_structure_prefix(structure_prefix, key_line) if '=' in key_value: key, value = key_value.split('=', 1) self.current_key = key if key in self.known_keys: self.known_keys[key].append...
Sets the current key for the instrumentation block. For unknown keys, the key is added to the value list in order to better contextualize the value in the output. Args: structure_prefix: string, the structure prefix that was matched and that needs to be removed. key_line: string, the raw instrumentation output line t...
github-repos
def _splitGenoSlidingWindow(self,size=5e4,step=None,minSnps=1.,maxSnps=SP.inf): if step is None: step = 0.5*size chroms = SP.unique(self.chrom) wnd_pos = [] idx_wnd_start = [] nSnps = [] wnd_i = 0 nSnps = [] for chrom_i in chrom...
split into windows using a slide criterion Args: size: window size step: moving step (default: 0.5*size) minSnps: only windows with nSnps>=minSnps are considered maxSnps: only windows with nSnps>=maxSnps are considered
juraj-google-style
def global_horizontal_radiation(self, value=9999.0): if (value is not None): try: value = float(value) except ValueError: raise ValueError('value {} need to be of type float for field `global_horizontal_radiation`'.format(value)) if (value < 0.0): raise Va...
Corresponds to IDD Field `global_horizontal_radiation` Args: value (float): value for IDD Field `global_horizontal_radiation` Unit: Wh/m2 value >= 0.0 Missing value: 9999.0 if `value` is None it will not be checked against the specification and is assumed to be a missing value Raises: ValueError: if `value` is not a ...
codesearchnet
def JoinPath(stem='', *parts): parts = [SmartUnicode(path) for path in parts] result = (stem + NormalizePath(u'/'.join(parts))).replace(' result = result.rstrip('/') return (result or '/')
A sane version of os.path.join. The intention here is to append the stem to the path. The standard module removes the path if the stem begins with a /. Args: stem: The stem to join to. *parts: parts of the path to join. The first arg is always the root and directory traversal is not allowed. Returns: a normalized pa...
codesearchnet
def conv2d_transpose(x, kernel, output_shape, strides=(1, 1), padding='valid', data_format=None, dilation_rate=(1, 1)): if data_format is None: data_format = image_data_format() if data_format not in {'channels_first', 'channels_last'}: raise ValueError('Unknown data_format: ' + str(data_format)...
2D deconvolution (i.e. transposed convolution). Args: x: Tensor or variable. kernel: kernel tensor. output_shape: 1D int tensor for the output shape. strides: strides tuple. padding: string, `"same"` or `"valid"`. data_format: string, `"channels_last"` or `"channels_first"`. dilation_rate: Tuple of 2 integers. Retur...
github-repos
def map_creative_and_association_feeds(self, creative_feed, creative_association_feed): for creative in creative_feed: creative['associations'] = [association for association in creative_association_feed if self._assignment_matches(creative, association)]
Maps creative association feed to the corresponding creative. Creative association is a child object to the creative, and there is a 1 creative to many creative association relationship. In Bulkdozer they are represented by two separate tab in the feed, and this method maps the creatives to their respective creative a...
github-repos
def get_read_write_resource_inputs(op): reads = object_identity.ObjectIdentitySet() writes = object_identity.ObjectIdentitySet() if op.type in RESOURCE_READ_OPS: reads.update((t for t in op.inputs if t.dtype == dtypes.resource)) return (reads, writes) try: read_only_input_indices...
Returns a tuple of resource reads, writes in op.inputs. Args: op: Operation Returns: A 2-tuple of ObjectIdentitySets, the first entry containing read-only resource handles and the second containing read-write resource handles in `op.inputs`.
github-repos
def refer(self, text): data = self.reply(text) data['refer_key'] = self['key'] return data
Refers current message and replys a new message Args: text(str): message content Returns: RTMMessage
juraj-google-style
def get_optional_artifacts_per_task_id(upstream_artifacts): optional_artifacts_per_task_id = {} for artifact_definition in upstream_artifacts: if (artifact_definition.get('optional', False) is True): task_id = artifact_definition['taskId'] artifacts_paths = artifact_definition['p...
Return every optional artifact defined in ``upstream_artifacts``, ordered by taskId. Args: upstream_artifacts: the list of upstream artifact definitions Returns: dict: list of paths to downloaded artifacts ordered by taskId
codesearchnet
def check_satpy(readers=None, writers=None, extras=None): from satpy.readers import configs_for_reader from satpy.writers import configs_for_writer print('Readers') print('=======') for (reader, res) in sorted(check_yaml_configs(configs_for_reader(reader=readers), 'reader').items()): print((...
Check the satpy readers and writers for correct installation. Args: readers (list or None): Limit readers checked to those specified writers (list or None): Limit writers checked to those specified extras (list or None): Limit extras checked to those specified Returns: bool True if all specified features were success...
codesearchnet
def cluster_spec(self): task_list = [] self._gpu_allocation = [] self._cluster_allocation = {} for host, num_tasks in sorted(self._task_configuration.items()): for port_offset, gpu_offset in zip(range(num_tasks), range(0, self._gpus_per_node, self._gpus_per_task)): host_addr = '%s:%d...
Returns a ClusterSpec object based on the latest instance group info. This returns a ClusterSpec object for use based on information from the specified initialization parameters and Slurm environment variables. The cluster specification is resolved each time this function is called. The resolver extract hostnames of n...
github-repos
def create_keyvault(access_token, subscription_id, rgname, vault_name, location, template_deployment=True, tenant_id=None, object_id=None): endpoint = ''.join([get_rm_endpoint(), '/subscriptions/', subscription_id, '/resourcegroups/', rgname, '/providers/Microsoft.KeyVault/vaults/', vault_name, '?api-version=', KEY...
Create a new key vault in the named resource group. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. rgname (str): Azure resource group name. vault_name (str): Name of the new key vault. location (str): Azure data center location. E.g. westus2. template_deploy...
codesearchnet