code stringlengths 20 4.93k | docstring stringlengths 33 1.27k | source stringclasses 3
values |
|---|---|---|
def create_index(self, model, waiting_models):
bucket_name = model._get_bucket_name()
bucket_type = client.bucket_type(settings.DEFAULT_BUCKET_TYPE)
index_name = "%s_%s" % (settings.DEFAULT_BUCKET_TYPE, bucket_name)
bucket = bucket_type.bucket(bucket_name)
try:
... | Creates search indexes.
Args:
model: model to execute
waiting_models: if riak can't return response immediately, model is taken to queue.
After first execution session, method is executed with waiting models and controlled.
And be ensured that all given models are executed properly.
Returns: | juraj-google-style |
def getConfig(self, section = None):
data = {}
if section is None:
for s in self.config.sections():
if '/' in s:
parent, _s = s.split('/')
data[parent][_s] = dict(self.config.items(s))
else:
data[s] = dict(self.config.items(s))
else:
data = dict(self.config.items(section)... | Returns a dictionary which contains the current config. If a section is setted,
only will returns the section config
Args:
section (str): (Optional) Section name.
Returns:
dict: Representation of current config | juraj-google-style |
def _parse_state(self, config):
value = STATE_RE.search(config).group('value')
return dict(state=value) | _parse_state scans the provided configuration block and extracts
the vlan state value. The config block is expected to always return
the vlan state config. The return dict is inteded to be merged into
the response dict.
Args:
config (str): The vlan configuration block from the nodes
running configuration
Returns:
d... | juraj-google-style |
def _validate_namespace(self, namespace):
if (self._namespace_regex.fullmatch(namespace) is None):
LOGGER.debug('Invalid namespace: %s', namespace)
raise _ResponseFailed(self._status.INVALID_ADDRESS) | Validates a namespace, raising a ResponseFailed error if invalid.
Args:
state_root (str): The state_root to validate
Raises:
ResponseFailed: The state_root was invalid, and a status of
INVALID_ROOT will be sent with the response. | codesearchnet |
def subtract_business_days(self, date_tensor, num_days, roll_convention=constants.BusinessDayConvention.NONE):
pass | Adds given number of business days to given dates.
Note that this is different from calling `subtract_period_and_roll` with
PeriodType.DAY. For example, subtracting 5 business days from Friday gives
the previous Friday (unless there are holidays on this week or previous
Friday). Subtracting 5 days and rolling means la... | github-repos |
def _find_bad_transition(self, mma, w_string):
conj_out = mma.consume_input(w_string)
targ_out = self._membership_query(w_string)
length = min(len(conj_out), len(targ_out))
diff = [i for i in range(length)
if conj_out[i] != targ_out[i]]
... | Checks for bad DFA transitions using the examined string
Args:
mma (DFA): The hypothesis automaton
w_string (str): The examined string to be consumed
Returns:
str: The prefix of the examined string that matches | juraj-google-style |
def get_pk_attrnames(obj) -> List[str]:
return [attrname
for attrname, column in gen_columns(obj)
if column.primary_key] | Asks an SQLAlchemy ORM object: "what are your primary key(s)?"
Args:
obj: SQLAlchemy ORM object
Returns:
list of attribute names of primary-key columns | juraj-google-style |
def _get_edges(self):
if (self._edges is None):
self._edges = self._compute_edges()
return self._edges | Get the edges for the current surface.
If they haven't been computed yet, first compute and store them.
This is provided as a means for internal calls to get the edges
without copying (since :attr:`.edges` copies before giving to
a user to keep the stored data immutable).
Returns:
Tuple[~bezier.curve.Curve, ~bezier.... | codesearchnet |
def _eval_once(saver, summary_writer, top_1_op, top_5_op, summary_op):
with tf.Session() as sess:
ckpt = tf.train.get_checkpoint_state(FLAGS.checkpoint_dir)
if ckpt and ckpt.model_checkpoint_path:
print("ckpt.model_checkpoint_path: {0}".format(ckpt.model_checkpoint_path))
saver.restore(sess, ck... | Runs Eval once.
Args:
saver: Saver.
summary_writer: Summary writer.
top_1_op: Top 1 op.
top_5_op: Top 5 op.
summary_op: Summary op. | juraj-google-style |
def _next_dna(self, dna: Optional[DNA]=None) -> Optional[DNA]:
if self.next_dna_fn is None:
cls_name = self.hyper_type or self.__class__.__name__
raise NotImplementedError(f'`next_dna` is not supported on {cls_name!r}.')
return self.next_dna_fn(dna) | Returns the next DNA in the space represented by this spec.
Args:
dna: The DNA whose next will be returned. If None, `next_dna` will return
the first DNA.
Returns:
The next DNA or None if there is no next DNA. | github-repos |
def reshape(self, shape: tf.TensorShape) -> 'TensorFluent':
t = tf.reshape(self.tensor, shape)
scope = self.scope.as_list()
batch = self.batch
return TensorFluent(t, scope, batch=batch) | Returns a TensorFluent for the reshape operation with given `shape`.
Args:
shape: The output's shape.
Returns:
A TensorFluent wrapping the reshape operation. | juraj-google-style |
def devno_alloc(self):
devno_int = self._devno_pool.alloc()
devno = '{:04X}'.format(devno_int)
return devno | Allocates a device number unique to this partition, in the range of
0x8000 to 0xFFFF.
Returns:
string: The device number as four hexadecimal digits in upper case.
Raises:
ValueError: No more device numbers available in that range. | codesearchnet |
def set_default(self, name, value):
fl = self._flags()
if (name not in fl):
self._set_unknown_flag(name, value)
return
fl[name]._set_default(value)
self._assert_validators(fl[name].validators) | Changes the default value of the named flag object.
The flag's current value is also updated if the flag is currently using
the default value, i.e. not specified in the command line, and not set
by FLAGS.name = value.
Args:
name: str, the name of the flag to modify.
value: The new default value.
Raises:
Unrecognized... | codesearchnet |
def get_content_of_file(self, name, full_path=False):
if self.handle:
for member in self.handle.getmembers():
if ((full_path and (member.name == name)) or ((not full_path) and (os.path.basename(member.name) == name))):
extracted = self.handle.extractfile(member)
r... | Returns content of file from archive.
If full_path is set to False and two files with given name exist,
content of one is returned (it is not specified which one that is).
If set to True, returns content of exactly that file.
Args:
name: name of the file to get content of
Returns:
Content of the file with given name ... | codesearchnet |
def _pre_action(self, action):
assert (len(action) == self.dof), 'environment got invalid action dimension'
(low, high) = self.action_spec
action = np.clip(action, low, high)
if self.has_gripper:
arm_action = action[:self.mujoco_robot.dof]
gripper_action_in = action[self.mujoco_robot.dof... | Overrides the superclass method to actuate the robot with the
passed joint velocities and gripper control.
Args:
action (numpy array): The control to apply to the robot. The first
@self.mujoco_robot.dof dimensions should be the desired
normalized joint velocities and if the robot has
a gripper, the next @self.gripper.... | codesearchnet |
def resolve(self, method, path):
if method in self._literal and path in self._literal[method]:
return self._literal[method][path], [], {}
else:
return self._resolve_non_literal_route(method, path) | Resolve a request to a route handler.
Arguments:
method (str): HTTP method, e.g. GET, POST, etc. (type: str)
path (str): Request path
Returns:
tuple or None: A tuple of three items:
1. Route handler (callable)
2. Positional arguments (list)
3. Keyword arguments (dict)
``None`` if no route matches the request. | juraj-google-style |
def find_in_matrix_2d(val, matrix):
dim = len(matrix[0])
item_index = 0
for row in matrix:
for i in row:
if (i == val):
break
item_index += 1
if (i == val):
break
loc = (int((item_index / dim)), (item_index % dim))
return loc | Returns a tuple representing the index of an item in a 2D matrix.
Arguments:
- val (str) Value to look for
- matrix (list) 2D matrix to search for val in
Returns:
- (tuple) Ordered pair representing location of val | codesearchnet |
def bulk_insert_extras(dialect_name: str,
fileobj: TextIO,
start: bool) -> None:
lines = []
if dialect_name == SqlaDialectName.MYSQL:
if start:
lines = [
"SET autocommit=0;",
"SET unique_checks=0;",
... | Writes bulk ``INSERT`` preamble (start=True) or end (start=False).
For MySQL, this temporarily switches off autocommit behaviour and index/FK
checks, for speed, then re-enables them at the end and commits.
Args:
dialect_name: SQLAlchemy dialect name (see :class:`SqlaDialectName`)
fileobj: file-like object to write to... | juraj-google-style |
def stop_ec2_instance(client, resource):
instance = EC2Instance.get(resource.id)
if instance.state in ('stopped', 'terminated'):
return ActionStatus.IGNORED, {}
client.stop_instances(InstanceIds=[resource.id])
return ActionStatus.SUCCEED, {'instance_type': resource.instance_type, 'public_i... | Stop an EC2 Instance
This function will attempt to stop a running instance.
Args:
client (:obj:`boto3.session.Session.client`): A boto3 client object
resource (:obj:`Resource`): The resource object to stop
Returns:
`ActionStatus` | juraj-google-style |
def _trychar(char, fallback, asciimode=None):
if asciimode is True:
return fallback
if hasattr(sys.stdout, 'encoding') and sys.stdout.encoding:
try:
char.encode(sys.stdout.encoding)
except Exception:
pass
else:
return char
... | Logic from IPython timeit to handle terminals that cant show mu
Args:
char (str): character, typically unicode, to try to use
fallback (str): ascii character to use if stdout cannot encode char
asciimode (bool): if True, always use fallback
Example:
>>> char = _trychar('µs', 'us')
>>> print('char = {}'.format(char))
... | juraj-google-style |
def _model_to_dict(model, ignore):
return {attr: value for (attr, value) in model.__dict__.items() if ((not attr.startswith('_')) and (attr not in ignore))} | Convert OSS model to dict.
Args:
model (oss2.models.RequestResult): Model.
ignore (tuple of str): Keys to not insert to dict.
Returns:
dict: Model dict version. | codesearchnet |
def verify_link_ed25519_cot_signature(chain, link, unsigned_path, signature_path):
if chain.context.config['verify_cot_signature']:
log.debug('Verifying the {} {} {} ed25519 chain of trust signature'.format(link.name, link.task_id, link.worker_impl))
signature = read_from_file(signature_path, file_t... | Verify the ed25519 signatures of the chain of trust artifacts populated in ``download_cot``.
Populate each link.cot with the chain of trust json body.
Args:
chain (ChainOfTrust): the chain of trust to add to.
Raises:
(CoTError, ScriptWorkerEd25519Error): on signature verification failure. | codesearchnet |
def unpack_archive(*components, **kwargs) -> str:
path = fs.abspath(*components)
compression = kwargs.get('compression', 'bz2')
dir = kwargs.get('dir', fs.dirname(path))
fs.cd(dir)
tar = tarfile.open(path, ('r:' + compression))
tar.extractall()
tar.close()
fs.cdpop()
return dir | Unpack a compressed archive.
Arguments:
*components (str[]): Absolute path.
**kwargs (dict, optional): Set "compression" to compression type.
Default: bz2. Set "dir" to destination directory. Defaults to the
directory of the archive.
Returns:
str: Path to directory. | codesearchnet |
def __frontend_limit_descriptor(self, api_info):
if (api_info.frontend_limits is None):
return None
descriptor = {}
for (propname, descname) in (('unregistered_user_qps', 'unregisteredUserQps'), ('unregistered_qps', 'unregisteredQps'), ('unregistered_daily', 'unregisteredDaily')):
if (getatt... | Builds a frontend limit descriptor from API info.
Args:
api_info: An _ApiInfo object.
Returns:
A dictionary with frontend limit information. | codesearchnet |
def Deserialize(self, reader):
self.PrevHash = reader.ReadUInt256()
self.PrevIndex = reader.ReadUInt16() | Deserialize full object.
Args:
reader (neo.IO.BinaryReader): | juraj-google-style |
def _guess_format_from_extension(ext):
ext = ext.strip('.')
formats = []
for fmt in FILE_FORMATS:
if ext in FILE_FORMATS[fmt]:
formats.append(fmt)
if formats == [] or len(formats) > 1:
return False
return formats[0] | Guess the appropriate data type from file extension.
Arguments:
ext: The file extension (period optional)
Returns:
String. The format (without leading period),
or False if none was found or couldn't be guessed | juraj-google-style |
def handle_upnp_error(self, xml_error):
xml_error = xml_error.encode('utf-8')
error = XML.fromstring(xml_error)
log.debug('Error %s', xml_error)
error_code = error.findtext('.
if (error_code is not None):
description = self.UPNP_ERRORS.get(int(error_code), '')
raise SoCoUPnPException... | Disect a UPnP error, and raise an appropriate exception.
Args:
xml_error (str): a unicode string containing the body of the
UPnP/SOAP Fault response. Raises an exception containing the
error code. | codesearchnet |
def get_signature_def(meta_graph, signature_key):
signature_def_map = meta_graph.signature_def
signature_def_keys = set(signature_def_map.keys())
logging.info('The given SavedModel MetaGraphDef contains SignatureDefs with the following keys: %s', signature_def_keys)
if signature_key not in signature_def... | Get the signature def from meta_graph with given signature_key.
Args:
meta_graph: meta_graph_def.
signature_key: signature_def in the meta_graph_def.
Returns:
The signature_def used for tflite conversion.
Raises:
ValueError: Given signature_key is not valid for this meta_graph. | github-repos |
def get_m49_from_iso3(cls, iso3, use_live=True, exception=None):
countriesdata = cls.countriesdata(use_live=use_live)
m49 = countriesdata['m49iso3'].get(iso3)
if (m49 is not None):
return m49
if (exception is not None):
raise exception
return None | Get M49 from ISO3 code
Args:
iso3 (str): ISO3 code for which to get M49 code
use_live (bool): Try to get use latest data from web rather than file in package. Defaults to True.
exception (Optional[ExceptionUpperBound]): An exception to raise if country not found. Defaults to None.
Returns:
Optional[int]: M49 code | codesearchnet |
def agent_version(self, value):
if value == self._defaults['ai.internal.agentVersion'] and 'ai.internal.agentVersion' in self._values:
del self._values['ai.internal.agentVersion']
else:
self._values['ai.internal.agentVersion'] = value | The agent_version property.
Args:
value (string). the property value. | juraj-google-style |
def byte_str(nBytes, unit='bytes', precision=2):
if unit.lower().startswith('b'):
nUnit = nBytes
elif unit.lower().startswith('k'):
nUnit = (nBytes / (2.0 ** 10))
elif unit.lower().startswith('m'):
nUnit = (nBytes / (2.0 ** 20))
elif unit.lower().startswith('g'):
nUnit = ... | representing the number of bytes with the chosen unit
Returns:
str | codesearchnet |
def report_error(self, read_tuple_name, error_name, wrong="", message="", warning=False):
if (not self.report_only_first) or (error_name not in self.reported_errors):
print("\t".join(["error" if warning == False else "warning", read_tuple_name, error_name, wrong, message]))
self.rep... | Report an error.
Args:
read_tuple_name (): Name of the read tuple.
error_name (): Name of the error.
wrong (str): What is wrong.
message (str): Additional msessage to be printed.
warning (bool): Warning (not an error). | juraj-google-style |
def activate_absence_with_duration(self, duration: int):
data = {"duration": duration}
return self._restCall(
"home/heating/activateAbsenceWithDuration", json.dumps(data)
) | activates the absence mode for a given time
Args:
duration(int): the absence duration in minutes | juraj-google-style |
def wb004(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 `wb004`'.format(value))
self._wb004 = value | Corresponds to IDD Field `wb004`
Wet-bulb temperature corresponding to 0.4% annual cumulative frequency of occurrence
Args:
value (float): value for IDD Field `wb004`
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 ... | codesearchnet |
async def download_cot(chain):
artifact_tasks = []
for link in chain.links:
task_id = link.task_id
parent_dir = link.cot_dir
urls = []
unsigned_url = get_artifact_url(chain.context, task_id, 'public/chain-of-trust.json')
urls.append(unsigned_url)
... | Download the signed chain of trust artifacts.
Args:
chain (ChainOfTrust): the chain of trust to add to.
Raises:
BaseDownloadError: on failure. | juraj-google-style |
def rtm(self, url: Optional[str]=None, bot_id: Optional[str]=None) -> Iterator[events.Event]:
while True:
bot_id = (bot_id or self._find_bot_id())
url = (url or self._find_rtm_url())
for event in self._incoming_from_rtm(url, bot_id):
(yield event)
url = None | Iterate over event from the RTM API
Args:
url: Websocket connection url
bot_id: Connecting bot ID
Returns:
:class:`slack.events.Event` or :class:`slack.events.Message` | codesearchnet |
class InputExample:
guid: str
text_a: str
text_b: Optional[str] = None
label: Optional[str] = None
def to_json_string(self):
return json.dumps(dataclasses.asdict(self), indent=2) + '\n' | A single training/test example for simple sequence classification.
Args:
guid: Unique id for the example.
text_a: string. The untokenized text of the first sequence. For single
sequence tasks, only this sequence must be specified.
text_b: (Optional) string. The untokenized text of the second sequence.
Only must be spe... | github-repos |
def _use_gl(objs):
from ..models.plots import Plot
return _any(objs, lambda obj: isinstance(obj, Plot) and obj.output_backend == "webgl") | Whether a collection of Bokeh objects contains a plot requesting WebGL
Args:
objs (seq[Model or Document]) :
Returns:
bool | juraj-google-style |
def _encode_slice_definition(self, root_builder: expressions.Builder, slice_: _fhir_path_data_types.Slice) -> List[validation_pb2.SqlRequirement]:
if slice_.relative_path:
slice_builder = self._get_new_child_builder(root_builder, slice_.relative_path)
else:
slice_builder = root_builder
if sl... | Encodes constraints for slices.
Args:
root_builder: The builder representing a path to the structure definition
defining the slice.
slice_: A slice defined by the structure definition at `root_builder`.
Returns:
A constraint enforcing the cardinality of `slice_` if `slice_` imposes a
non-zero or non-* min or max card... | github-repos |
def Convert(self, metadata, stat_entry, token=None):
if stat_entry.pathspec.pathtype != rdf_paths.PathSpec.PathType.REGISTRY:
return []
result = ExportedRegistryKey(
metadata=metadata,
urn=stat_entry.AFF4Path(metadata.client_urn),
last_modified=stat_entry.st_mtime)
if (s... | Converts StatEntry to ExportedRegistryKey.
Does nothing if StatEntry corresponds to a file and not a registry entry.
Args:
metadata: ExportedMetadata to be used for conversion.
stat_entry: StatEntry to be converted.
token: Security token.
Returns:
List or generator with resulting RDFValues. Empty list if StatEntry
c... | juraj-google-style |
def __init__(self, on_exception=Exception, limit=5, interval=None,
validator=None):
self.attempts = 0
self._on_exception = on_exception
self._setup_limit(limit)
self._setup_interval(interval)
self._setup_validator(validator) | Configure how a function should be retried.
Args:
on_exception (BaseException): The exception to catch. Use this to
set which exception and it's subclasses to catch.
limit () | juraj-google-style |
def _handle_agg_function(gb, agg_func, agg_name, *args, **kwargs):
if _is_associative(agg_func):
return _liftable_agg(agg_func)(gb, *args, **kwargs)
elif _is_liftable_with_sum(agg_func):
return _liftable_agg(agg_func, postagg_meth='sum')(gb, *args, **kwargs)
elif _is_unliftable(agg_func):
... | Handles the aggregation logic based on the function type passed.
Args:
gb: The groupby instance (DeferredGroupBy).
agg_name: The name/label of the aggregation function.
fn: The aggregation function to apply.
*args: Additional arguments to pass to the aggregation function.
**kwargs: Keyword arguments to pass to the agg... | github-repos |
def register_ops_if_needed(graph_ops):
missing_ops = (graph_ops - set(op_def_registry.get_registered_ops().keys()))
if (not missing_ops):
return
p_buffer = c_api.TF_GetAllOpList()
cpp_op_list = op_def_pb2.OpList()
cpp_op_list.ParseFromString(c_api.TF_GetBuffer(p_buffer))
cpp_registry_ops... | Register graph ops absent in op_def_registry, if present in c++ registry.
Args:
graph_ops: set with graph op names to register.
Raises:
RuntimeError: if `graph_ops` contains ops that are not in either python or
c++ registry. | codesearchnet |
async def dist(self, mesg):
if self.isfini:
return ()
ret = []
for func in self._syn_funcs.get(mesg[0], ()):
try:
ret.append(await s_coro.ornot(func, mesg))
except asyncio.CancelledError:
raise
except Exce... | Distribute an existing event tuple.
Args:
mesg ((str,dict)): An event tuple.
Example:
await base.dist( ('foo',{'bar':'baz'}) ) | juraj-google-style |
def extract_tree_with(self, labels, suppress_unifurcations=True):
return self.extract_tree(labels, False, suppress_unifurcations) | Extract a copy of this ``Tree`` with only the leaves labeled by the strings in ``labels``
Args:
``leaves`` (``set``): Set of leaf labels to include.
``suppress_unifurcations`` (``bool``): ``True`` to suppress unifurcations, otherwise ``False``
Returns:
Tree: Copy of this Tree, including only the leaves labeled by th... | codesearchnet |
def _clone_layers_and_model_config(model, input_layers, layer_fn):
created_layers = {}
def _copy_layer(layer):
if layer in input_layers:
created_layers[layer.name] = input_layers[layer]
elif layer in model._input_layers:
created_layers[layer.name] = InputLayer(**layer.ge... | Clones all layers, and returns the model config without serializing layers.
This function ensures that only the node graph is retrieved when getting the
model config. The `layer_fn` used to clone layers might not rely on
`layer.get_config()`, so some custom layers do not define `get_config`.
Trying to retrieve the con... | github-repos |
def _convert_validators_to_mapping(validators):
validators_mapping = {}
for validator in validators:
if (not isinstance(validator['check'], collections.Hashable)):
check = json.dumps(validator['check'])
else:
check = validator['check']
key = (check, validator['com... | convert validators list to mapping.
Args:
validators (list): validators in list
Returns:
dict: validators mapping, use (check, comparator) as key.
Examples:
>>> validators = [
{"check": "v1", "expect": 201, "comparator": "eq"},
{"check": {"b": 1}, "expect": 200, "comparator": "eq"}
]
>>> _convert_validators_to_mappi... | codesearchnet |
def get(self, secret_id):
return self.prepare_model(self.client.api.inspect_secret(secret_id)) | Get a secret.
Args:
secret_id (str): Secret ID.
Returns:
(:py:class:`Secret`): The secret.
Raises:
:py:class:`docker.errors.NotFound`
If the secret does not exist.
:py:class:`docker.errors.APIError`
If the server returns an error. | codesearchnet |
def filing_history(self, num, transaction=None, **kwargs):
baseuri = self._BASE_URI + "company/{}/filing-history".format(num)
if transaction is not None:
baseuri += "/{}".format(transaction)
res = self.session.get(baseuri, params=kwargs)
self.handle_http_error(res)
... | Search for a company's filling history by company number.
Args:
num (str): Company number to search on.
transaction (Optional[str]): Filing record number.
kwargs (dict): additional keywords passed into
requests.session.get params keyword. | juraj-google-style |
def binary_arguments_to_tensors(x1, x2):
if not isinstance(x1, Tensor) and not isinstance(x2, Tensor):
raise ValueError("at least one of x1 and x2 must be an mtf Tensor")
elif isinstance(x1, Tensor) and isinstance(x2, Tensor):
return x1, x2
elif isinstance(x1, Tensor):
return x1, import_tf_tensor(
... | Convert argument of a binary operation to Tensors.
Args:
x1: a Tensor or something convertible to a tf Scalar
x2: a Tensor or something convertible to a tf Scalar
Returns:
new_x1: a Tensor
new_x2: a Tensor
Raises:
ValueError: on failure | juraj-google-style |
def _stride(stride_spec):
if stride_spec is None:
return [1, 1, 1, 1]
elif isinstance(stride_spec, tf.compat.integral_types):
return [1, stride_spec, stride_spec, 1]
elif len(stride_spec) == 1:
return [1, stride_spec[0], stride_spec[0], 1]
elif len(stride_spec) == 2:
return [1, stride_spec[0]... | Expands the stride spec into a length 4 list.
Args:
stride_spec: If length 0, 1 or 2 then assign the inner dimensions, otherwise
return stride_spec if it is length 4.
Returns:
A length 4 list. | juraj-google-style |
def to_str(self, separator=''):
if self.closed():
raise ValueError('Attempt to call to_str() on a closed Queryable.')
return str(separator).join(self.select(str)) | Build a string from the source sequence.
The elements of the query result will each coerced to a string and then
the resulting strings concatenated to return a single string. This
allows the natural processing of character sequences as strings. An
optional separator which will be inserted between each item may be
spec... | codesearchnet |
def properties(self, value):
if value == self._defaults['properties'] and 'properties' in self._values:
del self._values['properties']
else:
self._values['properties'] = value | The properties property.
Args:
value (hash). the property value. | juraj-google-style |
def report_line(zipfilename: str, contentsfilename: str, line: str,
show_inner_file: bool) -> None:
if show_inner_file:
print("{} [{}]: {}".format(zipfilename, contentsfilename, line))
else:
print("{}: {}".format(zipfilename, line)) | Prints a line from a file, with the ``.zip`` filename and optionally also
the inner filename.
Args:
zipfilename: filename of the ``.zip`` file
contentsfilename: filename of the inner file
line: the line from the inner file
show_inner_file: if ``True``, show both filenames; if ``False``, show
just the ``.zip`` filename | juraj-google-style |
def _send(self, **req_kwargs):
auth_token = self._auth.getAuthToken()
if auth_token is None:
raise exception.LoginException('Not logged in')
req_kwargs.setdefault('headers', {
'Authorization': 'OAuth ' + auth_token
})
return self._session.reques... | Send an authenticated request to a Google API.
Args:
**req_kwargs: Arbitrary keyword arguments to pass to Requests.
Return:
requests.Response: The raw response.
Raises:
LoginException: If :py:meth:`login` has not been called. | juraj-google-style |
def _CheckGrayscaleImage(image, require_static=True):
try:
if image.get_shape().ndims is None:
image_shape = image.get_shape().with_rank(2)
else:
image_shape = image.get_shape().with_rank_at_least(2)
except ValueError:
raise ValueError('A grayscale image (shape %s... | Assert that we are working with properly shaped grayscale image.
Args:
image: >= 2-D Tensor of size [*, 1]
require_static: Boolean, whether static shape is required.
Raises:
ValueError: if image.shape is not a [>= 2] vector or if
last dimension is not size 1.
Returns:
An empty list, if `image` has fully defined dime... | github-repos |
def post_process_video_grounding(self, logits, video_durations):
start, end = (round(logits.tolist()[0][0] * video_durations, 1), round(logits.tolist()[0][1] * video_durations, 1))
return (start, end) | Compute the time of the video.
Args:
logits (`torch.Tensor`):
The logits output of TvpForVideoGrounding.
video_durations (`float`):
The video's duration.
Returns:
start (`float`):
The start time of the video.
end (`float`):
The end time of the video. | github-repos |
def get_commit_tree(profile, sha):
data = commits.get_commit(profile, sha)
tree = data.get("tree")
sha = tree.get("sha")
return sha | Get the SHA of a commit's tree.
Args:
profile
A profile generated from ``simplygithub.authentication.profile``.
Such profiles tell this module (i) the ``repo`` to connect to,
and (ii) the ``token`` to connect with.
sha
The SHA of a commit.
Returns:
The SHA of the commit's tree. | juraj-google-style |
def diffusion_mds(means, weights, d, diffusion_rounds=10):
for i in range(diffusion_rounds):
weights = (weights * weights)
weights = (weights / weights.sum(0))
X = dim_reduce(means, weights, d)
if (X.shape[0] == 2):
return X.dot(weights)
else:
return X.T.dot(weights) | Dimensionality reduction using MDS, while running diffusion on W.
Args:
means (array): genes x clusters
weights (array): clusters x cells
d (int): desired dimensionality
Returns:
W_reduced (array): array of shape (d, cells) | codesearchnet |
def WaitUntilDone(self, timeout=None):
utils.Poll(
generator=self.GetState,
condition=lambda s: s != self.__class__.STATE_RUNNING,
timeout=timeout)
self.target_file = self.target_file.Get()
return self | Wait until the operation is done.
Args:
timeout: timeout in seconds. None means default timeout (1 hour).
0 means no timeout (wait forever).
Returns:
Operation object with refreshed target_file.
Raises:
PollTimeoutError: if timeout is reached. | juraj-google-style |
def _compile_arithmetic_expression(self,
expr: Expression,
scope: Dict[str, TensorFluent],
batch_size: Optional[int] = None,
noise: Optional[List[tf.Tensor]] = None... | Compile an arithmetic expression `expr` into a TensorFluent
in the given `scope` with optional batch size.
Args:
expr (:obj:`rddl2tf.expr.Expression`): A RDDL arithmetic expression.
scope (Dict[str, :obj:`rddl2tf.fluent.TensorFluent`]): A fluent scope.
batch_size (Optional[size]): The batch size.
Returns:
:obj:`rddl2... | juraj-google-style |
def _check_etag(self, etag):
if (etag is None):
return
elif (self._etag is None):
self._etag = etag
elif (self._etag != etag):
raise ValueError('File on GCS has changed while reading.') | Check if etag is the same across requests to GCS.
If self._etag is None, set it. If etag is set, check that the new
etag equals the old one.
In the __init__ method, we fire one HEAD and one GET request using
ndb tasklet. One of them would return first and set the first value.
Args:
etag: etag from a GCS HTTP respons... | codesearchnet |
def stop_site(name):
ps_cmd = ['Stop-WebSite', "'{0}'".format(name)]
cmd_ret = _srvmgr(ps_cmd)
return (cmd_ret['retcode'] == 0) | Stop a Web Site in IIS.
.. versionadded:: 2017.7.0
Args:
name (str): The name of the website to stop.
Returns:
bool: True if successful, otherwise False
CLI Example:
.. code-block:: bash
salt '*' win_iis.stop_site name='My Test Site' | codesearchnet |
def assignSchedule(self, schedule, period, hour, minute, tariff):
if ((schedule not in range(Extents.Schedules)) or (period not in range(Extents.Tariffs)) or (hour < 0) or (hour > 23) or (minute < 0) or (minute > 59) or (tariff < 0)):
ekm_log(('Out of bounds in Schedule_' + str((schedule + 1))))
ret... | Assign one schedule tariff period to meter bufffer.
Args:
schedule (int): A :class:`~ekmmeters.Schedules` value or in range(Extents.Schedules).
tariff (int): :class:`~ekmmeters.Tariffs` value or in range(Extents.Tariffs).
hour (int): Hour from 0-23.
minute (int): Minute from 0-59.
tariff (int): Rate value.
Returns:
b... | codesearchnet |
def disease_term(self, disease_identifier):
query = {}
try:
disease_identifier = int(disease_identifier)
query['disease_nr'] = disease_identifier
except ValueError:
query['_id'] = disease_identifier
return self.disease_term_collection.find_one(query) | Return a disease term
Checks if the identifier is a disease number or a id
Args:
disease_identifier(str)
Returns:
disease_obj(dict) | codesearchnet |
def get_pool_context(self):
context = {self.current.lane_id: self.current.role, 'self': self.current.role}
for (lane_id, role_id) in self.current.pool.items():
if role_id:
context[lane_id] = lazy_object_proxy.Proxy((lambda : self.role_model(super_context).objects.get(role_id)))
return co... | Builds context for the WF pool.
Returns:
Context dict. | codesearchnet |
def semantic_eq(node1, node2):
if 'barrier' == node1.name == node2.name:
return set(node1.qargs) == set(node2.qargs)
return node1.data_dict == node2.data_dict | Check if DAG nodes are considered equivalent, e.g. as a node_match for nx.is_isomorphic.
Args:
node1 (DAGNode): A node to compare.
node2 (DAGNode): The other node to compare.
Return:
Bool: If node1 == node2 | juraj-google-style |
def match(self, name):
if self.method == Ex.Method.PREFIX:
return name.startswith(self.value)
elif self.method == Ex.Method.SUFFIX:
return name.endswith(self.value)
elif self.method == Ex.Method.CONTAINS:
return self.value in name
elif self.me... | Check if given name matches.
Args:
name (str): name to check.
Returns:
bool: matches name. | juraj-google-style |
class Rescaling(TFDataLayer):
def __init__(self, scale, offset=0.0, **kwargs):
super().__init__(**kwargs)
self.scale = scale
self.offset = offset
self.supports_masking = True
def call(self, inputs):
dtype = self.compute_dtype
scale = self.backend.cast(self.scale... | A preprocessing layer which rescales input values to a new range.
This layer rescales every value of an input (often an image) by multiplying
by `scale` and adding `offset`.
For instance:
1. To rescale an input in the `[0, 255]` range
to be in the `[0, 1]` range, you would pass `scale=1./255`.
2. To rescale an inpu... | github-repos |
def render(self, container, descender, state, space_below=0, first_line_only=False):
indent_first = (float(self.get_style('indent_first', container)) if state.initial else 0)
line_width = float(container.width)
line_spacing = self.get_style('line_spacing', container)
text_align = self.get_style('text_al... | Typeset the paragraph
The paragraph is typeset in the given container starting below the
current cursor position of the container. When the end of the container
is reached, the rendering state is preserved to continue setting the
rest of the paragraph when this method is called with a new container.
Args:
container (... | codesearchnet |
def __init__(self, sender, persistence_path=''):
if persistence_path and PersistQueue is None:
raise ValueError('persistence_path argument requires persist-queue dependency to be installed')
elif persistence_path:
self._queue = PersistQueue(persistence_path)
else... | Initializes a new instance of the class.
Args:
sender (:class:`SenderBase`) the sender object that will be used in conjunction with this queue.
persistence_path (str) if set, persist the queue on disk into the provided directory. | juraj-google-style |
def __init__(self, output_path, open_function=open):
self._output_path = output_path
self._open_function = open_function
self._old_enabled = None | Initialize.
Args:
output_path: The path for the metrics data. If empty, no metrics are
collected.
open_function: A custom file opening function. | github-repos |
def get_credentials(self):
return ReadOnlyCredentials(self.access_token, self.client_id, self.client_secret, self.refresh_token) | Get read-only credentials.
Returns:
class: Read-only credentials. | codesearchnet |
def set(self, option, value=None):
option = self._container.optionxform(option)
if option in self.options():
self.__getitem__(option).value = value
else:
self.__setitem__(option, value)
return self | Set an option for chaining.
Args:
option (str): option name
value (str): value, default None | juraj-google-style |
def measures(*measurements, **kwargs):
def _maybe_make(meas):
'Turn strings into Measurement objects if necessary.'
if isinstance(meas, Measurement):
return meas
elif isinstance(meas, six.string_types):
return Measurement(meas, **kwargs)
raise InvalidMeasurem... | Decorator-maker used to declare measurements for phases.
See the measurements module docstring for examples of usage.
Args:
measurements: Measurement objects to declare, or a string name from which
to create a Measurement.
kwargs: Keyword arguments to pass to Measurement constructor if we're
constructing one. Note t... | codesearchnet |
def _parse_request_arguments(self, request):
inference_addresses = request.args.get('inference_address').split(',')
model_names = request.args.get('model_name').split(',')
model_versions = request.args.get('model_version').split(',')
model_signatures = request.args.get('model_signature').split(',')
... | Parses comma separated request arguments
Args:
request: A request that should contain 'inference_address', 'model_name',
'model_version', 'model_signature'.
Returns:
A tuple of lists for model parameters | codesearchnet |
def get_terminal_size():
try:
from IPython import get_ipython
ipython = get_ipython()
from ipykernel import zmqshell
if isinstance(ipython, zmqshell.ZMQInteractiveShell):
return (79, 24)
except Exception:
pass
try:
import shutil
(w, h) = sh... | Get the current size of your terminal
Multiple returns are not always a good idea, but in this case it greatly
simplifies the code so I believe it's justified. It's not the prettiest
function but that's never really possible with cross-platform code.
Returns:
width, height: Two integers containing width and height | codesearchnet |
def find_mip(self, direction, mechanism, purview, allow_neg=False):
alpha_min = float('inf')
probability = self.probability(direction, mechanism, purview)
for partition in mip_partitions(mechanism, purview, self.node_labels):
partitioned_probability = self.partitioned_probability(direction, partitio... | Find the ratio minimum information partition for a mechanism
over a purview.
Args:
direction (str): |CAUSE| or |EFFECT|
mechanism (tuple[int]): A mechanism.
purview (tuple[int]): A purview.
Keyword Args:
allow_neg (boolean): If true, ``alpha`` is allowed to be negative.
Otherwise, negative values of ``alpha`` will be... | codesearchnet |
def del_hparam(self, name):
if hasattr(self, name):
delattr(self, name)
del self._hparam_types[name] | Removes the hyperparameter with key 'name'.
Does nothing if it isn't present.
Args:
name: Name of the hyperparameter. | codesearchnet |
def __squid_to_guid(self, squid):
if not squid:
return ''
squid_match = self.__squid_pattern.match(squid)
guid = ''
if squid_match is not None:
guid = '{' +\
squid_match.group(1)[::-1]+'-' +\
squid_match.group(2)[::-1]+'-' ... | Squished GUID (SQUID) to GUID.
A SQUID is a Squished/Compressed version of a GUID to use up less space
in the registry.
Args:
squid (str): Squished GUID.
Returns:
str: the GUID if a valid SQUID provided. | juraj-google-style |
def persist_experiment(experiment):
from benchbuild.utils.schema import Experiment, Session
session = Session()
cfg_exp = experiment.id
LOG.debug("Using experiment ID stored in config: %s", cfg_exp)
exps = session.query(Experiment).filter(Experiment.id == cfg_exp)
desc = str(CFG["experime... | Persist this experiment in the benchbuild database.
Args:
experiment: The experiment we want to persist. | juraj-google-style |
def __init__(self):
super(JLinkSpeedInfo, self).__init__()
self.SizeOfStruct = ctypes.sizeof(self) | Initializes the ``JLinkSpeedInfo`` instance.
Sets the size of the structure.
Args:
self (JLinkSpeedInfo): the ``JLinkSpeedInfo`` instance
Returns:
``None`` | juraj-google-style |
def connect_sync(self, connection_id, connection_string):
calldone = threading.Event()
results = {}
def connect_done(callback_connid, callback_adapterid, callback_success, failure_reason):
results['success'] = callback_success
results['failure_reason'] = failure_reason
calldone.set(... | Synchronously connect to a device
Args:
connection_id (int): A unique identifier that will refer to this connection
connection_string (string): A DeviceAdapter specific string that can be used to connect to
a device using this DeviceAdapter.
Returns:
dict: A dictionary with two elements
'success': a bool with the res... | codesearchnet |
def _get_programs_dict():
global __programs_dict
if (__programs_dict is not None):
return __programs_dict
d = __programs_dict = OrderedDict()
for pkgname in COLLABORATORS_S:
try:
package = importlib.import_module(pkgname)
except ImportError:
continue
... | Builds and returns programs dictionary
This will have to import the packages in COLLABORATORS_S in order to get their absolute path.
Returns:
dictionary: {"packagename": [ExeInfo0, ...], ...}
"packagename" examples: "f311.explorer", "numpy" | codesearchnet |
def add_comment(self, line):
if (not isinstance(self.last_item, Comment)):
comment = Comment(self._structure)
self._structure.append(comment)
self.last_item.add_line(line)
return self | Add a Comment object to the section
Used during initial parsing mainly
Args:
line (str): one line in the comment | codesearchnet |
def from_dim_sizes(dim_sizes):
with ops.name_scope(None, 'RaggedTensorDynamicShapeFromDimensionSizes', [dim_sizes]):
dim_sizes = tuple((ops.convert_to_tensor(size, preferred_dtype=dtypes.int64, name='dim_sizes') for size in dim_sizes))
inner_split = 0
for dim, dim_size in enumerate(dim_sizes... | Constructs a ragged shape from a list of dimension sizes.
This list contains a single tensor for each dimension, where the tensor
is a scalar if the dimension is uniform, or a vector if the dimension is
ragged.
Args:
dim_sizes: List of int32 or int64 scalars or vectors.
Returns:
A RaggedTensorDynamicShape. | github-repos |
def basis(sample_paths, time_index):
sample_paths = tf.convert_to_tensor(sample_paths, name='sample_paths')
if sample_paths.shape.rank == 3:
sample_paths = tf.expand_dims(sample_paths, axis=0)
shape = tf.shape(sample_paths)
num_samples = shape[1]
batch_size = shape[0]
dim = sample_paths.... | Computes polynomial basis expansion at the given sample points.
Args:
sample_paths: A `Tensor` of either `flaot32` or `float64` dtype and of
either shape `[num_samples, num_times, dim]` or
`[batch_size, num_samples, num_times, dim]`.
time_index: An integer scalar `Tensor` that corresponds to the time
coordinate at whi... | github-repos |
def TotalFees(self):
amount = Fixed8.Zero()
for tx in self.Transactions:
amount += tx.SystemFee()
return amount | Get the total transaction fees in the block.
Returns:
Fixed8: | codesearchnet |
def parse_table_data(lines):
data = '\n'.join([i.rstrip() for i in lines if ((not i.startswith(('^', '!', '
if data:
return read_csv(StringIO(data), index_col=None, sep='\t')
else:
return DataFrame() | Parse list of lines from SOFT file into DataFrame.
Args:
lines (:obj:`Iterable`): Iterator over the lines.
Returns:
:obj:`pandas.DataFrame`: Table data. | codesearchnet |
def depth_soil_density(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_soil_density`'.format(val... | Corresponds to IDD Field `depth_soil_density`
Args:
value (float): value for IDD Field `depth_soil_density`
Unit: kg/m3
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 _remove_files(files):
logger.debug("Request for file removal (_remove_files()).")
for fn in files:
if os.path.exists(fn):
logger.debug("Removing '%s'." % fn)
os.remove(fn) | Remove all given files.
Args:
files (list): List of filenames, which will be removed. | juraj-google-style |
def set_seed(seed: int, deterministic: bool=False):
random.seed(seed)
np.random.seed(seed)
if is_torch_available():
torch.manual_seed(seed)
torch.cuda.manual_seed_all(seed)
if deterministic:
torch.use_deterministic_algorithms(True)
if is_torch_mlu_available():
... | Helper function for reproducible behavior to set the seed in `random`, `numpy`, `torch` and/or `tf` (if installed).
Args:
seed (`int`):
The seed to set.
deterministic (`bool`, *optional*, defaults to `False`):
Whether to use deterministic algorithms where available. Can slow down training. | github-repos |
def validate(self, graph):
if not nx.is_directed_acyclic_graph(graph):
raise DirectedAcyclicGraphInvalid(graph_name=self._name) | Validate the graph by checking whether it is a directed acyclic graph.
Args:
graph (DiGraph): Reference to a DiGraph object from NetworkX.
Raises:
DirectedAcyclicGraphInvalid: If the graph is not a valid dag. | juraj-google-style |
def get_structure(atoms, cls=None):
symbols = atoms.get_chemical_symbols()
positions = atoms.get_positions()
lattice = atoms.get_cell()
cls = Structure if cls is None else cls
return cls(lattice, symbols, positions,
coords_are_cartesian=True) | Returns pymatgen structure from ASE Atoms.
Args:
atoms: ASE Atoms object
cls: The Structure class to instantiate (defaults to pymatgen structure)
Returns:
Equivalent pymatgen.core.structure.Structure | juraj-google-style |
def Verify(self):
return getattr(self, self._KEY) is not None | We can properly index this instance into a Map.
Returns:
True if the value in the attribute named by self._KEY for this class
is not None. False otherwise. | github-repos |
def set_epsilon(value):
global _EPSILON
_EPSILON = value | Sets the value of the fuzz factor used in numeric expressions.
Args:
value: float. New value of epsilon.
Example:
>>> tf.keras.backend.epsilon()
1e-07
>>> tf.keras.backend.set_epsilon(1e-5)
>>> tf.keras.backend.epsilon()
1e-05
>>> tf.keras.backend.set_epsilon(1e-7) | github-repos |
def __init__(self, state_handler: sdk_worker.CachingStateHandler, transform_id: str, key_coder: coders.Coder, window_coder: coders.Coder) -> None:
self._state_handler = state_handler
self._transform_id = transform_id
self._key_coder = key_coder
self._window_coder = window_coder
self._timers_info: Di... | Initialize a ``FnApiUserStateContext``.
Args:
state_handler: A StateServicer object.
transform_id: The name of the PTransform that this context is associated.
key_coder: Coder for the key type.
window_coder: Coder for the window type. | github-repos |
def __le__(self, other: 'TensorFluent') -> 'TensorFluent':
return self._binary_op(self, other, tf.less_equal, tf.float32) | Returns a TensorFluent for the less-than-or-equal relational operator.
Args:
self: The first operand.
other: The second operand. | juraj-google-style |
def _handle_emailauth(maildomain='', message=''):
print('SteamGuard requires email authentication...')
emailauth = input(('Please enter the code sent to your mail address at "%s": ' % maildomain))
emailauth.upper()
return emailauth | Called when SteamGuard requires authentication via e-mail.
Asks the user to enter the code.
Args:
maildomain: Optional. The mail domain of the e-mail address the SteamGuard
code is send to.
message: Optional. A message from Steam service.
Returns:
A string containing the code. | codesearchnet |
def load_transcripts(adapter, transcripts_lines=None, build='37', ensembl_genes=None):
ensembl_genes = ensembl_genes or adapter.ensembl_genes(build)
if transcripts_lines is None:
transcripts_lines = fetch_ensembl_transcripts(build=build)
transcripts_dict = parse_transcripts(transcri... | Load all the transcripts
Transcript information is from ensembl.
Args:
adapter(MongoAdapter)
transcripts_lines(iterable): iterable with ensembl transcript lines
build(str)
ensembl_genes(dict): Map from ensembl_id -> HgncGene
Returns:
transcript_objs(list): A list with all transcript objects | juraj-google-style |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.