code stringlengths 20 4.93k | docstring stringlengths 33 1.27k | source stringclasses 3
values |
|---|---|---|
def patch(self, id, name=None, description=None, whitelisted_container_task_types=None, whitelisted_executable_task_types=None):
request_url = (self._client.base_api_url + self.detail_url.format(id=id))
data_to_patch = {}
if (name is not None):
data_to_patch['name'] = name
if (description is not... | Partially updates a task whitelist on the saltant server.
Args:
id (int): The ID of the task whitelist.
name (str, optional): The name of the task whitelist.
description (str, optional): A description of the task whitelist.
whitelisted_container_task_types (list, optional): A list of
whitelisted container task type ID... | codesearchnet |
def _parse_metadata(self, message):
metadata = Metadata(source=self.actor_urn).__dict__
if 'author' in message['d']:
metadata['source_user'] = message['d']['author']['username']
else:
metadata['source_user'] = None
if 'channel_id' in message['d']:
... | Sets metadata in Legobot message
Args:
message (dict): Full message from Discord websocket connection"
Returns:
Legobot.Metadata | juraj-google-style |
def __init__(self, log_path, ref_path, run_path, output_path):
process_worker.ProcessWorkflow.__init__(
self, log_path, timeout_seconds=FLAGS.pdiff_timeout)
self.ref_path = ref_path
self.run_path = run_path
self.output_path = output_path | Initializer.
Args:
log_path: Where to write the verbose logging output.
ref_path: Path to reference screenshot to diff.
run_path: Path to the most recent run screenshot to diff.
output_path: Where the diff image should be written, if any. | juraj-google-style |
def has_value(self, name=None):
raise NotImplementedError('Optional.has_value()') | Returns a tensor that evaluates to `True` if this optional has a value.
>>> optional = tf.experimental.Optional.from_value(42)
>>> print(optional.has_value())
tf.Tensor(True, shape=(), dtype=bool)
Args:
name: (Optional.) A name for the created operation.
Returns:
A scalar `tf.Tensor` of type `tf.bool`. | github-repos |
def BuildParams(self, graph_fn, dtype, input_shapes, output_shapes):
input_mask = [[False] + [True] * (len(shape) - 1) for shape in input_shapes]
output_mask = [[False] + [True] * (len(shape) - 1) if shape else [] for shape in output_shapes]
return self.BuildParamsWithMask(graph_fn, dtype, input_shapes, out... | Build test parameters.
The input_shapes and output_shapes arguments are known (static) shapes that
can be used to generate test data. To define the model, we also specify
corresponding input/output TensorSpecs. These are defined using the shape
arguments. For each input tensor we define:
input_spec = [None] + input_s... | github-repos |
def nr_cases(self, institute_id=None):
query = {}
if institute_id:
query['collaborators'] = institute_id
LOG.debug('Fetch all cases with query {0}'.format(query))
nr_cases = self.case_collection.find(query).count()
return nr_cases | Return the number of cases
This function will change when we migrate to 3.7.1
Args:
collaborator(str): Institute id
Returns:
nr_cases(int) | codesearchnet |
def cn_occupation_energy(self, delta_occupation=None):
nn_occupations = self.site_specific_nn_occupation()
if delta_occupation:
for site in delta_occupation:
assert (site in nn_occupations)
nn_occupations[site] += delta_occupation[site]
return sum([self.cn_occupation_energies... | The coordination-number dependent energy for this site.
Args:
delta_occupation (:obj:Dict(Str:Int), optional): A dictionary of a change in (site-type specific) coordination number, e.g. { 'A' : 1, 'B' : -1 }.
If this is not None, the coordination-number dependent energy is calculated including these changes in neighbo... | codesearchnet |
def str2dict(str_in):
dict_out = safe_eval(str_in)
if (not isinstance(dict_out, dict)):
dict_out = None
return dict_out | Extracts a dict from a string.
Args:
str_in (string) that contains python dict
Returns:
(dict) or None if no valid dict was found
Raises:
- | codesearchnet |
def from_pretrained(cls, pretrained_processor_name_or_path, speaker_embeddings_dict_path='speaker_embeddings_path.json', **kwargs):
if speaker_embeddings_dict_path is not None:
speaker_embeddings_path = cached_file(pretrained_processor_name_or_path, speaker_embeddings_dict_path, subfolder=kwargs.pop('subfol... | Instantiate a Bark processor associated with a pretrained model.
Args:
pretrained_model_name_or_path (`str` or `os.PathLike`):
This can be either:
- a string, the *model id* of a pretrained [`BarkProcessor`] hosted inside a model repo on
huggingface.co.
- a path to a *directory* containing a processor saved using the... | github-repos |
class TFSharedEmbeddings(keras.layers.Layer):
def __init__(self, vocab_size: int, hidden_size: int, initializer_range: Optional[float]=None, **kwargs):
super().__init__(**kwargs)
self.vocab_size = vocab_size
self.hidden_size = hidden_size
self.initializer_range = hidden_size ** (-0.... | Construct shared token embeddings.
The weights of the embedding layer is usually shared with the weights of the linear decoder when doing language
modeling.
Args:
vocab_size (`int`):
The size of the vocabulary, e.g., the number of unique tokens.
hidden_size (`int`):
The size of the embedding vectors.
initializer_rang... | github-repos |
def total_seconds(td):
secs = td.seconds + td.days * 24 * 3600
if td.microseconds:
secs += 1
return secs | convert a timedelta to seconds.
This is patterned after timedelta.total_seconds, which is only
available in python 27.
Args:
td: a timedelta object.
Returns:
total seconds within a timedelta. Rounded up to seconds. | juraj-google-style |
def _check_call_func(self, node):
func = utils.safe_infer(node.func)
types = ("str", "unicode")
methods = ("format",)
if is_method_call(func, types, methods) and not is_complex_format_str(
func.bound
):
self.add_message("logging-format-interpolati... | Checks that function call is not format_string.format().
Args:
node (astroid.node_classes.Call):
Call AST node to be checked. | juraj-google-style |
def log_variable_sizes(var_list=None, tag=None, verbose=False):
if var_list is None:
var_list = tf.trainable_variables()
if tag is None:
tag = "Trainable Variables"
if not var_list:
return
name_to_var = {v.name: v for v in var_list}
total_size = 0
for v_name in sorted(list(name_to_var)):
... | Log the sizes and shapes of variables, and the total size.
Args:
var_list: a list of variables; defaults to trainable_variables
tag: a string; defaults to "Trainable Variables"
verbose: bool, if True, log every weight; otherwise, log total size only. | juraj-google-style |
def local_file(self, filename):
LOG.info('Retrieving "%s" from "%s".', filename, self.runway_dir)
file_contents = ''
file_path = os.path.join(self.runway_dir, filename)
try:
with open(file_path, 'rt') as lookup_file:
file_contents = lookup_file.read()
except FileNotFoundError:
... | Read the local file in _self.runway_dir_.
Args:
filename (str): Name of file to retrieve relative to root of
_runway_dir_.
Returns:
str: Contents of local file.
Raises:
FileNotFoundError: Requested file missing. | codesearchnet |
def Process(self, parser_mediator, date_time, syslog_tokens, **kwargs):
body = syslog_tokens.get('body', None)
if (not body):
raise AttributeError('Missing required attribute: body')
for (key, grammar) in iter(self.MESSAGE_GRAMMARS):
try:
tokens = grammar.parseString(body)
... | Processes the data structure produced by the parser.
Args:
parser_mediator (ParserMediator): mediates the interactions between
parsers and other components, such as storage and abort signals.
date_time (dfdatetime.DateTimeValues): date and time values.
syslog_tokens (dict[str, str]): names of the fields extracted by t... | codesearchnet |
def combine(self, x):
depth = tf.shape(x)[(- 1)]
x *= tf.expand_dims(self._nonpadding, (- 1))
ret = tf.unsorted_segment_sum(x, self._flat_indices, num_segments=(self._batch * self._length))
ret = tf.reshape(ret, [self._batch, self._length, depth])
return ret | Return the output from the experts.
When one example goes to multiple experts, the outputs are summed.
Args:
x: a Tensor with shape [batch, num_experts, expert_capacity, depth]
Returns:
a `Tensor` with shape `[batch, length, depth] | codesearchnet |
def scalar_mul(scalar, x, name=None):
base_dtype = dtypes.as_dtype(x.dtype).base_dtype
scalar = ops.convert_to_tensor(scalar, dtype=base_dtype, name='scalar')
shape = scalar.get_shape()
if shape.ndims == 0:
if isinstance(x, indexed_slices.IndexedSlices):
return indexed_slices.Indexed... | Multiplies a scalar times a `Tensor` or `IndexedSlices` object.
This is a special case of `tf.math.multiply`, where the first value must be a
`scalar`. Unlike the general form of `tf.math.multiply`, this is operation is
guaranteed to be efficient for `tf.IndexedSlices`.
>>> x = tf.reshape(tf.range(30, dtype=tf.float3... | github-repos |
def compute_dtype(self):
return self._dtype_policy.compute_dtype | The dtype of the layer's computations.
This is equivalent to `Layer.dtype_policy.compute_dtype`. Unless
mixed precision is used, this is the same as `Layer.dtype`, the dtype of
the weights.
Layers automatically cast their inputs to the compute dtype, which causes
computations and the output to be in the compute dtype... | github-repos |
def update_video(self, video_id, title='', description='', keywords='', access_control=AccessControl.Unlisted):
if (not self.authenticated):
raise ApiError(_('Authentication is required'))
entry = self.fetch_video(video_id)
extension = self._access_control(access_control)
if extension:
e... | Updates the video
Authentication is required
Params:
entry: video entry fetch via 'fetch_video()'
title: string
description: string
keywords: string
Returns:
a video entry on success
None otherwise | codesearchnet |
def functions(start=None, end=None):
start, end = fix_addresses(start, end)
for func_t in idautils.Functions(start, end):
yield Function(func_t) | Get all functions in range.
Args:
start: Start address of the range. Defaults to IDB start.
end: End address of the range. Defaults to IDB end.
Returns:
This is a generator that iterates over all the functions in the IDB. | juraj-google-style |
def calculate_oobatake_dS(seq, temp):
seq = ssbio.protein.sequence.utils.cast_to_str(seq)
dS = 0
temp += 273.15
T0 = 298.15
dCp_sum = _sum_of_dCp(seq)
for aa in seq:
S0 = oobatake_dictionary[aa]['dS']
dS += S0
return dS + dCp_sum * math.log(temp / T0) | Get dS using Oobatake method in units cal/mol.
Args:
seq (str, Seq, SeqRecord): Amino acid sequence
temp (float): Temperature in degrees C
Returns:
float: dS in units cal/mol | juraj-google-style |
def list_autoscale_settings(access_token, subscription_id):
endpoint = ''.join([get_rm_endpoint(), '/subscriptions/', subscription_id, '/providers/microsoft.insights/', '/autoscaleSettings?api-version=', INSIGHTS_API])
return do_get(endpoint, access_token) | List the autoscale settings in a subscription.
Args:
access_token (str): A valid Azure authentication token.
subscription_id (str): Azure subscription id.
Returns:
HTTP response. JSON body of autoscale settings. | codesearchnet |
def disconnect_sync(self, conn_id):
done = threading.Event()
result = {}
def disconnect_done(conn_id, adapter_id, status, reason):
result['success'] = status
result['failure_reason'] = reason
done.set()
self.disconnect_async(conn_id, disconnect_done)
done.wait()
return r... | Synchronously disconnect from a connected device
Args:
conn_id (int): A unique identifier that will refer to this connection
Returns:
dict: A dictionary with two elements
'success': a bool with the result of the connection attempt
'failure_reason': a string with the reason for the failure if we failed | codesearchnet |
class Mamba2Output(ModelOutput):
last_hidden_state: Optional[torch.FloatTensor] = None
cache_params: Optional[Mamba2Cache] = None
hidden_states: Optional[Tuple[torch.FloatTensor]] = None | Class for the MAMBA2 model outputs.
Args:
last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
Sequence of hidden-states at the output of the last layer of the model.
cache_params (`Mamba2Cache`):
The state of the model at the last time step. Can be used in a forward method wi... | github-repos |
def beta_to_uni(text, strict=False):
param_key = (strict,)
try:
t = _BETA_CONVERSION_TRIES[param_key]
except KeyError:
t = _create_conversion_trie(*param_key)
_BETA_CONVERSION_TRIES[param_key] = t
transform = []
idx = 0
possible_word_boundary = False
while (idx < len(... | Converts the given text from betacode to unicode.
Args:
text: The beta code text to convert. All of this text must be betacode.
strict: Flag to allow for flexible diacritic order on input.
Returns:
The converted text. | codesearchnet |
def handle_subscribe(self, request, path):
ret = []
if path:
name = path[0]
if (name not in self.children):
self.children[name] = NotifierNode(getattr(self.data, name, None), self)
ret += self.children[name].handle_subscribe(request, path[1:])
else:
serialized = s... | Add to the list of request to notify, and notify the initial value of
the data held
Args:
request (Subscribe): The subscribe request
path (list): The relative path from ourself
Returns:
list: [(callback, Response)] that need to be called | codesearchnet |
def evaluate_ising(linear, quad, state):
if _numpy and isinstance(state, np.ndarray):
return evaluate_ising(linear, quad, state.tolist())
energy = 0.0
for index, value in uniform_iterator(linear):
energy += state[index] * value
for (index_a, index_b), value in six.iterit... | Calculate the energy of a state given the Hamiltonian.
Args:
linear: Linear Hamiltonian terms.
quad: Quadratic Hamiltonian terms.
state: Vector of spins describing the system state.
Returns:
Energy of the state evaluated by the given energy function. | juraj-google-style |
def __init__(self, nonce_id=None, nonce_value=None):
super(Nonce, self).__init__(tag=enums.Tags.NONCE)
self._nonce_id = None
self._nonce_value = None
self.nonce_id = nonce_id
self.nonce_value = nonce_value | Construct a Nonce struct.
Args:
nonce_id (bytes): A binary string representing the ID of the nonce
value. Optional, defaults to None. Required for encoding and
decoding.
nonce_value (bytes): A binary string representing a random value.
Optional, defaults to None. Required for encoding and decoding. | juraj-google-style |
def _empty_dict_pylist_from_row_partitions(row_partitions, nrows):
if not row_partitions:
return [{} for _ in range(nrows)]
else:
values = _empty_dict_pylist_from_row_partitions(row_partitions[1:], row_partitions[0].row_splits()[-1])
splits = row_partitions[0].row_splits()
return... | Returns a python list of empty dicts from the given row partitions.
Args:
row_partitions: The row-partitions describing the ragged shape of the
result.
nrows: The number of rows in the outermost row-partition. (Or if
`len(row_partitions)==0`, then the number of empty dicts to return.)
Returns:
A nested python list w... | github-repos |
def _cursor_pb(cursor_pair):
if cursor_pair is not None:
data, before = cursor_pair
value_pbs = [_helpers.encode_value(value) for value in data]
return query_pb2.Cursor(values=value_pbs, before=before) | Convert a cursor pair to a protobuf.
If ``cursor_pair`` is :data:`None`, just returns :data:`None`.
Args:
cursor_pair (Optional[Tuple[list, bool]]): Two-tuple of
* a list of field values.
* a ``before`` flag
Returns:
Optional[google.cloud.firestore_v1beta1.types.Cursor]: A
protobuf cursor corresponding to the value... | juraj-google-style |
def writeCmdMsg(self, msg):
ekm_log(((('(writeCmdMsg | ' + self.getContext()) + ') ') + msg))
self.m_command_msg = msg | Internal method to set the command result string.
Args:
msg (str): Message built during command. | codesearchnet |
def _jacobian_both(nodes, degree, dimension):
r
_, num_nodes = nodes.shape
result = np.empty((2 * dimension, num_nodes - degree - 1), order="F")
result[:dimension, :] = jacobian_s(nodes, degree, dimension)
result[dimension:, :] = jacobian_t(nodes, degree, dimension)
return result | r"""Compute :math:`s` and :math:`t` partial of :math:`B`.
.. note::
There is also a Fortran implementation of this function, which
will be used if it can be built.
Args:
nodes (numpy.ndarray): Array of nodes in a surface.
degree (int): The degree of the surface.
dimension (int): The dimension the surface lives in.
... | juraj-google-style |
def __get_state_by_id(cls, job_id):
state = model.MapreduceState.get_by_job_id(job_id)
if (state is None):
raise ValueError(('Job state for job %s is missing.' % job_id))
return state | Get job state by id.
Args:
job_id: job id.
Returns:
model.MapreduceState for the job.
Raises:
ValueError: if the job state is missing. | codesearchnet |
def build_synchronize_decorator():
lock = threading.Lock()
def lock_decorator(fn):
@functools.wraps(fn)
def lock_decorated(*args, **kwargs):
with lock:
return fn(*args, **kwargs)
return lock_decorated
return lock_decorator | Returns a decorator which prevents concurrent calls to functions.
Usage:
synchronized = build_synchronize_decorator()
@synchronized
def read_value():
...
@synchronized
def write_value(x):
...
Returns:
make_threadsafe (fct): The decorator which lock all functions to which it
is applied under a same lock | codesearchnet |
def get_list(self, obj_class, data, subset):
url = obj_class.get_url(data)
if (obj_class.can_list and obj_class.can_get):
if ((subset and (len(subset) == 1) and (subset[0].upper() == 'BASIC')) and (obj_class is jssobjects.Computer)):
url += '/subset/basic'
result = self.jss.get(url)
... | Get a list of objects as JSSObjectList.
Args:
obj_class: The JSSObject subclass type to search for.
data: None
subset: Some objects support a subset for listing; namely
Computer, with subset="basic".
Returns:
JSSObjectList | codesearchnet |
def jump( self ):
potential_jumps = self.potential_jumps()
if not potential_jumps:
raise BlockedLatticeError('No moves are possible in this lattice')
all_transitions = transitions.Transitions( self.potential_jumps() )
random_jump = all_transitions.random()
de... | Select a jump at random from all potential jumps, then update the lattice state.
Args:
None
Returns:
None | juraj-google-style |
def take_bug_report(self, test_name=None, begin_time=None, timeout=300, destination=None):
prefix = DEFAULT_BUG_REPORT_NAME
if test_name:
prefix = '%s,%s' % (DEFAULT_BUG_REPORT_NAME, test_name)
if begin_time is None:
begin_time = mobly_logger.get_log_file_timestamp()
new_br = True
tr... | Takes a bug report on the device and stores it in a file.
Args:
test_name: Name of the test method that triggered this bug report.
begin_time: Timestamp of when the test started. If not set, then
this will default to the current time.
timeout: float, the number of seconds to wait for bugreport to
complete, default is ... | github-repos |
def space(self, newlines=1):
space = Space()
for line in range(newlines):
space.add_line('\n')
self._container.structure.insert(self._idx, space)
self._idx += 1
return self | Creates a vertical space of newlines
Args:
newlines (int): number of empty lines
Returns:
self for chaining | juraj-google-style |
def relative_batch_tokens_ids_to_midi(self, tokens: np.ndarray, beatstep: np.ndarray, beat_offset_idx: int=0, bars_per_batch: int=2, cutoff_time_idx: int=12):
beat_offset_idx = 0 if beat_offset_idx is None else beat_offset_idx
notes = self.relative_batch_tokens_ids_to_notes(tokens=tokens, beat_offset_idx=beat_o... | Converts tokens to Midi. This method calls `relative_batch_tokens_ids_to_notes` method to convert batch tokens
to notes then uses `notes_to_midi` method to convert them to Midi.
Args:
tokens (`numpy.ndarray`):
Denotes tokens which alongside beatstep will be converted to Midi.
beatstep (`np.ndarray`):
We get beatstep f... | github-repos |
def compress_mean(x, dim, compression_factor):
dims = x.shape.dims
pos = dims.index(dim)
compressed_dim = mtf.Dimension(dim.name, dim.size
compression_factor_dim = mtf.Dimension(
"compression_factor", compression_factor)
new_shape = (
dims[:pos] + [compressed_dim, compression_factor_dim] + dim... | Compress by taking group means.
Args:
x: a Tensor
dim: a dimension in x.shape
compression_factor: an integer
Returns:
a Tensor | juraj-google-style |
def deploy(app_id, version, promote, quiet):
gae_app = GaeApp.for_branch(git.current_branch().name)
if ((gae_app is None) and (None in (app_id, version))):
msg = "Can't find an AppEngine app setup for branch <35>{}<32> and--project and --version were not given."
log.err(msg, git.current_branch()... | Deploy the app to AppEngine.
Args:
app_id (str):
AppEngine App ID. Overrides config value app_id if given.
version (str):
AppEngine project version. Overrides config values if given.
promote (bool):
If set to **True** promote the current remote app version to the one
that's being deployed.
quiet (bool):
If set to **Tr... | codesearchnet |
def _broadcast_dynamic_shape_extended_helper(a: DynamicRaggedShape, b: DynamicRaggedShape) -> Tuple[DynamicRaggedShape, _Broadcaster, _Broadcaster]:
assert a.rank <= b.rank
assert 2 <= b.rank
assert 1 <= a.rank
a_rps = a._as_row_partitions()
b_rps = b._as_row_partitions()
if len(a_rps) < len(b_r... | Helper for broadcast_dynamic_shape_extended.
Here, we force:
a.rank <= b.rank
2 <= b.rank
1 <= a.rank
Args:
a: a DynamicRaggedShape
b: a DynamicRaggedShape
Returns:
A triple of a shape and two broadcasters. | github-repos |
def read_chunks(self, chunk_size, start, step, count) -> bytes:
return self.mglo.read_chunks(chunk_size, start, step, count) | Read the content.
Read and concatenate the chunks of size chunk_size
using offsets calculated from start, step and stop.
Args:
chunk_size (int): The chunk size.
start (int): First offset.
step (int): Offset increment.
count (int): The number of offsets.
Returns:
bytes | juraj-google-style |
def __init__(self, namespace: Optional[str], name: Optional[str], urn: Optional[str]=None, labels: Optional[Dict[str, str]]=None) -> None:
if not urn:
if not namespace:
raise ValueError('Metric namespace must be non-empty')
if not name:
raise ValueError('Metric name must be n... | Initializes ``MetricName``.
Note: namespace and name should be set for user metrics,
urn and labels should be set for an arbitrary metric to package into a
MonitoringInfo.
Args:
namespace: A string with the namespace of a metric.
name: A string with the name of a metric.
urn: URN to populate on a MonitoringInfo, when... | github-repos |
def update_current_state(self, value: str,
force: bool = False) -> datetime:
value = value.lower()
if not force:
current_state = self.current_state
if current_state == 'unknown':
allowed_transitions =... | Update the current state.
Args:
value (str): New value for sdp state
force (bool): If true, ignore allowed transitions
Returns:
datetime, update timestamp
Raises:
ValueError: If the specified current state is not allowed. | juraj-google-style |
def compute_mask_offsets(shard_id2num_examples):
total_num_examples = sum(shard_id2num_examples)
mask_offsets = []
total_num_examples = 0
for num_examples_in_shard in shard_id2num_examples:
mask_offsets.append(total_num_examples % 100)
total_num_examples += num_examples_in_shard
return ... | Return the list of offsets associated with each shards.
Args:
shard_id2num_examples: `list[int]`, mapping shard_id=>num_examples
Returns:
mask_offsets: `list[int]`, offset to skip for each of the shard | juraj-google-style |
def files_info(self, *, id: str, **kwargs) -> SlackResponse:
kwargs.update({'id': id})
return self.api_call('files.info', http_verb='GET', params=kwargs) | Gets information about a team file.
Args:
id (str): The file id. e.g. 'F1234467890' | codesearchnet |
def get(self, name):
return self.prepare_model(self.client.api.inspect_plugin(name)) | Gets a plugin.
Args:
name (str): The name of the plugin.
Returns:
(:py:class:`Plugin`): The plugin.
Raises:
:py:class:`docker.errors.NotFound` If the plugin does not
exist.
:py:class:`docker.errors.APIError`
If the server returns an error. | codesearchnet |
def load(self, label_lookup_path, uid_lookup_path):
if not tf.gfile.Exists(uid_lookup_path):
tf.logging.fatal('File does not exist %s', uid_lookup_path)
if not tf.gfile.Exists(label_lookup_path):
tf.logging.fatal('File does not exist %s', label_lookup_path)
proto_as_ascii_lines = tf.g... | Loads a human readable English name for each softmax node.
Args:
label_lookup_path: string UID to integer node ID.
uid_lookup_path: string UID to human-readable string.
Returns:
dict from integer node ID to human-readable string. | juraj-google-style |
def _ProcessUnknownEnums(message, encoded_message):
if (not encoded_message):
return message
decoded_message = json.loads(six.ensure_str(encoded_message))
for field in message.all_fields():
if (isinstance(field, messages.EnumField) and (field.name in decoded_message) and (message.get_assigne... | Add unknown enum values from encoded_message as unknown fields.
ProtoRPC diverges from the usual protocol buffer behavior here and
doesn't allow unknown fields. Throwing on unknown fields makes it
impossible to let servers add new enum values and stay compatible
with older clients, which isn't reasonable for us. We si... | codesearchnet |
def get_modules():
ret = list()
valid_extensions = ('.psd1', '.psm1', '.cdxml', '.xaml', '.dll')
root_paths = []
home_dir = os.environ.get('HOME', os.environ.get('HOMEPATH'))
system_dir = '{0}\\System32'.format(os.environ.get('WINDIR', 'C:\\Windows'))
program_files = os.environ.get('ProgramFiles... | Get a list of the PowerShell modules which are potentially available to be
imported. The intent is to mimic the functionality of ``Get-Module
-ListAvailable | Select-Object -Expand Name``, without the delay of loading
PowerShell to do so.
Returns:
list: A list of modules available to Powershell
Example:
.. code-bloc... | codesearchnet |
def _ReadRecordHeader(self, file_object, record_header_offset):
data_type_map = self._GetDataTypeMap('keychain_record_header')
(record_header, _) = self._ReadStructureFromFileObject(file_object, record_header_offset, data_type_map)
return record_header | Reads the record header.
Args:
file_object (file): file-like object.
record_header_offset (int): offset of the record header relative to
the start of the file.
Returns:
keychain_record_header: record header.
Raises:
ParseError: if the record header cannot be read. | codesearchnet |
def _GetModuleCodeObjects(module):
visit_recorder = _VisitRecorder()
current = [module]
code_objects = set()
while current:
current = _FindCodeObjectsReferents(module, current, visit_recorder)
code_objects |= current
current = [code_object.co_consts for code_object in current]
... | Gets all code objects defined in the specified module.
There are two BFS traversals involved. One in this function and the other in
_FindCodeObjectsReferents. Only the BFS in _FindCodeObjectsReferents has
a depth limit. This function does not. The motivation is that this function
explores code object of the module and... | codesearchnet |
def restore_collection(backup):
for (k, v) in six.iteritems(backup):
del tf.get_collection_ref(k)[:]
tf.get_collection_ref(k).extend(v) | Restore from a collection backup.
Args:
backup (dict): | codesearchnet |
def gather(params, indices, validate_indices=None, name=None, axis=None, batch_dims=0):
if name is None:
name = 'gather'
with ops.name_scope(name):
if axis is None:
axis = batch_dims
axis = array_ops.get_positive_axis(axis, params.shape.rank, ndims_name='params.shape.rank')
... | tf.gather for structured tensors.
Does not support (yet) checks on illegal axis values, et cetera.
Indices must be a ragged or dense tensor.
Args:
params: a structured tensor to be gathered
indices: a ragged tensor or tensor to gather by.
validate_indices: whether to validate the indices
name: the name of the op(s).
... | github-repos |
def save_screenshot(driver, name):
if hasattr(driver, 'save_screenshot'):
screenshot_dir = os.environ.get('SCREENSHOT_DIR')
if (not screenshot_dir):
LOGGER.warning('The SCREENSHOT_DIR environment variable was not set; not saving a screenshot')
return
elif (not os.path... | Save a screenshot of the browser.
The location of the screenshot can be configured
by the environment variable `SCREENSHOT_DIR`. If not set,
this defaults to the current working directory.
Args:
driver (selenium.webdriver): The Selenium-controlled browser.
name (str): A name for the screenshot, which will be used in... | codesearchnet |
def load(self, *modules):
for module in modules:
if isinstance(module, six.string_types):
try:
module = get_object(module)
except Exception as e:
self.errors[module] = e
continue
self.modules[module.__package__] = module
... | Load one or more modules.
Args:
modules: Either a string full path to a module or an actual module
object. | codesearchnet |
def __init__(self, context_name = 'default'):
if context_name in self.contexts:
raise Error("A context named '%s' already exists" % (context_name,))
self.name = context_name
self.handlers = {}
self.contexts[self.name] = self | Create a new Bubbler context
Params:
context_name (string):
Name of this context
Raises:
bubbler.Error:
If this context name already exists | juraj-google-style |
def changes(self, **kwargs):
path = ('%s/%s/changes' % (self.manager.path, self.get_id()))
return self.manager.gitlab.http_get(path, **kwargs) | List the merge request changes.
Args:
**kwargs: Extra options to send to the server (e.g. sudo)
Raises:
GitlabAuthenticationError: If authentication is not correct
GitlabListError: If the list could not be retrieved
Returns:
RESTObjectList: List of changes | codesearchnet |
def parse(self, body):
if isinstance(body, six.string_types):
body = json.loads(body)
version = body['version']
self.version = version
session = body['session']
self.session.new = session['new']
self.session.session_id = session['sessionId']
application_id = session['application']['a... | Parse JSON request, storing content in object attributes.
Args:
body: str. HTTP request body.
Returns:
self | codesearchnet |
def get_student_certificate(self, username, course_id):
resp = self.requester.get(
urljoin(
self.base_url,
'/api/certificates/v0/certificates/{username}/courses/{course_key}/'.format(
username=username,
course_... | Returns an Certificate object with the user certificates
Args:
username (str): an edx user's username
course_id (str): an edX course id.
Returns:
Certificate: object representing the student certificate for a course | juraj-google-style |
def read(self, n):
if self._EOF:
return ""
while self._seg_index <= self._last_seg_index:
result = self._read_from_seg(n)
if result != "":
return result
else:
self._next_seg()
self._EOF = True
return "" | Read data from file segs.
Args:
n: max bytes to read. Must be positive.
Returns:
some bytes. May be smaller than n bytes. "" when no more data is left. | juraj-google-style |
def console_get_width(con: tcod.console.Console) -> int:
return int(lib.TCOD_console_get_width(_console(con))) | Return the width of a console.
Args:
con (Console): Any Console instance.
Returns:
int: The width of a Console.
.. deprecated:: 2.0
Use `Console.width` instead. | juraj-google-style |
def lookup_prefix(self, prefix, timestamp=timestamp_now):
prefix = prefix.strip().upper()
if ((self._lookuptype == 'clublogxml') or (self._lookuptype == 'countryfile')):
return self._check_data_for_date(prefix, timestamp, self._prefixes, self._prefixes_index)
elif (self._lookuptype == 'redis'):
... | Returns lookup data of a Prefix
Args:
prefix (string): Prefix of a Amateur Radio callsign
timestamp (datetime, optional): datetime in UTC (tzinfo=pytz.UTC)
Returns:
dict: Dictionary containing the country specific data of the Prefix
Raises:
KeyError: No matching Prefix found
APIKeyMissingError: API Key for Clublog m... | codesearchnet |
def _freeze_concrete_function(self):
if len(self._funcs) == 0:
raise ValueError('No ConcreteFunction is specified.')
if len(self._funcs) > 1:
raise ValueError('This converter can only convert a single ConcreteFunction. Converting multiple functions is under development.')
frozen_func, graph_... | Convert the given ConcreteFunction to frozen graph.
Returns:
graph_def: The frozen GraphDef.
input_tensors: List of input tensors.
output_tensors: List of output tensors.
frozen_func: The frozen ConcreteFunction.
Raises:
ValueError: none or multiple ConcreteFunctions provided. | github-repos |
def get_changelog(repo_path, from_commit=None):
repo = dulwich.repo.Repo(repo_path)
tags = get_tags(repo)
refs = get_refs(repo)
changelog = []
maj_version = 0
feat_version = 0
fix_version = 0
start_including = False
cur_line = ''
if from_commit is None:
start_includ... | Given a repo path and an option commit/tag/refspec to start from, will
get the rpm compatible changelog
Args:
repo_path (str): path to the git repo
from_commit (str): refspec (partial commit hash, tag, branch, full
refspec, partial refspec) to start the changelog from
Returns:
str: Rpm compatible changelog | juraj-google-style |
def get_by_ip_hostname(self, ip_hostname):
resources = self._client.get_all()
resources_filtered = [x for x in resources if (x['credentials']['ip_hostname'] == ip_hostname)]
if resources_filtered:
return resources_filtered[0]
else:
return None | Retrieve a storage system by its IP.
Works only with API version <= 300.
Args:
ip_hostname: Storage system IP or hostname.
Returns:
dict | codesearchnet |
def map_defun(fn, elems, output_dtypes, output_shapes, max_intra_op_parallelism=1):
if not isinstance(elems, list):
raise ValueError(f'`elems` must be a list of tensors, but was {elems}.')
if not isinstance(output_dtypes, list):
raise ValueError(f'`output_dtypes` must be a list of `tf.DType` obj... | Map a function on the list of tensors unpacked from `elems` on dimension 0.
Args:
fn: A function (`function.defun`) that takes a list of tensors and returns
another list of tensors. The output list has the same types as
output_dtypes. The elements of the output list have the same dimension 0
as `elems`, and the remain... | github-repos |
def element_wise_op(array, other, op, ty):
weld_obj = WeldObject(encoder_, decoder_)
array_var = weld_obj.update(array)
if isinstance(array, WeldObject):
array_var = array.obj_id
weld_obj.dependencies[array_var] = array
other_var = weld_obj.update(other)
if isinstance(other, W... | Operation of series and other, element-wise (binary operator add)
Args:
array (WeldObject / Numpy.ndarray): Input array
other (WeldObject / Numpy.ndarray): Second Input array
op (str): Op string used to compute element-wise operation (+ / *)
ty (WeldType): Type of each element in the input array
Returns:
A WeldObject... | juraj-google-style |
def get_variation_from_id(self, experiment_key, variation_id):
variation_map = self.variation_id_map.get(experiment_key)
if variation_map:
variation = variation_map.get(variation_id)
if variation:
return variation
else:
self.logger.error('Variation ID "%s" is not in data... | Get variation given experiment and variation ID.
Args:
experiment: Key representing parent experiment of variation.
variation_id: ID representing the variation.
Returns
Object representing the variation. | juraj-google-style |
def __init__(self, max_str_len: int=100):
self.training_bar = None
self.prediction_bar = None
self.max_str_len = max_str_len | Initialize the callback with optional max_str_len parameter to control string truncation length.
Args:
max_str_len (`int`):
Maximum length of strings to display in logs.
Longer strings will be truncated with a message. | github-repos |
def pop_chunk(self, chunk_max_size):
if self._total_length < chunk_max_size:
res = self._tobytes()
self.clear()
return res
first_iteration = True
while True:
try:
data = self._deque.popleft()
da... | Pops a chunk of the given max size.
Optimized to avoid too much string copies.
Args:
chunk_max_size (int): max size of the returned chunk.
Returns:
string (bytes) with a size <= chunk_max_size. | juraj-google-style |
def listNodes(self, vendorSpecific=None):
response = self.listNodesResponse(vendorSpecific)
return self._read_dataone_type_response(response, 'NodeList') | See Also: listNodesResponse()
Args:
vendorSpecific:
Returns: | juraj-google-style |
def any_to_datetime(self, time_input, tz=None):
dt_value = self.unix_time_to_datetime(time_input, tz)
if (dt_value is None):
dt_value = self.date_to_datetime(time_input, tz)
if (dt_value is None):
dt_value = self.human_date_to_datetime(time_input, tz)
if (dt_value is None):
raise... | Return datetime object from multiple formats.
Formats:
#. Human Input (e.g 30 days ago, last friday)
#. ISO 8601 (e.g. 2017-11-08T16:52:42Z)
#. Loose Date format (e.g. 2017 12 25)
#. Unix Time/Posix Time/Epoch Time (e.g. 1510686617 or 1510686617.298753)
Args:
time_input (string): The time input string (see formats a... | codesearchnet |
def register_for_auto_class(cls, auto_class='TFAutoModel'):
if not isinstance(auto_class, str):
auto_class = auto_class.__name__
import transformers.models.auto as auto_module
if not hasattr(auto_module, auto_class):
raise ValueError(f'{auto_class} is not a valid auto class.')
cls._auto_... | Register this class with a given auto class. This should only be used for custom models as the ones in the
library are already mapped with an auto class.
Args:
auto_class (`str` or `type`, *optional*, defaults to `"TFAutoModel"`):
The auto class to register this new model with. | github-repos |
def remove_redistribution(self, protocol):
protocols = ['bgp', 'rip', 'static', 'connected']
if (protocol not in protocols):
raise ValueError('redistributed protocol must bebgp, connected, rip or static')
cmd = 'no redistribute {}'.format(protocol)
return self.configure_ospf(cmd) | Removes a protocol redistribution to OSPF
Args:
protocol (str): protocol to redistribute
route_map_name (str): route-map to be used to
filter the protocols
Returns:
bool: True if the command completes successfully
Exception:
ValueError: This will be raised if the protocol pass is not one
of the following: [rip, bgp,... | codesearchnet |
def _get_degree(num_nodes):
d_float = 0.5 * (np.sqrt(8.0 * num_nodes + 1.0) - 3.0)
d_int = int(np.round(d_float))
if (d_int + 1) * (d_int + 2) == 2 * num_nodes:
return d_int
else:
raise ValueError(num_nodes, "not a triangular n... | Get the degree of the current surface.
Args:
num_nodes (int): The number of control points for a
B |eacute| zier surface.
Returns:
int: The degree :math:`d` such that :math:`(d + 1)(d + 2)/2`
equals ``num_nodes``.
Raises:
ValueError: If ``num_nodes`` isn't a triangular number. | juraj-google-style |
class MimiDecoderOutput(ModelOutput):
audio_values: Optional[torch.FloatTensor] = None
decoder_past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None | Args:
audio_values (`torch.FloatTensor` of shape `(batch_size, segment_length)`, *optional*):
Decoded audio values, obtained using the decoder part of Mimi.
decoder_past_key_values (`Cache`, *optional*):
Pre-computed hidden-states (key and values in the self-attention blocks) that can be used to speed up sequential de... | github-repos |
def kill_mprocess(process):
if process and proc_alive(process):
process.terminate()
process.communicate()
return not proc_alive(process) | kill process
Args:
process - Popen object for process | juraj-google-style |
def getargspec(obj):
if isinstance(obj, functools.partial):
return _get_argspec_for_partial(obj)
decorators, target = tf_decorator.unwrap(obj)
spec = next((d.decorator_argspec for d in decorators if d.decorator_argspec is not None), None)
if spec:
return spec
try:
return _get... | TFDecorator-aware replacement for `inspect.getargspec`.
Note: `getfullargspec` is recommended as the python 2/3 compatible
replacement for this function.
Args:
obj: A function, partial function, or callable object, possibly decorated.
Returns:
The `ArgSpec` that describes the signature of the outermost decorator tha... | github-repos |
def wait_until_final(self, poll_interval=1, timeout=60):
start_time = time.time()
elapsed = 0
while (self.status != "complete" and
(timeout <= 0 or elapsed < timeout)):
time.sleep(poll_interval)
self.refresh()
elapsed = time.time() - s... | It will poll the URL to grab the latest status resource in a given
timeout and time interval.
Args:
poll_interval (int): how often to poll the status service.
timeout (int): how long to poll the URL until giving up. Use <= 0
to wait forever | juraj-google-style |
def save_graph_def(file_name, frozen_graph_def):
tf.io.write_graph(frozen_graph_def, os.path.dirname(file_name), os.path.basename(file_name), as_text=False)
tf.compat.v1.logging.info('Saved frozen graph to %s', file_name) | Writes a graph def file out to disk.
Args:
file_name: Where to save the file.
frozen_graph_def: GraphDef proto object to save. | github-repos |
def ws_db004(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 `ws_db004`'.format(value))
self._ws_db004 = value | Corresponds to IDD Field `ws_db004`
Mean wind speed coincident with 0.4% dry-bulb temperature
Args:
value (float): value for IDD Field `ws_db004`
Unit: m/s
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 pretty_dump(fn):
@wraps(fn)
def pretty_dump_wrapper(*args, **kwargs):
response.content_type = 'application/json; charset=utf-8'
return json.dumps(fn(*args, **kwargs), indent=4, separators=(',', ': '))
return pretty_dump_wrapper | Decorator used to output prettified JSON.
``response.content_type`` is set to ``application/json; charset=utf-8``.
Args:
fn (fn pointer): Function returning any basic python data structure.
Returns:
str: Data converted to prettified JSON. | codesearchnet |
def __init__(self, key_type=None, value_type=None, min_length=None, max_length=None, empty=True):
super(DictTypeChecker, self).__init__(base_type=dict)
self.key_type = key_type
self.value_type = value_type
self.min_length = min_length
self.max_length = max_length
... | Initialization method.
Args:
key_type (type): the type of the dict keys.
value_type (type): the type of the dict values.
min_length (int): minimum length of the dict (included).
max_length (int): maximum length of the dict (included).
empty (bool): whether empty dict is allowed. | juraj-google-style |
def _get_argspec_for_partial(obj):
n_prune_args = len(obj.args)
partial_keywords = obj.keywords or {}
args, varargs, keywords, defaults = getargspec(obj.func)
args = args[n_prune_args:]
no_default = object()
all_defaults = [no_default] * len(args)
if defaults:
all_defaults[-len(defau... | Implements `getargspec` for `functools.partial` objects.
Args:
obj: The `functools.partial` object
Returns:
An `inspect.ArgSpec`
Raises:
ValueError: When callable's signature can not be expressed with
ArgSpec. | github-repos |
def set_custom_getter_compose(custom_getter):
tf.get_variable_scope().set_custom_getter(_compose_custom_getters(tf.get_variable_scope().custom_getter, custom_getter)) | Set a custom getter in the current variable scope.
Do not overwrite the existing custom getter - rather compose with it.
Args:
custom_getter: a custom getter. | codesearchnet |
def __init__(self, resolver_context, encoding='utf-8'):
super(ZipFileSystem, self).__init__(resolver_context)
self._file_object = None
self._zip_file = None
self.encoding = encoding | Initializes a file system.
Args:
resolver_context (Context): a resolver context.
encoding (Optional[str]): encoding of the file entry name. | juraj-google-style |
def _publish_to_subscribers(event: Event):
subscribers = get_subscribers(event.object_type)
for sub in subscribers:
DB.prepend_to_list(_keys.published(event.object_type, sub), event.id, pipeline=True)
event_dict = deepcopy(event.config)
event_dict.pop('id')
DB.set_hash_value(_key... | Publish and event to all subscribers.
- Adds the event id to the published event list for all subscribers.
- Adds the event data to the published event data for all subscribers.
- Publishes the event id notification to all subscribers.
Args:
event (Event): Event object to publish. | codesearchnet |
def resolve_import(name, is_from, is_star):
if (name.startswith('.') or is_builtin(name)):
return None
ret = _resolve_import(name)
if ((ret is None) and is_from and (not is_star)):
(package, _) = name.rsplit('.', 1)
ret = _resolve_import(package)
return ret | Use python to resolve an import.
Args:
name: The fully qualified module name.
Returns:
The path to the module source file or None. | codesearchnet |
def send_message(msg: 'EFBMsg') -> Optional['EFBMsg']:
global middlewares, master, slaves
if msg is None:
return
for i in middlewares:
m = i.process_message(msg)
if m is None:
return None
assert m is not None
msg = m
msg.verify()
... | Deliver a message to the destination channel.
Args:
msg (EFBMsg): The message
Returns:
The message sent by the destination channel,
includes the updated message ID from there.
Returns ``None`` if the message is not sent. | juraj-google-style |
def enable_sns_notification(self, region, trailName):
ct = self.session.client('cloudtrail', region_name=region)
ct.update_trail(Name=trailName, SnsTopicName=self.topic_name)
auditlog(event='cloudtrail.enable_sns_notification', actor=self.ns, data={'account': self.account.account_name, 'region': region})
... | Enable SNS notifications for a Trail
Args:
region (`str`): Name of the AWS region
trailName (`str`): Name of the CloudTrail Trail
Returns:
`None` | codesearchnet |
def grepPDF(self, path):
with open(path, 'rb') as pdf_file_obj:
match = set()
text = ''
pdf_reader = PyPDF2.PdfFileReader(pdf_file_obj)
pages = pdf_reader.numPages
for page in range(pages):
page_obj = pdf_reader.getPage(page)
text += ('\n' + page_obj.e... | Parse PDF files text content for keywords.
Args:
path: PDF file path.
Returns:
match: set of unique occurrences of every match. | codesearchnet |
def convert_builtin_to_typing(typ):
if getattr(typ, '__origin__', None) in _BUILTINS_TO_TYPING:
args = map(convert_builtin_to_typing, typ.__args__)
typ = _BUILTINS_TO_TYPING[typ.__origin__].copy_with(tuple(args))
return typ | Convert recursively a given builtin to a typing object.
Args:
typ (`builtins`): builtin object that exist in _BUILTINS_TO_TYPING.
Returns:
type: The given builtins converted to a type. | github-repos |
def __init__(self, validator_map):
self.validators = dict(validator_map)
v_sorted = sorted(self.validators.items(), key=lambda t: t[0])
self.validator_descriptions = ['{}:<{}>'.format(k, v) for k, v in v_sorted]
self.name = 'dict({})'.format(', '.join(self.validator_descriptions... | Create a dictonary type from a dictionary of other types
Args:
validator_map -- a mapping from names to types
Examples:
>>> Dict({'a': int, 'b': int})('a:1,b:2')
{'a': 1, 'b': 2}
>>> Dict({'a': str, 'b': int})('a:asdf b=1234')
{'a': 'asdf', 'b': 1234}
>>> Dict({'a': Int() | Keyword('', None), 'b': Int()})('a,b=1')
{'... | juraj-google-style |
def __call__(self, class_logits, box_regression):
class_logits = cat(class_logits, dim=0)
box_regression = cat(box_regression, dim=0)
device = class_logits.device
if not hasattr(self, "_proposals"):
raise RuntimeError("subsample needs to be called before")
... | Computes the loss for Faster R-CNN.
This requires that the subsample method has been called beforehand.
Arguments:
class_logits (list[Tensor])
box_regression (list[Tensor])
Returns:
classification_loss (Tensor)
box_loss (Tensor) | juraj-google-style |
async def request(context, url, timeout=60, method='get', good=(200,), retry=tuple(range(500, 512)), return_type='text', **kwargs):
session = context.session
loggable_url = get_loggable_url(url)
async with async_timeout.timeout(timeout):
log.debug('{} {}'.format(method.upper(), loggable_url))
... | Async aiohttp request wrapper.
Args:
context (scriptworker.context.Context): the scriptworker context.
url (str): the url to request
timeout (int, optional): timeout after this many seconds. Default is 60.
method (str, optional): The request method to use. Default is 'get'.
good (list, optional): the set of good stat... | codesearchnet |
def CanSplit(self, must_split):
current = self.next_token
previous = current.previous_token
if current.is_pseudo:
return False
if not must_split and subtypes.DICTIONARY_KEY_PART in current.subtypes and (subtypes.DICTIONARY_KEY not in current.subtypes) and (not style.Get('ALLOW_MULTILINE_DICTIONA... | Determine if we can split before the next token.
Arguments:
must_split: (bool) A newline was required before this token.
Returns:
True if the line can be split before the next token. | github-repos |
def assignment_propagation(node):
n_reads = read_counts(node)
to_remove = []
for succ in gast.walk(node):
if (isinstance(succ, gast.Assign) and isinstance(succ.value, gast.Name) and
len(succ.targets) == 1 and isinstance(succ.targets[0], gast.Name)):
rhs_name = succ.value.id
... | Perform assignment propagation.
Assignment propagation is not a compiler optimization as much as a
readability optimization. If a variable name is used only once, it gets
renamed when possible e.g. `y = x; z = y` will become `z = x`.
Args:
node: The AST to optimize.
Returns:
The optimized AST. | juraj-google-style |
def foreach_worker(self, fn):
results = ray.get([w.foreach_worker.remote(fn) for w in self.workers])
return results | Apply the given function to each remote worker.
Returns:
List of results from applying the function. | codesearchnet |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.