code
stringlengths 20
4.93k
| docstring
stringlengths 33
1.27k
| source
stringclasses 3
values |
---|---|---|
def GetRelativePath(self, path_spec):
location = getattr(path_spec, 'location', None)
if location is None:
raise errors.PathSpecError('Path specification missing location.')
if path_spec_factory.Factory.IsSystemLevelTypeIndicator(
self._file_system.type_indicator):
if not location.startswith(self._mount_point.location):
raise errors.PathSpecError(
'Path specification does not contain mount point.')
else:
if not hasattr(path_spec, 'parent'):
raise errors.PathSpecError('Path specification missing parent.')
if path_spec.parent != self._mount_point:
raise errors.PathSpecError(
'Path specification does not contain mount point.')
path_segments = self._file_system.SplitPath(location)
if path_spec_factory.Factory.IsSystemLevelTypeIndicator(
self._file_system.type_indicator):
mount_point_path_segments = self._file_system.SplitPath(
self._mount_point.location)
path_segments = path_segments[len(mount_point_path_segments):]
return '{0:s}{1:s}'.format(
self._file_system.PATH_SEPARATOR,
self._file_system.PATH_SEPARATOR.join(path_segments))
|
Returns the relative path based on a resolved path specification.
The relative path is the location of the upper most path specification.
The the location of the mount point is stripped off if relevant.
Args:
path_spec (PathSpec): path specification.
Returns:
str: corresponding relative path or None if the relative path could not
be determined.
Raises:
PathSpecError: if the path specification is incorrect.
|
juraj-google-style
|
def inet_to_str(inet):
try:
return socket.inet_ntop(socket.AF_INET, inet)
except ValueError:
return socket.inet_ntop(socket.AF_INET6, inet)
|
Convert inet object to a string
Args:
inet (inet struct): inet network address
Returns:
str: Printable/readable IP address
|
codesearchnet
|
def destroy_iam(app='', env='dev', **_):
session = boto3.Session(profile_name=env)
client = session.client('iam')
generated = get_details(env=env, app=app)
generated_iam = generated.iam()
app_details = collections.namedtuple('AppDetails', generated_iam.keys())
details = app_details(**generated_iam)
LOG.debug('Application details: %s', details)
resource_action(
client,
action='remove_user_from_group',
log_format='Removed user from group: %(UserName)s ~> %(GroupName)s',
GroupName=details.group,
UserName=details.user)
resource_action(client, action='delete_user', log_format='Destroyed user: %(UserName)s', UserName=details.user)
resource_action(client, action='delete_group', log_format='Destroyed group: %(GroupName)s', GroupName=details.group)
resource_action(
client,
action='remove_role_from_instance_profile',
log_format='Destroyed Instance Profile from Role: '
'%(InstanceProfileName)s ~> %(RoleName)s',
InstanceProfileName=details.profile,
RoleName=details.role)
resource_action(
client,
action='delete_instance_profile',
log_format='Destroyed Instance Profile: %(InstanceProfileName)s',
InstanceProfileName=details.profile)
role_policies = []
try:
role_policies = resource_action(
client,
action='list_role_policies',
log_format='Found Role Policies for %(RoleName)s.',
RoleName=details.role)['PolicyNames']
except TypeError:
LOG.info('Role %s not found.', details.role)
for policy in role_policies:
resource_action(
client,
action='delete_role_policy',
log_format='Removed Inline Policy from Role: '
'%(PolicyName)s ~> %(RoleName)s',
RoleName=details.role,
PolicyName=policy)
attached_role_policies = []
try:
attached_role_policies = resource_action(
client,
action='list_attached_role_policies',
log_format='Found attached Role Polices for %(RoleName)s.',
RoleName=details.role)['AttachedPolicies']
except TypeError:
LOG.info('Role %s not found.', details.role)
for policy in attached_role_policies:
resource_action(
client,
action='detach_role_policy',
log_format='Detached Policy from Role: '
'%(PolicyArn)s ~> %(RoleName)s',
RoleName=details.role,
PolicyArn=policy['PolicyArn'])
resource_action(client, action='delete_role', log_format='Destroyed Role: %(RoleName)s', RoleName=details.role)
|
Destroy IAM Resources.
Args:
app (str): Spinnaker Application name.
env (str): Deployment environment, i.e. dev, stage, prod.
Returns:
True upon successful completion.
|
juraj-google-style
|
def movie_list(self, **kwargs):
path = self._get_path('movie_list')
response = self._GET(path, kwargs)
self._set_attrs_to_values(response)
return response
|
Get the list of Movie genres.
Args:
language: (optional) ISO 639-1 code.
Returns:
A dict respresentation of the JSON returned from the API.
|
juraj-google-style
|
def get_mnemonic(self, mnemonic, alias=None):
alias = (alias or {})
aliases = alias.get(mnemonic, [mnemonic])
for a in aliases:
if (a in self.data):
return a
return None
|
Instead of picking curves by name directly from the data dict, you
can pick them up with this method, which takes account of the alias
dict you pass it. If you do not pass an alias dict, then you get the
curve you asked for, if it exists, or None. NB Wells do not have alias
dicts, but Projects do.
Args:
mnemonic (str): the name of the curve you want.
alias (dict): an alias dictionary, mapping mnemonics to lists of
mnemonics.
Returns:
Curve.
|
codesearchnet
|
def ParseFileObject(self, parser_mediator, file_object):
file_offset = 0
file_size = file_object.get_size()
record_map = self._GetDataTypeMap('pls_recall_record')
while (file_offset < file_size):
try:
(pls_record, record_data_size) = self._ReadStructureFromFileObject(file_object, file_offset, record_map)
except (ValueError, errors.ParseError) as exception:
if (file_offset == 0):
raise errors.UnableToParseFile('Unable to parse first record.')
parser_mediator.ProduceExtractionWarning('unable to parse record at offset: 0x{0:08x} with error: {1!s}'.format(file_offset, exception))
break
if ((file_offset == 0) and (not self._VerifyRecord(pls_record))):
raise errors.UnableToParseFile('Verification of first record failed.')
event_data = PlsRecallEventData()
event_data.database_name = pls_record.database_name.rstrip('\x00')
event_data.sequence_number = pls_record.sequence_number
event_data.offset = file_offset
event_data.query = pls_record.query.rstrip('\x00')
event_data.username = pls_record.username.rstrip('\x00')
date_time = dfdatetime_delphi_date_time.DelphiDateTime(timestamp=pls_record.last_written_time)
event = time_events.DateTimeValuesEvent(date_time, definitions.TIME_DESCRIPTION_WRITTEN)
parser_mediator.ProduceEventWithEventData(event, event_data)
file_offset += record_data_size
|
Parses a PLSRecall.dat file-like object.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
file_object (dfvfs.FileIO): a file-like object.
Raises:
UnableToParseFile: when the file cannot be parsed.
|
codesearchnet
|
def loss(logits, labels, batch_size=None):
if not batch_size:
batch_size = FLAGS.batch_size
sparse_labels = tf.reshape(labels, [batch_size, 1])
indices = tf.reshape(tf.range(batch_size), [batch_size, 1])
concated = tf.concat(axis=1, values=[indices, sparse_labels])
num_classes = logits[0].get_shape()[-1].value
dense_labels = tf.sparse_to_dense(concated,
[batch_size, num_classes],
1.0, 0.0)
slim.losses.cross_entropy_loss(logits[0],
dense_labels,
label_smoothing=0.1,
weight=1.0)
slim.losses.cross_entropy_loss(logits[1],
dense_labels,
label_smoothing=0.1,
weight=0.4,
scope='aux_loss')
|
Adds all losses for the model.
Note the final loss is not returned. Instead, the list of losses are collected
by slim.losses. The losses are accumulated in tower_loss() and summed to
calculate the total loss.
Args:
logits: List of logits from inference(). Each entry is a 2-D float Tensor.
labels: Labels from distorted_inputs or inputs(). 1-D tensor
of shape [batch_size]
batch_size: integer
|
juraj-google-style
|
def _maintain_LC(self, obj, slice_id, last_slice=False, begin_slice=True,
shard_ctx=None, slice_ctx=None):
if obj is None or not isinstance(obj, shard_life_cycle._ShardLifeCycle):
return
shard_context = shard_ctx or self.shard_context
slice_context = slice_ctx or self.slice_context
if begin_slice:
if slice_id == 0:
obj.begin_shard(shard_context)
obj.begin_slice(slice_context)
else:
obj.end_slice(slice_context)
if last_slice:
obj.end_shard(shard_context)
|
Makes sure shard life cycle interface are respected.
Args:
obj: the obj that may have implemented _ShardLifeCycle.
slice_id: current slice_id
last_slice: whether this is the last slice.
begin_slice: whether this is the beginning or the end of a slice.
shard_ctx: shard ctx for dependency injection. If None, it will be read
from self.
slice_ctx: slice ctx for dependency injection. If None, it will be read
from self.
|
juraj-google-style
|
def update(self, **kwargs):
for arg in kwargs:
if hasattr(self, arg):
setattr(self, arg, kwargs[arg])
else:
raise ValueError(('Invalid RayParams parameter in update: %s' % arg))
self._check_usage()
|
Update the settings according to the keyword arguments.
Args:
kwargs: The keyword arguments to set corresponding fields.
|
codesearchnet
|
def assert_like_rnncell(cell_name, cell):
conditions = [_hasattr(cell, 'output_size'), _hasattr(cell, 'state_size'), _hasattr(cell, 'get_initial_state') or _hasattr(cell, 'zero_state'), callable(cell)]
errors = ["'output_size' property is missing", "'state_size' property is missing", "either 'zero_state' or 'get_initial_state' method is required", 'is not callable']
if not all(conditions):
errors = [error for error, cond in zip(errors, conditions) if not cond]
raise TypeError('The argument {!r} ({}) is not an RNNCell: {}.'.format(cell_name, cell, ', '.join(errors)))
|
Raises a TypeError if cell is not like an RNNCell.
NOTE: Do not rely on the error message (in particular in tests) which can be
subject to change to increase readability. Use
ASSERT_LIKE_RNNCELL_ERROR_REGEXP.
Args:
cell_name: A string to give a meaningful error referencing to the name of
the functionargument.
cell: The object which should behave like an RNNCell.
Raises:
TypeError: A human-friendly exception.
|
github-repos
|
def step(self, actions):
for index, (env, action) in enumerate(zip(self._envs, actions)):
if not env.action_space.contains(action):
message = 'Invalid action at index {}: {}'
raise ValueError(message.format(index, action))
if self._blocking:
transitions = [
env.step(action)
for env, action in zip(self._envs, actions)]
else:
transitions = [
env.step(action, blocking=False)
for env, action in zip(self._envs, actions)]
transitions = [transition() for transition in transitions]
observs, rewards, dones, infos = zip(*transitions)
observ = np.stack(observs)
reward = np.stack(rewards)
done = np.stack(dones)
info = tuple(infos)
return observ, reward, done, info
|
Forward a batch of actions to the wrapped environments.
Args:
actions: Batched action to apply to the environment.
Raises:
ValueError: Invalid actions.
Returns:
Batch of observations, rewards, and done flags.
|
juraj-google-style
|
def to_image(self, filename='palette.png', band_width=1, length=60, max_width=0, vertical=True, alpha_channel=False):
if (max_width < 1):
pass
else:
band_width = int((max_width / len(self._colours)))
image_width = (band_width * len(self._colours))
if alpha_channel:
my_image = Image.new('RGBA', (image_width, length))
else:
my_image = Image.new('RGB', (image_width, length))
image_loaded = my_image.load()
x = 0
for my_colour in self._colours:
for x1 in range(band_width):
for y in range(length):
image_loaded[(x, y)] = my_colour.rgb()
x = (x + 1)
if vertical:
my_image = my_image.rotate(270)
my_image.save(filename)
|
Creates an image from the palette.
Args:
filename(Optional[string]): filename of saved file. Defaults to
``palette.png`` in the current working directory.
band_width(optional[int]): how wide each colour band should be.
Defaults to 1 pixel.
length(Optional[int]): the length of the overall image in pixels.
This is the dimension orthogonal to ``band_width``. Defaults
to 60 pixels.
max_width(Optional[int]): if ``band_width`` is not set and this is,
this determines how wide the whole image should be.
vertical(Optional[bool]): if the image runs vertical (``True``,
default) or horizontal (``False``).
alpha_channel(Optional[bool]): if ``True``, the created image will
have an Alpha channel. Defaults to ``False``.
|
codesearchnet
|
def export_panels(adapter, panels, versions=None, build='37'):
if versions and (len(versions) != len(panels)):
raise SyntaxError("If version specify for each panel")
headers = []
build_string = ("
headers.append(build_string.format(build))
header_string = ("
contig_string = ("
bed_string = ("{0}\t{1}\t{2}\t{3}\t{4}")
panel_geneids = set()
chromosomes_found = set()
hgnc_geneobjs = []
for i,panel_id in enumerate(panels):
version = None
if versions:
version = versions[i]
panel_obj = adapter.gene_panel(panel_id, version=version)
if not panel_obj:
LOG.warning("Panel {0} version {1} could not be found".format(panel_id, version))
continue
headers.append(header_string.format(
panel_obj['panel_name'],
panel_obj['version'],
panel_obj['date'].date(),
panel_obj['display_name'],
))
for gene_obj in panel_obj['genes']:
panel_geneids.add(gene_obj['hgnc_id'])
gene_objs = adapter.hgncid_to_gene(build=build)
for hgnc_id in panel_geneids:
hgnc_geneobj = gene_objs.get(hgnc_id)
if hgnc_geneobj is None:
LOG.warn("missing HGNC gene: %s", hgnc_id)
continue
chrom = hgnc_geneobj['chromosome']
start = hgnc_geneobj['start']
chrom_int = CHROMOSOME_INTEGERS.get(chrom)
if not chrom_int:
LOG.warn("Chromosome %s out of scope", chrom)
continue
hgnc_geneobjs.append((chrom_int, start, hgnc_geneobj))
chromosomes_found.add(chrom)
hgnc_geneobjs.sort(key=lambda tup: (tup[0], tup[1]))
for chrom in CHROMOSOMES:
if chrom in chromosomes_found:
headers.append(contig_string.format(chrom))
headers.append("
for header in headers:
yield header
for hgnc_gene in hgnc_geneobjs:
gene_obj = hgnc_gene[-1]
gene_line = bed_string.format(gene_obj['chromosome'], gene_obj['start'],
gene_obj['end'], gene_obj['hgnc_id'],
gene_obj['hgnc_symbol'])
yield gene_line
|
Export all genes in gene panels
Exports the union of genes in one or several gene panels to a bed like format with coordinates.
Args:
adapter(scout.adapter.MongoAdapter)
panels(iterable(str)): Iterable with panel ids
bed(bool): If lines should be bed formated
|
juraj-google-style
|
def running(processid):
try:
os.kill(processid, 0)
except OverflowError as exc:
print('checking validity of pid ({p}) failed with: {e}'.format(p=processid, e=exc))
sys.exit(1)
except OSError:
return False
else:
return True
|
Check the validity of a process ID.
Arguments:
processid (int): Process ID number.
Returns:
True if process ID is found otherwise False.
|
codesearchnet
|
def make_repr(self, attrs):
if (config.REPR_VERBOSITY in [MEDIUM, HIGH]):
return self.__str__()
elif (config.REPR_VERBOSITY is LOW):
return '{}({})'.format(self.__class__.__name__, ', '.join((((attr + '=') + repr(getattr(self, attr))) for attr in attrs)))
raise ValueError('Invalid value for `config.REPR_VERBOSITY`')
|
Construct a repr string.
If `config.REPR_VERBOSITY` is ``1`` or ``2``, this function calls the
object's __str__ method. Although this breaks the convention that __repr__
should return a string which can reconstruct the object, readable reprs are
invaluable since the Python interpreter calls `repr` to represent all
objects in the shell. Since PyPhi is often used in the interpreter we want
to have meaningful and useful representations.
Args:
self (obj): The object in question
attrs (Iterable[str]): Attributes to include in the repr
Returns:
str: the ``repr``esentation of the object
|
codesearchnet
|
def override_default_args(**kwargs):
override_default_kwargs = kwargs
def custom_getter(getter, *args, **kwargs):
updated_kwargs = override_default_kwargs.copy()
updated_kwargs.update({kw: value for kw, value in six.iteritems(kwargs)
if value is not None})
return getter(*args, **updated_kwargs)
return custom_getter
|
Creates a custom getter that applies specified named arguments.
The returned custom getter treats the specified named arguments as revised
defaults, and does not override any non-`None` argument values supplied by
the original get_variable call (or by a nested scope's custom getter).
Args:
**kwargs: Overriding arguments for the custom getter to use in preference
the named arguments it's called with.
Returns:
Custom getter.
|
juraj-google-style
|
def render(raw_config, environment=None):
t = Template(raw_config)
buff = StringIO()
if not environment:
environment = {}
try:
substituted = t.substitute(environment)
except KeyError as e:
raise exceptions.MissingEnvironment(e.args[0])
except ValueError:
substituted = t.safe_substitute(environment)
if not isinstance(substituted, str):
substituted = substituted.decode('utf-8')
buff.write(substituted)
buff.seek(0)
return buff.read()
|
Renders a config, using it as a template with the environment.
Args:
raw_config (str): the raw stacker configuration string.
environment (dict, optional): any environment values that should be
passed to the config
Returns:
str: the stacker configuration populated with any values passed from
the environment
|
juraj-google-style
|
def update_hparams_for_universal_transformer(hparams):
hparams.daisy_chain_variables = False
hparams.add_hparam('mix_with_transformer', None)
hparams.add_hparam('num_mixedin_layers', 2)
hparams.add_hparam('num_inrecurrence_layers', 1)
hparams.add_hparam('recurrence_type', 'basic')
hparams.add_hparam('num_rec_steps', hparams.num_hidden_layers)
hparams.add_hparam('add_position_timing_signal', True)
if hparams.add_position_timing_signal:
hparams.pos = None
hparams.add_hparam('position_start_index', None)
hparams.add_hparam('add_step_timing_signal', True)
hparams.add_hparam('step_timing_signal_type', 'learned')
hparams.add_hparam('add_or_concat_timing_signal', 'add')
hparams.add_hparam('add_sru', False)
hparams.add_hparam('transformer_ffn_type', 'fc')
hparams.add_hparam('transform_bias_init', (- 1.0))
hparams.add_hparam('couple_carry_transform_gates', True)
hparams.add_hparam('depth_embedding', True)
hparams.add_hparam('dwa_elements', True)
hparams.add_hparam('gate_ffn_layer', 'dense')
hparams.add_hparam('lstm_forget_bias', 1.0)
hparams.add_hparam('use_memory_as_final_state', False)
hparams.add_hparam('add_ffn_unit_to_the_transition_function', False)
hparams.add_hparam('act_type', 'basic')
hparams.add_hparam('act_max_steps', (2 * hparams.num_hidden_layers))
hparams.add_hparam('act_halting_bias_init', 1.0)
hparams.add_hparam('act_epsilon', 0.01)
hparams.add_hparam('act_loss_weight', 0.01)
return hparams
|
Adds default hparams for all of the variants of the Universal Transformer.
Args:
hparams: default hparams (usually one of the standard hparams from
transformer model (like "transformer_base")
Returns:
hparams with default values for Universal Transformers hyper-parameters
|
codesearchnet
|
def InitUser():
result = AppUser.query((AppUser.user == users.get_current_user())).fetch()
if result:
app_user = result[0]
else:
app_user = AppUser(user=users.get_current_user(), email=users.get_current_user().email())
app_user.put()
return app_user
|
Initialize application user.
Retrieve existing user credentials from datastore or add new user.
Returns:
AppUser instance of the application user.
|
codesearchnet
|
def _get_rand_attn_plan(from_seq_length, from_block_size, num_rand_blocks):
plan_from_length = []
plan_num_rand_blocks = []
if 2 * num_rand_blocks + 5 < from_seq_length
plan_from_length.append(int((2 * num_rand_blocks + 5) * from_block_size))
plan_num_rand_blocks.append(num_rand_blocks)
plan_from_length.append(from_seq_length)
plan_num_rand_blocks.append(0)
elif num_rand_blocks + 5 < from_seq_length
plan_from_length.append(int((num_rand_blocks + 5) * from_block_size))
plan_num_rand_blocks.append(num_rand_blocks
plan_from_length.append(from_seq_length)
plan_num_rand_blocks.append(num_rand_blocks - num_rand_blocks
else:
plan_from_length.append(from_seq_length)
plan_num_rand_blocks.append(num_rand_blocks)
return (plan_from_length, plan_num_rand_blocks)
|
Gives the plan of where to put random attention.
Args:
from_seq_length: int. length of from sequence.
from_block_size: int. size of block in from sequence.
num_rand_blocks: int. Number of random chunks per row.
Returns:
plan_from_length: ending location of from block plan_num_rand_blocks: number of random ending location for
each block
|
github-repos
|
def json_set_description(recipe, variables):
if 'script' in recipe:
if 'description' in recipe['script']:
try:
recipe['script']['description'] = text_set_fields(recipe['script']['description'], variables)
except KeyError:
pass
|
Replaces all fields in description with values provided.
Checks if recipe['script']['description'] exist. The replaces all %(???)s
variables
with values provided. Note: %(???)s must match { "field":{ "name":"???" }}
in JOSN.
Args:
recipe: (dict) A dictionary representation of the JSON script.
variables: (dict) A lookup table of all values to be replaced, key is name
of field.
Returns:
Nothig. Description is modified in place.
|
github-repos
|
def _resize_for_patching(self, image: np.array, target_resolution: tuple, resample, input_data_format: ChannelDimension) -> np.array:
new_height, new_width = get_patch_output_size(image, target_resolution, input_data_format)
resized_image = resize(image, (new_height, new_width), resample=resample, input_data_format=input_data_format)
return resized_image
|
Resizes an image to a target resolution while maintaining aspect ratio.
Args:
image (np.array):
The input image.
target_resolution (tuple):
The target resolution (height, width) of the image.
resample (`PILImageResampling`):
Resampling filter to use if resizing the image.
input_data_format (`ChannelDimension` or `str`):
The channel dimension format of the input image.
Returns:
np.array: The resized and padded image.
|
github-repos
|
def __init__(self, bits: List[int], order: int, initializer: tf.keras.initializers.Initializer=tf.keras.initializers.RandomUniform(), name: Union[None, str]=None):
parity_layer = energy_utils.Parity(bits, order)
self._num_terms = parity_layer.num_terms
self._indices = parity_layer.indices
pre_process = [energy_utils.SpinsFromBitstrings(), parity_layer]
post_process = [energy_utils.VariableDot(initializer=initializer)]
super().__init__(bits, pre_process + post_process, name)
self._post_process = post_process
|
Initializes a KOBE.
Args:
bits: Each entry is an index on which the distribution is supported.
order: The order of the KOBE.
initializer: Specifies how to initialize the values of the parameters.
name: Optional name for the model.
|
github-repos
|
def holiday_name(self, value=None):
if value is not None:
try:
value = str(value)
except ValueError:
raise ValueError('value {} need to be of type str '
'for field `holiday_name`'.format(value))
if ',' in value:
raise ValueError('value should not contain a comma '
'for field `holiday_name`')
self._holiday_name = value
|
Corresponds to IDD Field `holiday_name`
Args:
value (str): value for IDD Field `holiday_name`
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 _minimum_one_is_missing(self, **kwargs):
rqset = self._meta_data['minimum_additional_parameters']
if rqset:
kwarg_set = set(iterkeys(kwargs))
if kwarg_set.isdisjoint(rqset):
args = sorted(rqset)
error_message = ('This resource requires at least one of the mandatory additional parameters to be provided: %s' % ', '.join(args))
raise MissingRequiredCreationParameter(error_message)
|
Helper function to do operation on sets
Verify if at least one of the elements
is present in **kwargs. If no items of rqset
are contained in **kwargs the function
raises exception.
This check will only trigger if rqset is not empty.
Raises:
MissingRequiredCreationParameter
|
codesearchnet
|
def _define_loop(graph, logdir, train_steps, eval_steps):
loop = tools.Loop(logdir, graph.step, graph.should_log, graph.do_report, graph.force_reset)
loop.add_phase('train', graph.done, graph.score, graph.summary, train_steps, report_every=train_steps, log_every=(train_steps
loop.add_phase('eval', graph.done, graph.score, graph.summary, eval_steps, report_every=eval_steps, log_every=(eval_steps
return loop
|
Create and configure a training loop with training and evaluation phases.
Args:
graph: Object providing graph elements via attributes.
logdir: Log directory for storing checkpoints and summaries.
train_steps: Number of training steps per epoch.
eval_steps: Number of evaluation steps per epoch.
Returns:
Loop object.
|
codesearchnet
|
def set_x_grid_info(self, x_low, x_high, num_x, xscale, xval_name):
self._set_grid_info('x', x_low, x_high, num_x, xscale, xval_name)
return
|
Set the grid values for x.
Create information for the grid of x values.
Args:
num_x (int): Number of points on axis.
x_low/x_high (float): Lowest/highest value for the axis.
xscale (str): Scale of the axis. Choices are 'log' or 'lin'.
xval_name (str): Name representing the axis. See GenerateContainer documentation
for options for the name.
|
juraj-google-style
|
def get_word_index(path='reuters_word_index.json'):
origin_folder = 'https:
path = get_file(path, origin=origin_folder + 'reuters_word_index.json', file_hash='4d44cc38712099c9e383dc6e5f11a921')
with open(path) as f:
return json.load(f)
|
Retrieves a dict mapping words to their index in the Reuters dataset.
Actual word indices starts from 3, with 3 indices reserved for:
0 (padding), 1 (start), 2 (oov).
E.g. word index of 'the' is 1, but the in the actual training data, the
index of 'the' will be 1 + 3 = 4. Vice versa, to translate word indices in
training data back to words using this mapping, indices need to subtract 3.
Args:
path: where to cache the data (relative to `~/.keras/dataset`).
Returns:
The word index dictionary. Keys are word strings, values are their
index.
|
github-repos
|
def _set_request_cache_if_django_cache_hit(key, django_cached_response):
if django_cached_response.is_found:
DEFAULT_REQUEST_CACHE.set(key, django_cached_response.value)
|
Sets the value in the request cache if the django cached response was a hit.
Args:
key (string)
django_cached_response (CachedResponse)
|
codesearchnet
|
def GetConsoleAttr(encoding=None, reset=False):
attr = ConsoleAttr._CONSOLE_ATTR_STATE
if not reset:
if not attr:
reset = True
elif encoding and encoding != attr.GetEncoding():
reset = True
if reset:
attr = ConsoleAttr(encoding=encoding)
ConsoleAttr._CONSOLE_ATTR_STATE = attr
return attr
|
Gets the console attribute state.
If this is the first call or reset is True or encoding is not None and does
not match the current encoding or out is not None and does not match the
current out then the state is (re)initialized. Otherwise the current state
is returned.
This call associates the out file stream with the console. All console related
output should go to the same stream.
Args:
encoding: Encoding override.
ascii -- ASCII. This is the default.
utf8 -- UTF-8 unicode.
win -- Windows code page 437.
reset: Force re-initialization if True.
Returns:
The global ConsoleAttr state object.
|
github-repos
|
class Sliceable:
def __init__(self, array):
self.array = array
def __getitem__(self, indices):
return self.array[indices]
@classmethod
def cast(cls, x, dtype):
return x.astype(dtype)
@classmethod
def convert_to_numpy(cls, x):
return x
@classmethod
def convert_to_tf_dataset_compatible(cls, x):
return x
@classmethod
def convert_to_jax_compatible(cls, x):
return x
@classmethod
def convert_to_torch_compatible(cls, x):
return x
|
`Sliceable` wrapping a tensor.
A `Sliceable` implements the subscript operator to slice or index against
the first dimension of the array. It also has conversion methods for each
one of the backends.
Args:
array: the native array or tensor to wrap.
Attributes:
shape: the shape of the full dense native array.
|
github-repos
|
def destroy_cloudwatch_event(app='', env='dev', region=''):
session = boto3.Session(profile_name=env, region_name=region)
cloudwatch_client = session.client('events')
event_rules = get_cloudwatch_event_rule(app_name=app, account=env, region=region)
for rule in event_rules:
cloudwatch_client.remove_targets(Rule=rule, Ids=[app])
return True
|
Destroy Cloudwatch event subscription.
Args:
app (str): Spinnaker Application name.
env (str): Deployment environment.
region (str): AWS region.
Returns:
bool: True upon successful completion.
|
juraj-google-style
|
def print_tensors_in_checkpoint_file(file_name, tensor_name, all_tensors, all_tensor_names=False, count_exclude_pattern=''):
try:
reader = py_checkpoint_reader.NewCheckpointReader(file_name)
if all_tensors or all_tensor_names:
var_to_shape_map = reader.get_variable_to_shape_map()
var_to_dtype_map = reader.get_variable_to_dtype_map()
for key, value in sorted(var_to_shape_map.items()):
print('tensor: %s (%s) %s' % (key, var_to_dtype_map[key].name, value))
if all_tensors:
try:
print(reader.get_tensor(key))
except errors_impl.InternalError:
print('<not convertible to a numpy dtype>')
elif not tensor_name:
print(reader.debug_string().decode('utf-8', errors='ignore'))
else:
if not reader.has_tensor(tensor_name):
print('Tensor %s not found in checkpoint' % tensor_name)
return
var_to_shape_map = reader.get_variable_to_shape_map()
var_to_dtype_map = reader.get_variable_to_dtype_map()
print('tensor: %s (%s) %s' % (tensor_name, var_to_dtype_map[tensor_name].name, var_to_shape_map[tensor_name]))
print(reader.get_tensor(tensor_name))
print('
except Exception as e:
print(str(e))
if 'corrupted compressed block contents' in str(e):
print("It's likely that your checkpoint file has been compressed with SNAPPY.")
if 'Data loss' in str(e) and any((e in file_name for e in ['.index', '.meta', '.data'])):
proposed_file = '.'.join(file_name.split('.')[0:-1])
v2_file_error_template = "\nIt's likely that this is a V2 checkpoint and you need to provide the filename\n*prefix*. Try removing the '.' and extension. Try:\ninspect checkpoint --file_name = {}"
print(v2_file_error_template.format(proposed_file))
|
Prints tensors in a checkpoint file.
If no `tensor_name` is provided, prints the tensor names and shapes
in the checkpoint file.
If `tensor_name` is provided, prints the content of the tensor.
Args:
file_name: Name of the checkpoint file.
tensor_name: Name of the tensor in the checkpoint file to print.
all_tensors: Boolean indicating whether to print all tensors.
all_tensor_names: Boolean indicating whether to print all tensor names.
count_exclude_pattern: Regex string, pattern to exclude tensors from count.
|
github-repos
|
def create_combination(list_of_sentences):
num_sentences = len(list_of_sentences) - 1
combinations = []
for i, _ in enumerate(list_of_sentences):
if i == num_sentences:
break
num_pairs = num_sentences - i
populated = num_pairs * [list_of_sentences[i]]
zipped = list(zip(populated, list_of_sentences[i + 1:]))
combinations += zipped
return combinations
|
Generates all possible pair combinations for the input list of sentences.
For example:
input = ["paraphrase1", "paraphrase2", "paraphrase3"]
output = [("paraphrase1", "paraphrase2"),
("paraphrase1", "paraphrase3"),
("paraphrase2", "paraphrase3")]
Args:
list_of_sentences: the list of input sentences.
Returns:
the list of all possible sentence pairs.
|
juraj-google-style
|
def reset_time_estimate(self, **kwargs):
path = ('%s/%s/reset_time_estimate' % (self.manager.path, self.get_id()))
return self.manager.gitlab.http_post(path, **kwargs)
|
Resets estimated time for the object to 0 seconds.
Args:
**kwargs: Extra options to send to the server (e.g. sudo)
Raises:
GitlabAuthenticationError: If authentication is not correct
GitlabTimeTrackingError: If the time tracking update cannot be done
|
codesearchnet
|
def get_key_by_job_id(cls, mapreduce_id):
return db.Key.from_path(cls.kind(), "%s:%s" % (mapreduce_id, cls._KEY_NAME))
|
Retrieves the Key for a mapreduce ID.
Args:
mapreduce_id: The job to fetch.
Returns:
Datastore Key for the command for the given job ID.
|
juraj-google-style
|
def get_attribute_from_config(config, section, attribute):
section = config.get(section)
if section:
option = section.get(attribute)
if option:
return option
raise ConfigurationError("Config file badly formed!\n"
"Failed to get attribute '{}' from section '{}'!"
.format(attribute, section))
|
Try to parse an attribute of the config file.
Args:
config (defaultdict): A defaultdict.
section (str): The section of the config file to get information from.
attribute (str): The attribute of the section to fetch.
Returns:
str: The string corresponding to the section and attribute.
Raises:
ConfigurationError
|
juraj-google-style
|
def hertz_to_mel(freq: Union[float, np.ndarray], mel_scale: str='htk') -> Union[float, np.ndarray]:
if mel_scale not in ['slaney', 'htk', 'kaldi']:
raise ValueError('mel_scale should be one of "htk", "slaney" or "kaldi".')
if mel_scale == 'htk':
return 2595.0 * np.log10(1.0 + freq / 700.0)
elif mel_scale == 'kaldi':
return 1127.0 * np.log(1.0 + freq / 700.0)
min_log_hertz = 1000.0
min_log_mel = 15.0
logstep = 27.0 / np.log(6.4)
mels = 3.0 * freq / 200.0
if isinstance(freq, np.ndarray):
log_region = freq >= min_log_hertz
mels[log_region] = min_log_mel + np.log(freq[log_region] / min_log_hertz) * logstep
elif freq >= min_log_hertz:
mels = min_log_mel + np.log(freq / min_log_hertz) * logstep
return mels
|
Convert frequency from hertz to mels.
Args:
freq (`float` or `np.ndarray`):
The frequency, or multiple frequencies, in hertz (Hz).
mel_scale (`str`, *optional*, defaults to `"htk"`):
The mel frequency scale to use, `"htk"`, `"kaldi"` or `"slaney"`.
Returns:
`float` or `np.ndarray`: The frequencies on the mel scale.
|
github-repos
|
def union(df, other, index=False, keep='first'):
validate_set_ops(df, other)
stacked = df.append(other)
if index:
stacked_reset_indexes = stacked.reset_index()
index_cols = [col for col in stacked_reset_indexes.columns if (col not in df.columns)]
index_name = df.index.names
return_df = stacked_reset_indexes.drop_duplicates(keep=keep).set_index(index_cols)
return_df.index.names = index_name
return return_df
else:
return stacked.drop_duplicates(keep=keep)
|
Returns rows that appear in either DataFrame.
Args:
df (pandas.DataFrame): data passed in through the pipe.
other (pandas.DataFrame): other DataFrame to use for set operation with
the first.
Kwargs:
index (bool): Boolean indicating whether to consider the pandas index
as part of the set operation (default `False`).
keep (str): Indicates which duplicate should be kept. Options are `'first'`
and `'last'`.
|
codesearchnet
|
def calculate_query_times(**kwargs):
return {'total_time_avg': round(numpy.mean(kwargs['total_times']), 1), 'total_time_min': round(numpy.min(kwargs['total_times']), 1), 'total_time_max': round(numpy.max(kwargs['total_times']), 1), 'total_time_85': round(numpy.percentile(kwargs['total_times'], 85), 1), 'execution_time_avg': round(numpy.mean(kwargs['execution_times']), 1), 'execution_time_min': round(numpy.min(kwargs['execution_times']), 1), 'execution_time_max': round(numpy.max(kwargs['execution_times']), 1), 'execution_time_85': round(numpy.percentile(kwargs['execution_times'], 85), 1), 'execution_time_25': round(numpy.percentile(kwargs['execution_times'], 25), 1), 'execution_time_std': round(numpy.std(kwargs['execution_times']), 1), 'connect_time_avg': round(numpy.mean(kwargs['connect_times']), 1), 'connect_time_min': round(numpy.min(kwargs['connect_times']), 1), 'connect_time_max': round(numpy.max(kwargs['connect_times']), 1), 'connect_time_85': round(numpy.percentile(kwargs['connect_times'], 85), 1), 'results_iter_time_avg': round(numpy.mean(kwargs['results_iter_times']), 1), 'results_iter_time_min': round(numpy.min(kwargs['results_iter_times']), 1), 'results_iter_time_max': round(numpy.max(kwargs['results_iter_times']), 1), 'results_iter_time_85': round(numpy.percentile(kwargs['results_iter_times'], 85), 1)}
|
Calculates aggregate query times from all iteration times
Kwargs:
total_times(list): List of total time calculations
execution_times(list): List of execution_time calculations
results_iter_times(list): List of results_iter_time calculations
connect_times(list): List of connect_time calculations
Returns:
query_execution(dict): Query times
False(bool): The query failed. Exception should be logged.
|
codesearchnet
|
def send_batches(self, batch_list):
if isinstance(batch_list, BaseMessage):
batch_list = batch_list.SerializeToString()
return self._post('/batches', batch_list)
|
Sends a list of batches to the validator.
Args:
batch_list (:obj:`BatchList`): the list of batches
Returns:
dict: the json result data, as a dict
|
juraj-google-style
|
def _get_user_id(arguments_dict):
if 'user_id' not in arguments_dict:
raise TypeError('Each invocation of a UserTaskMixin subclass must include the user_id')
user_id = arguments_dict['user_id']
try:
get_user_model().objects.get(pk=user_id)
except (ValueError, get_user_model().DoesNotExist):
raise TypeError('Invalid user_id: {}'.format(user_id))
return user_id
|
Get and validate the `user_id` argument to a task derived from `UserTaskMixin`.
Arguments:
arguments_dict (dict): The parsed positional and keyword arguments to the task
Returns
-------
int: The primary key of a user record (may not be an int if using a custom user model)
|
juraj-google-style
|
def import_certificate(self, certificate_data, bay_number=None):
uri = '{}/https/certificaterequest'.format(self.data['uri'])
if bay_number:
uri += ('?bayNumber=%d' % bay_number)
headers = {'Content-Type': 'application/json'}
return self._helper.do_put(uri, certificate_data, (- 1), headers)
|
Imports a signed server certificate into the enclosure.
Args:
certificate_data: Dictionary with Signed certificate and type.
bay_number: OA to which the signed certificate will be imported.
Returns:
Enclosure.
|
codesearchnet
|
def add_handler(self, handler):
handler['logger'] = self._get_logger(handler)
handler['reads'] = 0
handler['data_read'] = 0
self.capture_handlers.append(handler)
|
Add an additional handler
Args:
handler:
A dictionary of handler configuration for the handler
that should be added. See :func:`__init__` for details
on valid parameters.
|
codesearchnet
|
def picture_view(request, user_id, year=None):
try:
user = User.objects.get(id=user_id)
except User.DoesNotExist:
raise Http404
default_image_path = os.path.join(settings.PROJECT_ROOT, "static/img/default_profile_pic.png")
if user is None:
raise Http404
else:
if year is None:
preferred = user.preferred_photo
if preferred is None:
data = user.default_photo
if data is None:
image_buffer = io.open(default_image_path, mode="rb")
else:
image_buffer = io.BytesIO(data)
else:
data = preferred.binary
if data:
image_buffer = io.BytesIO(data)
else:
image_buffer = io.open(default_image_path, mode="rb")
else:
grade_number = Grade.number_from_name(year)
if user.photos.filter(grade_number=grade_number).exists():
data = user.photos.filter(grade_number=grade_number).first().binary
else:
data = None
if data:
image_buffer = io.BytesIO(data)
else:
image_buffer = io.open(default_image_path, mode="rb")
response = HttpResponse(content_type="image/jpeg")
response["Content-Disposition"] = "filename={}_{}.jpg".format(user_id, year or preferred)
try:
img = image_buffer.read()
except UnicodeDecodeError:
img = io.open(default_image_path, mode="rb").read()
image_buffer.close()
response.write(img)
return response
|
Displays a view of a user's picture.
Args:
user_id
The ID of the user whose picture is being fetched.
year
The user's picture from this year is fetched. If not
specified, use the preferred picture.
|
juraj-google-style
|
def listFormats(self, vendorSpecific=None):
response = self.listFormatsResponse(vendorSpecific)
return self._read_dataone_type_response(response, 'ObjectFormatList')
|
See Also: listFormatsResponse()
Args:
vendorSpecific:
Returns:
|
juraj-google-style
|
def is_supported(cls, desc):
for l in cls:
if l.matches(desc):
return True
return False
|
Determines if the given label descriptor is supported.
Args:
desc (:class:`endpoints_management.gen.servicemanagement_v1_messages.LabelDescriptor`):
the label descriptor to test
Return:
`True` if desc is supported, otherwise `False`
|
codesearchnet
|
def _get_longest_diag_index(input_matrix):
diags = AssistedCandidateGeneratorDifferentTokenizers._get_longest_diag_dict(input_matrix, input_matrix.nonzero())
diags_values = list(diags.values())
diags_keys = list(diags.keys())
best_diag = np.argmax(diags_values)
diag_start_index = diags_keys[best_diag]
diag_start_length = diags_values[best_diag]
return (diag_start_index, diag_start_length)
|
Returns the start index and length of the longest diagonal in the given input.
Args:
input_matrix (numpy.ndarray): The input matrix.
Returns:
tuple: A tuple containing the start index and length of the longest diagonal.
|
github-repos
|
def is_attribute_multivalued(self, attribute):
rule_set = self._attribute_rule_sets.get(attribute)
return rule_set.multiple_instances_permitted
|
Check if the attribute is allowed to have multiple instances.
Args:
attribute (string): The name of the attribute
(e.g., 'State'). Required.
|
codesearchnet
|
def load_configuration(config_file, config_dir, service_file):
config_files = [config_file]
config = configparser.ConfigParser()
config.read_dict(DEFAULT_OPTIONS)
if (not os.path.isfile(config_file)):
raise ValueError("{f} configuration file either isn't readable or doesn't exist".format(f=config_file))
if (service_file is not None):
if (not os.path.isfile(service_file)):
raise ValueError("{f} configuration file for a service check doesn't exist".format(f=service_file))
else:
config_files.append(service_file)
elif (config_dir is not None):
if (not os.path.isdir(config_dir)):
raise ValueError("{d} directory with configuration files for service checks doesn't exist".format(d=config_dir))
else:
config_files.extend(glob.glob(os.path.join(config_dir, '*.conf')))
try:
config.read(config_files)
except configparser.Error as exc:
raise ValueError(exc)
configuration_check(config)
bird_configuration = build_bird_configuration(config)
create_bird_config_files(bird_configuration)
return (config, bird_configuration)
|
Build configuration objects.
If all sanity checks against daemon and service check settings are passed
then it builds a ConfigParser object which holds all our configuration
and a dictionary data structure which holds Bird configuration per IP
protocol version.
Arguments:
config_file (str): The file name which holds daemon settings
config_dir (str): The directory name which has configuration files
for each service check
service_file (str): A file which contains configuration for a single
service check
Returns:
A tuple with 1st element a ConfigParser object and 2nd element
a dictionary.
Raises:
ValueError if a sanity check fails.
|
codesearchnet
|
def select_by_key(self, key):
self._selected_key = None
self._selected_item = None
for item in self.children.values():
item.attributes['selected'] = False
if key in self.children:
self.children[key].attributes['selected'] = True
self._selected_key = key
self._selected_item = self.children[key]
|
Selects an item by its key.
Args:
key (str): The unique string identifier of the item that have to be selected.
|
juraj-google-style
|
def _process_update(self, item, feed_item):
pass
|
Handles updates to the creative asset object.
Since creative assets are read only in DCM, there is nothing to do here,
this method is mandatory as it is invoked by the BaseDAO class.
Args:
item: The creative asset DCM object being updated.
feed_item: The feed item representing the creative asset from the
Bulkdozer feed.
|
github-repos
|
def roots_in_unit_interval(coeffs):
all_roots = polynomial.polyroots(coeffs)
all_roots = all_roots[((_UNIT_INTERVAL_WIGGLE_START < all_roots.real) & (all_roots.real < _UNIT_INTERVAL_WIGGLE_END))]
real_inds = (np.abs(all_roots.imag) < _IMAGINARY_WIGGLE)
return all_roots[real_inds].real
|
r"""Compute roots of a polynomial in the unit interval.
Args:
coeffs (numpy.ndarray): A 1D array (size ``d + 1``) of coefficients in
monomial / power basis.
Returns:
numpy.ndarray: ``N``-array of real values in :math:`\left[0, 1\right]`.
|
codesearchnet
|
def list_resource_groups(access_token, subscription_id):
endpoint = ''.join([get_rm_endpoint(), '/subscriptions/', subscription_id, '/resourceGroups/', '?api-version=', RESOURCE_API])
return do_get(endpoint, access_token)
|
List the resource groups in a subscription.
Args:
access_token (str): A valid Azure authentication token.
subscription_id (str): Azure subscription id.
Returns:
HTTP response.
|
codesearchnet
|
def find_gaps(self, index=False):
return self.__find_incongruities(op=operator.lt, index=index)
|
Finds gaps in a striplog.
Args:
index (bool): If True, returns indices of intervals with
gaps after them.
Returns:
Striplog: A striplog of all the gaps. A sort of anti-striplog.
|
codesearchnet
|
def inspect_plugin(self, name):
url = self._url('/plugins/{0}/json', name)
return self._result(self._get(url), True)
|
Retrieve plugin metadata.
Args:
name (string): The name of the plugin. The ``:latest`` tag is
optional, and is the default if omitted.
Returns:
A dict containing plugin info
|
juraj-google-style
|
def show(config, section, opt):
if (section not in config.keys()):
raise ConfigError("section '{}' doesn't exist".format(section))
if (opt not in config[section].keys()):
raise ConfigError("option '{}.{}' doesn't exist".format(section, opt))
logger.info(config[section][opt])
|
Prints option value from the config.
Args:
config (configobj.ConfigObj): config to work on.
section (str): section name.
opt (str): option name.
|
codesearchnet
|
def _run(self, cmd):
if isinstance(cmd, six.string_types):
cmd = salt.utils.args.shlex_split(cmd)
try:
log.debug(cmd)
p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
return p.communicate()
except (OSError, IOError) as exc:
log.debug('Command Failed: %s', ' '.join(cmd))
log.debug('Error: %s', exc)
raise CommandExecutionError(exc)
|
Internal function for running commands. Used by the uninstall function.
Args:
cmd (str, list): The command to run
Returns:
str: The stdout of the command
|
codesearchnet
|
def parse_query_param(url, param):
try:
return parse.parse_qs(parse.urlparse(url).query)[param][0]
except:
return None
|
Parses the query string of a URL and returns the value of a parameter.
Args:
url: A URL.
param: A string representing the name of the parameter.
Returns:
The value of the parameter.
|
codesearchnet
|
def get_lang_tags(index_page):
dom = dhtmlparser.parseString(index_page)
lang_tags = [get_html_lang_tags(dom), get_dc_lang_tags(dom), [detect_language(dom)], get_html_tag_lang_params(dom)]
return list(sorted(set((SourceString(normalize(lang), source=lang.source) for lang in sum(lang_tags, [])))))
|
Collect informations about language of the page from HTML and Dublin core
tags and langdetect guesses.
Args:
index_page (str): HTML content of the page you wish to analyze.
Returns:
list: List of :class:`.SourceString` objects.
|
codesearchnet
|
def resolve(self, name, version, max_id):
if (not isinstance(name, six.text_type)):
raise TypeError(('Name must be a Unicode sequence: %r' % name))
if (not isinstance(version, int)):
raise TypeError(('Version must be an int: %r' % version))
if (version <= 0):
raise ValueError(('Version must be positive: %s' % version))
if ((max_id is not None) and (max_id < 0)):
raise ValueError(('Max ID must be zero or positive: %s' % max_id))
versions = self.__tables.get(name)
if (versions is None):
if (max_id is None):
raise CannotSubstituteTable(('Found no table for %s, but no max_id' % name))
return placeholder_symbol_table(name, version, max_id)
table = versions.get(version)
if (table is None):
keys = list(versions)
keys.sort()
table = versions[keys[(- 1)]]
if ((table.version == version) and ((max_id is None) or (table.max_id == max_id))):
return table
if (max_id is None):
raise CannotSubstituteTable(('Found match for %s, but not version %d, and no max_id' % (name, version)))
return substitute_symbol_table(table, version, max_id)
|
Resolves the table for a given name and version.
Args:
name (unicode): The name of the table to resolve.
version (int): The version of the table to resolve.
max_id (Optional[int]): The maximum ID of the table requested.
May be ``None`` in which case an exact match on ``name`` and ``version``
is required.
Returns:
SymbolTable: The *closest* matching symbol table. This is either an exact match,
a placeholder, or a derived substitute depending on what tables are registered.
|
codesearchnet
|
def set_rgb_dim_level_with_time(
self,
channelIndex: int,
rgb: RGBColorState,
dimLevel: float,
onTime: float,
rampTime: float,
):
data = {
"channelIndex": channelIndex,
"deviceId": self.id,
"simpleRGBColorState": rgb,
"dimLevel": dimLevel,
"onTime": onTime,
"rampTime": rampTime,
}
return self._restCall(
"device/control/setSimpleRGBColorDimLevelWithTime", body=json.dumps(data)
)
|
sets the color and dimlevel of the lamp
Args:
channelIndex(int): the channelIndex of the lamp. Use self.topLightChannelIndex or self.bottomLightChannelIndex
rgb(RGBColorState): the color of the lamp
dimLevel(float): the dimLevel of the lamp. 0.0 = off, 1.0 = MAX
onTime(float):
rampTime(float):
Returns:
the result of the _restCall
|
juraj-google-style
|
def incoming(self, messages):
if self._observers:
campfire = self._room.get_campfire()
for message in messages:
for observer in self._observers:
observer(Message(campfire, message))
|
Called when incoming messages arrive.
Args:
messages (tuple): Messages (each message is a dict)
|
juraj-google-style
|
def _separable_conv_block(ip, filters, kernel_size=(3, 3), strides=(1, 1), block_id=None):
channel_dim = 1 if backend.image_data_format() == 'channels_first' else -1
with backend.name_scope(f'separable_conv_block_{block_id}'):
x = layers.Activation('relu')(ip)
if strides == (2, 2):
x = layers.ZeroPadding2D(padding=imagenet_utils.correct_pad(x, kernel_size), name=f'separable_conv_1_pad_{block_id}')(x)
conv_pad = 'valid'
else:
conv_pad = 'same'
x = layers.SeparableConv2D(filters, kernel_size, strides=strides, name=f'separable_conv_1_{block_id}', padding=conv_pad, use_bias=False)(x)
x = layers.BatchNormalization(axis=channel_dim, momentum=0.9997, epsilon=0.001, name=f'separable_conv_1_bn_{block_id}')(x)
x = layers.Activation('relu')(x)
x = layers.SeparableConv2D(filters, kernel_size, name=f'separable_conv_2_{block_id}', padding='same', use_bias=False)(x)
x = layers.BatchNormalization(axis=channel_dim, momentum=0.9997, epsilon=0.001, name=f'separable_conv_2_bn_{block_id}')(x)
return x
|
Adds 2 blocks of [relu-separable conv-batchnorm].
Args:
ip: Input tensor
filters: Number of output filters per layer
kernel_size: Kernel size of separable convolutions
strides: Strided convolution for downsampling
block_id: String block_id
Returns:
A Keras tensor
|
github-repos
|
def _transform_binary_composition_to_expression(expression, node, context):
if expression.operator not in constants.SUPPORTED_OPERATORS:
raise NotImplementedError(
u'Filter operation "{}" is not supported by the SQL backend.'.format(
expression.operator))
sql_operator = constants.SUPPORTED_OPERATORS[expression.operator]
left = _expression_to_sql(expression.left, node, context)
right = _expression_to_sql(expression.right, node, context)
if sql_operator.cardinality == constants.CARDINALITY_UNARY:
left, right = _get_column_and_bindparam(left, right, sql_operator)
clause = getattr(left, sql_operator.name)(right)
return clause
elif sql_operator.cardinality == constants.CARDINALITY_BINARY:
clause = getattr(sql_expressions, sql_operator.name)(left, right)
return clause
elif sql_operator.cardinality == constants.CARDINALITY_LIST_VALUED:
left, right = _get_column_and_bindparam(left, right, sql_operator)
right.expanding = True
clause = getattr(left, sql_operator.name)(right)
return clause
raise AssertionError(u'Unreachable, operator cardinality {} for compiler expression {} is '
u'unknown'.format(sql_operator.cardinality, expression))
|
Transform a BinaryComposition compiler expression into a SQLAlchemy expression.
Recursively calls _expression_to_sql to convert its left and right sub-expressions.
Args:
expression: expression, BinaryComposition compiler expression.
node: SqlNode, the SqlNode the expression applies to.
context: CompilationContext, global compilation state and metadata.
Returns:
Expression, SQLAlchemy expression.
|
juraj-google-style
|
def cast(self, value):
if self.type is None:
return value
if self.type in (str, int, float):
try:
return self.type(value)
except Exception as e:
raise errors.BisonError(
'Failed to cast {} to {}'.format(value, self.type)
) from e
elif self.type == bool:
return value.lower() == 'true'
else:
raise errors.BisonError('Unsupported type for casting: {}'.format(self.type))
|
Cast a value to the type required by the option, if one is set.
This is used to cast the string values gathered from environment
variable into their required type.
Args:
value: The value to cast.
Returns:
The value casted to the expected type for the option.
|
juraj-google-style
|
def _convert_appengine_app_assertion_credentials(credentials):
return google.auth.app_engine.Credentials(
scopes=_helpers.string_to_scopes(credentials.scope),
service_account_id=credentials.service_account_id)
|
Converts to :class:`google.auth.app_engine.Credentials`.
Args:
credentials (oauth2client.contrib.app_engine.AppAssertionCredentials):
The credentials to convert.
Returns:
google.oauth2.service_account.Credentials: The converted credentials.
|
juraj-google-style
|
def exp(array, 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
weld_template =
weld_obj.weld_code = weld_template % {"array": array_var, "ty": ty}
return weld_obj
|
Computes the per-element exponenet of the passed-in array.
Args:
array (WeldObject / Numpy.ndarray): Input array
ty (WeldType): Type of each element in the input array
Returns:
A WeldObject representing this computation
|
juraj-google-style
|
def update_config(self, new_config):
self._assert_not_running()
self._ad.log.info('[LogcatService] Changing config from %s to %s', self._config, new_config)
self._config = new_config
|
Updates the configuration for the service.
The service needs to be stopped before updating, and explicitly started
after the update.
This will reset the service. Previous output files may be orphaned if
output path is changed.
Args:
new_config: Config, the new config to use.
|
github-repos
|
def get_language(self, text):
files = {'text': text}
res, status_code = self.post(self.language_service, files=files)
if status_code != 200:
logger.debug('Language recognition failed.')
return self.decode(res), status_code
|
Recognise the language of the text in input
Args:
id (str): The text whose the language needs to be recognised
Returns:
dict, int: A dict containing the recognised language and the
confidence score.
|
juraj-google-style
|
def get_arrhenius_plot(temps, diffusivities, diffusivity_errors=None, **kwargs):
(Ea, c, _) = fit_arrhenius(temps, diffusivities)
from pymatgen.util.plotting import pretty_plot
plt = pretty_plot(12, 8)
arr = (c * np.exp(((- Ea) / ((const.k / const.e) * np.array(temps)))))
t_1 = (1000 / np.array(temps))
plt.plot(t_1, diffusivities, 'ko', t_1, arr, 'k--', markersize=10, **kwargs)
if (diffusivity_errors is not None):
n = len(diffusivity_errors)
plt.errorbar(t_1[0:n], diffusivities[0:n], yerr=diffusivity_errors, fmt='ko', ecolor='k', capthick=2, linewidth=2)
ax = plt.axes()
ax.set_yscale('log')
plt.text(0.6, 0.85, 'E$_a$ = {:.0f} meV'.format((Ea * 1000)), fontsize=30, transform=plt.axes().transAxes)
plt.ylabel('D (cm$^2$/s)')
plt.xlabel('1000/T (K$^{-1}$)')
plt.tight_layout()
return plt
|
Returns an Arrhenius plot.
Args:
temps ([float]): A sequence of temperatures.
diffusivities ([float]): A sequence of diffusivities (e.g.,
from DiffusionAnalyzer.diffusivity).
diffusivity_errors ([float]): A sequence of errors for the
diffusivities. If None, no error bar is plotted.
\\*\\*kwargs:
Any keyword args supported by matplotlib.pyplot.plot.
Returns:
A matplotlib.pyplot object. Do plt.show() to show the plot.
|
codesearchnet
|
def build_input(data, batch_size, dataset, train):
image_size = 32
depth = 3
num_classes = (10 if (dataset == 'cifar10') else 100)
(images, labels) = data
num_samples = (images.shape[0] - (images.shape[0] % batch_size))
dataset = tf.contrib.data.Dataset.from_tensor_slices((images[:num_samples], labels[:num_samples]))
def map_train(image, label):
image = tf.image.resize_image_with_crop_or_pad(image, (image_size + 4), (image_size + 4))
image = tf.random_crop(image, [image_size, image_size, 3])
image = tf.image.random_flip_left_right(image)
image = tf.image.per_image_standardization(image)
return (image, label)
def map_test(image, label):
image = tf.image.resize_image_with_crop_or_pad(image, image_size, image_size)
image = tf.image.per_image_standardization(image)
return (image, label)
dataset = dataset.map((map_train if train else map_test))
dataset = dataset.batch(batch_size)
dataset = dataset.repeat()
if train:
dataset = dataset.shuffle(buffer_size=(16 * batch_size))
(images, labels) = dataset.make_one_shot_iterator().get_next()
images = tf.reshape(images, [batch_size, image_size, image_size, depth])
labels = tf.reshape(labels, [batch_size, 1])
indices = tf.reshape(tf.range(0, batch_size, 1), [batch_size, 1])
labels = tf.sparse_to_dense(tf.concat([indices, labels], 1), [batch_size, num_classes], 1.0, 0.0)
assert (len(images.get_shape()) == 4)
assert (images.get_shape()[0] == batch_size)
assert (images.get_shape()[(- 1)] == 3)
assert (len(labels.get_shape()) == 2)
assert (labels.get_shape()[0] == batch_size)
assert (labels.get_shape()[1] == num_classes)
if (not train):
tf.summary.image('images', images)
return (images, labels)
|
Build CIFAR image and labels.
Args:
data_path: Filename for cifar10 data.
batch_size: Input batch size.
train: True if we are training and false if we are testing.
Returns:
images: Batches of images of size
[batch_size, image_size, image_size, 3].
labels: Batches of labels of size [batch_size, num_classes].
Raises:
ValueError: When the specified dataset is not supported.
|
codesearchnet
|
def get_reachable_ports(self, id_or_uri, start=0, count=(- 1), filter='', query='', sort='', networks=[]):
uri = (self._client.build_uri(id_or_uri) + '/reachable-ports')
if networks:
elements = "'"
for n in networks:
elements += (n + ',')
elements = (elements[:(- 1)] + "'")
uri = ((uri + '?networks=') + elements)
return self._client.get(self._client.build_query_uri(start=start, count=count, filter=filter, query=query, sort=sort, uri=uri))
|
Gets the storage ports that are connected on the specified networks
based on the storage system port's expected network connectivity.
Returns:
list: Reachable Storage Port List.
|
codesearchnet
|
def params(self, params):
url = furl(self._request.rawurl)
url = url.add(params)
self._request.url = url.url
self.add_matcher(matcher('QueryMatcher', params))
|
Defines a set of URL query params to match.
Arguments:
params (dict): set of params to match.
Returns:
self: current Mock instance.
|
juraj-google-style
|
def save_metrics(self, split, metrics, combined=True):
if not self.is_world_process_zero():
return
path = os.path.join(self.args.output_dir, f'{split}_results.json')
with open(path, 'w') as f:
json.dump(metrics, f, indent=4, sort_keys=True)
if combined:
path = os.path.join(self.args.output_dir, 'all_results.json')
if os.path.exists(path):
with open(path) as f:
all_metrics = json.load(f)
else:
all_metrics = {}
all_metrics.update(metrics)
with open(path, 'w') as f:
json.dump(all_metrics, f, indent=4, sort_keys=True)
|
Save metrics into a json file for that split, e.g. `train_results.json`.
Under distributed environment this is done only for a process with rank 0.
Args:
split (`str`):
Mode/split name: one of `train`, `eval`, `test`, `all`
metrics (`Dict[str, float]`):
The metrics returned from train/evaluate/predict
combined (`bool`, *optional*, defaults to `True`):
Creates combined metrics by updating `all_results.json` with metrics of this call
To understand the metrics please read the docstring of [`~Trainer.log_metrics`]. The only difference is that raw
unformatted numbers are saved in the current method.
|
github-repos
|
def __init__(self, xid=None, role=None, generation_id=None):
super().__init__(xid, role, generation_id)
self.header.message_type = Type.OFPT_ROLE_REQUEST
|
Create a RoleRequest with the optional parameters below.
Args:
xid (int): OpenFlow xid to the header.
role (:class:`~.controller2switch.common.ControllerRole`):
Is the new role that the controller wants to assume.
generation_id (int): Master Election Generation Id.
|
juraj-google-style
|
def get_parent_of_type(typ, obj):
if (type(typ) is not text):
typ = typ.__name__
while hasattr(obj, 'parent'):
obj = obj.parent
if (obj.__class__.__name__ == typ):
return obj
|
Finds first object up the parent chain of the given type.
If no parent of the given type exists None is returned.
Args:
typ(str or python class): The type of the model object we are
looking for.
obj (model object): Python model object which is the start of the
search process.
|
codesearchnet
|
def has_unchecked_field(self, locator, **kwargs):
kwargs['checked'] = False
return self.has_selector('field', locator, **kwargs)
|
Checks if the page or current node has a radio button or checkbox with the given label,
value, or id, that is currently unchecked.
Args:
locator (str): The label, name, or id of an unchecked field.
**kwargs: Arbitrary keyword arguments for :class:`SelectorQuery`.
Returns:
bool: Whether it exists.
|
codesearchnet
|
def _ParseLogLine(self, parser_mediator, structure):
try:
date_time = dfdatetime_time_elements.TimeElements(time_elements_tuple=structure.date_time)
date_time.is_local_time = True
except ValueError:
parser_mediator.ProduceExtractionWarning('invalid date time value: {0!s}'.format(structure.date_time))
return
event_data = WinFirewallEventData()
event_data.action = self._GetStructureValue(structure, 'action')
event_data.dest_ip = self._GetStructureValue(structure, 'dest_ip')
event_data.dest_port = self._GetStructureValue(structure, 'dest_port')
event_data.flags = self._GetStructureValue(structure, 'flags')
event_data.icmp_code = self._GetStructureValue(structure, 'icmp_code')
event_data.icmp_type = self._GetStructureValue(structure, 'icmp_type')
event_data.info = self._GetStructureValue(structure, 'info')
event_data.path = self._GetStructureValue(structure, 'path')
event_data.protocol = self._GetStructureValue(structure, 'protocol')
event_data.size = self._GetStructureValue(structure, 'size')
event_data.source_ip = self._GetStructureValue(structure, 'source_ip')
event_data.source_port = self._GetStructureValue(structure, 'source_port')
event_data.tcp_ack = self._GetStructureValue(structure, 'tcp_ack')
event_data.tcp_seq = self._GetStructureValue(structure, 'tcp_seq')
event_data.tcp_win = self._GetStructureValue(structure, 'tcp_win')
if self._use_local_timezone:
time_zone = parser_mediator.timezone
else:
time_zone = pytz.UTC
event = time_events.DateTimeValuesEvent(date_time, definitions.TIME_DESCRIPTION_WRITTEN, time_zone=time_zone)
parser_mediator.ProduceEventWithEventData(event, event_data)
|
Parse a single log line and and produce an event object.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
structure (pyparsing.ParseResults): structure of tokens derived from
a line of a text file.
|
codesearchnet
|
def get_max_size(pool, num_option, item_length):
max_items = POOL_SIZE / item_length
existing = POOL_OPTION_MIN_SIZE * num_option + sum([max(0, len(pool.get(i, {})) - 5) for i in xrange(num_option)])
return int(max_items - existing)
|
Calculate the max number of item that an option can stored in the pool at give time.
This is to limit the pool size to POOL_SIZE
Args:
option_index (int): the index of the option to calculate the size for
pool (dict): answer pool
num_option (int): total number of options available for the question
item_length (int): the length of the item
Returns:
int: the max number of items that `option_index` can have
|
juraj-google-style
|
def pyrdf2(value, class_type=None, datatype=None, lang=None, **kwargs):
try:
if isinstance(value, dict):
if value.get('type') == "literal":
if not value.get("datatype"):
return XsdString(value['value'])
else:
try:
if value.get("lang"):
return DT_LOOKUP[value['datatype']](value['value'],
lang=value.get("lang"))
else:
return DT_LOOKUP[value['datatype']](value['value'])
except:
rtn_val = BaseRdfDataType(value['value'])
rtn_val.datatype = Uri(value['datatype'])
return rtn_val
else:
return DT_LOOKUP[value['type']](value['value'])
elif isinstance(value, BaseRdfDataType):
return value
else:
return DT_LOOKUP[type(value)](value)
except:
pdb.set_trace()
pass
|
Coverts an input to one of the rdfdatatypes classes
Args:
value: any rdfdatatype, json dict or vlaue
class_type: "literal", "uri" or "blanknode"
datatype: "xsd:string", "xsd:int" , etc
|
juraj-google-style
|
def configure(cls, api_token, api_url='https:
cls._auth = QuboleAuth(api_token)
cls.api_token = api_token
cls.version = version
cls.baseurl = api_url
if (poll_interval < Qubole.MIN_POLL_INTERVAL):
log.warn(('Poll interval cannot be less than %s seconds. Setting it to %s seconds.\n' % (Qubole.MIN_POLL_INTERVAL, Qubole.MIN_POLL_INTERVAL)))
cls.poll_interval = Qubole.MIN_POLL_INTERVAL
else:
cls.poll_interval = poll_interval
cls.skip_ssl_cert_check = skip_ssl_cert_check
cls.cloud_name = cloud_name.lower()
cls.cached_agent = None
|
Set parameters governing interaction with QDS
Args:
`api_token`: authorization token for QDS. required
`api_url`: the base URL for QDS API. configurable for testing only
`version`: QDS REST api version. Will be used throughout unless overridden in Qubole.agent(..)
`poll_interval`: interval in secs when polling QDS for events
|
codesearchnet
|
def FindUnspentCoins(self, from_addr=None, use_standard=False, watch_only_val=0):
ret = []
for coin in self.GetCoins():
if (((coin.State & CoinState.Confirmed) > 0) and ((coin.State & CoinState.Spent) == 0) and ((coin.State & CoinState.Locked) == 0) and ((coin.State & CoinState.Frozen) == 0) and ((coin.State & CoinState.WatchOnly) == watch_only_val)):
do_exclude = False
if self._vin_exclude:
for to_exclude in self._vin_exclude:
if ((coin.Reference.PrevIndex == to_exclude.PrevIndex) and (coin.Reference.PrevHash == to_exclude.PrevHash)):
do_exclude = True
if do_exclude:
continue
if (from_addr is not None):
if (coin.Output.ScriptHash == from_addr):
ret.append(coin)
elif use_standard:
contract = self._contracts[coin.Output.ScriptHash.ToBytes()]
if contract.IsStandard:
ret.append(coin)
else:
ret.append(coin)
return ret
|
Finds unspent coin objects in the wallet.
Args:
from_addr (UInt160): a bytearray (len 20) representing an address.
use_standard (bool): whether or not to only include standard contracts ( i.e not a smart contract addr ).
watch_only_val (int): a flag ( 0 or 64 ) indicating whether or not to find coins that are in 'watch only' addresses.
Returns:
list: a list of ``neo.Wallet.Coins`` in the wallet that are not spent.
|
codesearchnet
|
def saveAsTFRecords(df, output_dir):
tf_rdd = df.rdd.mapPartitions(toTFExample(df.dtypes))
tf_rdd.saveAsNewAPIHadoopFile(output_dir, "org.tensorflow.hadoop.io.TFRecordFileOutputFormat",
keyClass="org.apache.hadoop.io.BytesWritable",
valueClass="org.apache.hadoop.io.NullWritable")
|
Save a Spark DataFrame as TFRecords.
This will convert the DataFrame rows to TFRecords prior to saving.
Args:
:df: Spark DataFrame
:output_dir: Path to save TFRecords
|
juraj-google-style
|
def run(self):
with util.timed_block() as t:
files = self._collect_files()
log.info('Collected <33>{} <32>files in <33>{}s'.format(len(files), t.elapsed_s))
if self.verbose:
for p in files:
log.info(' <0>{}', p)
if (not files):
return self.allow_empty
with util.timed_block() as t:
results = self._run_checks(files)
log.info('Code checked in <33>{}s', t.elapsed_s)
success = True
for (name, retcodes) in results.items():
if any(((x != 0) for x in retcodes)):
success = False
log.err('<35>{} <31>failed with: <33>{}'.format(name, retcodes))
return success
|
Run all linters and report results.
Returns:
bool: **True** if all checks were successful, **False** otherwise.
|
codesearchnet
|
def starts_with(self, prefix):
prefix = prefix.lower()
found_words = []
res = cgaddag.gdg_starts_with(self.gdg, prefix.encode(encoding="ascii"))
tmp = res
while tmp:
word = tmp.contents.str.decode("ascii")
found_words.append(word)
tmp = tmp.contents.next
cgaddag.gdg_destroy_result(res)
return found_words
|
Find all words starting with a prefix.
Args:
prefix: A prefix to be searched for.
Returns:
A list of all words found.
|
juraj-google-style
|
def _DeserializeAttributeContainer(self, container_type, serialized_data):
if not serialized_data:
return None
if self._serializers_profiler:
self._serializers_profiler.StartTiming(container_type)
try:
serialized_string = serialized_data.decode('utf-8')
except UnicodeDecodeError as exception:
raise IOError('Unable to decode serialized data: {0!s}'.format(
exception))
attribute_container = self._serializer.ReadSerialized(serialized_string)
if self._serializers_profiler:
self._serializers_profiler.StopTiming(container_type)
return attribute_container
|
Deserializes an attribute container.
Args:
container_type (str): attribute container type.
serialized_data (bytes): serialized attribute container data.
Returns:
AttributeContainer: attribute container or None.
Raises:
IOError: if the serialized data cannot be decoded.
OSError: if the serialized data cannot be decoded.
|
juraj-google-style
|
def __init__(self, pqc: cirq.Circuit, initializer: tf.keras.initializers.Initializer=tf.keras.initializers.RandomUniform(0, 2), name: Union[None, str]=None):
raw_symbol_names = list(sorted(tfq.util.get_circuit_symbols(pqc)))
symbol_names = tf.constant([str(x) for x in raw_symbol_names], dtype=tf.string)
values = [tf.Variable(initializer(shape=[len(raw_symbol_names)]))]
value_layers = [[]]
super().__init__(tfq.convert_to_tensor([pqc]), pqc.all_qubits(), symbol_names, values, value_layers)
|
Initializes a DirectQuantumCircuit.
Args:
pqc: Representation of a parameterized quantum circuit.
initializer: A `tf.keras.initializers.Initializer` which specifies how to
initialize the values of the parameters in `circuit`. The default
initializer assumes parameters of gates are exponents, so that one full
period is covered by the parameter range 0 to 2.
name: Optional name for the model.
|
github-repos
|
def get_rml(self, rml_def, **kwargs):
if isinstance(rml_def, str):
rml_procs = self.es_defs.get("kds_esRmlProcessor", [])
for item in rml_procs:
if item['name'] == rml_def:
rml_def = item
break
proc_kwargs = {rml_def['subj']: self.subject,
"dataset": self.dataset}
proc_kwargs.update(rml_def['proc_kwargs'])
return rml_def['processor'](**proc_kwargs)
|
returns the rml mapping output for specified mapping
Args:
-----
rml_def: The name of the mapping or a dictionary definition
|
juraj-google-style
|
def get_text_features(self, input_ids=None, attention_mask=None, position_ids=None, token_type_ids=None, output_attentions=None, output_hidden_states=None, return_dict=None):
text_outputs = self.text_model(input_ids=input_ids, attention_mask=attention_mask, position_ids=position_ids, token_type_ids=token_type_ids, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict)
pooled_output = text_outputs[1]
text_features = self.text_projection(pooled_output)
return text_features
|
Returns:
text_features (`tf.Tensor` of shape `(batch_size, output_dim`): The text embeddings obtained by applying
the projection layer to the pooled output of [`TFCLIPTextModel`].
Examples:
```python
>>> from transformers import TFVisionTextDualEncoderModel, AutoTokenizer
>>> model = TFVisionTextDualEncoderModel.from_pretrained("clip-italian/clip-italian", from_pt=True)
>>> tokenizer = AutoTokenizer.from_pretrained("clip-italian/clip-italian")
>>> inputs = tokenizer(["una foto di un gatto", "una foto di un cane"], padding=True, return_tensors="np")
>>> text_features = model.get_text_features(**inputs)
```
|
github-repos
|
def delete(self, resource, force=False, export_only=None, suppress_device_updates=None, timeout=(- 1)):
custom_headers = {'If-Match': '*'}
if ('uri' in resource):
uri = resource['uri']
else:
uri = self._client.build_uri(resource)
if suppress_device_updates:
uri += '?suppressDeviceUpdates=true'
if export_only:
custom_headers['exportOnly'] = True
return self._client.delete(uri, force=force, timeout=timeout, custom_headers=custom_headers)
|
Deletes a managed volume.
Args:
resource (dict):
Object to delete.
force:
If set to true, the operation completes despite any problems with
network connectivity or errors on the resource itself. The default is false.
timeout:
Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation
in OneView; it just stops waiting for its completion.
export_only:
Valid prior to API500. By default, volumes will be deleted from OneView, and storage system.
To delete the volume from OneView only, you must set its value to True.
Setting its value to False has the same behavior as the default behavior.
suppress_device_updates:
Valid API500 onwards. By default, volumes will be deleted from OneView, and storage system.
To delete the volume from OneView only, you must set its value to True.
Setting its value to False has the same behavior as the default behavior.
Returns:
bool: Indicates if the volume was successfully deleted.
|
codesearchnet
|
def _dataset_partition(self, mode, config, params):
if mode != tf.estimator.ModeKeys.TRAIN or not hasattr(config, "tpu_config"):
self._next_partition_id = 0
return 0, 1
phift = config.tpu_config.per_host_input_for_training
if (hasattr(tpu_config.InputPipelineConfig, "BROADCAST") and
phift == tpu_config.InputPipelineConfig.BROADCAST):
return 0, 1
if phift:
num_hosts = (params["context"].num_hosts if "context" in params
else config.tpu_config.num_shards
num_partitions = max(num_hosts, 1)
else:
num_partitions = config.tpu_config.num_shards
partition_id = getattr(self, "_next_partition_id", 0)
self._next_partition_id = partition_id + 1
tf.logging.info("num_partitions = %d partition_id = %d" %
(num_partitions, partition_id))
assert partition_id < num_partitions
return partition_id, num_partitions
|
Which part of the training data to read.
If there are multiple parallel calls to input_fn (multiple TPU hosts),
then we want each one to read from a separate partition of the training
data.
Args:
mode: tf.estimator.ModeKeys
config: RunConfig
params: A dict that contains parameters.
Returns:
partition_id: an integer
num_partitions: an integer
|
juraj-google-style
|
def __init__(self, debug=False):
facility = logging.handlers.SysLogHandler.LOG_DAEMON
self.logger = logger.Logger(
name='google-clock-skew', debug=debug, facility=facility)
self.distro_utils = distro_utils.Utils(debug=debug)
self.watcher = metadata_watcher.MetadataWatcher(logger=self.logger)
try:
with file_utils.LockFile(LOCKFILE):
self.logger.info('Starting Google Clock Skew daemon.')
self.watcher.WatchMetadata(
self.HandleClockSync, metadata_key=self.drift_token,
recursive=False)
except (IOError, OSError) as e:
self.logger.warning(str(e))
|
Constructor.
Args:
debug: bool, True if debug output should write to the console.
|
juraj-google-style
|
def add_user_role(self, user, role):
self.project_service.set_auth(self._token_project)
self.project_service.add_user_role(user, role)
|
Add role to given user.
Args:
user (string): User name.
role (string): Role to assign.
Raises:
requests.HTTPError on failure.
|
juraj-google-style
|
def getDelOps(self, buid):
return (
('prop:del', (buid, self.form.name, self.name, self.storinfo)),
)
|
Get a list of storage operations to delete this property from the buid.
Args:
buid (bytes): The node buid.
Returns:
(tuple): The storage operations
|
juraj-google-style
|
def set_description(self, name, value=None, default=False, disable=False):
string = 'description'
commands = self.command_builder(string, value=value, default=default, disable=disable)
return self.configure_interface(name, commands)
|
Configures the interface description
EosVersion:
4.13.7M
Args:
name (string): The interface identifier. It must be a full
interface name (ie Ethernet, not Et)
value (string): The value to set the description to.
default (boolean): Specifies to default the interface description
disable (boolean): Specifies to negate the interface description
Returns:
True if the operation succeeds otherwise False
|
codesearchnet
|
def GetName(self, number):
value = self._data_type_definition.values_per_number.get(number, None)
if (not value):
return None
return value.name
|
Retrieves the name of an enumeration value by number.
Args:
number (int): number.
Returns:
str: name of the enumeration value or None if no corresponding
enumeration value was found.
|
codesearchnet
|
def ignore_errors(log_warning=False):
def _apply_fn(dataset):
return dataset.ignore_errors(log_warning)
return _apply_fn
|
Creates a `Dataset` from another `Dataset` and silently ignores any errors.
Use this transformation to produce a dataset that contains the same elements
as the input, but silently drops any elements that caused an error. For
example:
```python
dataset = tf.data.Dataset.from_tensor_slices([1., 2., 0., 4.])
# Computing `tf.debugging.check_numerics(1. / 0.)` will raise an
InvalidArgumentError.
dataset = dataset.map(lambda x: tf.debugging.check_numerics(1. / x, "error"))
# Using `ignore_errors()` will drop the element that causes an error.
dataset =
dataset.apply(tf.data.experimental.ignore_errors()) # ==> {1., 0.5, 0.2}
```
Args:
log_warning: (Optional.) A 'tf.bool' scalar indicating whether ignored
errors should be logged to stderr. Defaults to 'False'.
Returns:
A `Dataset` transformation function, which can be passed to
`tf.data.Dataset.apply`.
|
github-repos
|
def timezone(self, timezone=0):
tz_dt = timedelta(hours=timezone)
for segment in self.segments:
for point in segment.points:
point.time = point.time + tz_dt
return self
|
Sets the timezone of the entire track
Args:
timezone (int): Timezone hour delta
|
juraj-google-style
|
def period_start_day(self, value=None):
if value is not None:
try:
value = str(value)
except ValueError:
raise ValueError('value {} need to be of type str '
'for field `period_start_day`'.format(value))
if ',' in value:
raise ValueError('value should not contain a comma '
'for field `period_start_day`')
self._period_start_day = value
|
Corresponds to IDD Field `period_start_day`
Args:
value (str): value for IDD Field `period_start_day`
if `value` is None it will not be checked against the
specification and is assumed to be a missing value
Raises:
ValueError: if `value` is not a valid value
|
juraj-google-style
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.