code stringlengths 20 4.93k | docstring stringlengths 33 1.27k | source stringclasses 3
values |
|---|---|---|
def add_module(self, module_name, module_ui):
m_button = tk.Label(self.module_selection, text=module_name, bg="white", anchor="w")
m_button.grid(column=0, row=len(self.module_selection.winfo_children()), padx=0, pady=0, sticky="W E N S")
self.module_buttons[module_name] = m_button
... | Adds a module to the list
Args:
module_name (str): The name of the module
module_ui: The function to call to create the module's UI | juraj-google-style |
def _PrintExtractionStatusUpdateLinear(self, processing_status):
for worker_status in processing_status.workers_status:
status_line = '{0:s} (PID: {1:d}) - events produced: {2:d} - file: {3:s} - running: {4!s}\n'.format(worker_status.identifier, worker_status.pid, worker_status.number_of_produced_events, wo... | Prints an extraction status update in linear mode.
Args:
processing_status (ProcessingStatus): processing status. | codesearchnet |
def status(self, job_ids):
statuses = []
for job_id in job_ids:
instance = self.client.instances().get(instance=job_id, project=self.project_id, zone=self.zone).execute()
self.resources[job_id]['status'] = translate_table[instance['status']]
statuses.append(t... | Get the status of a list of jobs identified by the job identifiers
returned from the submit request.
Args:
- job_ids (list) : A list of job identifiers
Returns:
- A list of status from ['PENDING', 'RUNNING', 'CANCELLED', 'COMPLETED',
'FAILED', 'TIMEOUT'] corresponding to each job_id in the job_ids list.
Raises:
- Ex... | juraj-google-style |
def _compute_inside_group(df):
inside_group = df.copy()
inside_group['type'] = 'child'
inside_group['variation'] = inside_group['value'] / inside_group[
'value_start']
inside_group.drop(['upperGroup_label', 'insideGroup', 'value_start'],
axis=1, inplace=True)
insid... | Compute inside Group
Args:
df(dataframe):
Returns: Dataframe | juraj-google-style |
def encode(self, builder: expressions.Builder, select_scalars_as_array: bool=True, use_resource_alias: bool=False) -> str:
self._use_resource_alias = use_resource_alias
result = self.visit(builder.node)
if select_scalars_as_array or _fhir_path_data_types.returns_collection(builder.node.return_type):
... | Returns a Standard SQL encoding of a FHIRPath expression.
If select_scalars_as_array is True, the resulting Standard SQL encoding
always returns a top-level `ARRAY`, whose elements are non-`NULL`. Otherwise
the resulting SQL will attempt to return a scalar when possible and only
return an `ARRAY` for actual collection... | github-repos |
def _is_node_return_ended(self, node):
if isinstance(node, astroid.Return):
return True
if isinstance(node, astroid.Call):
try:
funcdef_node = node.func.inferred()[0]
if self._is_function_def_never_returning(funcdef_node):
... | Check if the node ends with an explicit return statement.
Args:
node (astroid.NodeNG): node to be checked.
Returns:
bool: True if the node ends with an explicit statement, False otherwise. | juraj-google-style |
def xw_plus_b_v1(x, weights, biases, name=None):
with ops.name_scope(name, 'xw_plus_b_v1', [x, weights, biases]) as name:
x = ops.convert_to_tensor(x, name='x')
weights = ops.convert_to_tensor(weights, name='weights')
biases = ops.convert_to_tensor(biases, name='biases')
mm = math_op... | Computes matmul(x, weights) + biases.
This is a deprecated version of that will soon be removed.
Args:
x: a 2D tensor. Dimensions typically: batch, in_units
weights: a 2D tensor. Dimensions typically: in_units, out_units
biases: a 1D tensor. Dimensions: out_units
name: A name for the operation (optional). If not ... | github-repos |
def serializable_value(self, obj):
value = self.__get__(obj, obj.__class__)
return self.property.serialize_value(value) | Produce the value as it should be serialized.
Sometimes it is desirable for the serialized value to differ from
the ``__get__`` in order for the ``__get__`` value to appear simpler
for user or developer convenience.
Args:
obj (HasProps) : the object to get the serialized attribute for
Returns:
JSON-like | codesearchnet |
def is_control(input, model_file=None, model_proto=None, name=None):
return _gen_sentencepiece_processor_op.sentencepiece_get_piece_type(
input, model_file=model_file, model_proto=model_proto, name=name,
piece_type=1) | Returns true if input id is control piece.
Args:
input: An arbitrary tensor of int32.
model_file: The sentencepiece model file path.
model_proto: The sentencepiece model serialized proto.
Either `model_file` or `model_proto` must be set.
name: The name argument that is passed to the op function.
Returns:
A tensor of b... | juraj-google-style |
def set_hash_value(self, key, field, value, pipeline=False):
if pipeline:
self._pipeline.hset(key, field, str(value))
else:
self._db.hset(key, field, str(value)) | Set the value of field in a hash stored at key.
Args:
key (str): key (name) of the hash
field (str): Field within the hash to set
value: Value to set
pipeline (bool): True, start a transaction block. Default false. | codesearchnet |
def get_command_from_result(script, result, debug=False):
if (not debug):
command = (((('python waf --run "' + script) + ' ') + ' '.join([('--%s=%s' % (param, value)) for (param, value) in result['params'].items()])) + '"')
else:
command = ((((('python waf --run ' + script) + ' --command-templat... | Return the command that is needed to obtain a certain result.
Args:
params (dict): Dictionary containing parameter: value pairs.
debug (bool): Whether the command should include the debugging
template. | codesearchnet |
async def debug(self, conn_id, name, cmd_args):
device = self._get_property(conn_id, 'device')
retval = None
try:
if name == 'dump_state':
retval = device.dump_state()
elif name == 'restore_state':
state = cmd_args['snapshot']
... | Asynchronously complete a named debug command.
The command name and arguments are passed to the underlying device adapter
and interpreted there.
Args:
conn_id (int): A unique identifer that will refer to this connection
name (string): the name of the debug command we want to invoke
cmd_args (dict): any arguments that... | juraj-google-style |
async def update_flags(self, messages: Sequence[MessageT],
flag_set: FrozenSet[Flag], mode: FlagOp) -> None:
... | Update the permanent flags of each messages.
Args:
messages: The message objects.
flag_set: The set of flags for the update operation.
flag_op: The mode to change the flags. | juraj-google-style |
def parse(self, filepath, content):
try:
parsed = json.loads(content)
except ValueError:
msg = "No JSON object could be decoded from file: {}"
raise SettingsBackendError(msg.format(filepath))
return parsed | Parse opened settings content using JSON parser.
Args:
filepath (str): Settings object, depends from backend
content (str): Settings content from opened file, depends from
backend.
Raises:
boussole.exceptions.SettingsBackendError: If parser can not decode
a valid JSON object.
Returns:
dict: Dictionnary containing pa... | juraj-google-style |
def ParseFileObject(self, parser_mediator, file_object):
scca_file = pyscca.file()
try:
scca_file.open_file_object(file_object)
except IOError as exception:
parser_mediator.ProduceExtractionWarning(
'unable to open file with error: {0!s}'.format(exception))
return
form... | Parses a Windows Prefetch file-like object.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
file_object (dfvfs.FileIO): file-like object. | juraj-google-style |
def export_model(self, export_formats, export_dir=None):
export_dir = (export_dir or self.logdir)
return self._export_model(export_formats, export_dir) | Exports model based on export_formats.
Subclasses should override _export_model() to actually
export model to local directory.
Args:
export_formats (list): List of formats that should be exported.
export_dir (str): Optional dir to place the exported model.
Defaults to self.logdir.
Return:
A dict that maps ExportForm... | codesearchnet |
def map_texture_to_surface(texture, surface):
texture_x, texture_y = texture
surface_h, surface_w = surface.shape
surface_x = np.clip(
np.int32(surface_w * texture_x - 1e-9), 0, surface_w - 1)
surface_y = np.clip(
np.int32(surface_h * texture_y - 1e-9), 0, surface_h - 1)
surfa... | Returns values on a surface for points on a texture.
Args:
texture (texture): the texture to trace over the surface
surface (surface): the surface to trace along
Returns:
an array of surface heights for each point in the
texture. Line separators (i.e. values that are ``nan`` in
the texture) will be ``nan`` in the out... | juraj-google-style |
def _is_definition_section(source):
try:
definitions = textwrap.dedent(source).split('\n', 1)[1].splitlines()
return all(
re.match(r'\s\s+((?!\s\s).+)\s\s+.+', s) for s in definitions)
except IndexError:
return False | Determine if the source is a definition section.
Args:
source: The usage string source that may be a section.
Returns:
True if the source describes a definition section; otherwise, False. | juraj-google-style |
def broadcast_row_partition(self, rp):
if not rp.is_uniform():
return RowPartition.from_row_lengths(self.broadcast_tensor(rp.row_lengths()))
else:
return RowPartition.from_uniform_row_length(rp.uniform_row_length(), nvals=rp.uniform_row_length() * self.dest_nrows(), nrows=self.dest_nrows()) | Return a new shape where the rows are broadcasted.
*--self--->*
| |
rp result
| |
V V
*--------->*
This is equivalent to:
return RowPartition.from_row_lengths(self.broadcast(rp.row_lengths()))
However, if the shape has uniform row length, then that property is
maintained.
Args:
rp: ... | github-repos |
def add_pending(self, panel_obj, hgnc_gene, action, info=None):
valid_actions = ['add', 'delete', 'edit']
if (action not in valid_actions):
raise ValueError('Invalid action {0}'.format(action))
info = (info or {})
pending_action = {'hgnc_id': hgnc_gene['hgnc_id'], 'action': action, 'info': info,... | Add a pending action to a gene panel
Store the pending actions in panel.pending
Args:
panel_obj(dict): The panel that is about to be updated
hgnc_gene(dict)
action(str): choices=['add','delete','edit']
info(dict): additional gene info (disease_associated_transcripts,
reduced_penetrance, mosaicism, database_entry_vers... | codesearchnet |
def embed(self, x):
shape_x = common_layers.shape_list(x)
x_flat = tf.reshape(x, [-1, 1])
c = self.int_to_bit(x_flat, num_bits=self.hparams.z_size, base=2)
shape = common_layers.shape_list(c)
new_shape = shape
new_shape.append(self.hparams.num_blocks)
new_shape.append(int(self.hparams.z... | Embedding function that takes discrete latent and returns embedding.
Args:
x: Input to the discretization bottleneck.
Returns:
Continuous embedding to be passed on to the decoder.
Raises:
ValueError: For unknown or missing arguments. | juraj-google-style |
def download_aspera(self, user, host, silent=False):
aspera_home = os.environ.get('ASPERA_HOME', None)
if (not aspera_home):
raise ValueError('environment variable $ASPERA_HOME not set')
if (not os.path.exists(aspera_home)):
raise ValueError('$ASPERA_HOME directory {} does not exist'.format(... | Download file with Aspera Connect.
For details see the documentation ov Aspera Connect
Args:
user (:obj:`str`): FTP user.
host (:obj:`str`): FTP host. Defaults to "ftp-trace.ncbi.nlm.nih.gov". | codesearchnet |
def build_as_function_and_v1_graph(func: Callable[..., Any]) -> Callable[..., None]:
if tf_inspect.isclass(func):
raise ValueError('`run_in_graph_mode_and_function` only supports test methods.')
@parameterized.named_parameters(('_v1_graph', 'v1_graph'), ('_function', 'function'))
@functools.wraps(f... | Run a test case in v1 graph mode and inside tf.function in eager mode.
WARNING: This decorator can only be used in test cases that statically checks
generated graph. Attempting to evaluate graph or function results via.
session.run() or self.evaluate() will fail.
WARNING: This decorator can only be used for test case... | github-repos |
def _ScheduleTasks(self, storage_writer):
logger.debug('Task scheduler started')
self._status = definitions.STATUS_INDICATOR_RUNNING
event_source_heap = _EventSourceHeap()
self._FillEventSourceHeap(storage_writer, event_source_heap, start_with_first=True)
event_source = event_source_heap.PopEventSou... | Schedules tasks.
Args:
storage_writer (StorageWriter): storage writer for a session storage. | codesearchnet |
def _open_ring_2d(x_size: int, y_size: int, z_coord: int) -> List[Tuple[int, int, int]]:
ret = []
for i in range(y_size
for j in range(1, x_size):
ret.append((j, 2 * i, z_coord))
for j in range(x_size - 1, 0, -1):
ret.append((j, 2 * i + 1, z_coord))
for i in range(y_... | Ring-order of a X by Y mesh, with a fixed Z coordinate.
For example, in a 4x4 mesh, this returns the following order.
0 -- 1 -- 2 -- 3
| | | |
15-- 6 -- 5 -- 4
| | | |
14-- 7 -- 8 -- 9
| | | |
13-- 12-- 11-- 10
Note that chip 0 is not included in the output.
Args:
x_size: An integer repres... | github-repos |
def parse_sv_frequencies(variant):
frequency_keys = [
'clingen_cgh_benignAF',
'clingen_cgh_benign',
'clingen_cgh_pathogenicAF',
'clingen_cgh_pathogenic',
'clingen_ngi',
'clingen_ngiAF',
'swegen',
'swegenAF',
'decipherAF',
'decipher... | Parsing of some custom sv frequencies
These are very specific at the moment, this will hopefully get better over time when the
field of structural variants is more developed.
Args:
variant(cyvcf2.Variant)
Returns:
sv_frequencies(dict) | juraj-google-style |
def has_no_title(self, title, **kwargs):
try:
self.assert_no_title(title, **kwargs)
return True
except ExpectationNotMet:
return False | Checks if the page doesn't have the given title.
Args:
title (str | RegexObject): The string that the title should include.
**kwargs: Arbitrary keyword arguments for :class:`TitleQuery`.
Returns:
bool: Whether it doesn't match. | juraj-google-style |
def namespace_for_prefix(self, prefix):
try:
ni = self.__lookup_prefix(prefix)
except PrefixNotFoundError:
return None
else:
return ni.uri | Get the namespace the given prefix maps to.
Args:
prefix (str): The prefix
Returns:
str: The namespace, or None if the prefix isn't mapped to
anything in this set. | juraj-google-style |
def schema_from_json(self, file_or_path):
if isinstance(file_or_path, io.IOBase):
return self._schema_from_json_file_object(file_or_path)
with open(file_or_path) as file_obj:
return self._schema_from_json_file_object(file_obj) | Takes a file object or file path that contains json that describes
a table schema.
Returns:
List of schema field objects. | codesearchnet |
def video_augmentation(features, hue=False, saturate=False, contrast=False):
(inputs, targets) = (features['inputs'], features['targets'])
in_steps = common_layers.shape_list(inputs)[0]
video = tf.concat((inputs, targets), axis=0)
if hue:
video = tf.image.random_hue(video, max_delta=0.2)
if ... | Augments video with optional hue, saturation and constrast.
Args:
features: dict, with keys "inputs", "targets".
features["inputs"], 4-D Tensor, shape=(THWC)
features["targets"], 4-D Tensor, shape=(THWC)
hue: bool, apply hue_transform.
saturate: bool, apply saturation transform.
contrast: bool, apply constrast transfo... | codesearchnet |
def minimize(self, minimize):
self._minimize = minimize
self._logger.log('debug', 'Minimize set to {}'.format(minimize)) | Configures the ABC to minimize fitness function return value or
derived score
Args:
minimize (bool): if True, minimizes fitness function return value;
if False, minimizes derived score | juraj-google-style |
def dump(o, f):
if (not f.write):
raise TypeError('You can only dump an object to a file descriptor')
d = dumps(o)
f.write(d)
return d | Writes out dict as toml to a file
Args:
o: Object to dump into toml
f: File descriptor where the toml should be stored
Returns:
String containing the toml corresponding to dictionary
Raises:
TypeError: When anything other than file descriptor is passed | codesearchnet |
def get_axis_value(self, axis):
if (self.type != EventType.POINTER_AXIS):
raise AttributeError(_wrong_meth.format(self.type))
return self._libinput.libinput_event_pointer_get_axis_value(self._handle, axis) | Return the axis value of the given axis.
The interpretation of the value depends on the axis. For the two
scrolling axes :attr:`~libinput.constant.PointerAxis.SCROLL_VERTICAL`
and :attr:`~libinput.constant.PointerAxis.SCROLL_HORIZONTAL`, the value
of the event is in relative scroll units, with the positive direction
b... | codesearchnet |
def list_pull_requests(self, username, page, status=None):
request_url = '{}/api/0/user/{}/requests/filed'.format(self.instance, username)
payload = {}
if (username is not None):
payload['username'] = username
if (page is not None):
payload['page'] = page
if (status is not None):
... | List pull-requests filed by user.
Params:
username (string): filters the username of the user whose activity you are interested in.
page (integer): the page requested. Defaults to 1.
status (string): filter the status of pull requests. Default: Open,
can be Closed, Merged, All.
Returns:
list: A list of Pull-Requests ... | codesearchnet |
def find_primitive(self):
(lattice, scaled_positions, numbers) = spglib.find_primitive(self._cell, symprec=self._symprec)
species = [self._unique_species[(i - 1)] for i in numbers]
return Structure(lattice, species, scaled_positions, to_unit_cell=True).get_reduced_structure() | Find a primitive version of the unit cell.
Returns:
A primitive cell in the input cell is searched and returned
as an Structure object. If no primitive cell is found, None is
returned. | codesearchnet |
def _hard_upsample(self, hidden_states, durations):
if hidden_states.size(0) == 1:
hidden_states = torch.repeat_interleave(hidden_states, durations.view(-1), dim=1)
else:
if hidden_states.shape[0] > 1 and self.training:
logger.warning_once('`self.training=True` and you use batching. ... | Repeats the time dimension of each sample in the batch based on the corresponding duration.
Args:
hidden_states (`torch.Tensor` of shape `(batch_size, sequence_length, *)`, *optional*):
The sequence to repeat, where `*` is any number of sequence-specific dimensions including none.
durations (`torch.Tensor` of shape `(... | github-repos |
def _update_inplace(self, new_query_compiler):
old_query_compiler = self._query_compiler
self._query_compiler = new_query_compiler
old_query_compiler.free() | Updates the current DataFrame inplace.
Args:
new_query_compiler: The new QueryCompiler to use to manage the data | juraj-google-style |
def write_config_file(config_instance, appdirs=DEFAULT_APPDIRS,
file_name=DEFAULT_CONFIG_FILENAME):
path = get_config_path(appdirs, file_name)
with open(path, 'w') as fobj:
config_instance.write(fobj)
return config_instance | Write a ConfigParser instance to file at the correct location.
Args:
config_instance: Config instance to safe to file.
appdirs (HamsterAppDirs, optional): ``HamsterAppDirs`` instance storing app/user specific
path information.
file_name (text_type, optional): Name of the config file. Defaults to
``DEFAULT_CONFIG_FILEN... | juraj-google-style |
def _get_corrupted_example(self, x):
corruption_type = self.builder_config.corruption_type
severity = self.builder_config.severity
return {'gaussian_noise': corruptions.gaussian_noise, 'shot_noise': corruptions.shot_noise, 'impulse_noise': corruptions.impulse_noise, 'defocus_blur': corruptions.defocus_blur,... | Return corrupted images.
Args:
x: numpy array, uncorrupted image.
Returns:
numpy array, corrupted images. | codesearchnet |
def cos(times: np.ndarray, amp: complex, freq: float, phase: float=0) -> np.ndarray:
return (amp * np.cos(((((2 * np.pi) * freq) * times) + phase)).astype(np.complex_)) | Continuous cosine wave.
Args:
times: Times to output wave for.
amp: Pulse amplitude.
freq: Pulse frequency, units of 1/dt.
phase: Pulse phase. | codesearchnet |
def CreateUnit(self, parent=None, value=None, bid_amount=None):
unit = {'xsi_type': 'ProductPartition', 'partitionType': 'UNIT'}
if (parent is not None):
unit['parentCriterionId'] = parent['id']
unit['caseValue'] = value
if ((bid_amount is not None) and (bid_amount > 0)):
bidding_str... | Creates a unit node.
Args:
parent: The node that should be this node's parent.
value: The value being partitioned on.
bid_amount: The amount to bid for matching products, in micros.
Returns:
A new unit node. | codesearchnet |
def normalize(code):
if (len(code) == 3):
return code
normalized = translate(code)
if normalized:
return normalized
country = countries.get(code, None)
if country:
return country.alpha3.lower()
return code | Normalize language codes to ISO 639-2. If all conversions fails, return the
`code` as it was given.
Args:
code (str): Language / country code.
Returns:
str: ISO 639-2 country code. | codesearchnet |
def unpack_small_tensors(tower_grads, packing):
if not packing:
return tower_grads
new_tower_grads = []
num_devices = len(tower_grads)
num_packed = len(packing.keys())
for dev_idx, gv_list in enumerate(tower_grads):
new_gv_list = gv_list[num_packed:]
for i in xrange(0, ... | Undo the structure alterations to tower_grads done by pack_small_tensors.
Args:
tower_grads: List of List of (grad, var) tuples.
packing: A dict generated by pack_small_tensors describing the changes
it made to tower_grads.
Returns:
new_tower_grads: identical to tower_grads except that concatentations
of small tensor... | juraj-google-style |
def vcf_records(self, qualified=False):
if qualified:
sample_names = self.qualified_sample_names
else:
sample_names = self.sample_names
for line in self._file_reader.read_lines():
if line.startswith("
continue
yield VcfRec... | Generates parsed VcfRecord objects.
Typically called in a for loop to process each vcf record in a
VcfReader. VcfReader must be opened in advanced and closed when
complete. Skips all headers.
Args:
qualified: When True, sample names are prefixed with file name
Returns:
Parsed VcfRecord
Raises:
StopIteration: when r... | juraj-google-style |
def convert(self, vroot, entry_variables):
self.graph_info = GraphInfo(vroot)
self.entry_variables = entry_variables
cnt = 0
with nn.parameter_scope(self.name):
for t, func in enumerate(self.graph_info.funcs):
if func.name == "BatchNorma... | All functions are replaced with the same `new` function.
Args:
vroot (:obj:`Variable`): NNabla Variable
entry_variables (:obj:`Variable`): Entry variable from which the conversion starts. | juraj-google-style |
def _compute_upper_group(df):
upper_group = df.groupby(['groups']).agg({
'value': sum,
'value_start': sum,
'upperGroup_label': 'first',
'upperGroup_order': 'first'
}).reset_index()
upper_group['type'] = 'parent'
upper_group['variation'] = upper_group['value'] / upper... | Compute upperGroup
Args:
df (Dataframe):
Returns: Dataframe | juraj-google-style |
def CreateBiddingStrategy(client):
bidding_strategy_service = client.GetService(
'BiddingStrategyService', version='v201809')
shared_bidding_strategy = {
'name': 'Maximize Clicks %s' % uuid.uuid4(),
'biddingScheme': {
'xsi_type': 'TargetSpendBiddingScheme',
... | Creates a bidding strategy object.
Args:
client: AdWordsClient the client to run the example with.
Returns:
dict An object representing a bidding strategy. | juraj-google-style |
def apply2(self, func, *args, **kwargs):
ret = func(args[0], self._t, *args[1:], **kwargs)
return LinearWrap(ret) | Apply a function on the wrapped tensor. The tensor
will be the second argument of func.
This is because many symbolic functions
(such as tensorpack's layers) takes 'scope' as the first argument.
Returns:
LinearWrap: ``LinearWrap(func(args[0], self.tensor(), *args[1:], **kwargs))``. | codesearchnet |
def _avro_rows(block, avro_schema):
blockio = six.BytesIO(block.avro_rows.serialized_binary_rows)
while True:
try:
yield fastavro.schemaless_reader(blockio, avro_schema)
except StopIteration:
break | Parse all rows in a stream block.
Args:
block ( \
~google.cloud.bigquery_storage_v1beta1.types.ReadRowsResponse \
):
A block containing Avro bytes to parse into rows.
avro_schema (fastavro.schema):
A parsed Avro schema, used to deserialized the bytes in the
block.
Returns:
Iterable[Mapping]:
A sequence of rows, repre... | juraj-google-style |
def execute_show(args, root_dir):
key = None
if args.get('key'):
key = args['key']
status = command_factory('status')({}, root_dir=root_dir)
if ((key not in status['data']) or (status['data'][key]['status'] != 'running')):
print('No running process with this key, use `log` to... | Print stderr and stdout of the current running process.
Args:
args['watch'] (bool): If True, we open a curses session and tail
the output live in the console.
root_dir (string): The path to the root directory the daemon is running in. | codesearchnet |
def compute_loss(self, model: nn.Module, inputs: dict[str, Union[torch.Tensor, Any]], return_outputs: bool=False, num_items_in_batch: Optional[torch.Tensor]=None):
if (self.label_smoother is not None or self.compute_loss_func is not None) and 'labels' in inputs:
labels = inputs.pop('labels')
else:
... | How the loss is computed by Trainer. By default, all models return the loss in the first element.
Args:
model (`nn.Module`):
The model to compute the loss for.
inputs (`Dict[str, Union[torch.Tensor, Any]]`):
The input data for the model.
return_outputs (`bool`, *optional*, defaults to `False`):
Whether to return the m... | github-repos |
def proxy_num(self, protocol=None):
http_num = len(self.proxies['http'])
https_num = len(self.proxies['https'])
if (protocol == 'http'):
return http_num
elif (protocol == 'https'):
return https_num
else:
return (http_num + https_num) | Get the number of proxies in the pool
Args:
protocol (str, optional): 'http' or 'https' or None. (default None)
Returns:
If protocol is None, return the total number of proxies, otherwise,
return the number of proxies of corresponding protocol. | codesearchnet |
def get_njobs_in_queue(self, username=None):
if (username is None):
username = getpass.getuser()
(njobs, process) = self._get_njobs_in_queue(username=username)
if ((process is not None) and (process.returncode != 0)):
err_msg = ('Error trying to get the number of jobs in the queue' + 'The er... | returns the number of jobs in the queue, probably using subprocess or shutil to
call a command like 'qstat'. returns None when the number of jobs cannot be determined.
Args:
username: (str) the username of the jobs to count (default is to autodetect) | codesearchnet |
def forward(self, hidden_states: torch.Tensor, attention_mask: torch.Tensor, position_embeddings: Optional[torch.Tensor]=None, output_attentions: bool=False):
residual = hidden_states
query = key = self.with_pos_embed(hidden_states, position_embeddings)
hidden_states = self.self_attn(queries=query, keys=key... | Args:
hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
attention_mask (`torch.FloatTensor`): attention mask of size
`(batch, 1, target_len, source_len)` where padding elements are indicated by very large negative
values.
position_embeddings (`torch.FloatTensor`, *optional*)... | github-repos |
def CacheFileSystem(self, path_spec, file_system):
identifier = self._GetFileSystemCacheIdentifier(path_spec)
self._file_system_cache.CacheObject(identifier, file_system) | Caches a file system object based on a path specification.
Args:
path_spec (PathSpec): path specification.
file_system (FileSystem): file system object. | codesearchnet |
def insert_tokenizer_in_auto_module(old_model_patterns: ModelPatterns, new_model_patterns: ModelPatterns):
if old_model_patterns.tokenizer_class is None or new_model_patterns.tokenizer_class is None:
return
with open(TRANSFORMERS_PATH / 'models' / 'auto' / 'tokenization_auto.py', 'r', encoding='utf-8') ... | Add a tokenizer to the relevant mappings in the auto module.
Args:
old_model_patterns (`ModelPatterns`): The patterns for the old model.
new_model_patterns (`ModelPatterns`): The patterns for the new model. | github-repos |
def load_generation_config(gen_config_arg: Union[str, GenerationConfig]) -> GenerationConfig:
if isinstance(gen_config_arg, GenerationConfig):
gen_config = deepcopy(gen_config_arg)
else:
pretrained_model_name = Path(gen_config_arg) if isinstance(gen_config_arg, str) else gen_config_arg
c... | Loads a `~generation.GenerationConfig` from the `Seq2SeqTrainingArguments.generation_config` arguments.
Args:
gen_config_arg (`str` or [`~generation.GenerationConfig]`):
`Seq2SeqTrainingArguments.generation_config` argument.
Returns:
A `~generation.GenerationConfig`. | github-repos |
def from_linearized(first, second, intersections):
(s, t, success) = segment_intersection(first.start_node, first.end_node, second.start_node, second.end_node)
bad_parameters = False
if success:
if (not (_helpers.in_interval(s, 0.0, 1.0) and _helpers.in_interval(t, 0.0, 1.0))):
bad_param... | Determine curve-curve intersection from pair of linearizations.
.. note::
This assumes that at least one of ``first`` and ``second`` is
not a line. The line-line case should be handled "early"
by :func:`check_lines`.
.. note::
This assumes the caller has verified that the bounding boxes
for ``first`` and ``second``... | codesearchnet |
def transform(self, path):
if ((path is None) or (not path)):
return None
obj_parent_modules = path.split('.')
objects = [obj_parent_modules.pop((- 1))]
while True:
try:
parent_module_path = '.'.join(obj_parent_modules)
parent_module = importlib.import_module(pare... | Transform a path into an actual Python object.
The path can be arbitrary long. You can pass the path to a package,
a module, a class, a function or a global variable, as deep as you
want, as long as the deepest module is importable through
``importlib.import_module`` and each object is obtainable through
the ``getattr... | codesearchnet |
def list_leases(self, uuid=None):
try:
lease_files = os.listdir(self.path)
except OSError as e:
raise_from(LagoSubnetLeaseBadPermissionsException(self.path, e.strerror), e)
leases = [self.create_lease_object_from_idx(lease_file.split('.')[0]) for lease_file in lease_files if (lease_file != L... | List current subnet leases
Args:
uuid(str): Filter the leases by uuid
Returns:
list of :class:~Lease: current leases | codesearchnet |
async def download_cot_artifact(chain, task_id, path):
link = chain.get_link(task_id)
log.debug('Verifying {} is in {} cot artifacts...'.format(path, task_id))
if (not link.cot):
log.warning('Chain of Trust for "{}" in {} does not exist. See above log for more details. Skipping download of this arti... | Download an artifact and verify its SHA against the chain of trust.
Args:
chain (ChainOfTrust): the chain of trust object
task_id (str): the task ID to download from
path (str): the relative path to the artifact to download
Returns:
str: the full path of the downloaded artifact
Raises:
CoTError: on failure. | codesearchnet |
def _format_line(headers, fields):
assert len(fields) == len(headers), (fields, headers)
fields = ["%2.4f" % field if isinstance(field, float) else str(field)
for field in fields]
return ' '.join(' ' * max(0, len(header) - len(field)) + field
for (header, field) in zip(headers, ... | Format a line of a table.
Arguments:
headers: A list of strings that are used as the table headers.
fields: A list of the same length as `headers` where `fields[i]` is
the entry for `headers[i]` in this row. Elements can be of
arbitrary types. Pass `headers` to print the header row.
Returns:
A pretty string. | juraj-google-style |
def eig_one_step(current_vector, learning_rate, vector_prod_fn):
grad = 2*vector_prod_fn(current_vector)
current_objective = tf.reshape(tf.matmul(tf.transpose(current_vector),
grad) / 2., shape=())
grad = grad - current_vector*tf.matmul(tf.transpose(cu... | Function that performs one step of gd (variant) for min eigen value.
Args:
current_vector: current estimate of the eigen vector with minimum eigen
value.
learning_rate: learning rate.
vector_prod_fn: function which returns product H*x, where H is a matrix for
which we computing eigenvector.
Returns:
updated vector af... | juraj-google-style |
def sg_regularizer_loss(scale=1.0):
return (scale * tf.reduce_mean(tf.get_collection(tf.GraphKeys.REGULARIZATION_LOSSES))) | r""" Get regularizer losss
Args:
scale: A scalar. A weight applied to regularizer loss | codesearchnet |
def RegisterDefinition(self, artifact_definition):
artifact_definition_name = artifact_definition.name.lower()
if artifact_definition_name in self._artifact_definitions:
raise KeyError(
'Artifact definition already set for name: {0:s}.'.format(
artifact_definition.name))
... | Registers an artifact definition.
Artifact definitions are identified based on their lower case name.
Args:
artifact_definition (ArtifactDefinition): an artifact definition.
Raises:
KeyError: if artifact definition is already set for the corresponding
name. | juraj-google-style |
def __init__(self, unicodeHexValue, block):
if unicodeHexValue < 0 or unicodeHexValue > 0x10FFFF:
raise (ValueError, "numeric value outside Unicode range")
self.unicodeHexValue = unicodeHexValue
self.chr = chr(self.unicodeHexValue)
self.name = unicodedata.na... | Set up a unicode character.
Arguments:
unicodeHexValue -- an integer that should correspond to a
Unicode code point.
block -- the CharacterBlock this character belongs to.
Raises:
ValueError -- if unicodeHexValue is not a valid code point. | juraj-google-style |
def list_json_files(directory, recursive=False):
json_files = []
for (top, dirs, files) in os.walk(directory):
dirs.sort()
paths = (os.path.join(top, f) for f in sorted(files))
json_files.extend((x for x in paths if is_json(x)))
if (not recursive):
break
return js... | Return a list of file paths for JSON files within `directory`.
Args:
directory: A path to a directory.
recursive: If ``True``, this function will descend into all
subdirectories.
Returns:
A list of JSON file paths directly under `directory`. | codesearchnet |
def run(self):
accounts = list(AWSAccount.get_all(include_disabled=False).values())
for account in accounts:
self.log.debug('Updating VPC Flow Logs for {}'.format(account))
self.session = get_aws_session(account)
role_arn = self.confirm_iam_role(account)
for aws_region in AWS_REG... | Main entry point for the auditor worker.
Returns:
`None` | codesearchnet |
def multiply(x1, x2, output_shape=None, name=None):
if (not isinstance(x2, Tensor)):
return ScalarMultiplyOperation(x1, x2).outputs[0]
with tf.name_scope(name, default_name='mul'):
(x1, x2) = binary_arguments_to_tensors(x1, x2)
return einsum([x1, x2], output_shape=_infer_binary_broadcast... | Binary multiplication with broadcasting.
Args:
x1: a Tensor
x2: a Tensor
output_shape: an optional Shape
name: an optional string
Returns:
a Tensor | codesearchnet |
def relu(x):
if any_symbolic_tensors((x,)):
return Relu().symbolic_call(x)
return backend.nn.relu(x) | Rectified linear unit activation function.
It is defined as `f(x) = max(0, x)`.
Args:
x: Input tensor.
Returns:
A tensor with the same shape as `x`.
Example:
>>> x1 = keras.ops.convert_to_tensor([-1.0, 0.0, 1.0, 0.2])
>>> keras.ops.relu(x1)
array([0.0, 0.0, 1.0, 0.2], dtype=float32) | github-repos |
def replace_characters(self, text, characters, replacement=''):
if (not characters):
return text
characters = ''.join(sorted(characters))
if (characters in self._characters_regexes):
characters_regex = self._characters_regexes[characters]
else:
characters_regex = re.compile(('[%s... | Remove characters from text.
Removes custom characters from input text or replaces them
with a string if specified.
Args:
text: The text to be processed.
characters: Characters that will be replaced.
replacement: New text that will replace the custom characters.
Returns:
The text without the given characters. | codesearchnet |
def regroup(values, wrap_class=values_lib.PerReplica, always_wrap=False):
v0 = values[0]
if isinstance(v0, list):
for v in values[1:]:
assert isinstance(v, list)
assert len(v) == len(v0), 'len(v) == %d, len(v0) == %d, v: %s, v0: %s' % (len(v), len(v0), v, v0)
return [regr... | Makes a nest per-replica into a nest of PerReplica/Mirrored values.
Args:
values: Values to regroup
wrap_class: Class that `values` be wrapped in.
always_wrap: Always wrap the `values` in `wrap_class` even if the values
are the same except for DistributeVariable.
Returns:
Wrapped `values`. | github-repos |
def authenticate(self, username, password):
if self.config.get('LDAP_BIND_DIRECT_CREDENTIALS'):
result = self.authenticate_direct_credentials(username, password)
elif not self.config.get('LDAP_ALWAYS_SEARCH_BIND') and \
self.config.get('LDAP_USER_RDN_ATTR') == \
... | An abstracted authentication method. Decides whether to perform a
direct bind or a search bind based upon the login attribute configured
in the config.
Args:
username (str): Username of the user to bind
password (str): User's password to bind with.
Returns:
AuthenticationResponse | juraj-google-style |
def get_metrics_for_resource(access_token, subscription_id, resource_group, resource_provider, resource_type, resource_name):
endpoint = ''.join([get_rm_endpoint(), '/subscriptions/', subscription_id, '/resourceGroups/', resource_group, '/providers/', resource_provider, '/', resource_type, '/', resource_name, '/pro... | Get the monitoring metrics for a resource.
Args:
access_token (str): A valid Azure authentication token.
subscription_id (str): Azure subscription id.
resource_group (str): Azure resource group name.
resource_type (str): Type of resource.
resource_name (str): Name of resource.
Returns:
HTTP response. JSON body of res... | codesearchnet |
def get_posts(self, num=None, tag=None, private=False):
posts = self.posts
if not private:
posts = [post for post in posts if post.public]
if tag:
posts = [post for post in posts if tag in post.tags]
if num:
return posts[:num]
return posts | Get all the posts added to the blog.
Args:
num (int): Optional. If provided, only return N posts (sorted by date,
most recent first).
tag (Tag): Optional. If provided, only return posts that have a
specific tag.
private (bool): By default (if False), private posts are not included.
If set to True, private posts will a... | juraj-google-style |
def load_steps(working_dir=None, steps_dir=None, step_file=None,
step_list=None):
if steps_dir is not None:
step_files = glob.glob(os.path.join(steps_dir, '*.cwl'))
elif step_file is not None:
step_files = [step_file]
elif step_list is not None:
step_files = []
... | Return a dictionary containing Steps read from file.
Args:
steps_dir (str, optional): path to directory containing CWL files.
step_file (str, optional): path or http(s) url to a single CWL file.
step_list (list, optional): a list of directories, urls or local file
paths to CWL files or directories containing CWL files... | juraj-google-style |
def moveRel(xOffset=None, yOffset=None, duration=0.0, tween=linear, pause=None, _pause=True):
_failSafeCheck()
(xOffset, yOffset) = _unpackXY(xOffset, yOffset)
_mouseMoveDrag('move', None, None, xOffset, yOffset, duration, tween)
_autoPause(pause, _pause) | Moves the mouse cursor to a point on the screen, relative to its current
position.
The x and y parameters detail where the mouse event happens. If None, the
current mouse position is used. If a float value, it is rounded down. If
outside the boundaries of the screen, the event happens at edge of the
screen.
Args:
x (... | codesearchnet |
def Kdp(scatterer):
if (scatterer.thet0 != scatterer.thet) or \
(scatterer.phi0 != scatterer.phi):
raise ValueError("A forward scattering geometry is needed to " + \
"compute the specific differential phase.")
S = scatterer.get_S()
return 1e-3 * (180.0/np.pi) * sca... | Specific differential phase (K_dp) for the current setup.
Args:
scatterer: a Scatterer instance.
Returns:
K_dp [deg/km].
NOTE: This only returns the correct value if the particle diameter and
wavelength are given in [mm]. The scatterer object should be set to
forward scattering geometry before calling this function. | juraj-google-style |
def _ircounts2radiance(counts, scale, offset):
rad = ((counts - offset) / scale)
return rad.clip(min=0) | Convert IR counts to radiance
Reference: [IR].
Args:
counts: Raw detector counts
scale: Scale [mW-1 m2 cm sr]
offset: Offset [1]
Returns:
Radiance [mW m-2 cm-1 sr-1] | codesearchnet |
def random_hermitian_matrix(num_qubits):
dim = 2 ** num_qubits
val_range = 2
random_real = tf.cast(tf.random.uniform([dim, dim], -val_range, val_range), tf.complex128)
random_imag = 1j * tf.cast(tf.random.uniform([dim, dim], -val_range, val_range), tf.complex128)
random_matrix = random_real + random... | Returns a random Hermitian matrix.
Uses the property that A + A* is Hermitian for any matrix A.
Args:
num_qubits: Number of qubits on which the matrix acts. | github-repos |
def select_char_code_table(self, table):
tables = {'standard': 0,
'eastern european': 1,
'western european': 2,
'spare': 3
}
if table in tables:
self.send(chr(27)+'t'+chr(tables[table]))
else:
... | Select character code table, from tree built in ones.
Args:
table: The desired character code table. Choose from 'standard', 'eastern european', 'western european', and 'spare'
Returns:
None
Raises:
RuntimeError: Invalid chartable. | juraj-google-style |
def mols_to_file(mols, path):
with open(path, 'w') as f:
f.write(mols_to_text(mols)) | Save molecules to the SDFile format file
Args:
mols: list of molecule objects
path: file path to save | codesearchnet |
def create(labels=None, **kw):
if labels is not None:
kw[u'labels'] = encoding.PyValueToMessage(MetricValue.LabelsValue,
labels)
return MetricValue(**kw) | Constructs a new metric value.
This acts as an alternate to MetricValue constructor which
simplifies specification of labels. Rather than having to create
a MetricValue.Labels instance, all that's necessary to specify the
required string.
Args:
labels (dict([string, [string]]):
**kw: any other valid keyword args val... | juraj-google-style |
def __init__(self, batch_env, step, is_training, should_log, config):
self._batch_env = batch_env
self._step = step
self._is_training = is_training
self._should_log = should_log
self._config = config
self._observ_filter = parts.StreamingNormalize(
self._batch_env.observ[0], center=T... | Create an instance of the PPO algorithm.
Args:
batch_env: In-graph batch environment.
step: Integer tensor holding the current training step.
is_training: Boolean tensor for whether the algorithm should train.
should_log: Boolean tensor for whether summaries should be returned.
config: Object containing the agent conf... | juraj-google-style |
def __init__(self, filename, content_generator=None, content_length=None):
precondition.AssertType(filename, Text)
self.filename = filename
self.content_length = content_length
if content_generator is None:
raise ValueError("content_generator can't be None")
self.content_generator = cont... | ApiBinaryStream constructor.
Args:
filename: A file name to be used by the browser when user downloads the
file.
content_generator: A generator that yields byte chunks (of any size) to
be streamed to the user.
content_length: The length of the stream, if known upfront.
Raises:
ValueError: if content_generator is None... | juraj-google-style |
def _create_w_objective(m, X, R):
genes, clusters = m.shape
cells = X.shape[1]
R1 = R.reshape((genes, 1)).dot(np.ones((1, cells)))
def objective(w):
w = w.reshape((m.shape[1], X.shape[1]))
d = m.dot(w)+eps
return np.sum((X + R1)*np.log(d + R1) - X*np.log(d)... | Creates an objective function and its derivative for W, given M and X (data)
Args:
m (array): genes x clusters
X (array): genes x cells
R (array): 1 x genes | juraj-google-style |
def all_distances(coords1, coords2):
c1 = np.array(coords1)
c2 = np.array(coords2)
z = (c1[:, None, :] - c2[None, :, :]) ** 2
return np.sum(z, axis=-1) ** 0.5 | Returns the distances between two lists of coordinates
Args:
coords1: First set of cartesian coordinates.
coords2: Second set of cartesian coordinates.
Returns:
2d array of cartesian distances. E.g the distance between
coords1[i] and coords2[j] is distances[i,j] | juraj-google-style |
def write_index(self, overwrite: bool=False, mock: bool=False) -> None:
write_if_allowed(self.index_filename, self.index_content(), overwrite=overwrite, mock=mock) | Writes the index file, if permitted.
Args:
overwrite: allow existing files to be overwritten?
mock: pretend to write, but don't | codesearchnet |
def tournament_number2name(self, number):
tournaments = self.get_tournaments()
d = {t['tournament']: t['name'] for t in tournaments}
return d.get(number, None) | Translate tournament number to tournament name.
Args:
number (int): tournament number to translate
Returns:
name (str): name of the tournament or `None` if unknown.
Examples:
>>> NumerAPI().tournament_number2name(4)
'delta'
>>> NumerAPI().tournament_number2name(99)
None | juraj-google-style |
def build_ellipse(X, Y):
x_mean = np.mean(X)
y_mean = np.mean(Y)
cov_matrix = np.cov(np.vstack((X, Y)))
(U, s, V) = linalg.svd(cov_matrix, full_matrices=False)
chi_95 = np.sqrt(4.61)
width = ((np.sqrt(cov_matrix[0][0]) * chi_95) * 2)
height = ((np.sqrt(cov_matrix[1][1]) * chi_95) * 2)
ei... | Construct ellipse coordinates from two arrays of numbers.
Args:
X (1D array_like)
Y (1D array_like)
Returns:
float: The mean of `X`.
float: The mean of `Y`.
float: The width of the ellipse.
float: The height of the ellipse.
float: The angle of orientation of the ellipse. | codesearchnet |
def record(*fields):
@six.add_metaclass(_RecordMetaClass)
class RecordType(object):
_record_sentinel = True
_record_fields = fields
return RecordType | Constructs a type that can be extended to create immutable, value types.
Examples:
A typical declaration looks like::
class MyRecord(record('a', ('b', 1))):
pass
The above would make a sub-class of ``collections.namedtuple`` that was named ``MyRecord`` with
a constructor that had the ``b`` field set to 1 by default.... | codesearchnet |
def remove_site(name):
current_sites = list_sites()
if name not in current_sites:
log.debug('Site already absent: %s', name)
return True
ps_cmd = ['Remove-WebSite', '-Name', r"'{0}'".format(name)]
cmd_ret = _srvmgr(ps_cmd)
if cmd_ret['retcode'] != 0:
msg = 'Unable to... | Delete a website from IIS.
Args:
name (str): The IIS site name.
Returns:
bool: True if successful, otherwise False
.. note::
This will not remove the application pool used by the site.
CLI Example:
.. code-block:: bash
salt '*' win_iis.remove_site name='My Test Site' | juraj-google-style |
def get_likelihood(self, uni_matrix):
uni_dim = uni_matrix.shape[1]
num_edge = len(self.edges)
values = np.zeros([1, num_edge])
new_uni_matrix = np.empty([uni_dim, uni_dim])
for i in range(num_edge):
edge = self.edges[i]
value, left_u, right_u = ... | Compute likelihood of the tree given an U matrix.
Args:
uni_matrix(numpy.array): univariate matrix to evaluate likelihood on.
Returns:
tuple[float, numpy.array]:
likelihood of the current tree, next level conditional univariate matrix | juraj-google-style |
def updateParams(self, newvalues):
for (param, value) in newvalues.items():
if param not in self.model.freeparams:
raise RuntimeError("Can't handle param: {0}".format(
param))
if newvalues:
self.model.updateParams(newvalues)
... | Update model parameters and re-compute likelihoods.
This method is the **only** acceptable way to update model
parameters. The likelihood is re-computed as needed
by this method.
Args:
`newvalues` (dict)
A dictionary keyed by param name and with value as new
value to set. Each parameter name must either be a
valid mo... | juraj-google-style |
class ByteRewriter:
LEAF = '[LEAF]'
def __init__(self, rewriting_rules: Union[str, Dict[str, str]]):
if isinstance(rewriting_rules, str):
with open(rewriting_rules, 'r') as f:
rewriting_rules = json.load(f)
elif not isinstance(rewriting_rules, dict):
rais... | Byte rewriter class for MyT5 tokenizer.
This class is used to rewrite bytes using a hash tree. The hash tree is constructed from a set of rewriting rules.
Args:
rewriting_rules (`str` or `Dict[str, str]`):
A path to a json file containing the rewriting rules or a dictionary containing the rewriting rules. | github-repos |
def load_compositors(self, sensor_names):
comps = {}
mods = {}
for sensor_name in sensor_names:
if (sensor_name not in self.compositors):
self.load_sensor_composites(sensor_name)
if (sensor_name in self.compositors):
comps[sensor_name] = DatasetDict(self.compositors[s... | Load all compositor configs for the provided sensors.
Args:
sensor_names (list of strings): Sensor names that have matching
``sensor_name.yaml`` config files.
Returns:
(comps, mods): Where `comps` is a dictionary:
sensor_name -> composite ID -> compositor object
And `mods` is a dictionary:
sensor_name -> modifier ... | codesearchnet |
def DeleteSignedBinary(binary_urn,
token = None):
if _ShouldUseLegacyDatastore():
try:
aff4.FACTORY.Open(
binary_urn, aff4_type=aff4.AFF4Stream, mode="r", token=token)
except aff4.InstantiationError:
raise SignedBinaryNotFoundError(binary_urn)
aff4.FACTORY.D... | Deletes the binary with the given urn from the datastore.
Args:
binary_urn: RDFURN that serves as a unique identifier for the binary.
token: ACL token to use with the legacy (non-relational) datastore.
Raises:
SignedBinaryNotFoundError: If the signed binary does not exist. | juraj-google-style |
def appliance_device_snmp_v3_trap_destinations(self):
if (not self.__appliance_device_snmp_v3_trap_destinations):
self.__appliance_device_snmp_v3_trap_destinations = ApplianceDeviceSNMPv3TrapDestinations(self.__connection)
return self.__appliance_device_snmp_v3_trap_destinations | Gets the ApplianceDeviceSNMPv3TrapDestinations API client.
Returns:
ApplianceDeviceSNMPv3TrapDestinations: | codesearchnet |
def mark_flags_as_mutual_exclusive(flag_names, required=False, flag_values=_flagvalues.FLAGS):
for flag_name in flag_names:
if (flag_values[flag_name].default is not None):
warnings.warn('Flag --{} has a non-None default value. That does not make sense with mark_flags_as_mutual_exclusive, which ... | Ensures that only one flag among flag_names is not None.
Important note: This validator checks if flag values are None, and it does not
distinguish between default and explicit values. Therefore, this validator
does not make sense when applied to flags with default values other than None,
including other false values ... | codesearchnet |
def __init__(self, client=None, workingdir='/workingdir'):
self.client = self.connect_to_docker(client)
self.default_wdir = workingdir
self.hostname = self.client.base_url | Initialization:
Args:
client (docker.Client): a docker-py client. If not passed, we will try to create the
client from the job's environmental varaibles
workingdir (str): default working directory to create in the containers | juraj-google-style |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.