code
stringlengths
20
4.93k
docstring
stringlengths
33
1.27k
source
stringclasses
3 values
def launch_run(self, command, project=None, entity=None, run_id=None): query = gql() patch = BytesIO() if self.git.dirty: self.git.repo.git.execute(['git', 'diff'], output_stream=patch) patch.seek(0) cwd = "." if self.git.enabled: cwd ...
Launch a run in the cloud. Args: command (str): The command to run program (str): The file to run project (str): The project to scope the runs to entity (str, optional): The entity to scope this project to. Defaults to public models run_id (str, optional): The run_id to scope to Returns: [{"podName","status"}]
juraj-google-style
def abs_path(path): return os.path.abspath(os.path.expanduser(path))
Resolve the '.' and '~' in a path to get the absolute path. Args: path: The path to expand. Returns: The absolute path of the input path.
github-repos
class InformerFeatureEmbedder(nn.Module): def __init__(self, cardinalities: List[int], embedding_dims: List[int]) -> None: super().__init__() self.num_features = len(cardinalities) self.embedders = nn.ModuleList([nn.Embedding(c, d) for c, d in zip(cardinalities, embedding_dims)]) def f...
Embed a sequence of categorical features. Args: cardinalities (`list[int]`): List of cardinalities of the categorical features. embedding_dims (`list[int]`): List of embedding dimensions of the categorical features.
github-repos
def init_backend(self, phonemizer_lang: str): requires_backends(self, 'phonemizer') from phonemizer.backend import BACKENDS self.backend = BACKENDS[self.phonemizer_backend](phonemizer_lang, language_switch='remove-flags')
Initializes the backend. Args: phonemizer_lang (`str`): The language to be used.
github-repos
def serialCmdPwdAuth(self, password_str): result = False try: req_start = "0150310228" + binascii.hexlify(password_str) + "2903" req_crc = self.calc_crc16(req_start[2:].decode("hex")) req_str = req_start + req_crc self.m_serial_port.write(req_str....
Password step of set commands This method is normally called within another serial command, so it does not issue a termination string. Any default password is set in the caller parameter list, never here. Args: password_str (str): Required password. Returns: bool: True on completion and ACK.
juraj-google-style
def decode_conjure_union_type(cls, obj, conjure_type): type_of_union = obj['type'] for (attr, conjure_field) in conjure_type._options().items(): if (conjure_field.identifier == type_of_union): attribute = attr conjure_field_definition = conjure_field break else: ...
Decodes json into a conjure union type. Args: obj: the json object to decode conjure_type: a class object which is the union type we're decoding into Returns: An instance of type conjure_type.
codesearchnet
def init_config_json(config_file): json_data = None try: if os.path.exists(config_file): with open(config_file) as json_file: json_data = json.load(json_file) return unicode_convert(json_data) else: return None except: ...
Deserializes a JSON configuration file. Args: config_file (str): The path to the JSON file. Returns: dict: A dictionary object containing the JSON data. If ``config_file`` does not exist, returns ``None``.
juraj-google-style
def add_sync_methods(cls): for name in cls.__dict__.keys(): if name.endswith('_async'): sync_name = name[:-6] if not hasattr(cls, sync_name): setattr(cls, sync_name, _make_sync_method(name)) return cls
Class decorator to add synchronous methods corresponding to async methods. This modifies the class in place, adding additional methods to it. If a synchronous method of a given name already exists it is not replaced. Args: cls: A class. Returns: The same class, modified in place.
juraj-google-style
def load_validation_plugin(name=None): if not name: return BaseValidationRules plugin = None for entry_point in iter_entry_points('bigchaindb.validation', name): plugin = entry_point.load() if not plugin: raise ResolutionError( 'No plug...
Find and load the chosen validation plugin. Args: name (string): the name of the entry_point, as advertised in the setup.py of the providing package. Returns: an uninstantiated subclass of ``bigchaindb.validation.AbstractValidationRules``
juraj-google-style
async def selfplay(state, flagfile='selfplay'): output_dir = os.path.join(fsdb.selfplay_dir(), state.output_model_name) holdout_dir = os.path.join(fsdb.holdout_dir(), state.output_model_name) lines = await run( 'bazel-bin/cc/selfplay', '--flagfile={}.flags'.format(os.path.join(FLAGS.flags_dir, fl...
Run selfplay and write a training chunk to the fsdb golden_chunk_dir. Args: state: the RL loop State instance. flagfile: the name of the flagfile to use for selfplay, either 'selfplay' (the default) or 'boostrap'.
juraj-google-style
def _group_and_publish_tasks_statistics(self, result): for i in result: executor_id = i['executor_id'] i['executor_id'] = executor_id[:executor_id.rfind('.')] i['statistics']['instances_count'] = 1 r = {} for i in result: executor_id = i['executor_id'] r[executor_id] ...
This function group statistics of same tasks by adding them. It also add 'instances_count' statistic to get information about how many instances is running on the server Args: result: result of mesos query. List of dictionaries with 'executor_id', 'framework_id' as a strings and 'statistics' as dictionary of labeled n...
codesearchnet
def find_dependencies(self, dataset_keys, **dfilter): unknown_datasets = set() for key in dataset_keys.copy(): n, unknowns = self._find_dependencies(key, **dfilter) dataset_keys.discard(key) if n is not None: dataset_keys.add(n.name) ...
Create the dependency tree. Args: dataset_keys (iterable): Strings or DatasetIDs to find dependencies for **dfilter (dict): Additional filter parameters. See `satpy.readers.get_key` for more details. Returns: (Node, set): Root node of the dependency tree and a set of unknown datasets
juraj-google-style
def run_cm(cm, time_scale): cm = np.linalg.matrix_power(cm, time_scale) cm[(cm > 1)] = 1 return cm
Iterate a connectivity matrix the specified number of steps. Args: cm (np.ndarray): A connectivity matrix. time_scale (int): The number of steps to run. Returns: np.ndarray: The connectivity matrix at the new timescale.
codesearchnet
def CheckVlogArguments(filename, clean_lines, linenum, error): line = clean_lines.elided[linenum] if Search(r'\bVLOG\((INFO|ERROR|WARNING|DFATAL|FATAL)\)', line): error(filename, linenum, 'runtime/vlog', 5, 'VLOG() should be used with numeric verbosity level. ' 'Use LOG() if you want sym...
Checks that VLOG() is only used for defining a logging level. For example, VLOG(2) is correct. VLOG(INFO), VLOG(WARNING), VLOG(ERROR), and VLOG(FATAL) are not. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The ...
juraj-google-style
def clean_output_files(self, follow_parents=True): paths = [] if self.status != self.S_OK: logger.warning("Calling task.clean_output_files on a task whose status != S_OK") self.tmpdir.clean() except_exts = set() for child in self....
This method is called when the task reaches S_OK. It removes all the output files produced by the task that are not needed by its children as well as the output files produced by its parents if no other node needs them. Args: follow_parents: If true, the output files of the parents nodes will be removed if possible. ...
juraj-google-style
def GetSysFeeAmountByHeight(self, height): hash = self.GetBlockHash(height) return self.GetSysFeeAmount(hash)
Get the system fee for the specified block. Args: height (int): block height. Returns: int:
juraj-google-style
def merge_csv(filenames: List[str], outfile: TextIO = sys.stdout, input_dialect: str = 'excel', output_dialect: str = 'excel', debug: bool = False, headers: bool = True) -> None: writer = csv.writer(outfile, dialect=output_dialect) writt...
Amalgamate multiple CSV/TSV/similar files into one. Args: filenames: list of filenames to process outfile: file-like object to write output to input_dialect: dialect of input files, as passed to ``csv.reader`` output_dialect: dialect to write, as passed to ``csv.writer`` debug: be verbose? headers: do the files have h...
juraj-google-style
def parse_keys(self, sn: 'DataNode') -> Dict[(InstanceName, ScalarValue)]: res = {} for k in self.keys: knod = sn.get_data_child(*k) if (knod is None): raise NonexistentSchemaNode(sn.qual_name, *k) kval = knod.type.parse_value(self.keys[k]) if (kval is None): ...
Parse key dictionary in the context of a schema node. Args: sn: Schema node corresponding to a list.
codesearchnet
def van_enc_2d(x, first_depth, reuse=False): with tf.variable_scope('van_enc', reuse=reuse): a = 4 b = 4 enc = tf.nn.relu(x) enc = tf.layers.dense(enc, first_depth * a * b, tf.nn.relu) enc = tf.contrib.layers.layer_norm(enc) enc = tf.reshape(enc, [-1, a, b, first_depth]) enc = ...
The higher level structure encoder for the VAN. The high level structure is a vector instead of an image. Args: x: The higher level structure to encode. first_depth: The depth of the first layer. Depth is increased in subsequent layers. reuse: To reuse in variable scope or not. Returns: The encoded image.
juraj-google-style
def get_descriptor_defaults(self, api_info, hostname=None): hostname = (hostname or endpoints_util.get_app_hostname() or api_info.hostname) protocol = 'http' if ((hostname and hostname.startswith('localhost')) or endpoints_util.is_running_on_devserver()) else 'http...
Gets a default configuration for a service. Args: api_info: _ApiInfo object for this service. hostname: string, Hostname of the API, to override the value set on the current service. Defaults to None. Returns: A dictionary with the default configuration.
juraj-google-style
def query_icao(icao: str): params = { 'dataSource': 'metars', 'requestType': 'retrieve', 'format': 'csv', 'hoursBeforeNow': 24, } AWC._validate_icao(icao) params['stationString'] = icao try: return AWC._query(pa...
Queries AWC for the METAR of a given station Args: icao: station ID as a four letters-digits ICAO code Returns: AWC result for the station
juraj-google-style
def recipe_dv360_segmentology(config, auth_read, recipe_timezone, auth_write, recipe_name, date_range, recipe_slug, partners, advertisers): dataset(config, {'description': 'Create a dataset for bigquery tables.', 'hour': [4], 'auth': auth_write, 'dataset': recipe_slug}) bigquery(config, {'auth': auth_write, 'fu...
DV360 funnel analysis using Census data. Args: auth_read (authentication) - Credentials used for reading data. recipe_timezone (timezone) - Timezone for report dates. auth_write (authentication) - Authorization used for writing data. recipe_name (string) - Name of report, not needed if ID used. date_range (choice) - T...
github-repos
def delete(self, *, auto_commit=False): try: db.session.delete(self.resource) if auto_commit: db.session.commit() except SQLAlchemyError: self.log.exception('Failed deleting resource: {}'.format(self.id)) db.session.rollback()
Removes a resource from the database Args: auto_commit (bool): Automatically commit the transaction. Default: `False` Returns: `None`
codesearchnet
class AriaSharedExpertsMLP(LlamaMLP): def __init__(self, config: AriaTextConfig): super().__init__(self) self.intermediate_size = config.intermediate_size * config.moe_num_shared_experts
Shared Expert MLP for shared experts. Unlike routed experts, shared experts process all tokens without routing. This class reconfigures the intermediate size in comparison to the LlamaMLP. Args: config (`AriaTextConfig`): Configuration object for the Aria language model.
github-repos
def take_bug_reports(ads, test_name, begin_time, destination=None): begin_time = mobly_logger.normalize_log_line_timestamp(str(begin_time)) def take_br(test_name, begin_time, ad, destination): ad.take_bug_report(test_name, begin_time, destination=destination) args = [(test_name, begin_time, ad, des...
Takes bug reports on a list of android devices. If you want to take a bug report, call this function with a list of android_device objects in on_fail. But reports will be taken on all the devices in the list concurrently. Bug report takes a relative long time to take, so use this cautiously. Args: ads: A list of Andr...
codesearchnet
def setup(options): if not options.misc.debug: requests.packages.urllib3.disable_warnings( requests.packages.urllib3.exceptions.InsecureRequestWarning )
Initialize debug/logging in third party libraries correctly. Args: options (:class:`nyawc.Options`): The options to use for the current crawling runtime.
juraj-google-style
def _virtual_molecule(self, mol, ilabels, eq_atoms): vmol = ob.OBMol() non_unique_atoms = set([a for g in eq_atoms for a in g]) all_atoms = set(range(1, (len(ilabels) + 1))) unique_atom_labels = sorted((all_atoms - non_unique_atoms)) for i in unique_atom_labels: orig_idx = ilabels[(i - 1)] ...
Create a virtual molecule by unique atoms, the centriods of the equivalent atoms Args: mol: The molecule. OpenBabel OBMol object ilables: inchi label map eq_atoms: equivalent atom labels farthest_group_idx: The equivalent atom group index in which there is the farthest atom to the centroid Return: The virtual molecul...
codesearchnet
def lu_slogdet(LU): LU = (asarray(LU[0], float), asarray(LU[1], float)) adet = _sum(log(_abs(LU[0].diagonal()))) s = prod(sign(LU[0].diagonal())) nrows_exchange = (LU[1].size - _sum((LU[1] == arange(LU[1].size, dtype='int32')))) odd = ((nrows_exchange % 2) == 1) if odd: s *= (- 1.0) ...
r"""Natural logarithm of a LU decomposition. Args: LU (tuple): LU decomposition. Returns: tuple: sign and log-determinant.
codesearchnet
def save(self, filething=None, padding=None): self.to_content_description = {} self.to_extended_content_description = {} self.to_metadata = {} self.to_metadata_library = [] for name, value in self.tags: library_only = (value.data_size() > 0xFFFF or ...
save(filething=None, padding=None) Save tag changes back to the loaded file. Args: filething (filething) padding (:obj:`mutagen.PaddingFunction`) Raises: mutagen.MutagenError
juraj-google-style
def read_submissions_from_directory(dirname, use_gpu): result = [] for sub_dir in os.listdir(dirname): submission_path = os.path.join(dirname, sub_dir) try: if not os.path.isdir(submission_path): continue if not os.path.exists(os.path.join(submission_path, 'metadata.json')): c...
Scans directory and read all submissions. Args: dirname: directory to scan. use_gpu: whether submissions should use GPU. This argument is used to pick proper Docker container for each submission and create instance of Attack or Defense class. Returns: List with submissions (subclasses of Submission class).
juraj-google-style
def from_api_repr(cls, resource, client): job_ref_properties = resource.get("jobReference", {"projectId": client.project}) job_ref = _JobReference._from_api_repr(job_ref_properties) job = cls(job_ref, client) resource["jobReference"] = job_ref_properties ...
Construct an UnknownJob from the JSON representation. Args: resource (dict): JSON representation of a job. client (google.cloud.bigquery.client.Client): Client connected to BigQuery API. Returns: UnknownJob: Job corresponding to the resource.
juraj-google-style
def set(self, value): pywrap_tfe.TFE_MonitoringBoolGaugeCellSet(self._cell, value)
Atomically set the value. Args: value: bool value.
github-repos
def delete_handler(Model, name=None, **kwds): from nautilus.database import db async def action_handler(service, action_type, payload, props, notify=True, **kwds): if (action_type == get_crud_action('delete', (name or Model))): try: message_props = {} if ('co...
This factory returns an action handler that deletes a new instance of the specified model when a delete action is recieved, assuming the action follows nautilus convetions. Args: Model (nautilus.BaseModel): The model to delete when the action received. Returns: function(type, payload): The action handler for this mod...
codesearchnet
def _post(self, url, data, scope): self._create_session(scope) response = self.session.post(url, data=data) return (response.status_code, response.text)
Make a POST request using the session object to a Degreed endpoint. Args: url (str): The url to send a POST request to. data (str): The json encoded payload to POST. scope (str): Must be one of the scopes Degreed expects: - `CONTENT_PROVIDER_SCOPE` - `COMPLETION_PROVIDER_SCOPE`
codesearchnet
def delete(self, main_type, sub_type, unique_id, owner=None): params = {'owner': owner} if owner else {} if not sub_type: url = '/v2/{}/{}'.format(main_type, unique_id) else: url = '/v2/{}/{}/{}'.format(main_type, sub_type, unique_id) return self.tcex.ses...
Deletes the Indicator/Group/Victim or Security Label Args: main_type: sub_type: unique_id: owner:
juraj-google-style
def set_string(self, option, value): if (not isinstance(value, str)): raise TypeError(('%s must be a string' % option)) self.options[option] = value
Set a string option. Args: option (str): name of option. value (str): value of the option. Raises: TypeError: Value must be a string.
codesearchnet
def group_associations(self, main_type, sub_type, unique_id, owner=None, params=None): params = params or {} if owner: params['owner'] = owner if not sub_type: url = '/v2/{}/{}/groups'.format(main_type, unique_id) else: url = '/v2/{}/{}/{}/gr...
Args: owner: main_type: sub_type: unique_id: params: Return:
juraj-google-style
def get_cached_filename(self, filename, extention, settings_list=None): cached_name = '_'.join([filename, self.get_hash()]) return '.'.join([cached_name, extention])
Creates a filename with md5 cache string based on settings list Args: filename (str): the filename without extention extention (str): the file extention without dot. (i.e. 'pkl') settings_list (dict|list): the settings list as list (optional) NB! The dictionaries have to be sorted or hash id will change arbitrarely.
codesearchnet
def delete(self, table_name): dataset = Dataset(self, table_name) deleted = dataset.delete() if deleted: return deleted raise CartoException(.format(table_name))
Delete a table in user's CARTO account. Args: table_name (str): Name of table to delete Returns: bool: `True` if table is removed
juraj-google-style
def relu6(x): if any_symbolic_tensors((x,)): return Relu6().symbolic_call(x) return backend.nn.relu6(x)
Rectified linear unit activation function with upper bound of 6. It is defined as `f(x) = np.clip(x, 0, 6)`. Args: x: Input tensor. Returns: A tensor with the same shape as `x`. Example: >>> x = keras.ops.convert_to_tensor([-3.0, -2.0, 0.1, 0.2, 6.0, 8.0]) >>> keras.ops.relu6(x) array([0.0, 0.0, 0.1, 0.2, 6.0, 6.0...
github-repos
def normalized_start(self): namespaces_after_key = list(self.make_datastore_query().Run(limit=1)) if (not namespaces_after_key): return None namespace_after_key = (namespaces_after_key[0].name() or '') return NamespaceRange(namespace_after_key, self.namespace_end, _app=self.app)
Returns a NamespaceRange with leading non-existant namespaces removed. Returns: A copy of this NamespaceRange whose namespace_start is adjusted to exclude the portion of the range that contains no actual namespaces in the datastore. None is returned if the NamespaceRange contains no actual namespaces in the datastore.
codesearchnet
def create_binary_descriptor(descriptor): func_names = {0: 'copy_latest_a', 1: 'average_a', 2: 'copy_all_a', 3: 'sum_a', 4: 'copy_count_a', 5: 'trigger_streamer', 6: 'call_rpc', 7: 'subtract_afromb'} func_codes = {y: x for x, y in func_names.items()} ...
Convert a string node descriptor into a 20-byte binary descriptor. This is the inverse operation of parse_binary_descriptor and composing the two operations is a noop. Args: descriptor (str): A string node descriptor Returns: bytes: A 20-byte binary node descriptor.
juraj-google-style
def world_info(world_name, world_config=None, initial_indent="", next_indent=" "): if world_config is None: for config, _ in _iter_packages(): for world in config["maps"]: if world["name"] == world_name: world_config = world if world_config is None:...
Gets and prints the information of a world. Args: world_name (str): the name of the world to retrieve information for world_config (dict optional): A dictionary containing the world's configuration. Will find the config if None. Defaults to None. initial_indent (str optional): This indent will apply to each output lin...
juraj-google-style
def clip_gradient(net, clip_value_min, clip_value_max, name=None): if (not net.dtype.is_floating): raise ValueError('clip_gradient does not support non-float `net` inputs.') with tf.name_scope(name, 'clip_gradient', values=[net]): dtype = net.dtype.base_dtype min_tensor = tf.convert_to_t...
Clips respective gradients of a given tensor. Acts as identity for the forward pass, but clips gradient tensor element-wise by value during the backward pass. Any gradient values less than `clip_value_min` or greater than `clip_values_max` are set to the respective limit values. Args: net: A `tf.Tensor`. clip_value_m...
codesearchnet
def _get_oauth2_client_id_and_secret(settings_instance): secret_json = getattr(settings_instance, 'GOOGLE_OAUTH2_CLIENT_SECRETS_JSON', None) if (secret_json is not None): return _load_client_secrets(secret_json) else: client_id = getattr(settings_instance, 'GOOGLE_OAUTH2_CLIENT_ID', None) ...
Initializes client id and client secret based on the settings. Args: settings_instance: An instance of ``django.conf.settings``. Returns: A 2-tuple, the first item is the client id and the second item is the client secret.
codesearchnet
def tanh(x): return nn.tanh(x)
Hyperbolic tangent activation function. For example: >>> a = tf.constant([-3.0,-1.0, 0.0,1.0,3.0], dtype = tf.float32) >>> b = tf.keras.activations.tanh(a) >>> b.numpy() array([-0.9950547, -0.7615942, 0., 0.7615942, 0.9950547], dtype=float32) Args: x: Input tensor. Returns: Tensor of same shape and dtype of inpu...
github-repos
def __init__(self, value, ctype=None): if isinstance(value, str) and value == 'INFINITY': self._value = np.inf elif isinstance(value, str) and value == '-INFINITY': self._value = -np.inf else: self._value = np.array(value) self._ctype = ctype ...
A kernel input scalar. This will insert the given value directly into the kernel's source code, and will not load it as a buffer. Args: value (number): the number to insert into the kernel as a scalar. ctype (str): the desired c-type for in use in the kernel, like ``int``, ``float`` or ``mot_float_type``. If None it ...
juraj-google-style
def prepare_data(data_dir, fileroot, block_pct_tokens_thresh=0.1): if (not (0.0 <= block_pct_tokens_thresh <= 1.0)): raise ValueError('block_pct_tokens_thresh must be in the range [0.0, 1.0]') html = read_html_file(data_dir, fileroot) blocks = read_gold_standard_blocks_file(data_dir, fileroot, split...
Prepare data for a single HTML + gold standard blocks example, uniquely identified by ``fileroot``. Args: data_dir (str) fileroot (str) block_pct_tokens_thresh (float): must be in [0.0, 1.0] Returns: Tuple[str, Tuple[np.array[int], np.array[int], List[str]], Tuple[np.array[int], np.array[int], List[str]]]: The first ...
codesearchnet
def run_multiple(self, eventLoops): self.nruns += len(eventLoops) return self.communicationChannel.put_multiple(eventLoops)
run the event loops in the background. Args: eventLoops (list): a list of event loops to run
codesearchnet
def enqueue_tpu_embedding_integer_batch(batch, device_ordinal, mode_override=None, name=None): if mode_override is None: mode_override = 'unspecified' return gen_tpu_ops.enqueue_tpu_embedding_integer_batch(batch=batch, device_ordinal=device_ordinal, mode_override=mode_override, name=name)
A placeholder op for enqueueing embedding IDs to the TPU. Args: batch: A list of 1D tensors, one for each embedding table, containing the indices into the tables. device_ordinal: The TPU device to use. Should be >= 0 and less than the number of TPU cores in the task on which the node is placed. mode_override: A string...
github-repos
def output_classes(self): return nest.map_structure(lambda component_spec: component_spec._to_legacy_output_classes(), self._element_spec)
Returns the class of each component of an element of this iterator. The expected values are `tf.Tensor` and `tf.sparse.SparseTensor`. Returns: A (nested) structure of Python `type` objects corresponding to each component of an element of this dataset.
github-repos
def in_labelset(xmrs, nodeids, label=None): nodeids = set(nodeids) if (label is None): label = xmrs.ep(next(iter(nodeids))).label return nodeids.issubset(xmrs._vars[label]['refs']['LBL'])
Test if all nodeids share a label. Args: nodeids: iterable of nodeids label (str, optional): the label that all nodeids must share Returns: bool: `True` if all nodeids share a label, otherwise `False`
codesearchnet
def zpath(filename): for ext in ["", '.gz', '.GZ', '.bz2', '.BZ2', '.z', '.Z']: zfilename = "{}{}".format(filename, ext) if os.path.exists(zfilename): return zfilename return filename
Returns an existing (zipped or unzipped) file path given the unzipped version. If no path exists, returns the filename unmodified. Args: filename: filename without zip extension Returns: filename with a zip extension (unless an unzipped version exists). If filename is not found, the same filename is returned unchange...
juraj-google-style
def fillPelicanHole(site, username, password, tstat_name, start_time, end_time): start = datetime.strptime(start_time, _INPUT_TIME_FORMAT).replace(tzinfo=pytz.utc).astimezone(_pelican_time) end = datetime.strptime(end_time, _INPUT_TIME_FORMAT).replace(tzinfo=pytz.utc).astimezone(_pelican_time) heat_needs_fa...
Fill a hole in a Pelican thermostat's data stream. Arguments: site -- The thermostat's Pelican site name username -- The Pelican username for the site password -- The Pelican password for the site tstat_name -- The name of the thermostat, as identified by Pelican start_time -- The start of the data hole in UTC, e.g. "...
codesearchnet
def getent(refresh=False): if 'group.getent' in __context__ and not refresh: return __context__['group.getent'] ret = [] results = _get_all_groups() for result in results: group = {'gid': __salt__['file.group_to_gid'](result.Name), 'members': [_get_username(x) for...
Return info on all groups Args: refresh (bool): Refresh the info for all groups in ``__context__``. If False only the groups in ``__context__`` will be returned. If True the ``__context__`` will be refreshed with current data and returned. Default is False Returns: A list of groups and their information CLI Example...
juraj-google-style
def get_sitej(self, site_index, image_index): atoms_n_occu = self.s[site_index].species lattice = self.s.lattice coords = self.s[site_index].frac_coords + self.offsets[image_index] return PeriodicSite(atoms_n_occu, coords, lattice)
Assuming there is some value in the connectivity array at indices (1, 3, 12). sitei can be obtained directly from the input structure (structure[1]). sitej can be obtained by passing 3, 12 to this function Args: site_index (int): index of the site (3 in the example) image_index (int): index of the image (12 in the exa...
juraj-google-style
def get_roles(self): prefix = (_IDENTITY_NS + _ROLE_NS) rolelist_list = [_create_from_bytes(d, identity_pb2.RoleList) for (_, d) in self._state_view.leaves(prefix=prefix)] roles = [] for role_list in rolelist_list: for role in role_list.roles: roles.append(role) return sorted(rol...
Return all the Roles under the Identity namespace. Returns: (list): A list containing all the Roles under the Identity namespace.
codesearchnet
def get_items_by_ids(self, item_ids, item_type=None): urls = [urljoin(self.item_url, F"{i}.json") for i in item_ids] result = self._run_async(urls=urls) items = [Item(r) for r in result if r] if item_type: return [item for item in items if item.item_type == item_type...
Given a list of item ids, return all the Item objects Args: item_ids (obj): List of item IDs to query item_type (str): (optional) Item type to filter results with Returns: List of `Item` objects for given item IDs and given item type
juraj-google-style
def parse_readable_time_str(time_str): def parse_positive_float(value_str): value = float(value_str) if value < 0: raise ValueError('Invalid time %s. Time value must be positive.' % value_str) return value time_str = time_str.strip() if time_str.endswith('us'): r...
Parses a time string in the format N, Nus, Nms, Ns. Args: time_str: (`str`) string consisting of an integer time value optionally followed by 'us', 'ms', or 's' suffix. If suffix is not specified, value is assumed to be in microseconds. (e.g. 100us, 8ms, 5s, 100). Returns: Microseconds value.
github-repos
def __init__(self, msg, exception_details=None): message = '%s with exceptions %s' % (msg, exception_details) super().__init__(message) self.exception_details = exception_details
Class representing the errors thrown in the batch file operations. Args: msg: Message string for the exception thrown exception_details: Optional map of individual input to exception for failed operations in batch. This parameter is optional so if specified the user can assume that the all errors in the filesystem oper...
github-repos
def replace_in_file(filename: str, text_from: str, text_to: str) -> None: log.info('Amending {}: {} -> {}', filename, repr(text_from), repr(text_to)) with open(filename) as infile: contents = infile.read() contents = contents.replace(text_from, text_to) with open(filename, 'w') as outfile: ...
Replaces text in a file. Args: filename: filename to process (modifying it in place) text_from: original text to replace text_to: replacement text
codesearchnet
async def client_event_handler(self, client_id, event_tuple, user_data): conn_string, event_name, event = event_tuple if event_name == 'report': report = event.serialize() report['encoded_report'] = base64.b64encode(report['encoded_report']) msg_p...
Forward an event on behalf of a client. This method is called by StandardDeviceServer when it has an event that should be sent to a client. Args: client_id (str): The client that we should send this event to event_tuple (tuple): The conn_string, event_name and event object passed from the call to notify_event. user_d...
juraj-google-style
def RegisterRecordType(cls, record_class): record_type = record_class.MatchType() if record_type not in UpdateRecord.KNOWN_CLASSES: UpdateRecord.KNOWN_CLASSES[record_type] = [] UpdateRecord.KNOWN_CLASSES[record_type].append(record_class)
Register a known record type in KNOWN_CLASSES. Args: record_class (UpdateRecord): An update record subclass.
juraj-google-style
def create_graph_from_data(self, data, **kwargs): self.arguments['{VERBOSE}'] = str(self.verbose).upper() results = self._run_ccdr(data, verbose=self.verbose) return nx.relabel_nodes(nx.DiGraph(results), {idx: i for idx, i in enumerate(data.colum...
Apply causal discovery on observational data using CCDr. Args: data (pandas.DataFrame): DataFrame containing the data Returns: networkx.DiGraph: Solution given by the CCDR algorithm.
juraj-google-style
def validate_instance(instance, options=None): if 'type' not in instance: raise ValidationError("Input must be an object with a 'type' property.") if not options: options = ValidationOptions() error_gens = [] if instance['type'] == 'bundle' and 'objects' in instance: ...
Perform STIX JSON Schema validation against STIX input. Find the correct schema by looking at the 'type' property of the `instance` JSON object. Args: instance: A Python dictionary representing a STIX object with a 'type' property. options: ValidationOptions instance with validation options for this validation run. ...
juraj-google-style
def extract_string_pairs_in_ib_file(file_path, special_ui_components_prefix): try: results = [] xmldoc = minidom.parse(file_path) element_name_to_add_func = {'label': add_string_pairs_from_label_element, 'button': add_string_pairs_from_button_element...
Extract the strings pairs (key and comment) from a xib file. Args: file_path (str): The path to the xib file. special_ui_components_prefix (str): If not None, extraction will not warn about internationalized UI components with this class prefix. Returns: list: List of tuples representing the string pairs.
juraj-google-style
def __init__(self, name, fn, dataFormat = DataFormats.DEFAULT): Aggregator.__init__(self, name) self.fn = fn
Creates a highlight aggregator - this will pick one of the values to highlight. Args: name: The name of this aggregator. fn: Callable that takes (a, b) and returns True if b should be selected as the highlight, where as is the previous chosen highlight.
juraj-google-style
def line_distance_similarity(p1a, p1b, p2a, p2b, T=CLOSE_DISTANCE_THRESHOLD): d1 = distance_similarity(p1a, p1b, p2a, T=T) d2 = distance_similarity(p1a, p1b, p2b, T=T) return abs(d1 + d2) * 0.5
Line distance similarity between two line segments Args: p1a ([float, float]): x and y coordinates. Line A start p1b ([float, float]): x and y coordinates. Line A end p2a ([float, float]): x and y coordinates. Line B start p2b ([float, float]): x and y coordinates. Line B end Returns: float: between 0 and 1. Where 1 i...
juraj-google-style
def moma(self, wt_fluxes): reactions = set(self._adjustment_reactions()) v = self._v obj_expr = 0 for f_reaction, f_value in iteritems(wt_fluxes): if f_reaction in reactions: obj_expr += (f_value - v[f_reaction])**2 self._pr...
Minimize the redistribution of fluxes using Euclidean distance. Minimizing the redistribution of fluxes using a quadratic objective function. The distance is minimized by minimizing the sum of (wild type - knockout)^2. Args: wt_fluxes: Dictionary of all the wild type fluxes that will be used to find a close MOMA solu...
juraj-google-style
def set_of_vars(arg_plot): sovs = set(tuple((var + '+').split('+')[:2]) for var in arg_plot.split(',')) sovs.discard(('', '')) return sovs
Build set of needed field variables. Each var is a tuple, first component is a scalar field, second component is either: - a scalar field, isocontours are added to the plot. - a vector field (e.g. 'v' for the (v1,v2,v3) vector), arrows are added to the plot. Args: arg_plot (str): string with variable names separated...
juraj-google-style
def _default_ising_beta_range(h, J): abs_h = [abs(hh) for hh in h.values() if hh != 0] abs_J = [abs(jj) for jj in J.values() if jj != 0] abs_biases = abs_h + abs_J if not abs_biases: return [0.1, 1.0] min_delta_energy = min(abs_biases) abs_bias_dict = {k: abs(v) fo...
Determine the starting and ending beta from h J Args: h (dict) J (dict) Assume each variable in J is also in h. We use the minimum bias to give a lower bound on the minimum energy gap, such at the final sweeps we are highly likely to settle into the current valley.
juraj-google-style
def get_mac_dot_app_dir(directory): return os.path.dirname(os.path.dirname(os.path.dirname(directory)))
Returns parent directory of mac .app Args: directory (str): Current directory Returns: (str): Parent directory of mac .app
juraj-google-style
def index(self, text, terms=None, **kwargs): self.clear() terms = (terms or text.terms.keys()) pairs = combinations(terms, 2) count = comb(len(terms), 2) for (t1, t2) in bar(pairs, expected_size=count, every=1000): score = text.score_braycurtis(t1, t2, **kwargs) self.set_pair(t1, t2,...
Index all term pair distances. Args: text (Text): The source text. terms (list): Terms to index.
codesearchnet
def get_checkpoint_path(model_path): if (os.path.basename(model_path) == model_path): model_path = os.path.join('.', model_path) if (os.path.basename(model_path) == 'checkpoint'): assert tfv1.gfile.Exists(model_path), model_path model_path = tf.train.latest_checkpoint(os.path.dirname(mod...
Work around TF problems in checkpoint path handling. Args: model_path: a user-input path Returns: str: the argument that can be passed to NewCheckpointReader
codesearchnet
def create_config(sections, section_contents): (sections_length, section_contents_length) = (len(sections), len(section_contents)) if (sections_length != section_contents_length): raise ValueError('Mismatch between argument lengths.\nlen(sections) = {}\nlen(section_contents) = {}'.format(sections_length...
Create a config file from the provided sections and key value pairs. Args: sections (List[str]): A list of section keys. key_value_pairs (Dict[str, str]): A list of of dictionaries. Must be as long as the list of sections. That is to say, if there are two sections, there should be two dicts. Returns: configparser.Conf...
codesearchnet
def Aggregated(self, request, global_params=None): config = self.GetMethodConfig('Aggregated') return self._RunMethod(config, request, global_params=global_params)
List the jobs of a project across all regions. **Note:** This method doesn't support filtering the list of jobs by name. Args: request: (DataflowProjectsJobsAggregatedRequest) input message global_params: (StandardQueryParameters, default: None) global arguments Returns: (ListJobsResponse) The response message.
github-repos
def _date_to_datetime(value): if (not isinstance(value, datetime.date)): raise TypeError(('Cannot convert to datetime expected date value; received %s' % value)) return datetime.datetime(value.year, value.month, value.day)
Convert a date to a datetime for Cloud Datastore storage. Args: value: A datetime.date object. Returns: A datetime object with time set to 0:00.
codesearchnet
def get_by_alias(self, alias): if alias not in self._aliases: raise DataInvalidAlias('A dataset with alias {} does not exist'.format(alias)) return self.get_by_index(self._aliases[alias])
Return a dataset by its alias. Args: alias (str): The alias of the dataset that should be returned. Raises: DataInvalidAlias: If the alias does not represent a valid dataset.
juraj-google-style
def PyParseJoinList(string, location, tokens): join_list = [] for token in tokens: try: join_list.append(str(token)) except UnicodeDecodeError: join_list.append(repr(token)) tokens[0] = ''.join(join_list) del tokens[1:]
Return a joined token from a list of tokens. This is a callback method for pyparsing setParseAction that modifies the returned token list to join all the elements in the list to a single token. Args: string (str): original string. location (int): location in the string where the match was made. tokens (list[str]): ex...
juraj-google-style
def rep(parser: Union[(Parser, Sequence[Input])]) -> RepeatedParser: if isinstance(parser, str): parser = lit(parser) return RepeatedParser(parser)
Match a parser zero or more times repeatedly. This matches ``parser`` multiple times in a row. A list is returned containing the value from each match. If there are no matches, an empty list is returned. Args: parser: Parser or literal
codesearchnet
def _normalize_pattern(pattern): if pattern.startswith('regex:'): pattern_type = 'regex' pattern = pattern[len('regex:'):] elif pattern.startswith('wildcard:'): pattern_type = 'wildcard' pattern = pattern[len('wildcard:'):] elif pattern.st...
Return a normalized form of the pattern. Normalize the pattern by removing pattern type prefix if it exists in the pattern. Then return the pattern type and the pattern as a tuple of two strings. Arguments: pattern (str): Route pattern to match request paths Returns: tuple: Ruple of pattern type (str) and pattern (s...
juraj-google-style
def trunc_normal_tf_(tensor: torch.Tensor, mean: float=0.0, std: float=1.0, a: float=-2.0, b: float=2.0) -> torch.Tensor: with torch.no_grad(): _trunc_normal_(tensor, 0, 1.0, a, b) tensor.mul_(std).add_(mean)
Fills the input Tensor with values drawn from a truncated normal distribution. The values are effectively drawn from the normal distribution :math:`\mathcal{N}( ext{mean}, ext{std}^2)` with values outside :math:`[a, b]` redrawn until they are within the bounds. The method used for generating the random values ...
github-repos
def serialize_example(transformed_json_data, info_dict): import six import tensorflow as tf def _make_int64_list(x): return tf.train.Feature(int64_list=tf.train.Int64List(value=x)) def _make_bytes_list(x): return tf.train.Feature(bytes_list=tf.train.BytesList(value=x)) def _make_float_list(x): ...
Makes a serialized tf.example. Args: transformed_json_data: dict of transformed data. info_dict: output of feature_transforms.get_transfrormed_feature_info() Returns: The serialized tf.example version of transformed_json_data.
juraj-google-style
def handle_document_error(self, item_session: ItemSession) -> Actions: self._waiter.increment() self._statistics.errors[ServerError] += 1 action = self.handle_response(item_session) if (action == Actions.NORMAL): item_session.set_status(Status.error) return action
Callback for when the document only describes an server error. Returns: A value from :class:`.hook.Actions`.
codesearchnet
def sort_prefixes(orig, prefixes='@+'): new = '' for prefix in prefixes: if prefix in orig: new += prefix return new
Returns a sorted list of prefixes. Args: orig (str): Unsorted list of prefixes. prefixes (str): List of prefixes, from highest-priv to lowest.
juraj-google-style
def send_tpu_embedding_gradients(inputs, config, learning_rates=None, name=None): if learning_rates is None: learning_rates = [] return gen_tpu_ops.send_tpu_embedding_gradients(inputs=inputs, learning_rates=learning_rates, config=config, name=name)
A placeholder op for feeding per-sample gradients to the embedding layer. Args: inputs: A TensorList of gradients with which to update embedding tables. This argument has the same length and shapes as the return value of RecvTPUEmbeddingActivations, but contains gradients of the model's loss with respect to the embedd...
github-repos
def shift(self, time: int) -> 'Timeslot': return Timeslot(self.interval.shift(time), self.channel)
Return a new Timeslot shifted by `time`. Args: time: time to be shifted
codesearchnet
def protein_only_and_noH(self, keep_ligands=None, force_rerun=False): log.debug('{}: running protein receptor isolation...'.format(self.id)) if (not self.dockprep_path): return ValueError('Please run dockprep') receptor_mol2 = op.join(self.dock_dir, '{}_receptor.mol2'.format(self.id)) receptor_n...
Isolate the receptor by stripping everything except protein and specified ligands. Args: keep_ligands (str, list): Ligand(s) to keep in PDB file force_rerun (bool): If method should be rerun even if output file exists
codesearchnet
def limit(self, accountID, **kwargs): return self.create( accountID, order=LimitOrderRequest(**kwargs) )
Shortcut to create a Limit Order in an Account Args: accountID : The ID of the Account kwargs : The arguments to create a LimitOrderRequest Returns: v20.response.Response containing the results from submitting the request
juraj-google-style
def unexpected_disconnect(self, conn_or_internal_id): data = { 'id': conn_or_internal_id } action = ConnectionAction('force_disconnect', data, sync=False) self._actions.put(action)
Notify that there was an unexpected disconnection of the device. Any in progress operations are canceled cleanly and the device is transitioned to a disconnected state. Args: conn_or_internal_id (string, int): Either an integer connection id or a string internal_id
juraj-google-style
def copy_update(pb_message, **kwds): result = pb_message.__class__() result.CopyFrom(pb_message) for (k, v) in kwds.items(): setattr(result, k, v) return result
Returns a copy of the PB object, with some fields updated. Args: pb_message: **kwds: Returns:
codesearchnet
def _extract_nn_info(self, structure, nns): if (self.targets is None): targets = structure.composition.elements else: targets = self.targets siw = [] max_weight = max((nn[self.weight] for nn in nns.values())) for nstats in nns.values(): site = nstats['site'] if ((nsta...
Given Voronoi NNs, extract the NN info in the form needed by NearestNeighbors Args: structure (Structure): Structure being evaluated nns ([dicts]): Nearest neighbor information for a structure Returns: (list of tuples (Site, array, float)): See nn_info
codesearchnet
def orthologize(ast, bo, species_id: str): if (not species_id): bo.validation_messages.append(('WARNING', 'No species id was provided for orthologization')) return ast if isinstance(ast, NSArg): if ast.orthologs: if ast.orthologs.get(species_id, None): ortholo...
Recursively orthologize BEL Entities in BEL AST using API endpoint NOTE: - will take first ortholog returned in BEL.bio API result (which may return more than one ortholog) Args: ast (BEL): BEL AST endpoint (str): endpoint url with a placeholder for the term_id Returns: BEL: BEL AST
codesearchnet
def CreateSmartCampaign(client, budget_id, merchant_id): campaign_service = client.GetService('CampaignService', version='v201809') campaign = {'name': ('Shopping campaign campaign_operations = [{'operator': 'ADD', 'operand': campaign}] result = campaign_service.mutate(campaign_operations)['value'][0] ...
Adds a new Smart Shopping campaign. Args: client: an AdWordsClient instance. budget_id: the str ID of the budget to be associated with the Shopping campaign. merchant_id: the str ID of the merchant account to be associated with the Shopping campaign. Returns: A campaign ID.
codesearchnet
def update_course(self, course, enterprise_customer, enterprise_context): course['course_runs'] = self.update_course_runs(course_runs=(course.get('course_runs') or []), enterprise_customer=enterprise_customer, enterprise_context=enterprise_context) marketing_url = course.get('marketing_url') if marketing_ur...
Update course metadata of the given course and return updated course. Arguments: course (dict): Course Metadata returned by course catalog API enterprise_customer (EnterpriseCustomer): enterprise customer instance. enterprise_context (dict): Enterprise context to be added to course runs and URLs.. Returns: (dict): Up...
codesearchnet
def beam_row_from_dict(row: dict, schema): if not isinstance(schema, (bigquery.TableSchema, bigquery.TableFieldSchema)): schema = get_bq_tableschema(schema) beam_row = {} for field in schema.fields: name = field.name mode = field.mode.upper() type = field.type.upper() ...
Converts a dictionary row to a Beam Row. Nested records and lists are supported. Args: row (dict): The row to convert. schema (str, dict, ~apache_beam.io.gcp.internal.clients.bigquery.bigquery_v2_messages.TableSchema): The table schema. Will be used to help convert the row. Returns: ~apache_beam.pvalue.Row: The conve...
github-repos
def match(self, message: Message) -> bool: if self.template: return self.template.match(message) return True
Matches a message with the behaviour's template Args: message(spade.message.Message): the message to match with Returns: bool: wheter the messaged matches or not
codesearchnet
def write_data(worksheet, data): if not data: return if isinstance(data, list): rows = data else: rows = [data] if isinstance(rows[0], dict): keys = get_keys(rows) worksheet.append([utilities.convert_snake_to_title_case(key) for key in keys]) for ro...
Writes data into worksheet. Args: worksheet: worksheet to write into data: data to be written
juraj-google-style
def crop_and_resize(image, boxes, box_ind, crop_size, pad_border=True): assert isinstance(crop_size, int), crop_size boxes = tf.stop_gradient(boxes) if pad_border: image = tf.pad(image, [[0, 0], [0, 0], [1, 1], [1, 1]], mode='SYMMETRIC') boxes = boxes + 1 @under_name...
Aligned version of tf.image.crop_and_resize, following our definition of floating point boxes. Args: image: NCHW boxes: nx4, x1y1x2y2 box_ind: (n,) crop_size (int): Returns: n,C,size,size
juraj-google-style
def cn_occupation_energy( self, delta_occupation=None ): nn_occupations = self.site_specific_nn_occupation() if delta_occupation: for site in delta_occupation: assert( site in nn_occupations ) nn_occupations[ site ] += delta_occupation[ site ] ...
The coordination-number dependent energy for this site. Args: delta_occupation (:obj:Dict(Str:Int), optional): A dictionary of a change in (site-type specific) coordination number, e.g. { 'A' : 1, 'B' : -1 }. If this is not None, the coordination-number dependent energy is calculated including these changes in neighbo...
juraj-google-style