code
stringlengths
20
4.93k
docstring
stringlengths
33
1.27k
source
stringclasses
3 values
def as_qubit_order(val: 'qubit_order_or_list.QubitOrderOrList' ) -> 'QubitOrder': if isinstance(val, collections.Iterable): return QubitOrder.explicit(val) if isinstance(val, QubitOrder): return val raise ValueError( "Don't know...
Converts a value into a basis. Args: val: An iterable or a basis. Returns: The basis implied by the value.
juraj-google-style
def get_all_prefixes(module_name): parts = module_name.split('.') name = parts[0] out = [name] for part in parts[1:]: name = '.'.join([name, part]) out.append(name) return out
Return all the prefixes of a module name. e.g. x.y.z => x, x.y, x.y.z Args: module_name: module name Returns: List of prefixes
github-repos
def run_multiple_processes(args_list: List[List[str]], die_on_failure: bool = True) -> None: for procargs in args_list: start_process(procargs) wait_for_processes(die_on_failure=die_on_failure)
Fire up multiple processes, and wait for them to finihs. Args: args_list: command arguments for each process die_on_failure: see :func:`wait_for_processes`
juraj-google-style
def _log_band_edge_information(bs, edge_data): if bs.is_spin_polarized: spins = edge_data['band_index'].keys() b_indices = [(', '.join([str((i + 1)) for i in edge_data['band_index'][spin]]) + '({})'.format(spin.name.capitalize())) for spin in spins] b_indices = ', '.join(b_indices) else:...
Log data about the valence band maximum or conduction band minimum. Args: bs (:obj:`~pymatgen.electronic_structure.bandstructure.BandStructureSymmLine`): The band structure. edge_data (dict): The :obj:`dict` from ``bs.get_vbm()`` or ``bs.get_cbm()``
codesearchnet
def db_ws010c(self, value=None): if (value is not None): try: value = float(value) except ValueError: raise ValueError('value {} need to be of type float for field `db_ws010c`'.format(value)) self._db_ws010c = value
Corresponds to IDD Field `db_ws010c` Mean coincident dry-bulb temperature to wind speed corresponding to 1.0% cumulative frequency for coldest month Args: value (float): value for IDD Field `db_ws010c` Unit: C if `value` is None it will not be checked against the specification and is assumed to be a missing value Rai...
codesearchnet
def _VerifyValues(self, tensor_in_sizes, glimpse_sizes, offsets, expected_rows, expected_cols): rows = tensor_in_sizes[0] cols = tensor_in_sizes[1] t_rows = array_ops.tile([[1.0 * r] for r in range(1, rows + 1)], [1, cols], name='tile_rows') t_rows_4d = array_ops.transpose(array_ops.expand_dims(array_op...
Verifies the output values of the glimpse extraction kernel. Args: tensor_in_sizes: Input tensor dimensions in [input_rows, input_cols]. glimpse_sizes: Dimensions of the glimpse in [glimpse_rows, glimpse_cols]. offsets: Relative location of the center of the glimpse in the input image expressed as [row_offset, col_off...
github-repos
def ParseAutofillRow(self, parser_mediator, query, row, **unused_kwargs): query_hash = hash(query) event_data = ChromeAutofillEventData() event_data.field_name = self._GetRowValue(query_hash, row, 'name') event_data.value = self._GetRowValue(query_hash, row, 'value') event_data.usage_count = self._G...
Parses an autofill entry 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.
codesearchnet
def load_subset_weights_from_hdf5_group(f): weight_names = load_attributes_from_hdf5_group(f, 'weight_names') return [np.asarray(f[weight_name]) for weight_name in weight_names]
Load layer weights of a model from hdf5. Args: f: A pointer to a HDF5 group. Returns: List of NumPy arrays of the weight values. Raises: ValueError: in case of mismatch between provided model and weights file.
github-repos
def get_storage_pools(self, id_or_uri): uri = self._client.build_uri(id_or_uri) + "/storage-pools" return self._client.get(uri)
Gets a list of Storage pools. Returns a list of storage pools belonging to the storage system referred by the Path property {ID} parameter or URI. Args: id_or_uri: Can be either the storage system ID (serial number) or the storage system URI. Returns: dict: Host types.
juraj-google-style
def update(self, token_id: int): raise NotImplementedError(f'{self.__class__} is an abstract class. Only classes inheriting this class can be called.')
Reads in a token and returns booleans that indicate the progress made by it. This function will update the state of this object unlikes `does_advance(self, token_id: int)`. This isn't to test whether a certain token will advance the progress; it's to update its state as if it has been generated. This becomes important...
github-repos
def update_shapes_dict_for_target_fn(target_fn, shapes_dict, call_spec, class_name): if utils.is_default(target_fn): return None sig = inspect.signature(target_fn) expected_names = [] for name, param in sig.parameters.items(): if param.kind in (param.POSITIONAL_OR_KEYWORD, param.POSITION...
Updates a `shapes_dict` for `build()` or `compute_output_shape()`. This function will align a dictionary of the shapes of all tensor passed to `call`, with the signatures of `build()` or `compute_output_shape()`. The alignment is a follows: - If `build()` or `compute_output_shape()` accept only one argument, forward...
github-repos
def is_cpu(self): return (self._device.get_info(cl.device_info.TYPE) == cl.device_type.CPU)
Check if the device associated with this environment is a CPU. Returns: boolean: True if the device is an CPU, false otherwise.
codesearchnet
def save_issue_data_task(self, issue, task_id, namespace='open'): issue_data = self.get_saved_issue_data(issue, namespace) if not issue_data.has_key('tasks'): issue_data['tasks'] = [task_id] elif task_id not in issue_data['tasks']: issue_data['tasks'].append(ta...
Saves a issue data (tasks, etc.) to local data. Args: issue: `int`. Github issue number. task: `int`. Asana task ID. namespace: `str`. Namespace for storing this issue.
juraj-google-style
def _decode(obj): if obj is None: return u'' if six.PY3 and isinstance(obj, six.binary_type): return obj.decode('latin1') elif six.PY3: return str(obj) elif isinstance(obj, six.text_type): return obj else: return str(...
Decode an object to unicode. Args: obj (bytes or str or unicode or anything serializable): object to be decoded Returns: object decoded in unicode.
juraj-google-style
def __init__(self, **connection_args): super(DistributionServer, self).__init__(**connection_args) self.connection["url"] = self.connection["jss"].base_url
Set up a connection to a distribution server. Args: connection_args: Dict, with required key: jss: A JSS Object.
juraj-google-style
def _read_coord_h5(files, shapes, header, twod): meshes = [] for h5file, shape in zip(files, shapes): meshes.append({}) with h5py.File(h5file, 'r') as h5f: for coord, mesh in h5f.items(): meshes[-1][coord] = mesh[()].reshape(shape).T ...
Read all coord hdf5 files of a snapshot. Args: files (list of pathlib.Path): list of NodeCoordinates files of a snapshot. shapes (list of (int,int)): shape of mesh grids. header (dict): geometry info. twod (str): 'XZ', 'YZ' or None depending on what is relevant.
juraj-google-style
def hpo_terms(store, query=None, limit=None): hpo_phenotypes = {} if limit: limit = int(limit) hpo_phenotypes['phenotypes'] = list(store.hpo_terms(text=query, limit=limit)) return hpo_phenotypes
Retrieves a list of HPO terms from scout database Args: store (obj): an adapter to the scout database query (str): the term to search in the database limit (str): the number of desired results Returns: hpo_phenotypes (dict): the complete list of HPO objects stored in scout
codesearchnet
def pretty_print(input_word, anagrams, by_length=False): scores = {} if by_length: noun = "tiles" for word, score in anagrams: try: scores[len(word)].append("{0} ({1:d})".format(word, score)) except KeyError: scores[len(word)] = ["{0}...
Prints the anagram results sorted by score to stdout. Args: input_word: the base word we searched on anagrams: generator of (word, score) from anagrams_in_word by_length: a boolean to declare printing by length instead of score
juraj-google-style
def default(self, obj): from ..model import Model from ..colors import Color from .has_props import HasProps if pd and isinstance(obj, (pd.Series, pd.Index)): return transform_series(obj, force_list=True) elif isinstance(obj, np.ndarray): ...
The required ``default`` method for ``JSONEncoder`` subclasses. Args: obj (obj) : The object to encode. Anything not specifically handled in this method is passed on to the default system JSON encoder.
juraj-google-style
def dump_orm_object_as_insert_sql(engine: Engine, obj: object, fileobj: TextIO) -> None: insp = inspect(obj) meta = MetaData(bind=engine) table_name = insp.mapper.mapped_table.name ...
Takes a SQLAlchemy ORM object, and writes ``INSERT`` SQL to replicate it to the output file-like object. Args: engine: SQLAlchemy :class:`Engine` obj: SQLAlchemy ORM object to write fileobj: file-like object to write to
juraj-google-style
def get_iterator_type(script_settings, subscripts={}): if 'iterator_type' in script_settings: if script_settings['iterator_type'] == 'Loop': iterator_type = 'loop' elif script_settings['iterator_type'] == 'Parameter Sweep': iterator_...
figures out the iterator type based on the script settings and (optionally) subscripts Args: script_settings: iterator_type subscripts: subscripts Returns:
juraj-google-style
def tf_retrieve_indices(self, indices): states = dict() for name in sorted(self.states_memory): states[name] = tf.gather(params=self.states_memory[name], indices=indices) internals = dict() for name in sorted(self.internals_memory): internals[name] = tf....
Fetches experiences for given indices. Args: indices: Index tensor Returns: Batch of experiences
juraj-google-style
def _format_field_name(self, field_name) -> str: field = self._get_model_field(field_name) return self.qn(field.column)
Formats a field's name for usage in SQL. Arguments: field_name: The field name to format. Returns: The specified field name formatted for usage in SQL.
codesearchnet
def list_bucket(self, bucket): self.response.write('Listbucket result:\n') page_size = 1 stats = gcs.listbucket((bucket + '/foo'), max_keys=page_size) while True: count = 0 for stat in stats: count += 1 self.response.write(repr(stat)) self.response.wri...
Create several files and paginate through them. Production apps should set page_size to a practical value. Args: bucket: bucket.
codesearchnet
def readCmd(cls, cmd): args = shlex.split(cmd) proc = subprocess.Popen(args, stdout=subprocess.PIPE) (proc_stdout, proc_stderr) = proc.communicate(input=None) return proc_stdout.decode()
run command and return the str format stdout Args: cmd: string Returns: str: what the command's echo
juraj-google-style
def __init__( self, knowledge_base, formatter_mediator, fields_filter=None, preferred_encoding='utf-8'): super(OutputMediator, self).__init__() self._formatter_mediator = formatter_mediator self._knowledge_base = knowledge_base self._preferred_encoding = preferred_encoding self._tim...
Initializes an output mediator. Args: knowledge_base (KnowledgeBase): knowledge base. formatter_mediator (FormatterMediator): formatter mediator. fields_filter (Optional[FilterObject]): filter object that indicates which fields to output. preferred_encoding (Optional[str]): preferred encoding to output.
juraj-google-style
def toregex(text, exact=False): if isregex(text): return text escaped = re.escape(normalize_text(text)) if exact: escaped = '\\A{}\\Z'.format(escaped) return re.compile(escaped)
Returns a compiled regular expression for the given text. Args: text (str | RegexObject): The text to match. exact (bool, optional): Whether the generated regular expression should match exact strings. Defaults to False. Returns: RegexObject: A compiled regular expression that will match the text.
codesearchnet
def concat_excel_reports(addresses, output_file_name, endpoint, report_type, retry, api_key, api_secret, files_path): master_workbook = openpyxl.Workbook() if ((api_key is not None) and (api_secret is not None)): client = ApiClient(api_key, api_secret) else: client = ApiClient() errors =...
Creates an Excel file made up of combining the Value Report or Rental Report Excel output for the provided addresses. Args: addresses: A list of (address, zipcode) tuples output_file_name: A file name for the Excel output endpoint: One of 'value_report' or 'rental_report' report_type: One of 'full' or 'summary' retry:...
codesearchnet
def CheckSpacing(filename, clean_lines, linenum, nesting_state, error): raw = clean_lines.lines_without_raw_strings line = raw[linenum] if (IsBlankLine(line) and (not nesting_state.InNamespaceBody()) and (not nesting_state.InExternC())): elided = clean_lines.elided prev_line = elided[(linenu...
Checks for the correctness of various spacing issues in the code. Things we check for: spaces around operators, spaces after if/for/while/switch, no spaces around parens in function calls, two spaces between code and comment, don't start a block with a blank line, don't end a function with a blank line, don't add a bl...
codesearchnet
def convert_optional_traversals_to_compound_match_query(match_query, complex_optional_roots, location_to_optional_roots): tree = construct_optional_traversal_tree(complex_optional_roots, location_to_optional_roots) rooted_optional_root_location_subsets = tree.get_all_rooted_subtrees_as_lists() omitted_locat...
Return 2^n distinct MatchQuery objects in a CompoundMatchQuery. Given a MatchQuery containing `n` optional traverses that expand vertex fields, construct `2^n` different MatchQuery objects: one for each possible subset of optional edges that can be followed. For each edge `e` in a subset of optional edges chosen to be...
codesearchnet
def match(self, expected, actual, assert_items_equal=False): if isinstance(expected, np.ndarray): expected = expected.tolist() if isinstance(actual, np.ndarray): actual = actual.tolist() self.assertEqual(type(expected), type(actual)) if nest.is_nested(expected): self.assertEqual(...
Matches nested structures. Recursively matches shape and values of `expected` and `actual`. Handles scalars, numpy arrays and other python sequence containers e.g. list, dict, as well as SparseTensorValue and RaggedTensorValue. Args: expected: Nested structure 1. actual: Nested structure 2. assert_items_equal: Tests ...
github-repos
def add_child(self, key, value): if type(value) in (list, tuple, dict): if type(value)==dict: for k in value.keys(): self.add_child(k, value[k]) return i = 0 for child in value: self.add_child(key[i]...
Adds a child to the Tag To retrieve the child call get_child or access to the Tag.children[key] dictionary. Args: key (str): Unique child's identifier, or iterable of keys value (Tag, str): can be a Tag, an iterable of Tag or a str. In case of iterable of Tag is a dict, each item's key is set as 'key' param
juraj-google-style
def moves_from_last_n_games(self, n, moves, shuffle, column_family, column): self.wait_for_fresh_games() latest_game = self.latest_game_number utils.dbg('Latest game in %s: %s' % (self.btspec.table, latest_game)) if latest_game == 0: r...
Randomly choose a given number of moves from the last n games. Args: n: number of games at the end of this GameQueue to source. moves: number of moves to be sampled from `n` games. shuffle: if True, shuffle the selected moves. column_family: name of the column family containing move examples. column: name of the ...
juraj-google-style
def interpolate_graph(message, graph): parsed_messaged, _, node_tags = parse_message(message) error_message = ['Graph execution error:', ''] for tag in node_tags: try: op = graph.get_operation_by_name(tag.name) except KeyError: continue else: error...
Interpolates an error message. The error message can contain tags of form `{{node_type node_name}}` which will be parsed to identify the tf.Graph and op. If the op contains traceback, the traceback will be attached to the error message. Args: message: A string to interpolate. graph: ops.Graph object containing all no...
github-repos
def prefixlen_to_mask(prefixlen): prefixlen = (prefixlen or '32') addr = ('0.0.0.0/%s' % prefixlen) return str(netaddr.IPNetwork(addr).netmask)
Converts a prefix length to a dotted decimal subnet mask Args: prefixlen (str): The prefix length value to convert Returns: str: The subt mask as a dotted decimal string
codesearchnet
def fit(dataset_train: Dataset, dataset_val: typing.Optional[Dataset], features: typing.List[str], iters: int, weights_filename: str, log_filename: str, out_span: int) -> jax.Array: with open(weights_filename, 'w') as f: f.write('') with open(log_filename, 'w') as f: f.write('iter\ttrain_accurac...
Trains an AdaBoost binary classifier. Args: dataset_train (Dataset): A training dataset. dataset_val (Optional[Dataset]): A validation dataset. features (List[str]): Features, which correspond to the columns of entries. iters (int): A number of training iterations. weights_filename (str): A file path to write the lear...
github-repos
def __init__(self, fold_scope_location): super(FoldCountContextField, self).__init__(fold_scope_location) self.fold_scope_location = fold_scope_location self.validate()
Construct a new FoldCountContextField object for this fold. Args: fold_scope_location: FoldScopeLocation specifying the fold whose size is being output. Returns: new FoldCountContextField object
juraj-google-style
def _get_hash(self): if (self.optionals and self.optionals.ISBN): isbn = self.optionals.ISBN.replace('-', '') if (len(isbn) <= 10): return ('97880' + isbn) return isbn if (self.optionals and self.optionals.EAN): return self.optionals.EAN return (self.title + ','.j...
Create hash of the class. Hash should be unique for given ebook, so ISBN is main component of the hash if provided. Returns: str: Hash.
codesearchnet
def type_check(self, instance): raise NotImplementedError
Determines if the type of 'instance' satisfies this type constraint. Args: instance: An instance of a Python object. Raises: :class:`TypeError`: The passed **instance** doesn't satisfy this :class:`TypeConstraint`. Subclasses of :class:`TypeConstraint` are free to raise any of the subclasses of :class:`TypeError` def...
github-repos
def _step(time, output_ta_t, prev_output, *states): current_input = tuple((ta[time] for ta in input_ta)) current_input = tree.pack_sequence_as(inputs, current_input) mask_t = masking_fn(time) output, new_states = step_function(current_input, tuple(states) + tuple(constants)) flat_output = tree.flatt...
RNN step function. Args: time: Current timestep value. output_ta_t: TensorArray. prev_output: tuple of outputs from time - 1. *states: List of states. Returns: Tuple: `(time + 1, output_ta_t, output) + tuple(new_states)`
github-repos
def _ParseIdentifierMappingsTable(self, parser_mediator, esedb_table): identifier_mappings = {} for esedb_record in esedb_table.records: if parser_mediator.abort: break identifier, mapped_value = self._ParseIdentifierMappingRecord( parser_mediator, esedb_table.name, esedb_re...
Extracts identifier mappings from the SruDbIdMapTable table. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. esedb_table (pyesedb.table): table. Returns: dict[int, str]: mapping of numeric identifiers to their string representation.
juraj-google-style
def generator_container(generator_function): @functools.wraps(generator_function) def generator_container_wrapper(*args, **kwargs): return GeneratorContainer(generator_function, *args, **kwargs) return generator_container_wrapper
Function Decorator: Containerize calls to a generator function. Args: generator_function(func): The generator function being containerized. Returns: func: A wrapper function that containerizes the calls to the generator function.
juraj-google-style
def error_print(msg, color=colorama.Fore.RED, file=sys.stderr): if CLI_QUIET: return file.write('{sep}{bright}{color}Error: {normal}{msg}{sep}{reset}'.format( sep=_linesep_for_file(file), bright=colorama.Style.BRIGHT, color=color, normal=colorama.Style.NORMAL, msg=msg, reset=colorama.Style.RESET_...
Print the error message to the file in the specified color. Args: msg: The error message to be printed. color: Optional colorama color string to be applied to the message. You can concatenate colorama color strings together here, but note that style strings will not be applied. file: A file object to which the baracke...
juraj-google-style
def initial_value_of_masked_time_series(time_series_tensor, broadcast_mask): num_timesteps = tf.shape(input=time_series_tensor)[(- 1)] unmasked_negindices = (tf.cast((~ broadcast_mask), tf.int32) * tf.range(num_timesteps, 0, (- 1))) first_unmasked_indices = (num_timesteps - tf.reduce_max(input_tensor=unmask...
Get the first unmasked entry of each time series in the batch. Args: time_series_tensor: float `Tensor` of shape [..., num_timesteps]. broadcast_mask: bool `Tensor` of same shape as `time_series`.
codesearchnet
def decode(self, decoder_input_ids, encoder_outputs, encoder_attention_mask: Optional[jnp.ndarray]=None, decoder_attention_mask: Optional[jnp.ndarray]=None, decoder_position_ids: Optional[jnp.ndarray]=None, past_key_values: Optional[dict]=None, output_attentions: Optional[bool]=None, output_hidden_states: Optional[bool...
Returns: Example: ```python >>> import jax.numpy as jnp >>> from transformers import AutoTokenizer, FlaxBlenderbotForConditionalGeneration >>> model = FlaxBlenderbotForConditionalGeneration.from_pretrained("facebook/blenderbot-400M-distill") >>> tokenizer = AutoTokenizer.from_pretrained("facebook/blenderbot-400M-dis...
github-repos
def update_instance(self, data): for (key, val) in iteritems(data): if (not hasattr(self, key)): raise AttributeError('No field named {key} for model {model}'.format(key=key, model=self.__class__.__name__)) setattr(self, key, val) self.save() return self
Update a single record by id with the provided data. Args: data (dict): The new data to update the record with. Returns: self: This is an instance of itself with the updated data. Raises: AttributeError: This is raised if a key in the ``data`` isn't a field on the model.
codesearchnet
def _list(self, dir_or_prefix): if not self.exists(dir_or_prefix): return def list_files(root): for dirpath, _, files in os.walk(root): for filename in files: yield self.join(dirpath, filename) try: for f in list_files(dir_or_prefix): try: ...
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 wer...
github-repos
def unravel_sections(section_data): sections = [] for type, subsection_list in section_data.items(): for section in subsection_list: section['sectionType'] = type sections.append(section) return sections
Unravels section type dictionary into flat list of sections with section type set as an attribute. Args: section_data(dict): Data return from py:method::get_sections Returns: list: Flat list of sections with ``sectionType`` set to type (i.e. recitation, lecture, etc)
juraj-google-style
def _UnserializableObjectFallback(self, obj): if isinstance(obj, libpython.PyInstanceObjectPtr): in_class = obj.pyop_field('in_class') result_dict = in_class.pyop_field('cl_dict').proxyval(set()) instanceproxy = obj.proxyval(set()) result_dict.update(instanceproxy.attrdict) r...
Handles sanitizing of unserializable objects for Json. For instances of heap types, we take the class dict, augment it with the instance's __dict__, tag it and transmit it over to the RPC client to be reconstructed there. (Works with both old and new style classes) Args: obj: The object to Json-serialize Returns: A Js...
codesearchnet
def AddDescriptor(self, desc): if not isinstance(desc, descriptor.Descriptor): raise TypeError('Expected instance of descriptor.Descriptor.') self._descriptors[desc.full_name] = desc self._AddFileDescriptor(desc.file)
Adds a Descriptor to the pool, non-recursively. If the Descriptor contains nested messages or enums, the caller must explicitly register them. This method also registers the FileDescriptor associated with the message. Args: desc: A Descriptor.
juraj-google-style
def __init__(self, **options): self._def = {} for opt_name, opt_meta in options.items(): if _is_valid(opt_name): self._def[opt_name] = opt_meta self[opt_name] = opt_meta.default else: raise error.OptionError(opt_name)
Initialization of instances. Args: options (:class:`ConfOpt`): option metadata. The name of each *option* is the name of the keyword argument passed on to this function. Option names should be valid identifiers, otherwise an :class:`~loam.error.OptionError` is raised.
juraj-google-style
def find_synonymous_field(field, model=DEFAULT_MODEL, app=DEFAULT_APP, score_cutoff=50, root_preference=1.02): fields = (util.listify(field) + list(synonyms(field))) model = get_model(model, app) available_field_names = model._meta.get_all_field_names() (best_match, best_ratio) = (None, None) for (i...
Use a dictionary of synonyms and fuzzy string matching to find a similarly named field Returns: A single model field name (string) Examples: >>> find_synonymous_field('date', model='WikiItem') 'end_date_time' >>> find_synonymous_field('date', model='WikiItem') 'date_time' >>> find_synonymous_field('time', model='Wik...
codesearchnet
def kill_reporter(self, check_alive=True): if PY3: self._kill_process_type(ray_constants.PROCESS_TYPE_REPORTER, check_alive=check_alive)
Kill the reporter. Args: check_alive (bool): Raise an exception if the process was already dead.
codesearchnet
def set_expected_update_frequency(self, update_frequency): try: int(update_frequency) except ValueError: update_frequency = Dataset.transform_update_frequency(update_frequency) if (not update_frequency): raise HDXError('Invalid update frequency supplied!') self.data['data_update_...
Set expected update frequency Args: update_frequency (str): Update frequency Returns: None
codesearchnet
def to_service(self, service, version): service_url = self._service_locator.get_service_url(service, version) return self.__copy_and_set('service_url', self.__strip_trailing_slashes(service_url))
Sets the service name and version the request should target Args: service (str): The name of the service as displayed in the services.json file version (str): The version of the service as displayed in the services.json file Returns: The request builder instance in order to chain calls
juraj-google-style
def fetch(self): raise NotImplementedError('Must be implemented in subclasses.')
Wait for the result of `RemoteValue` and return the numpy result. This makes the value concrete by copying the remote value to local. Returns: The numpy array structure of the actual output of the `tf.function` associated with this `RemoteValue`, previously returned by a `tf.distribute.experimental.coordinator.Cluste...
github-repos
def _ReadRecordSchemaAttributes(self, tables, file_object, record_offset): record_header = self._ReadRecordHeader(file_object, record_offset) attribute_value_offsets = self._ReadRecordAttributeValueOffset( file_object, record_offset + 24, 6) file_offset = file_object.tell() attribute_valu...
Reads a schema attributes (CSSM_DL_DB_SCHEMA_ATTRIBUTES) record. Args: tables (dict[int, KeychainDatabaseTable]): tables per identifier. file_object (file): file-like object. record_offset (int): offset of the record relative to the start of the file. Raises: ParseError: if the record cannot be read.
juraj-google-style
def iou(boxes1, boxes2): intersect = intersection(boxes1, boxes2) area1 = area(boxes1) area2 = area(boxes2) union = np.expand_dims(area1, axis=1) + np.expand_dims( area2, axis=0) - intersect return intersect / union
Computes pairwise intersection-over-union between box collections. Args: boxes1: a numpy array with shape [N, 4] holding N boxes. boxes2: a numpy array with shape [M, 4] holding M boxes. Returns: a numpy array with shape [N, M] representing pairwise iou scores.
juraj-google-style
def rename_custom_ops(model, map_custom_op_renames): for op_code in model.operatorCodes: if op_code.customCode: op_code_str = op_code.customCode.decode('ascii') if op_code_str in map_custom_op_renames: op_code.customCode = map_custom_op_renames[op_code_str].encode('as...
Rename custom ops so they use the same naming style as builtin ops. Args: model: The input tflite model. map_custom_op_renames: A mapping from old to new custom op names.
github-repos
def create_van_der_corput_samples(idx, number_base=2): assert (number_base > 1) idx = (numpy.asarray(idx).flatten() + 1) out = numpy.zeros(len(idx), dtype=float) base = float(number_base) active = numpy.ones(len(idx), dtype=bool) while numpy.any(active): out[active] += ((idx[active] % nu...
Van der Corput samples. Args: idx (int, numpy.ndarray): The index of the sequence. If array is provided, all values in array is returned. number_base (int): The numerical base from where to create the samples from. Returns (float, numpy.ndarray): Van der Corput samples.
codesearchnet
def get_file_size(file_object): position = file_object.tell() file_object.seek(0, 2) file_size = file_object.tell() file_object.seek(position, 0) return file_size
Returns the size, in bytes, of a file. Expects an object that supports seek and tell methods. Args: file_object (file_object) - The object that represents the file Returns: (int): size of the file, in bytes
juraj-google-style
def from_json_and_lambdas(cls, file: str, lambdas): with open(file, 'r') as f: data = json.load(f) return cls.from_dict(data, lambdas)
Builds a GrFN from a JSON object. Args: cls: The class variable for object creation. file: Filename of a GrFN JSON file. Returns: type: A GroundedFunctionNetwork object.
codesearchnet
def __init__(self, num_tasks): self._num_tasks = num_tasks self._next_task = 0
Create a new `_RoundRobinStrategy`. Args: num_tasks: Number of ps tasks to cycle among.
github-repos
def is_ready(self, node_id, metadata_priority=True): if not self._can_send_request(node_id): return False if metadata_priority: if self._metadata_refresh_in_progress: return False if self.cluster.ttl() == 0: ...
Check whether a node is ready to send more requests. In addition to connection-level checks, this method also is used to block additional requests from being sent during a metadata refresh. Arguments: node_id (int): id of the node to check metadata_priority (bool): Mark node as not-ready if a metadata refresh is requ...
juraj-google-style
def _entry_allocated_bitmap(self, entry_number): (index, offset) = divmod(entry_number, 8) return bool((self._bitmap[index] & (1 << offset)))
Checks if a particular index is allocated. Args: entry_number (int): Index to verify Returns: bool: True if it is allocated, False otherwise.
codesearchnet
def unzip(archive, destination, filenames=None): close = False try: if (not isinstance(archive, zipfile.ZipFile)): archive = zipfile.ZipFile(archive, 'r', allowZip64=True) close = True logger.info(('Extracting: %s -> %s' % (archive.filename, destination))) if isin...
Unzip a zip archive into destination directory. It unzips either the whole archive or specific file(s) from the archive. Usage: >>> output = os.path.join(os.getcwd(), 'output') >>> # Archive can be an instance of a ZipFile class >>> archive = zipfile.ZipFile('test.zip', 'r') >>> # Or just a filename >>> archive = 'te...
codesearchnet
def __init__(self, name=IGNORED, origin=IGNORED, context=IGNORED): if context != IGNORED and (not isinstance(context, dict)): raise ValueError('context must be a Python dictionary.') self.name = name self.origin = origin self.context = context
Creates a MetricsStructuredNameMatcher. Any property not passed in to the constructor will be ignored when matching. Args: name: A string with the metric name. origin: A string with the metric namespace. context: A key:value dictionary that will be matched to the structured name.
github-repos
def __init__(self, promise): super(BrokenPromise, self).__init__() self._promise = promise
Configure the broken promise error. Args: promise (Promise): The promise that was not satisfied.
juraj-google-style
def dqdv_cycle(cycle, splitter=True, **kwargs): c_first = cycle.loc[(cycle['direction'] == (- 1))] c_last = cycle.loc[(cycle['direction'] == 1)] converter = Converter(**kwargs) converter.set_data(c_first['capacity'], c_first['voltage']) converter.inspect_data() converter.pre_process_data() c...
Convenience functions for creating dq-dv data from given capacity and voltage cycle. Returns the a DataFrame with a 'voltage' and a 'incremental_capacity' column. Args: cycle (pandas.DataFrame): the cycle data ('voltage', 'capacity', 'direction' (1 or -1)). splitter (bool): insert a np.NaN row between charge and disc...
codesearchnet
def plot_summaries(self, show=False, save=True, figure_type=None): if (not figure_type): figure_type = self.default_figure_type if (not (figure_type in self.default_figure_types)): logger.debug('unknown figure type selected') figure_type = self.default_figure_type (color_list, symbol...
Plot summary graphs. Args: show: shows the figure if True. save: saves the figure if True. figure_type: optional, figure type to create.
codesearchnet
def display_required_items(msg_type): print("Configure a profile for: " + msg_type) print("You will need the following information:") for k, v in CONFIG[msg_type]["settings"].items(): print(" * " + v) print("Authorization/credentials required:") for k, v in CONFIG[msg_type]["auth"].it...
Display the required items needed to configure a profile for the given message type. Args: :msg_type: (str) message type to create config entry.
juraj-google-style
def parse_attributes(attributes=None, classname=None): if not attributes: attributes = {} attributes.setdefault('class', DEFAULT_CLASS_NAME) if classname: attributes['class'] = classname return attributes
Parses attributes, Args: attributes (dict): Input attributes. classname (:obj:`str`, optional): Class name of output SPAN tags. Returns: Parsed attributes. (dict)
juraj-google-style
def write_files(abs_data, basename='absorption', prefix=None, directory=None): for (i, absorption) in enumerate(abs_data): num_txt = ('_{}'.format((i + 1)) if (len(abs_data) > 1) else '') prefix_txt = ('{}_'.format(prefix) if prefix else '') filename = (((prefix_txt + basename) + num_txt) + ...
Write the absorption or loss spectra to a file. Note that this function expects to receive an iterable series of spectra. Args: abs_data (tuple): Series (either :obj:`list` or :obj:`tuple`) of optical absorption or loss spectra. Each spectrum should be formatted as a :obj:`tuple` of :obj:`list` of :obj:`float`. If th...
codesearchnet
def merge_requests(self, **kwargs): path = ('%s/%s/merge_requests' % (self.manager.path, self.get_id())) return self.manager.gitlab.http_get(path, **kwargs)
List the merge requests related to the commit. Args: **kwargs: Extra options to send to the server (e.g. sudo) Raises: GitlabAuthenticationError: If authentication is not correct GitlabGetError: If the references could not be retrieved Returns: list: The merge requests related to the commit.
codesearchnet
def __init__(self, name, exchange, topics=[], enable_ping=True, listen_all=False): self.name = name self.exchange = exchange self.topics = topics self.listeners = [] self.listen_all = listen_all if enable_ping: self.listeners.append(...
Initialize the client with connection settings. Args: name; name of the client exchange: name of the exchange to connect to topics: list of routing keys to listen to enable_ping: enable answering to ping requests By default, the 'ping' routing key will be added in order to enable response to ping requests expect spec...
juraj-google-style
def _get_filename_from_url(url): parse = urlparse(url) return os.path.basename(parse.path)
Return a filename from a URL Args: url (str): URL to extract filename from Returns: (str): Filename in URL
codesearchnet
def gumbel_sample(shape): uniform_samples = tf.random_uniform(shape, minval=1e-05, maxval=0.99998) return (- tf.log((- tf.log(uniform_samples))))
Sample from the Gumbel distribution, protect from overflows. Args: shape: Shape of Gumbel samples. Returns: Noise drawn from Gumbel distribution.
codesearchnet
def compute_inv_covariance(L_aug, Y, k, p): return np.linalg.inv(compute_covariance(L_aug, Y, k, p))
Given label matrix L and labels Y, compute the covariance. Args: L: (np.array) [n, d] The augmented (indicator) label matrix Y: (np.array int) [n] The true labels in {1,...,k}
juraj-google-style
def group_items(items, groupids): if callable(groupids): keyfunc = groupids pair_list = ((keyfunc(item), item) for item in items) else: pair_list = zip(groupids, items) groupid_to_items = defaultdict(list) for (key, item) in pair_list: groupid_to_items[key].append(item) ...
r""" Groups a list of items by group id. Args: items (Iterable): a list of items to group groupids (Iterable or Callable): a corresponding list of item groupids or a function mapping an item to a groupid. Returns: dict: groupid_to_items: maps a groupid to a list of items CommandLine: python -m ubelt.util_dict group_...
codesearchnet
def remove_temp_dir_with_filepath(filepath, strategy): remove_temp_dirpath(os.path.dirname(filepath), strategy)
Removes the temp path for file after writing is finished. Args: filepath: Original filepath that would be used without distribution. strategy: The tf.distribute strategy object currently used.
github-repos
def do_conneg(accept, supported): for result in parse_accept_header(accept): mime_type = result[0] if (mime_type in supported): return mime_type return None
Parse accept header and look for preferred type in supported list. Arguments: accept - HTTP Accept header supported - list of MIME type supported by the server Returns: supported MIME type with highest q value in request, else None. FIXME - Should replace this with negotiator2
codesearchnet
def request(self, request_method, api_method, *args, **kwargs): url = self._build_url(api_method) resp = requests.request(request_method, url, *args, **kwargs) try: rv = resp.json() except ValueError: raise RequestFailedError(resp, 'not a json body') ...
Perform a request. Args: request_method: HTTP method for this request. api_method: API method name for this request. *args: Extra arguments to pass to the request. **kwargs: Extra keyword arguments to pass to the request. Returns: A dict contains the request response data. Raises: RequestFailedError: Raises when Bea...
juraj-google-style
async def get_jsone_context_and_template(chain, parent_link, decision_link, tasks_for): if tasks_for == 'action': jsone_context, tmpl = await get_action_context_and_template( chain, parent_link, decision_link ) else: tmpl = await get_in_tree_template(decision_link) ...
Get the appropriate json-e context and template for any parent task. Args: chain (ChainOfTrust): the chain of trust. parent_link (LinkOfTrust): the parent link to test. decision_link (LinkOfTrust): the parent link's decision task link. tasks_for (str): the reason the parent link was created (cron, hg-push, action) Re...
juraj-google-style
def add(self, timestamp, information): try: item = Schema(CollectorStage.schema_event_items()).validate({ 'timestamp': timestamp, 'information': information }) self.events.append(item) except SchemaError as exception: Logger.get_lo...
Add event information. Args: timestamp (int): event timestamp. information (dict): event information. Raises: RuntimeError: when validation of parameters has failed.
juraj-google-style
def delete(self, key, noreply=None): if noreply is None: noreply = self.default_noreply cmd = b'delete ' + self.check_key(key) if noreply: cmd += b' noreply' cmd += b'\r\n' results = self._misc_cmd([cmd], b'delete', noreply) if noreply: ...
The memcached "delete" command. Args: key: str, see class docs for details. noreply: optional bool, True to not wait for the reply (defaults to self.default_noreply). Returns: If noreply is True, always returns True. Otherwise returns True if the key was deleted, and False if it wasn't found.
juraj-google-style
def recipe_anonymize(config, auth, from_project, from_dataset, to_project, to_dataset): anonymize(config, {'auth': auth, 'bigquery': {'from': {'project': from_project, 'dataset': from_dataset}, 'to': {'project': to_project, 'dataset': to_dataset}}})
Copies tables and view from one dataset to another and anynonamizes all rows. Used to create sample datasets for dashboards. Args: auth (authentication) - Credentials used. from_project (string) - Original project to read from. from_dataset (string) - Original dataset to read from. to_project (string) - Anonymous data...
github-repos
def clone(self, data=None, shared_data=True, new_type=None, *args, **overrides): return Element2D.clone(self, data, shared_data, new_type, *args, **overrides)
Clones the object, overriding data and parameters. Args: data: New data replacing the existing data shared_data (bool, optional): Whether to use existing data new_type (optional): Type to cast object to *args: Additional arguments to pass to constructor **overrides: New keyword arguments to pass to constructor Return...
juraj-google-style
def FromBinary(cls, script_data, allow_unknown=True, show_rpcs=False): curr = 0 records = [] header = cls.ParseHeader(script_data) curr = header.header_length cls.logger.debug('Parsed script header: %s, skipping %d bytes', header, curr) record_count = 0 record_data = bytearray() partial_...
Parse a binary update script. Args: script_data (bytearray): The binary data containing the script. allow_unknown (bool): Allow the script to contain unknown records so long as they have correct headers to allow us to skip them. show_rpcs (bool): Show SendRPCRecord matches for each record rather than the more specific...
codesearchnet
def create_queue(self, register=False): queue = asyncio.Queue(loop=self._loop) if register: self._work_queues.add(queue) return queue
Create a new work queue and optionally register it. This will make sure the queue is attached to the correct event loop. You can optionally choose to automatically register it so that wait_idle() will block until the queue is empty. Args: register (bool): Whether to call register_workqueue() automatically. Returns: ...
codesearchnet
def read_uint16(self, little_endian=True): if little_endian: endian = "<" else: endian = ">" return self.unpack('%sH' % endian, 2)
Read 2 byte as an unsigned integer value from the stream. Args: little_endian (bool): specify the endianness. (Default) Little endian. Returns: int:
juraj-google-style
def print_info(self, obj=None, buf=sys.stdout): if (not obj): self._print_info(buf) return True b = False for fn in (self._print_tool_info, self._print_package_info, self._print_suite_info, self._print_context_info): b_ = fn(obj, buf, b) b |= b_ if b_: ((p...
Print a status message about the given object. If an object is not provided, status info is shown about the current environment - what the active context is if any, and what suites are visible. Args: obj (str): String which may be one of the following: - A tool name; - A package name, possibly versioned; - A context ...
codesearchnet
def FormatAST(ast, style_config=None, lines=None): style.SetGlobalStyle(style.CreateStyleFromConfig(style_config)) llines = pyparser.ParseCode(ast) for lline in llines: lline.CalculateFormattingInformation() lines = _LineRangesToSet(lines) _MarkLinesToFormat(llines, lines) return reforma...
Format a parsed lib2to3 pytree. This provides an alternative entry point to YAPF. Arguments: unformatted_source: (unicode) The code to format. style_config: (string) Either a style name or a path to a file that contains formatting style settings. If None is specified, use the default style as set in style.DEFAULT_STY...
github-repos
def create_window(size=None, samples=16, *, fullscreen=False, title=None, threaded=True) -> Window: if (size is None): (width, height) = (1280, 720) else: (width, height) = size if ((samples < 0) or ((samples & (samples - 1)) != 0)): raise Exception(('Invalid number of samples: %d' %...
Create the main window. Args: size (tuple): The width and height of the window. samples (int): The number of samples. Keyword Args: fullscreen (bool): Fullscreen? title (bool): The title of the window. threaded (bool): Threaded? Returns: Window: The main window.
codesearchnet
def get_role(self, item, state_root, from_state=False): if from_state: if self._identity_view is None: self.update_view(state_root) value = self._identity_view.get_role(item) return value value = self._cache.get(item) if ...
Used to retrieve an identity role. Args: item (string): the name of the role to be fetched state_root(string): The state root of the previous block. from_state (bool): Whether the identity value should be read directly from state, instead of using the cached values. This should be used when the state_root passed is not...
juraj-google-style
def success(channel, post): datapacks = [("Game", post[0], True), ("Upvotes", post[2], True)] gui = ui_embed.UI( channel, "Link", post[1], modulename=modulename, colour=0xFF8800, thumbnail=post[1], datapacks=datapacks ) return gui
Creates an embed UI containing the Reddit posts Args: channel (discord.Channel): The Discord channel to bind the embed to post (tuple): Tuples of (field, value, percentile) Returns:
juraj-google-style
def append(self, annotation): self._annotations[annotation.id] = annotation self._dirty = True return annotation
Add an annotation. Args: annotation (gkeepapi.node.Annotation): An Annotation object. Returns: gkeepapi.node.Annotation: The Annotation.
codesearchnet
def _Aff4Size(aff4_obj): if (not isinstance(aff4_obj, aff4.AFF4Stream)): message = 'Expected an instance of `%s` but received `%s`' raise TypeError((message % (aff4.AFF4Stream, type(aff4_obj)))) return int(aff4_obj.Get(aff4_obj.Schema.SIZE))
Retrieves the total size in bytes of an AFF4 object. Args: aff4_obj: An AFF4 stream instance to retrieve size for. Returns: An integer representing number of bytes. Raises: TypeError: If `aff4_obj` is not an instance of AFF4 stream.
codesearchnet
def publishFeatureCollections(self, configs): if self.securityhandler is None: print ("Security handler required") return config = None res = None resItm = None try: res = [] if isinstance(configs, list): fo...
Publishes feature collections to a feature service. Args: configs (list): A list of JSON configuration feature service details to publish. Returns: dict: A dictionary of results objects.
juraj-google-style
def memory_write16(self, addr, data, zone=None): return self.memory_write(addr, data, zone, 16)
Writes half-words to memory of a target system. Args: self (JLink): the ``JLink`` instance addr (int): start address to write to data (list): list of half-words to write zone (str): optional memory zone to access Returns: Number of half-words written to target. Raises: JLinkException: on memory access error.
juraj-google-style
def laid_out_pcoord(self, mesh_axis): divisor = list_product(self.shape.to_integer_list[(mesh_axis + 1):]) modulus = self.shape[mesh_axis].size def my_fn(pnum): return ((pnum return self.slicewise(my_fn, self.laid_out_pnum())
Returns a LaidOutTensor containing the processor coordinate. Args: mesh_axis: int. Returns: LaidOutTensor where each slice is an integer scalar.
codesearchnet