code
stringlengths
20
4.93k
docstring
stringlengths
33
1.27k
source
stringclasses
3 values
def __decode_dictionary(self, message_type, dictionary): message = message_type() for key, value in six.iteritems(dictionary): if value is None: try: message.reset(key) except AttributeError: pass ...
Merge dictionary in to message. Args: message: Message to merge dictionary in to. dictionary: Dictionary to extract information from. Dictionary is as parsed from JSON. Nested objects will also be dictionaries.
juraj-google-style
def sin(x): return math_ops.sin(x)
Computes sin of x element-wise. Args: x: Tensor or variable. Returns: A tensor.
github-repos
def Decrement(self, key): with self._lock: if _IsHashable(key): if key in self._d: if self._d[key] > 1: self._d[key] -= 1 else: del self._d[key] else: try: i = self._unhashable_items.index...
Atomically decrement a count by 1. Expunge the item if the count is 0. If the item is not present, has no effect. Args: key: the key being counted.
github-repos
def random(self, shape, tf_fn, kwargs): slice_shape = self.slice_shape(shape) x = tf_fn(slice_shape, **kwargs) layout = self.tensor_layout(shape) mesh_axes = [i for i in xrange(self.ndims) if i not in layout.tensor_axis_to_mesh_axis] multiplier = 1.0 ...
Call a random tf operation (e.g. random_uniform). Args: shape: a Shape tf_fn: a function such as tf.random.uniform kwargs: kwargs to pass to tf_fn, except for seed Returns: a LaidOutTensor
juraj-google-style
def plot(self, data): import IPython if ((not isinstance(data, dict)) or (not all((isinstance(v, pd.DataFrame) for v in data.values())))): raise ValueError('Expect a dictionary where the values are all dataframes.') gfsg = GenericFeatureStatisticsGenerator() data = [{'name': k, 'table': self._re...
Plots an overview in a list of dataframes Args: data: a dictionary with key the name, and value the dataframe.
codesearchnet
def __call__(self, request: beam.Row, *args, **kwargs): try: entity_id = request._asdict()[self.row_key] except KeyError: raise KeyError('Enrichment requests to Vertex AI Feature Store should contain a field: %s in the input `beam.Row` to join the input with fetched response. This is used as the...
Fetches feature value for an entity-id from Vertex AI Feature Store. Args: request: the input `beam.Row` to enrich.
github-repos
def get_cached_response(cls, key): request_cached_response = DEFAULT_REQUEST_CACHE.get_cached_response(key) if not request_cached_response.is_found: django_cached_response = cls._get_cached_response_from_django_cache(key) cls._set_request_cache_if_django_cache_hit(key, d...
Retrieves a CachedResponse for the provided key. Args: key (string) Returns: A CachedResponse with is_found status and value.
juraj-google-style
def print_dict(py_dict): for gpu, cc in py_dict.items(): print('{:<25}{:<25}'.format(gpu, cc))
Prints dictionary with formatting (2 column table). Args: py_dict: Dictionary that is to be printed out in a table format.
github-repos
def __init__(self, project_key, conf_path=settings.ZEO_CLIENT_PATH): super(self.__class__, self).__init__( conf_path=conf_path, project_key=project_key )
Constructor. Args: project_key (str): Project key which is used for the root of DB. conf_path (str): Path to the client zeo configuration file. Default :attr:`.settings.ZEO_CLIENT_PATH`.
juraj-google-style
def load(self, filepath, file_encoding=None): with open(filepath, encoding=file_encoding) as inf: for line in inf: current_line = str(line).strip() if current_line.startswith("@prefix"): self._add_ttl_ns(current_line.replace("\n","")) ...
Reads the the beginning of a turtle file and sets the prefix's used in that file and sets the prefix attribute Args: filepath: the path to the turtle file file_encoding: specify a specific encoding if necessary
juraj-google-style
def delete(self, timeout=-1, custom_headers=None, force=False): uri = self.data['uri'] logger.debug("Delete resource (uri = %s)" % (str(uri))) return self._helper.delete(uri, timeout=timeout, custom_headers=custom_headers, force=force)
Deletes current resource. Args: timeout: Timeout in seconds. custom_headers: Allows to set custom http headers. force: Flag to force the operation.
juraj-google-style
def add_tags(self, ID3=None): if ID3 is None: ID3 = self.ID3 if self.tags is None: self.ID3 = ID3 self.tags = ID3() else: raise error("an ID3 tag already exists")
Add an empty ID3 tag to the file. Args: ID3 (ID3): An ID3 subclass to use or `None` to use the one that used when loading. A custom tag reader may be used in instead of the default `ID3` object, e.g. an `mutagen.easyid3.EasyID3` reader.
juraj-google-style
def assert_inbounds(num, low, high, msg='', eq=False, verbose=not util_arg.QUIET): r from utool import util_str if util_arg.NO_ASSERTS: return passed = util_alg.inbounds(num, low, high, eq=eq) if isinstance(passed, np.ndarray): passflag = np.all(passed) else: passflag = p...
r""" Args: num (scalar): low (scalar): high (scalar): msg (str):
juraj-google-style
def data_received(self, data): try: self.responders[-1].on_data(data) except Exception as error: self.handle_error(error)
(asyncio.Protocol member) Called upon when there is new data to be passed to the protocol. The data is forwarded to the top of the responder stack (via the on_data method). If an excpetion occurs while this is going on, the Exception is forwarded to the protocol's handle_error method. Args: data (bytes): Bytes from t...
juraj-google-style
def get(self, *args, **kwargs): if (not self.enabled): return None cache_key = self.make_key(args, kwargs) with self._cache_lock: if (cache_key in self._cache): (expirytime, item) = self._cache[cache_key] if (expirytime >= time()): return item ...
Get an item from the cache for this combination of args and kwargs. Args: *args: any arguments. **kwargs: any keyword arguments. Returns: object: The object which has been found in the cache, or `None` if no unexpired item is found. This means that there is no point storing an item in the cache if it is `None`.
codesearchnet
def _publish_status(self, slug, data): status_topic = self.topics.prefix + 'devices/{}/data/status'.format(slug) self._logger.debug("Publishing status message: (topic=%s) (message=%s)", status_topic, str(data)) self.client.publish(status_topic, data)
Publish a status message for a device Args: slug (string): The device slug that we are publishing on behalf of data (dict): The status message data to be sent back to the caller
juraj-google-style
def get_unverified_claims(token): try: claims = jws.get_unverified_claims(token) except: raise JWTError('Error decoding token claims.') try: claims = json.loads(claims.decode('utf-8')) except ValueError as e: raise JWTError(('Invalid claims string: %s' % e)) if (not i...
Returns the decoded claims without verification of any kind. Args: token (str): A signed JWT to decode the headers from. Returns: dict: The dict representation of the token claims. Raises: JWTError: If there is an exception decoding the token.
codesearchnet
def convert_to_eager_tensor(value, ctx, dtype=None) -> ops._EagerTensorBase: if isinstance(value, np.ndarray): value = value.copy() if isinstance(value, ops.EagerTensor): if dtype is not None and value.dtype != dtype: raise TypeError(f'Expected tensor {value} with dtype {dtype!r}, bu...
Converts the given `value` to an `EagerTensor`. Note that this function could return cached copies of created constants for performance reasons. Args: value: value to convert to EagerTensor. ctx: value of context.context(). dtype: optional desired dtype of the converted EagerTensor. Returns: EagerTensor created from...
github-repos
def get_config(self, key_name): if (key_name in self.config): return self.config.get(key_name) return self.Configuration.default(key_name, inst=self)
Return configuration value Args: key_name (str): configuration key Returns: The value for the specified configuration key, or if not found in the config the default value specified in the Configuration Handler class specified inside this component
codesearchnet
def GetYearFromPosixTime(posix_time, timezone=pytz.UTC): datetime_object = datetime.datetime.fromtimestamp(posix_time, tz=timezone) return datetime_object.year
Gets the year from a POSIX timestamp The POSIX time is the number of seconds since 1970-01-01 00:00:00 UTC. Args: posix_time: An integer containing the number of seconds since 1970-01-01 00:00:00 UTC. timezone: Optional timezone of the POSIX timestamp. Returns: The year of the POSIX timestamp. Raises: ValueError: I...
juraj-google-style
def coordination_number_delta_E( self ): initial_site_neighbours = [ s for s in self.initial_site.p_neighbours if s.is_occupied ] final_site_neighbours = [ s for s in self.final_site.p_neighbours if s.is_occupied and s is not self.initial_site ] initial_cn_occupation_energy = ( self.i...
Coordination-number dependent energy conrtibution to the change in system energy if this jump were accepted. Args: None Returns: (Float): delta E (coordination-number)
juraj-google-style
def get_custom_modules_path() -> Path: channel_path = (get_base_path() / 'modules') if (not channel_path.exists()): channel_path.mkdir(parents=True) return channel_path
Get the path to custom channels Returns: The path for custom channels.
codesearchnet
def check_absolute_refs(self, construction_table): c_table = construction_table problem_index = [i for i in c_table.index[:3] if (not self._has_valid_abs_ref(i, c_table))] return problem_index
Checks first three rows of ``construction_table`` for linear references Checks for each index from first to third row of the ``construction_table``, if the references are colinear. This case has to be specially treated, because the references are not only atoms (to fix internal degrees of freedom) but also points in c...
codesearchnet
def holiday_day(self, value=None): if (value is not None): try: value = str(value) except ValueError: raise ValueError('value {} need to be of type str for field `holiday_day`'.format(value)) if (',' in value): raise ValueError('value should not contain a ...
Corresponds to IDD Field `holiday_day` Args: value (str): value for IDD Field `holiday_day` if `value` is None it will not be checked against the specification and is assumed to be a missing value Raises: ValueError: if `value` is not a valid value
codesearchnet
def run_job(self, section_id, session=None): if (not self.parser.has_section(section_id)): raise KeyError('section not found: {}'.format(section_id)) session = (session or Session()) for (name, looter_cls) in six.iteritems(self._CLS_MAP): targets = self.get_targets(self._get(section_id, name...
Run a job as described in the section named ``section_id``. Raises: KeyError: when the section could not be found.
codesearchnet
def skipForDeviceType(self, device_type: typing.List[str], reason: str, unless_device_count_equals_to=None): physical_device_types = set([d.device_type for d in tf_config.list_physical_devices()]) for device in device_type: if device == 'TPU' and is_tpu_present(): if unless_device_count_equa...
Skip the test for the specific device_type. Args: device_type: list of device types, one of "CPU", "GPU", or "TPU". reason: string that describe the reason for skipping the test. unless_device_count_equals_to: Optional int. This parameter only works if device_type is "TPU". If set, the test will be skipped unless the ...
github-repos
def volume(self): return np.dot(self.matrix[0], np.cross(self.matrix[1], self.matrix[2]))
The cell volume. Args: None Returns: (float): The cell volume.
codesearchnet
async def on_message(message): server = message.server author = message.author channel = message.channel content = message.content data = datatools.get_data() if server is not None and author != channel.server.me: prefix = data["discord"]["servers"][server.id][...
The on_message event handler for this module Args: message (discord.Message): Input message
juraj-google-style
def validate_default_element(self, value): if isinstance(value, (six.string_types, six.integer_types)): if self.__type: self.__type(value) return value return super(EnumField, self).validate_default_element(value)
Validate default element of Enum field. Enum fields allow for delayed resolution of default values when the type of the field has not been resolved. The default value of a field may be a string or an integer. If the Enum type of the field has been resolved, the default value is validated against that type. Args: valu...
juraj-google-style
class GraniteMoeHybridMLP(nn.Module): def __init__(self, config: GraniteMoeHybridConfig): super(GraniteMoeHybridMLP, self).__init__() self.input_size = config.hidden_size self.hidden_size = config.shared_intermediate_size self.activation = ACT2FN[config.hidden_act] self.inpu...
MLP layer for shared experts Args: config: Configuration object with model hyperparameters.
github-repos
def delete_volume(self, volume_name: str): if not self._manager: raise RuntimeError('Volumes can only be deleted ' 'on swarm manager nodes') self._api_client.remove_volume(volume_name)
Removes/stops a docker volume. Only the manager nodes can delete a volume Args: volume_name (string): Name of the volume
juraj-google-style
def unionfs(rw='rw', ro=None, union='union'): from functools import wraps def wrap_in_union_fs(func): '\n Function that wraps a given function inside the file system.\n\n Args:\n func: The function that needs to be wrapped inside the unions fs.\n Return:\n The...
Decorator for the UnionFS feature. This configures a unionfs for projects. The given base_dir and/or image_dir are layered as follows: image_dir=RW:base_dir=RO All writes go to the image_dir, while base_dir delivers the (read-only) versions of the rest of the filesystem. The unified version will be provided in the pr...
codesearchnet
class AutoContrast(BaseImagePreprocessingLayer): _USE_BASE_FACTOR = False _VALUE_RANGE_VALIDATION_ERROR = 'The `value_range` argument should be a list of two numbers. ' def __init__(self, value_range=(0, 255), **kwargs): super().__init__(**kwargs) self._set_value_range(value_range) def...
Performs the auto-contrast operation on an image. Auto contrast stretches the values of an image across the entire available `value_range`. This makes differences between pixels more obvious. An example of this is if an image only has values `[0, 1]` out of the range `[0, 255]`, auto contrast will change the `1` value...
github-repos
def get_atomic_python_constant(variable: cfg.Variable, constant_type=None): atomic = get_atomic_value(variable) return atomic.ctx.convert.value_to_constant(atomic, constant_type)
Get the concrete atomic Python value stored in this variable. This is used for things that are stored in cfg.Variable, but we need the actual data in order to proceed. E.g. function / class definitions. Args: variable: A cfg.Variable. It can only have one possible value. constant_type: Optionally, the required type o...
github-repos
def _ParseOrMerge(self, lines, message): tokenizer = _Tokenizer(lines) while not tokenizer.AtEnd(): self._MergeField(tokenizer, message)
Converts an text representation of a protocol message into a message. Args: lines: Lines of a message's text representation. message: A protocol buffer message to merge into. Raises: ParseError: On text parsing problems.
juraj-google-style
def save(self, outfname): f = BZ2File(outfname, 'w') self.doc.writexml(f, addindent=' ', newl='\n') f.close()
Save the environment of a sv file to be used with soniv visualiser Args: outfname(str): full path to the file storing the environment
juraj-google-style
def wrap(tensor, books=None, tensor_shape=None): if (books is None): books = bookkeeper.for_default_graph() if isinstance(tensor, PrettyTensor): return tensor.as_layer() elif isinstance(tensor, UnboundVariable): def set_input_from_unbound_var(data): 'Sets the input from ...
Creates an input layer representing the given tensor. Args: tensor: The tensor. books: The bookkeeper; this is usually not required unless you are building multiple `tf.Graphs.` tensor_shape: An optional shape that will be set on the Tensor or verified to match the tensor. Returns: A layer.
codesearchnet
def __init__( self, cert, urlbase='https: ): self.cert = cert self.urlbase = urlbase if not urlbase.endswith('/'): self.urlbase += '/' self._session = requests.Session() self._session.cert = cert self....
Initialize Base instance. Args: cert (unicode): File path to the certificate used to authenticate access to LMod Web service urlbase (str): The URL of the LMod Web service. i.e. ``learning-modules.mit.edu`` or ``learning-modules-test.mit.edu``
juraj-google-style
def obtain(self, dest): (url, rev_options) = self.get_url_rev_options(self.url) if (not os.path.exists(dest)): self.fetch_new(dest, url, rev_options) return rev_display = rev_options.to_display() if self.is_repository_directory(dest): existing_url = self.get_remote_url(dest) ...
Install or update in editable mode the package represented by this VersionControl object. Args: dest: the repository directory in which to install or update.
codesearchnet
def _GetFormatErrorLocation(self, yaml_definition, last_definition_object): name = yaml_definition.get('name', None) if name: error_location = 'in: {0:s}'.format((name or '<NAMELESS>')) elif last_definition_object: error_location = 'after: {0:s}'.format(last_definition_object.name) else:...
Retrieves a format error location. Args: yaml_definition (dict[str, object]): current YAML definition. last_definition_object (DataTypeDefinition): previous data type definition. Returns: str: format error location.
codesearchnet
def asarray(self, array_like, *, xnp: numpy_utils.NpModule, casting: Union[Casting, str]=Casting.ALL): casting = Casting(casting) from_dtype = numpy_utils.lazy.dtype_from_array(array_like, strict=False) to_dtype = self._get_target_dtype(from_dtype) if casting == casting.NONE: if to_dtype is None...
Creates an `xnp.ndarray` from the `array_like`. Args: array_like: Any array-like xnp: Target numpy module casting: If `NONE`, prevent casting. Returns: array: The xnp array.
github-repos
def depth_july_average_ground_temperature(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 `depth_july_a...
Corresponds to IDD Field `depth_july_average_ground_temperature` Args: value (float): value for IDD Field `depth_july_average_ground_temperature` Unit: C if `value` is None it will not be checked against the specification and is assumed to be a missing value Raises: ValueError: if `value` is not a valid value
juraj-google-style
def LoadGDAL(filename, no_data=None): if (not GDAL_AVAILABLE): raise Exception('richdem.LoadGDAL() requires GDAL.') allowed_types = {gdal.GDT_Byte, gdal.GDT_Int16, gdal.GDT_Int32, gdal.GDT_UInt16, gdal.GDT_UInt32, gdal.GDT_Float32, gdal.GDT_Float64} src_ds = gdal.Open(filename) srcband = src_ds....
Read a GDAL file. Opens any file GDAL can read, selects the first raster band, and loads it and its metadata into a RichDEM array of the appropriate data type. If you need to do something more complicated, look at the source of this function. Args: filename (str): Name of the raster file to open no_data (float):...
codesearchnet
def is_full(cm, nodes1, nodes2): if ((not nodes1) or (not nodes2)): return True cm = cm[np.ix_(nodes1, nodes2)] return (cm.sum(0).all() and cm.sum(1).all())
Test connectivity of one set of nodes to another. Args: cm (``np.ndarrray``): The connectivity matrix nodes1 (tuple[int]): The nodes whose outputs to ``nodes2`` will be tested. nodes2 (tuple[int]): The nodes whose inputs from ``nodes1`` will be tested. Returns: bool: ``True`` if all elements in ``nodes1`` output to s...
codesearchnet
def download_and_extract(uri, name, path): if (not os.path.exists(path)): os.makedirs(path) if (not os.listdir(path)): with tmpdir() as tmp: if uri.startswith('s3: dst = os.path.join(tmp, 'tar_file') s3_download(uri, dst) with tarfile.o...
Download, prepare and install a compressed tar file from S3 or local directory as an entry point. SageMaker Python SDK saves the user provided entry points as compressed tar files in S3 Args: name (str): name of the entry point. uri (str): the location of the entry point. path (bool): The path where the script will b...
codesearchnet
def Collect( self, knowledge_base, artifact_definition, searcher): for source in artifact_definition.sources: if source.type_indicator not in ( artifact_definitions.TYPE_INDICATOR_WINDOWS_REGISTRY_KEY, artifact_definitions.TYPE_INDICATOR_WINDOWS_REGISTRY_VALUE): continue...
Collects values using a Windows Registry value artifact definition. Args: knowledge_base (KnowledgeBase): to fill with preprocessing information. artifact_definition (artifacts.ArtifactDefinition): artifact definition. searcher (dfwinreg.WinRegistrySearcher): Windows Registry searcher to preprocess the Windows Registr...
juraj-google-style
def join(self, basepath, *paths): if not basepath.startswith(BlobStorageFileSystem.AZURE_FILE_SYSTEM_PREFIX): raise ValueError('Basepath %r must be an Azure Blob Storage path.' % basepath) path = basepath for p in paths: path = path.rstrip('/') + '/' + p.lstrip('/') return path
Join two or more pathname components for the filesystem Args: basepath: string path of the first component of the path paths: path components to be added Returns: full path after combining all the passed components
github-repos
def create_band_mask_from_inputs(from_blocked_mask, to_blocked_mask): exp_blocked_to_pad = jnp.concatenate([to_blocked_mask[:, 1:-3], to_blocked_mask[:, 2:-2], to_blocked_mask[:, 3:-1]], axis=2) band_mask = jnp.einsum('blq,blk->blqk', from_blocked_mask[:, 2:-2], exp_blocked_to_pad) band_mask = jnp.expand_di...
Create 3D attention mask from a 2D tensor mask. Args: from_blocked_mask: 2D Tensor of shape [batch_size, from_seq_length//from_block_size, from_block_size]. to_blocked_mask: int32 Tensor of shape [batch_size, to_seq_length//to_block_size, to_block_size]. Returns: float Tensor of shape [batch_size, 1, from_seq_length/...
github-repos
def get_experiment_from_id(self, experiment_id): experiment = self.experiment_id_map.get(experiment_id) if experiment: return experiment self.logger.error('Experiment ID "%s" is not in datafile.' % experiment_id) self.error_handler.handle_error(exceptions.InvalidExperimentException(enums.E...
Get experiment for the provided experiment ID. Args: experiment_id: Experiment ID for which experiment is to be determined. Returns: Experiment corresponding to the provided experiment ID.
juraj-google-style
def export_json_object(dict_obj, filename=None): try: if filename: try: with open(filename, 'w') as handle: handle.write(json.dumps(dict_obj, indent=4, sort_keys=True)) logger.info( '%s: Wrote %s to local filesy...
Summary: exports object to block filesystem object Args: :dict_obj (dict): dictionary object :filename (str): name of file to be exported (optional) Returns: True | False Boolean export status
juraj-google-style
def _append_expectation(self, expectation_config): expectation_type = expectation_config['expectation_type'] json.dumps(expectation_config) if ('column' in expectation_config['kwargs']): column = expectation_config['kwargs']['column'] self._expectations_config.expectations = [f for f in filt...
Appends an expectation to `DataAsset._expectations_config` and drops existing expectations of the same type. If `expectation_config` is a column expectation, this drops existing expectations that are specific to \ that column and only if it is the same expectation type as `expectation_config`. Otherwise, if it's not a...
codesearchnet
def _testExportImportAcrossScopes(self, graph_fn, use_resource): with ops.Graph().as_default() as original_graph: with variable_scope.variable_scope('dropA/dropB/keepA'): graph_fn(use_resource=use_resource) exported_meta_graph_def = meta_graph.export_scoped_meta_graph(graph=original_graph, e...
Tests export and importing a graph across scopes. Args: graph_fn: A closure that creates a graph on the current scope. use_resource: A bool indicating whether or not to use ResourceVariables.
github-repos
def log_variables(variables=None): if (variables is None): variables = (tf.global_variables() + tf.local_variables()) for row in format_variables(variables, join_lines=False): tf.logging.info(row)
Logs variable information. This function logs the name, shape, type, collections, and device for either all variables or a given iterable of variables. In the "Device" columns, the nature of the variable (legacy or resource (for ResourceVariables)) is also specified in parenthesis. Args: variables: iterable of variab...
codesearchnet
def mean_min_time_distance(item_a, item_b, max_value): times_a = item_a.times.reshape((item_a.times.size, 1)) times_b = item_b.times.reshape((1, item_b.times.size)) distance_matrix = (times_a - times_b) ** 2 mean_min_distances = np.sqrt(distance_matrix.min(axis=0).mean() + distance_matrix.min(axis=...
Calculate the mean time difference among the time steps in each object. Args: item_a: STObject from the first set in TrackMatcher item_b: STObject from the second set in TrackMatcher max_value: Maximum distance value used as scaling value and upper constraint. Returns: Distance value between 0 and 1.
juraj-google-style
def reset_logformat_timestamped(logger: logging.Logger, extraname: str='', level: int=logging.INFO) -> None: namebit = ((extraname + ':') if extraname else '') fmt = (('%(asctime)s.%(msecs)03d:%(levelname)s:%(name)s:' + namebit) + '%(message)s') reset_logformat(logger, fmt=fmt) logger.setLevel(level)
Apply a simple time-stamped log format to an existing logger, and set its loglevel to either ``logging.DEBUG`` or ``logging.INFO``. Args: logger: logger to modify extraname: additional name to append to the logger's name level: log level to set
codesearchnet
def GetFrequencyStartTimes(self): start_times = [] for freq_tuple in self.GetFrequencyTuples(): (start_secs, end_secs, headway_secs) = freq_tuple[0:3] run_secs = start_secs while (run_secs < end_secs): start_times.append(run_secs) run_secs += headway_secs retu...
Return a list of start time for each headway-based run. Returns: a sorted list of seconds since midnight, the start time of each run. If this trip doesn't have headways returns an empty list.
codesearchnet
def adafactor_decay_rate_adam(beta2): t = tf.cast(tf.train.get_or_create_global_step(), tf.float32) + 1.0 decay = beta2 * (1.0 - tf.pow(beta2, t - 1.0)) / (1.0 - tf.pow(beta2, t)) return decay
Second-moment decay rate like Adam, subsuming the correction factor. Args: beta2: a float between 0 and 1 Returns: a scalar
juraj-google-style
def unroll_state_saver(input_layer, name, state_shapes, template, lengths=None): state_saver = input_layer.bookkeeper.recurrent_state state_names = [((STATE_NAME % name) + ('_%d' % i)) for i in xrange(len(state_shapes))] if hasattr(state_saver, 'add_state'): for (state_name, state_shape) in zip(stat...
Unrolls the given function with state taken from the state saver. Args: input_layer: The input sequence. name: The name of this layer. state_shapes: A list of shapes, one for each state variable. template: A template with unbound variables for input and states that returns a RecurrentResult. lengths: The length of eac...
codesearchnet
def to_value(original_string, corenlp_value=None): if isinstance(original_string, Value): return original_string if not corenlp_value: corenlp_value = original_string amount = NumberValue.parse(corenlp_value) if amount is not None: return NumberValue(amount, or...
Convert the string to Value object. Args: original_string (basestring): Original string corenlp_value (basestring): Optional value returned from CoreNLP Returns: Value
juraj-google-style
def precipitable_water(self, value=999.0): if (value is not None): try: value = float(value) except ValueError: raise ValueError('value {} need to be of type float for field `precipitable_water`'.format(value)) self._precipitable_water = value
Corresponds to IDD Field `precipitable_water` Args: value (float): value for IDD Field `precipitable_water` Unit: mm Missing value: 999.0 if `value` is None it will not be checked against the specification and is assumed to be a missing value Raises: ValueError: if `value` is not a valid value
codesearchnet
def read_bytes(self, length) -> bytes: value = self.stream.read(length) return value
Read the specified number of bytes from the stream. Args: length (int): number of bytes to read. Returns: bytes: `length` number of bytes.
codesearchnet
def hash_file(path, block_size=65536): sha256 = hashlib.sha256() with open(path, 'rb') as f: for block in iter((lambda : f.read(block_size)), b''): sha256.update(block) return sha256.hexdigest()
Returns SHA256 checksum of a file Args: path (string): Absolute file path of file to hash block_size (int, optional): Number of bytes to read per block
codesearchnet
def search_by_user(self, screen_name, count=100): results = self._api.user_timeline(screen_name=screen_name, count=count) return results
Search tweets by user. Args: screen_name: screen name count: the number of tweets Returns: list: tweet list
juraj-google-style
def RegisterCredentials(cls, credentials): if credentials.type_indicator in cls._credentials: raise KeyError( 'Credentials object already set for type indicator: {0:s}.'.format( credentials.type_indicator)) cls._credentials[credentials.type_indicator] = credentials
Registers a path specification credentials. Args: credentials (Credentials): credentials. Raises: KeyError: if credentials object is already set for the corresponding type indicator.
juraj-google-style
def build_one_definition_example(self, def_name): if def_name in self.definitions_example.keys(): return True elif def_name not in self.specification['definitions'].keys(): return False self.definitions_example[def_name] = {} def_spec = self.specific...
Build the example for the given definition. Args: def_name: Name of the definition. Returns: True if the example has been created, False if an error occured.
juraj-google-style
class AnomalyDetector(abc.ABC): def __init__(self, model_id: Optional[str]=None, features: Optional[Iterable[str]]=None, target: Optional[str]=None, threshold_criterion: Optional[ThresholdFn]=None, **kwargs): self._model_id = model_id if model_id is not None else getattr(self, 'spec_type', lambda: 'unknown...
An abstract base class for anomaly detectors. Args: model_id: The ID of detector (model). Defaults to the value of the `spec_type` attribute, or 'unknown' if not set. features: An Iterable of strings representing the names of the input features in the `beam.Row` target: The name of the target field in the `beam.Row`. ...
github-repos
def make_grid_texture(num_h_lines=10, num_v_lines=10, resolution=50): x_h, y_h = make_lines_texture(num_h_lines, resolution) y_v, x_v = make_lines_texture(num_v_lines, resolution) return np.concatenate([x_h, x_v]), np.concatenate([y_h, y_v])
Makes a texture consisting of a grid of vertical and horizontal lines. Args: num_h_lines (int): the number of horizontal lines to draw num_v_lines (int): the number of vertical lines to draw resolution (int): the number of midpoints to draw on each line Returns: A texture.
juraj-google-style
def RemoveTransaction(self, tx): if BC.Default() is None: return False if not BC.Default().ContainsTransaction(tx.Hash): return False if tx.Hash.ToBytes() in self.MemPool: del self.MemPool[tx.Hash.ToBytes()] return True return F...
Remove a transaction from the memory pool if it is found on the blockchain. Args: tx (neo.Core.TX.Transaction): instance. Returns: bool: True if successfully removed. False otherwise.
juraj-google-style
def _cumprod(l): ret = [1] for item in l: ret.append((ret[(- 1)] * item)) return ret
Cumulative product of a list. Args: l: a list of integers Returns: a list with one more element (starting with 1)
codesearchnet
def __init__(self, filename, damethod, date, ensize): self.filename = filename self.damethod = damethod self.date = date self.ensize = ensize self.dafile = h5py.File(self.filename, "a") self.dafile.attrs['damethod'] = self.damethod ...
Initialize darun attributes Args: filename (str): Absolute path of file name as a string with `hdf5` extension damethod (str): Name of the assimilation method used, i.e. `enkf`. date (str): Date of the experiment `MM-DD-YYYY:HHHH` ensize (int): ensemble size
juraj-google-style
def _GetUserTypeAndPassword(username, password=None, is_admin=False): if is_admin: user_type = api_user.ApiGrrUser.UserType.USER_TYPE_ADMIN else: user_type = api_user.ApiGrrUser.UserType.USER_TYPE_STANDARD if password is None: password = getpass.getpass(prompt="Please enter password for u...
Returns the user-type and password for a user. Args: username: Username for the user. password: Password for the user. If None, or not provided, we will prompt for one via the terminal. is_admin: Indicates whether the user should have admin privileges.
juraj-google-style
def __init__(self, configs): self.tests = [] class_identifier = self.__class__.__name__ if configs.test_class_name_suffix: class_identifier = '%s_%s' % (class_identifier, configs.test_class_name_suffix) if self.TAG is None: self.TAG = class_identifier self.root_output_path = configs....
Constructor of BaseTestClass. The constructor takes a config_parser.TestRunConfig object and which has all the information needed to execute this test class, like log_path and controller configurations. For details, see the definition of class config_parser.TestRunConfig. Args: configs: A config_parser.TestRunConfig ...
github-repos
def read_lines(self, max_lines=None): if max_lines is None: return self.read_stream().split('\n') max_to_read = self.metadata.size bytes_to_read = min(100 * max_lines, self.metadata.size) while True: content = self.read_stream(byte_count=bytes_to_read) lines = content.split('\n'...
Reads the content of this object as text, and return a list of lines up to some max. Args: max_lines: max number of lines to return. If None, return all lines. Returns: The text content of the object as a list of lines. Raises: Exception if there was an error requesting the object's content.
juraj-google-style
def edit_miz( infile: str, outfile: str = None, metar: typing.Union[str, Metar] = None, time: str = None, min_wind: int = 0, max_wind: int = 40 ) -> str: if outfile is None: LOGGER.debug('editing in place: %s', infile) outfile = infile ...
Edit an opened MIZ file and sets the time and date and the weather Args: infile: source file outfile: output file (will default to source file) metar: metar string, ICAO or object to apply time: time string to apply (YYYYMMDDHHMMSS) min_wind: minimum wind max_wind: maximum wind Returns: String containing error
juraj-google-style
class FlaubertPoolerEndLogits(nn.Module): def __init__(self, config: FlaubertConfig): super().__init__() self.dense_0 = nn.Linear(config.hidden_size * 2, config.hidden_size) self.activation = nn.Tanh() self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps) ...
Compute SQuAD end logits from sequence hidden states. Args: config ([`FlaubertConfig`]): The config used by the model, will be used to grab the `hidden_size` of the model and the `layer_norm_eps` to use.
github-repos
def get_installed_version(vcs): version_path = _get_version_path(vcs) if not os.path.exists(version_path): raise VersionNotInstalledError with open(version_path, 'r') as f: return f.read().strip()
Get the installed version for this project. Args: vcs (easyci.vcs.base.Vcs) Returns: str - version number Raises: VersionNotInstalledError
juraj-google-style
def _postprocess_for_mg_tf(rle_masks, iou_scores, mask_boxes, amg_crops_nms_thresh=0.7): keep_by_nms = tf.image.combined_non_max_suppression(boxes=mask_boxes.float(), scores=iou_scores, idxs=torch.zeros(mask_boxes.shape[0]), iou_threshold=amg_crops_nms_thresh) iou_scores = iou_scores[keep_by_nms] rle_masks ...
Perform NMS (Non Maximum Suppression) on the outputs. Args: rle_masks (`tf.Tensor`): binary masks in the RLE format iou_scores (`tf.Tensor` of shape (nb_masks, 1)): iou_scores predicted by the model mask_boxes (`tf.Tensor`): The bounding boxes corresponding to segmentation masks amg_crops_nms_thresh (`float`, *optiona...
github-repos
def validate(self, corpus): invalid_utterances = {} for utterance in corpus.utterances.values(): duration = utterance.duration ll = utterance.label_lists[self.label_list_idx] transcription = ' '.join([l.value for l in ll]) num_chars...
Perform the validation on the given corpus. Args: corpus (Corpus): The corpus to test/validate. Returns: InvalidUtterancesResult: Validation result.
juraj-google-style
def get_events_for_block_ids(self, block_ids, subscriptions): blocks = [self._block_store[block_id] for block_id in block_ids] return self.get_events_for_blocks(blocks, subscriptions)
Get a list of events associated with all the block ids. Args: block_ids (list of str): The block ids to search for events that match each subscription. subscriptions (list of EventSubscriptions): EventFilter and event type to filter events. Returns (list of Events): The Events associated which each block id. Raises:...
codesearchnet
def add_evolved_transformer_hparams(hparams): hparams.num_encoder_layers = 3 hparams.num_decoder_layers = 4 hparams.learning_rate_constant /= (hparams.learning_rate_warmup_steps ** 0.5) hparams.learning_rate_schedule = 'constant*linear_warmup*single_cycle_cos_decay*rsqrt_hidden_size' hparams.learnin...
Add Evolved Transformer hparams. Note: These are for the Adam optimizer, not the Adafactor optimizer used in the paper. Args: hparams: Current hparams. Returns: hparams updated with Evolved Transformer values.
codesearchnet
def device(device_name_or_function) -> ContextManager[None]: if context.executing_eagerly(): if callable(device_name_or_function): raise RuntimeError('tf.device does not support functions when eager execution is enabled.') return context.device(device_name_or_function) elif executing...
Wrapper for `Graph.device()` using the default graph. See `tf.Graph.device` for more details. Args: device_name_or_function: The device name or function to use in the context. Returns: A context manager that specifies the default device to use for newly created ops. Raises: RuntimeError: If eager execution is enabl...
github-repos
def _parse_parameters(val_type, val): if val_type == "logical": return val == "T" elif val_type == "int": return int(val) elif val_type == "string": return val.strip() else: return float(val)
Helper function to convert a Vasprun parameter into the proper type. Boolean, int and float types are converted. Args: val_type: Value type parsed from vasprun.xml. val: Actual string value parsed for vasprun.xml.
juraj-google-style
def get_resource_group(access_token, subscription_id, rgname): endpoint = ''.join([get_rm_endpoint(), '/subscriptions/', subscription_id, '/resourceGroups/', rgname, '?api-version=', RESOURCE_API]) return do_get(endpoint, access_token)
Get details about the named resource group. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. rgname (str): Azure resource group name. Returns: HTTP response. JSON body.
codesearchnet
def end_parallel(self): outport = self.oport if isinstance(self.oport.operator, streamsx.topology.graph.Marker): if (self.oport.operator.kind == '$Union$'): pto = self.topology.graph.addPassThruOperator() pto.addInputPort(outputPort=self.oport) outport = pto.addOutput...
Ends a parallel region by merging the channels into a single stream. Returns: Stream: Stream for which subsequent transformations are no longer parallelized. .. seealso:: :py:meth:`set_parallel`, :py:meth:`parallel`
codesearchnet
def unindent(lines): unindented_lines = [] for line in lines: unindented_line = line.lstrip() indent = (len(line) - len(unindented_line)) unindented_lines.append((indent, unindented_line)) return unindented_lines
Convert an iterable of indented lines into a sequence of tuples. The first element of each tuple is the indent in number of characters, and the second element is the unindented string. Args: lines: A sequence of strings representing the lines of text in a docstring. Returns: A list of tuples where each tuple corresp...
codesearchnet
def _set_c_attrs(self, attrs): for name, attr_value in attrs.items(): serialized = attr_value.SerializeToString() with self._c_func.get() as func: c_api.TF_FunctionSetAttrValueProto(func, compat.as_str(name), serialized)
Sets `attrs` as attributes of self._c_func. Requires that self._c_func is not None. Args: attrs: a dictionary from attribute name to attribute proto value
github-repos
def body(self, body): if isinstance(body, bytes): body = body.decode('utf-8') self._body = body
Defines response body data. Arguments: body (str|bytes): response body to use. Returns: self: ``pook.Response`` current instance.
codesearchnet
def add_rec_new(self, k, val): self.rec_new(val) self[k] = val return val
Recursively add a new value and its children to me, and assign a variable to it. Args: k (str): The name of the variable to assign. val (LispVal): The value to be added and assigned. Returns: LispVal: The added value.
juraj-google-style
def add_subscriber(self, connection_id, subscriptions, last_known_block_id): with self._subscribers_cv: self._subscribers[connection_id] = EventSubscriber(connection_id, subscriptions, last_known_block_id) LOGGER.debug('Added Subscriber %s for %s', connection_id, subscriptions)
Register the subscriber for the given event subscriptions. Raises: InvalidFilterError One of the filters in the subscriptions is invalid.
codesearchnet
def download_file(self, url): response = requests.get(url, stream=True) response.raise_for_status() return (int(response.headers.get('content-length', 0)), response)
Initiate a streaming download Args: url (str): The url to download Returns: A tuple of the content length and the streaming response
codesearchnet
def _resolve_if_choice_type(fhir_message: message.Message) -> Optional[message.Message]: if annotation_utils.is_choice_type(fhir_message): choice_field = fhir_message.WhichOneof('choice') if choice_field is None: return None return cast(message.Message, proto_utils.get_value_at_f...
Resolve to the proper field if given a choice type, return as-is if not. Each value in a FHIR choice type is a different field on the protobuf representation wrapped under a proto onoeof field. Therefore, if an expression points to a choice type, we should return the populated field -- while just returning the field ...
github-repos
def sget_voltage(self, cycle, step, set_number=None): time_00 = time.time() set_number = self._validate_dataset_number(set_number) if (set_number is None): self._report_empty_dataset() return cycle_index_header = self.headers_normal.cycle_index_txt voltage_header = self.headers_norma...
Returns voltage for cycle, step. Convinience function; same as issuing dfdata[(dfdata[cycle_index_header] == cycle) & (dfdata[step_index_header] == step)][voltage_header] Args: cycle: cycle number step: step number set_number: the dataset number (automatic selection if None) Returns: pandas.Series or None if empty
codesearchnet
def _evalDecodeJpeg(self, image_name, parallelism, num_iters, crop_during_decode=None, crop_window=None, tile=None): ops.reset_default_graph() image_file_path = resource_loader.get_path_to_datafile(os.path.join('core', 'lib', 'jpeg', 'testdata', image_name)) if not os.path.exists(image_file_path): i...
Evaluate DecodeJpegOp for the given image. TODO(tanmingxing): add decoding+cropping as well. Args: image_name: a string of image file name (without suffix). parallelism: the number of concurrent decode_jpeg ops to be run. num_iters: number of iterations for evaluation. crop_during_decode: If true, use fused DecodeAnd...
github-repos
def write_to(self, content, content_type): try: self._api.object_upload(self._bucket, self._key, content, content_type) except Exception as e: raise e
Writes text content to this item. Args: content: the text content to be written. content_type: the type of text content. Raises: Exception if there was an error requesting the item's content.
codesearchnet
def stage_signature(vcs, signature): evidence_path = _get_staged_history_path(vcs) staged = get_staged_signatures(vcs) if signature in staged: raise AlreadyStagedError staged.append(signature) string = '\n'.join(staged) with open(evidence_path, 'w') as f: f.write(string)
Add `signature` to the list of staged signatures Args: vcs (easyci.vcs.base.Vcs) signature (basestring) Raises: AlreadyStagedError
juraj-google-style
def _to_reader_home(self): self.switch_to_default_content() self.get(_KindleCloudReaderBrowser._CLOUD_READER_URL) if (self.title == u'Problem loading page'): raise ConnectionError login_or_reader_loaded = (lambda br: (br.find_elements_by_id('amzn_kcr') or br.find_elements_by_id('KindleLibraryIFr...
Navigate to the Cloud Reader library page. Raises: BrowserError: If the KCR homepage could not be loaded. ConnectionError: If there was a connection error.
codesearchnet
def run(self, env: env_tools.PreparedEnv, verbose: bool, previous_failures: Set['Check']) -> CheckResult: if previous_failures.intersection(self.dependencies): print(shell_tools.highlight( 'Skipped ' + self.command_line_switch(),...
Evaluates this check. Args: env: The prepared python environment to run the check in. verbose: When set, more progress output is produced. previous_failures: Checks that have already run and failed. Returns: A CheckResult instance.
juraj-google-style
def recipe_cm360_to_dv360(config, auth_dv, auth_cm, auth_sheet, auth_bigquery, recipe_name, recipe_slug, command): dataset(config, {'__comment__': 'Ensure dataset exists.', 'auth': auth_bigquery, 'dataset': recipe_slug}) drive(config, {'__comment__': 'Copy the default template to sheet with the recipe name', 'a...
Allows bulk creating DV360 Insertion Orders and Line Items from CM360. Args: auth_dv (authentication) - Credentials used for dv. auth_cm (authentication) - Credentials used for dv. auth_sheet (authentication) - Credentials used for sheet. auth_bigquery (authentication) - Credentials used for bigquery. recipe_name (str...
github-repos
def plot_script_validate(self, script): script.plot_validate([self.matplotlibwidget_1.figure, self.matplotlibwidget_2.figure]) self.matplotlibwidget_1.draw() self.matplotlibwidget_2.draw()
checks the plottype of the script and plots it accordingly Args: script: script to be plotted
juraj-google-style
def request(self, method_name: str, *args: Any, trim_log_values: bool=False, validate_against_schema: bool=True, id_generator: Optional[Iterator]=None, **kwargs: Any) -> Response: return self.send(Request(method_name, *args, id_generator=id_generator, **kwargs), trim_log_values=trim_log_values, validate_against_sch...
Send a request by passing the method and arguments. >>> client.request("cat", name="Yoko") <Response[1] Args: method_name: The remote procedure's method name. args: Positional arguments passed to the remote procedure. kwargs: Keyword arguments passed to the remote procedure. trim_log_values: Abbreviate the log entrie...
codesearchnet