code
stringlengths 20
4.93k
| docstring
stringlengths 33
1.27k
| source
stringclasses 3
values |
---|---|---|
def extract_tendency_grid(self, model_grid):
var_name = model_grid.variable + "-tendency"
self.attributes[var_name] = []
timesteps = np.arange(self.start_time, self.end_time + 1)
for ti, t in enumerate(timesteps):
t_index = t - model_grid.start_hour
self.attributes[var_name].append(
model_grid.data[t_index, self.i[ti], self.j[ti]] - model_grid.data[t_index - 1, self.i[ti], self.j[ti]]
)
|
Extracts the difference in model outputs
Args:
model_grid: ModelOutput or ModelGrid object.
|
juraj-google-style
|
def get(self, key, default=None):
if key in self.__cli:
return self.__cli[key]
if key in self.__config:
return self.__config.get(key)
if key in self.__defaults:
return self.__defaults.get(key)
return default
|
Get the value for `key`.
Gives priority to command-line overrides.
Args:
key: str, the key to get the value for.
Returns:
object: The value for `key`
|
juraj-google-style
|
def _calibrate_vis(radiance, k):
logger.debug('Calibrating to reflectance')
refl = ((100 * k) * radiance)
return refl.clip(min=0)
|
Convert VIS radiance to reflectance
Note: Angle of incident radiation and annual variation of the
earth-sun distance is not taken into account. A value of 100%
corresponds to the radiance of a perfectly reflecting diffuse surface
illuminated at normal incidence when the sun is at its annual-average
distance from the Earth.
TODO: Take angle of incident radiation (cos sza) and annual variation
of the earth-sun distance into account.
Reference: [VIS]
Args:
radiance: Radiance [mW m-2 cm-1 sr-1]
k: pi / H, where H is the solar spectral irradiance at
annual-average sun-earth distance, averaged over the spectral
response function of the detector). Units of k: [m2 um sr W-1]
Returns:
Reflectance [%]
|
codesearchnet
|
def transfer(self, rights_assignment_data=None, *, from_user, to_user, rights_assignment_format='jsonld'):
rights_assignment = RightsAssignment.from_data((rights_assignment_data or {}), plugin=self.plugin)
transfer_payload = rights_assignment._to_format(data_format=rights_assignment_format)
transfer_id = super().transfer(transfer_payload, from_user=from_user, to_user=to_user)
rights_assignment.persist_id = transfer_id
return rights_assignment
|
Transfer this Right to another owner on the backing
persistence layer.
Args:
rights_assignment_data (dict): Model data for the resulting
:class:`~.RightsAssignment`
from_user (any, keyword): A user based on the model specified
by the persistence layer
to_user (any, keyword): A user based on the model specified
by the persistence layer
rights_assignment_format (str, keyword, optional): Data
format of the created entity; must be one of:
- 'jsonld' (default)
- 'json'
- 'ipld'
Returns:
:class:`~.RightsAssignment`: The RightsAssignment entity
created from this transfer
Raises:
See :meth:`~.TransferrableEntity.transfer`
|
codesearchnet
|
def export(self, last_checkpoint, output_dir):
logging.info('Exporting prediction graph to %s', output_dir)
with tf.Session(graph=tf.Graph()) as sess:
inputs, outputs = self.build_prediction_graph()
signature_def_map = {
'serving_default': signature_def_utils.predict_signature_def(inputs, outputs)
}
init_op = tf.global_variables_initializer()
sess.run(init_op)
self.restore_from_checkpoint(sess, self.inception_checkpoint_file,
last_checkpoint)
init_op_serving = control_flow_ops.group(
variables.local_variables_initializer(),
tf.tables_initializer())
builder = saved_model_builder.SavedModelBuilder(output_dir)
builder.add_meta_graph_and_variables(
sess, [tag_constants.SERVING],
signature_def_map=signature_def_map,
legacy_init_op=init_op_serving)
builder.save(False)
|
Builds a prediction graph and xports the model.
Args:
last_checkpoint: Path to the latest checkpoint file from training.
output_dir: Path to the folder to be used to output the model.
|
juraj-google-style
|
def get_absl_log_prefix(record):
created_tuple = time.localtime(record.created)
created_microsecond = int(((record.created % 1.0) * 1000000.0))
critical_prefix = ''
level = record.levelno
if _is_non_absl_fatal_record(record):
level = logging.ERROR
critical_prefix = _CRITICAL_PREFIX
severity = converter.get_initial_for_level(level)
return ('%c%02d%02d %02d:%02d:%02d.%06d %5d %s:%d] %s' % (severity, created_tuple.tm_mon, created_tuple.tm_mday, created_tuple.tm_hour, created_tuple.tm_min, created_tuple.tm_sec, created_microsecond, _get_thread_id(), record.filename, record.lineno, critical_prefix))
|
Returns the absl log prefix for the log record.
Args:
record: logging.LogRecord, the record to get prefix for.
|
codesearchnet
|
def fibo(max_value=None):
a = 1
b = 1
while True:
if max_value is None or a < max_value:
yield a
a, b = b, a + b
else:
yield max_value
|
Generator for fibonaccial decay.
Args:
max_value: The maximum value to yield. Once the value in the
true fibonacci sequence exceeds this, the value
of max_value will forever after be yielded.
|
juraj-google-style
|
def flux_randomization(model, threshold, tfba, solver):
optimize = {}
for reaction_id in model.reactions:
if model.is_reversible(reaction_id):
optimize[reaction_id] = 2*random.random() - 1.0
else:
optimize[reaction_id] = random.random()
fba = _get_fba_problem(model, tfba, solver)
for reaction_id, value in iteritems(threshold):
fba.prob.add_linear_constraints(fba.get_flux_var(reaction_id) >= value)
fba.maximize(optimize)
for reaction_id in model.reactions:
yield reaction_id, fba.get_flux(reaction_id)
|
Find a random flux solution on the boundary of the solution space.
The reactions in the threshold dictionary are constrained with the
associated lower bound.
Args:
model: MetabolicModel to solve.
threshold: dict of additional lower bounds on reaction fluxes.
tfba: If True enable thermodynamic constraints.
solver: LP solver instance to use.
Returns:
An iterator of reaction ID and reaction flux pairs.
|
juraj-google-style
|
def match_objects(self, set_a, set_b, time_a, time_b):
costs = self.cost_matrix(set_a, set_b, time_a, time_b) * 100
min_row_costs = costs.min(axis=1)
min_col_costs = costs.min(axis=0)
good_rows = np.where(min_row_costs < 100)[0]
good_cols = np.where(min_col_costs < 100)[0]
assignments = []
if len(good_rows) > 0 and len(good_cols) > 0:
munk = Munkres()
initial_assignments = munk.compute(costs[tuple(np.meshgrid(good_rows, good_cols, indexing='ij'))].tolist())
initial_assignments = [(good_rows[x[0]], good_cols[x[1]]) for x in initial_assignments]
for a in initial_assignments:
if costs[a[0], a[1]] < 100:
assignments.append(a)
return assignments
|
Match two sets of objects at particular times.
Args:
set_a: list of STObjects
set_b: list of STObjects
time_a: time at which set_a is being evaluated for matching
time_b: time at which set_b is being evaluated for matching
Returns:
List of tuples containing (set_a index, set_b index) for each match
|
juraj-google-style
|
def __init__(self, port_no=None, queue_id=None, tx_bytes=None,
tx_packets=None, tx_errors=None):
super().__init__()
self.port_no = port_no
self.queue_id = queue_id
self.tx_bytes = tx_bytes
self.tx_packets = tx_packets
self.tx_errors = tx_errors
|
Create a QueueStats with the optional parameters below.
Args:
port_no (:class:`int`, :class:`~pyof.v0x01.common.phy_port.Port`):
Port Number.
queue_id (int): Queue ID.
tx_bytes (int): Number of transmitted bytes.
tx_packets (int): Number of transmitted packets.
tx_errors (int): Number of packets dropped due to overrun.
|
juraj-google-style
|
def VerifyStructure(self, parser_mediator, line):
self._last_month = 0
self._year_use = parser_mediator.GetEstimatedYear()
try:
structure = self.FIREWALL_LINE.parseString(line)
except pyparsing.ParseException as exception:
logger.debug((
'Unable to parse file as a Mac AppFirewall log file with error: '
'{0!s}').format(exception))
return False
if structure.action != 'creating /var/log/appfirewall.log':
logger.debug(
'Not a Mac AppFirewall log file, invalid action: {0!s}'.format(
structure.action))
return False
if structure.status != 'Error':
logger.debug(
'Not a Mac AppFirewall log file, invalid status: {0!s}'.format(
structure.status))
return False
time_elements_tuple = self._GetTimeElementsTuple(structure)
try:
dfdatetime_time_elements.TimeElements(
time_elements_tuple=time_elements_tuple)
except ValueError:
logger.debug((
'Not a Mac AppFirewall log file, invalid date and time: '
'{0!s}').format(structure.date_time))
return False
self._last_month = time_elements_tuple[1]
return True
|
Verify that this file is a Mac AppFirewall log file.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
line (str): line from a text file.
Returns:
bool: True if the line is in the expected format, False if not.
|
juraj-google-style
|
def save(self, filename):
if filename is None:
filename = self.filename('.b26s')
with open(filename, 'w') as outfile:
outfile.write(pickle.dumps(self.__dict__))
|
saves the instance of the script to a file using pickle
Args:
filename: target filename
|
juraj-google-style
|
def add(x1, x2, output_shape=None, name=None):
output_shape = convert_to_shape(output_shape)
if not isinstance(x2, Tensor):
return ScalarAddOperation(x1, x2).outputs[0]
with tf.name_scope(name, default_name="add"):
x1, x2 = binary_arguments_to_tensors(x1, x2)
return AddOperation(
x1, x2, output_shape=_infer_binary_broadcast_shape(
x1.shape, x2.shape, output_shape)).outputs[0]
|
Binary addition with broadcsting.
Args:
x1: a Tensor
x2: a Tensor
output_shape: an optional Shape
name: an optional string
Returns:
a Tensor
|
juraj-google-style
|
def search_user_directory(self, term: str) -> List[User]:
response = self.api._send(
'POST',
'/user_directory/search',
{
'search_term': term,
},
)
try:
return [
User(self.api, _user['user_id'], _user['display_name'])
for _user in response['results']
]
except KeyError:
return []
|
Search user directory for a given term, returning a list of users
Args:
term: term to be searched for
Returns:
user_list: list of users returned by server-side search
|
juraj-google-style
|
def _process_thread(self, client):
system_type = client.data.os_info.system
print('System type: {0:s}'.format(system_type))
artifact_list = []
if self.artifacts:
print('Artifacts to be collected: {0!s}'.format(self.artifacts))
artifact_list = self.artifacts
else:
default_artifacts = self.artifact_registry.get(system_type, None)
if default_artifacts:
print('Collecting default artifacts for {0:s}: {1:s}'.format(system_type, ', '.join(default_artifacts)))
artifact_list.extend(default_artifacts)
if self.extra_artifacts:
print('Throwing in an extra {0!s}'.format(self.extra_artifacts))
artifact_list.extend(self.extra_artifacts)
artifact_list = list(set(artifact_list))
if (not artifact_list):
return
flow_args = flows_pb2.ArtifactCollectorFlowArgs(artifact_list=artifact_list, use_tsk=self.use_tsk, ignore_interpolation_errors=True, apply_parsers=False)
flow_id = self._launch_flow(client, 'ArtifactCollectorFlow', flow_args)
self._await_flow(client, flow_id)
collected_flow_data = self._download_files(client, flow_id)
if collected_flow_data:
print('{0!s}: Downloaded: {1:s}'.format(flow_id, collected_flow_data))
fqdn = client.data.os_info.fqdn.lower()
self.state.output.append((fqdn, collected_flow_data))
|
Process a single GRR client.
Args:
client: a GRR client object.
|
codesearchnet
|
def get_v1_constants(module: Any) -> Sequence[str]:
constants_v1 = []
tensorflow_constants_attr_v1 = API_ATTRS_V1[TENSORFLOW_API_NAME].constants
if hasattr(module, tensorflow_constants_attr_v1):
constants_v1.extend(getattr(module, tensorflow_constants_attr_v1))
return constants_v1
|
Get a list of TF 1.* constants in this module.
Args:
module: TensorFlow module.
Returns:
List of all API constants under the given module.
|
github-repos
|
def is_valid_transition(self, source: str, dest: str) -> bool:
if dest not in self._states or source not in self._states:
raise NotValidState
elif dest not in self._transitions[source]:
raise NotValidTransition
return True
|
Checks if a transitions is registered in the FSM
Args:
source (str): the source state name
dest (str): the destination state name
Returns:
bool: wether the transition is valid or not
|
juraj-google-style
|
def run_tpm(tpm, time_scale):
sbs_tpm = convert.state_by_node2state_by_state(tpm)
if sparse(tpm):
tpm = sparse_time(sbs_tpm, time_scale)
else:
tpm = dense_time(sbs_tpm, time_scale)
return convert.state_by_state2state_by_node(tpm)
|
Iterate a TPM by the specified number of time steps.
Args:
tpm (np.ndarray): A state-by-node tpm.
time_scale (int): The number of steps to run the tpm.
Returns:
np.ndarray
|
juraj-google-style
|
def contains(array, ty, string):
weld_obj = WeldObject(encoder_, decoder_)
string_obj = weld_obj.update(string)
if isinstance(string, WeldObject):
string_obj = string.obj_id
weld_obj.dependencies[string_obj] = string
array_var = weld_obj.update(array)
if isinstance(array, WeldObject):
array_var = array.obj_id
weld_obj.dependencies[array_var] = array
(start, end) = 0, len(string)
weld_template =
weld_obj.weld_code = weld_template % {"array": array_var, "ty": ty,
"start": start, "end": end,
"cmpstr": string_obj}
return weld_obj
|
Checks if given string is contained in each string in the array.
Output is a vec of booleans.
Args:
array (WeldObject / Numpy.ndarray): Input array
start (int): starting index
size (int): length to truncate at
ty (WeldType): Type of each element in the input array
Returns:
A WeldObject representing this computation
|
juraj-google-style
|
def query_dict_to_string(query):
query_params = []
for (key, value) in query.items():
query_params.append(((key + '=') + value))
return '&'.join(query_params)
|
Convert an OrderedDict to a query string.
Args:
query (obj): The key value object with query params.
Returns:
str: The query string.
Note:
This method does the same as urllib.parse.urlencode except
that it doesn't actually encode the values.
|
codesearchnet
|
def bin_to_mac(bin, size=6):
if (len(bin) != size):
raise Exception(('Invalid MAC address: %s' % bin))
return ':'.join([binascii.hexlify(o) for o in bin])
|
Convert 6 bytes into a MAC string.
Args:
bin (str): hex string of lenth 6.
Returns:
str: String representation of the MAC address in lower case.
Raises:
Exception: if ``len(bin)`` is not 6.
|
codesearchnet
|
def BSearchCeil(a, x, lo=0, hi=None):
if len(a) == 0: return -1
hi = hi if hi is not None else len(a)
pos = bisect_left(a, x, lo, hi)
return pos if pos < hi else -1
|
Returns lowest i such as a[i] >= x, or -1 if x > all elements in a
So, if x is in between two elements in a, this function will return the
index of the higher element, hence "Ceil".
Arguments:
a -- ordered numeric sequence
x -- element to search within a
lo -- lowest index to consider in search
hi -- highest index to consider in search
|
juraj-google-style
|
def validate_args(self, qubits: Sequence[Qid]) -> None:
if len(qubits) == 0:
raise ValueError(
"Applied a gate to an empty set of qubits. Gate: {}".format(
repr(self)))
if len(qubits) != self.num_qubits():
raise ValueError(
'Wrong number of qubits for <{!r}>. '
'Expected {} qubits but got <{!r}>.'.format(
self,
self.num_qubits(),
qubits))
if any([not isinstance(qubit, Qid)
for qubit in qubits]):
raise ValueError(
'Gate was called with type different than Qid.')
|
Checks if this gate can be applied to the given qubits.
By default checks if input is of type Qid and qubit count.
Child classes can override.
Args:
qubits: The collection of qubits to potentially apply the gate to.
Throws:
ValueError: The gate can't be applied to the qubits.
|
juraj-google-style
|
def update(self, task_name, task_json):
r = self.gbdx_connection.put(((self._base_url + '/') + task_name), json=task_json)
raise_for_status(r)
return r.json()
|
Updates a GBDX task.
Args:
task_name (str): Task name.
task_json (dict): Dictionary representing updated task definition.
Returns:
Dictionary representing the updated task definition.
|
codesearchnet
|
def find_field(item_list, cond, comparator, target_field):
for item in item_list:
if comparator(item, cond) and target_field in item:
return item[target_field]
return None
|
Finds the value of a field in a dict object that satisfies certain
conditions.
Args:
item_list: A list of dict objects.
cond: A param that defines the condition.
comparator: A function that checks if an dict satisfies the condition.
target_field: Name of the field whose value to be returned if an item
satisfies the condition.
Returns:
Target value or None if no item satisfies the condition.
|
juraj-google-style
|
def new_message_from_header(header):
message_type = header.message_type
if not isinstance(message_type, Type):
try:
if isinstance(message_type, str):
message_type = Type[message_type]
elif isinstance(message_type, int):
message_type = Type(message_type)
except ValueError:
raise ValueError
message = new_message_from_message_type(message_type)
message.header.xid = header.xid
message.header.length = header.length
return message
|
Given an OF Header, return an empty message of header's message_type.
Args:
header (~pyof.v0x01.common.header.Header): Unpacked OpenFlow Header.
Returns:
Empty OpenFlow message of the same type of message_type attribute from
the given header.
The header attribute of the message will be populated.
Raises:
KytosUndefinedMessageType: Unkown Message_Type.
|
juraj-google-style
|
def ParseFileEntry(self, parser_mediator, file_entry):
filename = parser_mediator.GetFilename()
database = SQLiteDatabase(
filename, temporary_directory=parser_mediator.temporary_directory)
file_object = file_entry.GetFileObject()
try:
database.Open(file_object)
except (IOError, ValueError, sqlite3.DatabaseError) as exception:
parser_mediator.ProduceExtractionWarning(
'unable to open SQLite database with error: {0!s}'.format(exception))
file_object.close()
return
database_wal, wal_file_entry = self._OpenDatabaseWithWAL(
parser_mediator, file_entry, file_object, filename)
file_object.close()
cache = SQLiteCache()
try:
table_names = frozenset(database.tables)
for plugin in self._plugins:
if not plugin.REQUIRED_TABLES.issubset(table_names):
continue
schema_match = plugin.CheckSchema(database)
if plugin.REQUIRES_SCHEMA_MATCH and not schema_match:
parser_mediator.ProduceExtractionWarning((
'plugin: {0:s} found required tables but not a matching '
'schema').format(plugin.NAME))
continue
parser_mediator.SetFileEntry(file_entry)
parser_mediator.AddEventAttribute('schema_match', schema_match)
try:
plugin.UpdateChainAndProcess(
parser_mediator, cache=cache, database=database,
database_wal=database_wal, wal_file_entry=wal_file_entry)
except Exception as exception:
parser_mediator.ProduceExtractionWarning((
'plugin: {0:s} unable to parse SQLite database with error: '
'{1!s}').format(plugin.NAME, exception))
finally:
parser_mediator.RemoveEventAttribute('schema_match')
if not database_wal:
continue
schema_match = plugin.CheckSchema(database)
parser_mediator.SetFileEntry(wal_file_entry)
parser_mediator.AddEventAttribute('schema_match', schema_match)
try:
plugin.UpdateChainAndProcess(
parser_mediator, cache=cache, database=database,
database_wal=database_wal, wal_file_entry=wal_file_entry)
except Exception as exception:
parser_mediator.ProduceExtractionWarning((
'plugin: {0:s} unable to parse SQLite database and WAL with '
'error: {1!s}').format(plugin.NAME, exception))
finally:
parser_mediator.RemoveEventAttribute('schema_match')
finally:
database.Close()
|
Parses a SQLite database file entry.
Args:
parser_mediator (ParserMediator): parser mediator.
file_entry (dfvfs.FileEntry): file entry to be parsed.
Raises:
UnableToParseFile: when the file cannot be parsed.
|
juraj-google-style
|
def preprocess_na(sent, label_type):
if label_type == "phonemes_and_tones":
phonemes = True
tones = True
tgm = True
elif label_type == "phonemes_and_tones_no_tgm":
phonemes = True
tones = True
tgm = False
elif label_type == "phonemes":
phonemes = True
tones = False
tgm = False
elif label_type == "tones":
phonemes = False
tones = True
tgm = True
elif label_type == "tones_notgm":
phonemes = False
tones = True
tgm = False
else:
raise ValueError("Unrecognized label type: %s" % label_type)
def pop_phoneme(sentence):
if phonemes:
if sentence[:4] in ["əəə…", "mmm…"]:
return sentence[:4], sentence[4:]
if sentence.startswith("ə…"):
return "əəə…", sentence[2:]
if sentence.startswith("m…"):
return "mmm…", sentence[2:]
if sentence.startswith("mm…"):
return "mmm…", sentence[3:]
if sentence[:3] == "wæ̃":
if phonemes:
return "w̃æ", sentence[3:]
else:
return None, sentence[3:]
if sentence[:3] == "ṽ̩":
if phonemes:
return "ṽ̩", sentence[3:]
else:
return None, sentence[3:]
if sentence[:3] in TRI_PHNS:
if phonemes:
return sentence[:3], sentence[3:]
else:
return None, sentence[3:]
if sentence[:2] in BI_PHNS:
if phonemes:
return sentence[:2], sentence[2:]
else:
return None, sentence[2:]
if sentence[:2] == "˧̩":
return "˧", sentence[2:]
if sentence[:2] == "˧̍":
return "˧", sentence[2:]
if sentence[0] in UNI_PHNS:
if phonemes:
return sentence[0], sentence[1:]
else:
return None, sentence[1:]
if sentence[:2] in BI_TONES:
if tones:
return sentence[:2], sentence[2:]
else:
return None, sentence[2:]
if sentence[0] in UNI_TONES:
if tones:
return sentence[0], sentence[1:]
else:
return None, sentence[1:]
if sentence[0] in MISC_SYMBOLS:
return None, sentence[1:]
if sentence[0] in BAD_NA_SYMBOLS:
return None, sentence[1:]
if sentence[0] in PUNC_SYMBOLS:
return None, sentence[1:]
if sentence[0] in ["-", "ʰ", "/"]:
return None, sentence[1:]
if sentence[0] in set(["<", ">"]):
return None, sentence[1:]
if sentence[0] == "[":
if sentence.find("]") == len(sentence)-1:
return None, ""
else:
return None, sentence[sentence.find("]")+1:]
if sentence[0] in set([" ", "\t", "\n"]):
return " ", sentence[1:]
if sentence[0] == "|" or sentence[0] == "ǀ" or sentence[0] == "◊":
if tgm:
return "|", sentence[1:]
else:
return None, sentence[1:]
if sentence[0] in "()":
return None, sentence[1:]
print("***" + sentence)
raise ValueError("Next character not recognized: " + sentence[:1])
def filter_for_phonemes(sentence):
filtered_sentence = []
while sentence != "":
phoneme, sentence = pop_phoneme(sentence)
if phoneme != " ":
filtered_sentence.append(phoneme)
filtered_sentence = [item for item in filtered_sentence if item != None]
return " ".join(filtered_sentence)
if "BEGAIEMENT" in sent:
return ""
sent = filter_for_phonemes(sent)
return sent
|
Preprocess Na sentences
Args:
sent: A sentence
label_type: The type of label provided
|
juraj-google-style
|
def validate(self, profile):
ij = self.load_install_json(profile.get('install_json'))
print('{}{}Profile: "{}".'.format(c.Style.BRIGHT, c.Fore.BLUE, profile.get('profile_name')))
for arg in self.profile_settings_args_install_json(ij, None):
if profile.get('args', {}).get('app', {}).get(arg) is None:
print('{}{}Input "{}" not found.'.format(c.Style.BRIGHT, c.Fore.YELLOW, arg))
|
Check to see if any args are "missing" from profile.
Validate all args from install.json are in the profile. This can be helpful to validate
that any new args added to App are included in the profiles.
.. Note:: This method does not work with layout.json Apps.
Args:
profile (dict): The current profile to validate.
|
juraj-google-style
|
def xmoe2_dense(sz):
hparams = mtf_transformer.mtf_transformer_paper_lm(sz)
hparams.attention_dropout = 0.0
hparams.relu_dropout = 0.0
hparams.layer_prepostprocess_dropout = 0.0
hparams.max_length = 1024
hparams.batch_size = 128
hparams.learning_rate_schedule = 'rsqrt_decay*linear_decay'
hparams.learning_rate_decay_steps = 65536
hparams.layout = 'batch:batch;vocab:model;d_ff:model;heads:model'
hparams.mesh_shape = 'batch:32'
return hparams
|
Series of architectural experiments on language modeling.
Larger models than the ones above.
All models are trained on sequences of 1024 tokens.
We assume infinite training data, so no dropout necessary.
We process 2^36 tokens in training = 524288 steps at batch size 128
TODO(noam): find a large enough dataset for these experiments.
You can use languagemodel_wiki_noref_v32k_l1k, but this is too small,
(1 epoch = ~46000 steps) so training will cover about 11 epochs.
Note: configurations and code are likely to change without notice.
Run on TPU 4x4 for 524288 steps unless otherwise indicated.
Args:
sz: an integer
Returns:
a hparams
|
codesearchnet
|
def filter_values(cls, part_info):
filtered = []
for info_list in cls.filter_parts(part_info).values():
filtered += info_list
return filtered
|
Filter the part_info dict list looking for instances of our class
Args:
part_info (dict): {part_name: [Info] or None} as returned from
Controller.run_hook()
Returns:
list: [info] where info is a subclass of cls
|
juraj-google-style
|
def DeserializeExclusiveData(self, reader):
self.Type = TransactionType.IssueTransaction
if self.Version > 1:
raise Exception('Invalid TX Type')
|
Deserialize full object.
Args:
reader (neo.IO.BinaryReader):
|
juraj-google-style
|
def export_analytics_data_to_csv(data, output_folder, result_info_key, identifier_keys):
workbook = create_excel_workbook(data, result_info_key, identifier_keys)
suffix = '.csv'
if not os.path.exists(output_folder):
os.makedirs(output_folder)
for worksheet in workbook.worksheets:
file_name = utilities.convert_title_to_snake_case(worksheet.title)
file_path = os.path.join(output_folder, file_name + suffix)
mode = 'w'
if sys.version_info[0] < 3:
mode = 'wb'
with io.open(file_path, mode) as output_file:
csv_writer = csv.writer(output_file)
for row in worksheet.rows:
csv_writer.writerow([cell.value for cell in row])
print('Saved CSV files to {}'.format(output_folder))
|
Creates CSV files containing data returned by the Analytics API.
Creates one file per requested endpoint and saves it into the
specified output_folder
Args:
data: Analytics API data as a list of dicts
output_folder: Path to a folder to save the CSV files into
|
juraj-google-style
|
def set_margin(self, top=40, bottom=30, left=50, right=10, buffer_size=8):
self.set_integer('top', top)
self.set_integer('bottom', bottom)
self.set_integer('left', left)
self.set_integer('right', right)
self.set_integer('buffer', buffer_size)
|
Set margin of the chart.
Args:
top (int): size of top margin in pixels.
bottom (int): size of bottom margin in pixels.
left (int): size of left margin in pixels.
right (int): size of right margin in pixels.
buffer_size (int): buffer size in pixels between the chart and margins.
|
codesearchnet
|
def napalm_get(task: Task, getters: List[str], getters_options: GetterOptionsDict=None, **kwargs: Any) -> Result:
device = task.host.get_connection('napalm', task.nornir.config)
getters_options = (getters_options or {})
if isinstance(getters, str):
getters = [getters]
result = {}
for g in getters:
options = copy.deepcopy(kwargs)
options.update(getters_options.get(g, {}))
getter = (g if g.startswith('get_') else 'get_{}'.format(g))
method = getattr(device, getter)
result[g] = method(**options)
return Result(host=task.host, result=result)
|
Gather information from network devices using napalm
Arguments:
getters: getters to use
getters_options (dict of dicts): When passing multiple getters you
pass a dictionary where the outer key is the getter name
and the included dictionary represents the options to pass
to the getter
**kwargs: will be passed as they are to the getters
Examples:
Simple example::
> nr.run(task=napalm_get,
> getters=["interfaces", "facts"])
Passing options using ``**kwargs``::
> nr.run(task=napalm_get,
> getters=["config"],
> retrieve="all")
Passing options using ``getters_options``::
> nr.run(task=napalm_get,
> getters=["config", "interfaces"],
> getters_options={"config": {"retrieve": "all"}})
Returns:
Result object with the following attributes set:
* result (``dict``): dictionary with the result of the getter
|
codesearchnet
|
def tag_match(self, tags=None):
if 'tags' not in self.database.collection_names():
print 'Warning: Searching on non-existance tags collection'
return None
if not tags:
cursor = self.database['tags'].find({}, {'_id':0, 'md5':1})
else:
cursor = self.database['tags'].find({'tags': {'$in': tags}}, {'_id':0, 'md5':1})
tag_md5s = set([item['md5'] for item in cursor])
sample_md5s = set(item['md5'] for item in self.database['samples'].find({}, {'_id':0, 'md5':1}))
return list(tag_md5s.intersection(sample_md5s))
|
List all samples that match the tags or all if tags are not specified.
Args:
tags: Match samples against these tags (or all if not specified)
Returns:
List of the md5s for the matching samples
|
juraj-google-style
|
def delete(self, delete_contents=False):
if (not self.exists()):
raise Exception(('Cannot delete non-existent dataset %s' % self._full_name))
try:
self._api.datasets_delete(self._name_parts, delete_contents=delete_contents)
except Exception as e:
raise e
self._info = None
return None
|
Issues a request to delete the dataset.
Args:
delete_contents: if True, any tables and views in the dataset will be deleted. If False
and the dataset is non-empty an exception will be raised.
Returns:
None on success.
Raises:
Exception if the delete fails (including if table was nonexistent).
|
codesearchnet
|
def symmetric_difference_update(self, other):
other = self._as_multiset(other)
elements = (set(self.distinct_elements()) | set(other.distinct_elements()))
for element in elements:
multiplicity = self[element]
other_count = other[element]
self[element] = ((multiplicity - other_count) if (multiplicity > other_count) else (other_count - multiplicity))
|
r"""Update the multiset to contain only elements in either this multiset or the other but not both.
>>> ms = Multiset('aab')
>>> ms.symmetric_difference_update('abc')
>>> sorted(ms)
['a', 'c']
You can also use the ``^=`` operator for the same effect. However, the operator version
will only accept a set as other operator, not any iterable, to avoid errors.
>>> ms = Multiset('aabbbc')
>>> ms ^= Multiset('abd')
>>> sorted(ms)
['a', 'b', 'b', 'c', 'd']
For a variant of the operation which does not modify the multiset, but returns a new
multiset instead see :meth:`symmetric_difference`.
Args:
other: The other set to take the symmetric difference with. Can also be any :class:`~typing.Iterable`\[~T]
or :class:`~typing.Mapping`\[~T, :class:`int`] which are then converted to :class:`Multiset`\[~T].
|
codesearchnet
|
def get_inventory_str(self, keys=None):
inventory = self.get_inventory(keys)
lines = []
for name, hosts in inventory.viewitems():
lines.append('[{name}]'.format(name=name))
for host in sorted(hosts):
lines.append(host)
return '\n'.join(lines)
|
Convert a dict generated by ansible.LagoAnsible.get_inventory
to an INI-like file.
Args:
keys (list of str): Path to the keys that will be used to
create groups.
Returns:
str: INI-like Ansible inventory
|
juraj-google-style
|
def ver(self, value):
if value == self._defaults['ver'] and 'ver' in self._values:
del self._values['ver']
else:
self._values['ver'] = value
|
The ver property.
Args:
value (int). the property value.
|
juraj-google-style
|
def _circuit_as_layers(circuit: circuits.Circuit,
grouping: _QubitGrouping) -> List[_TransformsThenCzs]:
frontier = {q: 0 for q in circuit.all_qubits()}
layers = []
while True:
any_group_matrices = False
group_matrices = []
for g in grouping.groups:
start_frontier = {q: frontier[q] for q in g}
end_frontier = circuit.reachable_frontier_from(start_frontier)
mergeable_ops = circuit.findall_operations_between(start_frontier,
end_frontier)
for q, v in end_frontier.items():
frontier[q] = v
group_matrix = np.eye(1 << len(g)).reshape((2, 2) * len(g))
if mergeable_ops:
any_group_matrices = True
for _, op in mergeable_ops:
group_matrix = linalg.targeted_left_multiply(
left_matrix=protocols.unitary(op).reshape(
(2, 2) * len(op.qubits)),
right_target=group_matrix,
target_axes=[grouping.loc(q)[1] for q in op.qubits])
group_matrices.append(np.transpose(group_matrix.reshape(
1 << len(g), 1 << len(g))))
end_frontier = circuit.reachable_frontier_from(
frontier,
is_blocker=lambda op: grouping.all_in_same_group(*op.qubits))
cz_ops = circuit.findall_operations_between(frontier, end_frontier)
frontier = end_frontier
cz_indices = []
for _, cz in cz_ops:
a, b = cz.qubits
assert cz == ops.CZ(a, b)
cz_indices.append((grouping.ind(a), grouping.ind(b)))
if not any_group_matrices and not cz_indices:
break
layer = _TransformsThenCzs(group_matrices=group_matrices,
cz_indices=cz_indices)
layers.append(layer)
assert frontier == {q: len(circuit) for q in circuit.all_qubits()}
return layers
|
Transforms a circuit into a series of GroupMatrix+CZ layers.
Args:
circuit: The circuit to transform.
grouping: How the circuit's qubits are combined into groups.
Returns:
A list of layers. Each layer has a matrix to apply to each group of
qubits, and a list of CZs to apply to pairs of qubits crossing
between groups.
|
juraj-google-style
|
def _CheckCompositeMap(self, data_type_definition):
if (not data_type_definition):
raise errors.FormatError('Missing data type definition')
members = getattr(data_type_definition, 'members', None)
if (not members):
raise errors.FormatError('Invalid data type definition missing members')
is_composite_map = False
last_member_byte_order = data_type_definition.byte_order
for member_definition in members:
if member_definition.IsComposite():
is_composite_map = True
break
if ((last_member_byte_order != definitions.BYTE_ORDER_NATIVE) and (member_definition.byte_order != definitions.BYTE_ORDER_NATIVE) and (last_member_byte_order != member_definition.byte_order)):
is_composite_map = True
break
last_member_byte_order = member_definition.byte_order
return is_composite_map
|
Determines if the data type definition needs a composite map.
Args:
data_type_definition (DataTypeDefinition): structure data type definition.
Returns:
bool: True if a composite map is needed, False otherwise.
Raises:
FormatError: if a composite map is needed cannot be determined from the
data type definition.
|
codesearchnet
|
def cluster_sites(mol, tol, give_only_index=False):
dists = [[np.linalg.norm(site.coords), 0] for site in mol]
import scipy.cluster as spcluster
f = spcluster.hierarchy.fclusterdata(dists, tol, criterion='distance')
clustered_dists = defaultdict(list)
for i, site in enumerate(mol):
clustered_dists[f[i]].append(dists[i])
avg_dist = {label: np.mean(val) for label, val in clustered_dists.items()}
clustered_sites = defaultdict(list)
origin_site = None
for i, site in enumerate(mol):
if avg_dist[f[i]] < tol:
if give_only_index:
origin_site = i
else:
origin_site = site
else:
if give_only_index:
clustered_sites[
(avg_dist[f[i]], site.species)].append(i)
else:
clustered_sites[
(avg_dist[f[i]], site.species)].append(site)
return origin_site, clustered_sites
|
Cluster sites based on distance and species type.
Args:
mol (Molecule): Molecule **with origin at center of mass**.
tol (float): Tolerance to use.
Returns:
(origin_site, clustered_sites): origin_site is a site at the center
of mass (None if there are no origin atoms). clustered_sites is a
dict of {(avg_dist, species_and_occu): [list of sites]}
|
juraj-google-style
|
def call(self, input_features=None, decoder_input_ids=None, decoder_attention_mask=None, decoder_position_ids=None, head_mask=None, decoder_head_mask=None, cross_attn_head_mask=None, encoder_outputs=None, past_key_values=None, decoder_inputs_embeds=None, use_cache=None, output_attentions=None, output_hidden_states=None, return_dict=None, training=False):
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
output_hidden_states = output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
use_cache = use_cache if use_cache is not None else self.config.use_cache
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
if encoder_outputs is None:
encoder_outputs = self.encoder(input_features, head_mask=head_mask, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict, training=training)
elif return_dict and (not isinstance(encoder_outputs, TFBaseModelOutput)):
encoder_outputs = TFBaseModelOutput(last_hidden_state=encoder_outputs[0], hidden_states=encoder_outputs[1] if len(encoder_outputs) > 1 else None, attentions=encoder_outputs[2] if len(encoder_outputs) > 2 else None)
decoder_outputs = self.decoder(input_ids=decoder_input_ids, attention_mask=decoder_attention_mask, position_ids=decoder_position_ids, encoder_hidden_states=encoder_outputs[0], head_mask=decoder_head_mask, cross_attn_head_mask=cross_attn_head_mask, past_key_values=past_key_values, inputs_embeds=decoder_inputs_embeds, use_cache=use_cache, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict, training=training)
if not return_dict:
return decoder_outputs + encoder_outputs
return TFSeq2SeqModelOutput(last_hidden_state=decoder_outputs.last_hidden_state, past_key_values=decoder_outputs.past_key_values, decoder_hidden_states=decoder_outputs.hidden_states, decoder_attentions=decoder_outputs.attentions, cross_attentions=decoder_outputs.cross_attentions, encoder_last_hidden_state=encoder_outputs.last_hidden_state, encoder_hidden_states=encoder_outputs.hidden_states, encoder_attentions=encoder_outputs.attentions)
|
Returns:
Example:
```python
>>> import tensorflow as tf
>>> from transformers import TFWhisperModel, AutoFeatureExtractor
>>> from datasets import load_dataset
>>> model = TFWhisperModel.from_pretrained("openai/whisper-base")
>>> feature_extractor = AutoFeatureExtractor.from_pretrained("openai/whisper-base")
>>> ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation")
>>> inputs = feature_extractor(ds[0]["audio"]["array"], return_tensors="tf")
>>> input_features = inputs.input_features
>>> decoder_input_ids = tf.convert_to_tensor([[1, 1]]) * model.config.decoder_start_token_id
>>> last_hidden_state = model(input_features, decoder_input_ids=decoder_input_ids).last_hidden_state
>>> list(last_hidden_state.shape)
[1, 2, 512]
```
|
github-repos
|
def conv_output_length(input_length, filter_size, padding, stride, dilation=1):
if input_length is None:
return None
assert padding in {'same', 'valid', 'full', 'causal'}
dilated_filter_size = filter_size + (filter_size - 1) * (dilation - 1)
if padding in ['same', 'causal']:
output_length = input_length
elif padding == 'valid':
output_length = input_length - dilated_filter_size + 1
elif padding == 'full':
output_length = input_length + dilated_filter_size - 1
return (output_length + stride - 1)
|
Determines output length of a convolution given input length.
Args:
input_length: integer.
filter_size: integer.
padding: one of "same", "valid", "full", "causal"
stride: integer.
dilation: dilation rate, integer.
Returns:
The output length (integer).
|
github-repos
|
def __call__(self, *args, **kwargs):
if not self._verified:
model = self._get_func()
concrete_func = model.get_concrete_function(*args, **kwargs)
converter = lite.TFLiteConverterV2.from_concrete_functions([concrete_func], model)
if self._converter_target_spec is not None:
converter.target_spec = self._converter_target_spec
if self._converter_allow_custom_ops is not None:
converter.allow_custom_ops = self._converter_allow_custom_ops
try:
converter.convert()
except convert.ConverterError as err:
self._decode_error(err)
finally:
self._verified = True
return self._get_func()(*args, **kwargs)
|
Calls decorated function object.
Also verifies if the function is compatible with TFLite.
Returns:
A execution result of the decorated function.
|
github-repos
|
def _GetShortFlags(flags):
short_flags = [f[0] for f in flags]
short_flag_counts = collections.Counter(short_flags)
return [v for v in short_flags if short_flag_counts[v] == 1]
|
Gets a list of single-character flags that uniquely identify a flag.
Args:
flags: list of strings representing flags
Returns:
List of single character short flags,
where the character occurred at the start of a flag once.
|
github-repos
|
def run(
self,
num_episodes=-1,
max_episode_timesteps=-1,
episode_finished=None,
summary_report=None,
summary_interval=0,
num_timesteps=None,
deterministic=False,
episodes=None,
max_timesteps=None,
testing=False,
sleep=None
):
if episodes is not None:
num_episodes = episodes
warnings.warn("WARNING: `episodes` parameter is deprecated, use `num_episodes` instead.",
category=DeprecationWarning)
assert isinstance(num_episodes, int)
if max_timesteps is not None:
max_episode_timesteps = max_timesteps
warnings.warn("WARNING: `max_timesteps` parameter is deprecated, use `max_episode_timesteps` instead.",
category=DeprecationWarning)
assert isinstance(max_episode_timesteps, int)
if summary_report is not None:
warnings.warn("WARNING: `summary_report` parameter is deprecated, use `episode_finished` callback "
"instead to generate summaries every n episodes.",
category=DeprecationWarning)
self.reset()
self.global_episode = 0
self.global_timestep = 0
self.should_stop = False
threads = [threading.Thread(target=self._run_single, args=(t, self.agent[t], self.environment[t],),
kwargs={"deterministic": deterministic,
"max_episode_timesteps": max_episode_timesteps,
"episode_finished": episode_finished,
"testing": testing,
"sleep": sleep})
for t in range(len(self.agent))]
self.start_time = time.time()
[t.start() for t in threads]
try:
next_summary = 0
next_save = 0 if self.save_frequency_unit != "s" else time.time()
while any([t.is_alive() for t in threads]) and self.global_episode < num_episodes or num_episodes == -1:
self.time = time.time()
if summary_report is not None and self.global_episode > next_summary:
summary_report(self)
next_summary += summary_interval
if self.save_path and self.save_frequency is not None:
do_save = True
current = None
if self.save_frequency_unit == "e" and self.global_episode > next_save:
current = self.global_episode
elif self.save_frequency_unit == "s" and self.time > next_save:
current = self.time
elif self.save_frequency_unit == "t" and self.global_timestep > next_save:
current = self.global_timestep
else:
do_save = False
if do_save:
self.agent[0].save_model(self.save_path)
while next_save < current:
next_save += self.save_frequency
time.sleep(1)
except KeyboardInterrupt:
print('Keyboard interrupt, sending stop command to threads')
self.should_stop = True
[t.join() for t in threads]
print('All threads stopped')
|
Executes this runner by starting all Agents in parallel (each one in one thread).
Args:
episodes (int): Deprecated; see num_episodes.
max_timesteps (int): Deprecated; see max_episode_timesteps.
|
juraj-google-style
|
def easeOutBack(n, s=1.70158):
_checkRange(n)
n = n - 1
return n * n * ((s + 1) * n + s) + 1
|
A tween function that overshoots the destination a little and then backs into the destination.
Args:
n (float): The time progress, starting at 0.0 and ending at 1.0.
Returns:
(float) The line progress, starting at 0.0 and ending at 1.0. Suitable for passing to getPointOnLine().
|
juraj-google-style
|
def compare_version(a, b):
aa = string.split(a, ".")
bb = string.split(b, ".")
for i in range(0, 4):
if aa[i] != bb[i]:
return cmp(int(aa[i]), int(bb[i]))
return 0
|
Compare two version number strings of the form W.X.Y.Z.
The numbers are compared most-significant to least-significant.
For example, 12.345.67.89 > 2.987.88.99.
Args:
a: First version number string to compare
b: Second version number string to compare
Returns:
0 if the numbers are identical, a positive number if 'a' is larger, and
a negative number if 'b' is larger.
|
juraj-google-style
|
def log_jwt_dict_info(log, msg_str, jwt_dict):
d = ts_to_str(jwt_dict)
log_list = [(b, d.pop(a)) for a, b, c in CLAIM_LIST if a in d] + [
(k, d[k]) for k in sorted(d)
]
list(
map(
log,
['{}:'.format(msg_str)] + [' {}: {}'.format(k, v) for k, v in log_list],
)
)
|
Dump JWT to log.
Args:
log: Logger
Logger to which to write the message.
msg_str: str
A message to write to the log before the JWT values.
jwt_dict: dict
JWT containing values to log.
Returns:
None
|
juraj-google-style
|
def histogram_pb(tag, data, buckets=None, description=None):
bucket_count = (DEFAULT_BUCKET_COUNT if (buckets is None) else buckets)
data = np.array(data).flatten().astype(float)
if (data.size == 0):
buckets = np.array([]).reshape((0, 3))
else:
min_ = np.min(data)
max_ = np.max(data)
range_ = (max_ - min_)
if (range_ == 0):
center = min_
buckets = np.array([[(center - 0.5), (center + 0.5), float(data.size)]])
else:
bucket_width = (range_ / bucket_count)
offsets = (data - min_)
bucket_indices = np.floor((offsets / bucket_width)).astype(int)
clamped_indices = np.minimum(bucket_indices, (bucket_count - 1))
one_hots = (np.array([clamped_indices]).transpose() == np.arange(0, bucket_count))
assert (one_hots.shape == (data.size, bucket_count)), (one_hots.shape, (data.size, bucket_count))
bucket_counts = np.sum(one_hots, axis=0)
edges = np.linspace(min_, max_, (bucket_count + 1))
left_edges = edges[:(- 1)]
right_edges = edges[1:]
buckets = np.array([left_edges, right_edges, bucket_counts]).transpose()
tensor = tensor_util.make_tensor_proto(buckets, dtype=np.float64)
summary_metadata = metadata.create_summary_metadata(display_name=None, description=description)
summary = summary_pb2.Summary()
summary.value.add(tag=tag, metadata=summary_metadata, tensor=tensor)
return summary
|
Create a histogram summary protobuf.
Arguments:
tag: String tag for the summary.
data: A `np.array` or array-like form of any shape. Must have type
castable to `float`.
buckets: Optional positive `int`. The output will have this
many buckets, except in two edge cases. If there is no data, then
there are no buckets. If there is data but all points have the
same value, then there is one bucket whose left and right
endpoints are the same.
description: Optional long-form description for this summary, as a
`str`. Markdown is supported. Defaults to empty.
Returns:
A `summary_pb2.Summary` protobuf object.
|
codesearchnet
|
def tournament_name2number(self, name):
tournaments = self.get_tournaments()
d = {t['name']: t['tournament'] for t in tournaments}
return d.get(name, None)
|
Translate tournament name to tournament number.
Args:
name (str): tournament name to translate
Returns:
number (int): number of the tournament or `None` if unknown.
Examples:
>>> NumerAPI().tournament_name2number('delta')
4
>>> NumerAPI().tournament_name2number('foo')
None
|
codesearchnet
|
def GetEntries(self, parser_mediator, match=None, **unused_kwargs):
if 'RememberedNetworks' not in match:
return
for wifi in match['RememberedNetworks']:
ssid = wifi.get('SSIDString', 'UNKNOWN_SSID')
security_type = wifi.get('SecurityType', 'UNKNOWN_SECURITY_TYPE')
event_data = plist_event.PlistTimeEventData()
event_data.desc = (
'[WiFi] Connected to network: <{0:s}> using security {1:s}').format(
ssid, security_type)
event_data.key = 'item'
event_data.root = '/RememberedNetworks'
datetime_value = wifi.get('LastConnected', None)
if datetime_value:
event = time_events.PythonDatetimeEvent(
datetime_value, definitions.TIME_DESCRIPTION_WRITTEN)
else:
date_time = dfdatetime_semantic_time.SemanticTime('Not set')
event = time_events.DateTimeValuesEvent(
date_time, definitions.TIME_DESCRIPTION_NOT_A_TIME)
parser_mediator.ProduceEventWithEventData(event, event_data)
|
Extracts relevant Airport entries.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
match (Optional[dict[str: object]]): keys extracted from PLIST_KEYS.
|
juraj-google-style
|
def predecesors_pattern(element, root):
def is_root_container(el):
return (el.parent.parent.getTagName() == '')
if ((not element.parent) or (not element.parent.parent) or is_root_container(element)):
return []
trail = [[element.parent.parent.getTagName(), _params_or_none(element.parent.parent.params)], [element.parent.getTagName(), _params_or_none(element.parent.params)], [element.getTagName(), _params_or_none(element.params)]]
match = root.match(*trail)
if (element in match):
return [PathCall('match', match.index(element), trail)]
|
Look for `element` by its predecesors.
Args:
element (obj): HTMLElement instance of the object you are looking for.
root (obj): Root of the `DOM`.
Returns:
list: ``[PathCall()]`` - list with one :class:`PathCall` object (to \
allow use with ``.extend(predecesors_pattern())``).
|
codesearchnet
|
def _read_message(self):
line = self._rfile.readline()
if (not line):
return None
content_length = self._content_length(line)
while (line and line.strip()):
line = self._rfile.readline()
if (not line):
return None
return self._rfile.read(content_length)
|
Reads the contents of a message.
Returns:
body of message if parsable else None
|
codesearchnet
|
def get_signatures_with_results(vcs):
results_dir = os.path.join(vcs.private_dir(), 'results')
if (not os.path.exists(results_dir)):
return []
rel_paths = os.listdir(results_dir)
return [p for p in rel_paths if os.path.isdir(os.path.join(results_dir, p))]
|
Returns the list of signatures for which test results are saved.
Args:
vcs (easyci.vcs.base.Vcs)
Returns:
List[str]
|
codesearchnet
|
def __init__(self, object_type=None, attributes=None):
super(ObjectDefaults, self).__init__(tag=enums.Tags.OBJECT_DEFAULTS)
self._object_type = None
self._attributes = None
self.object_type = object_type
self.attributes = attributes
|
Construct an ObjectDefaults structure.
Args:
object_type (enum): An ObjectType enumeration identifying the type
to which the defaults pertain. Optional, defaults to None.
Required for read/write.
attributes (structure): An Attributes structure containing
attribute values that are defaults for an object type.
Optional, defaults to None. Required for read/write.
|
juraj-google-style
|
class AsDict(AsSideInput):
@staticmethod
def _from_runtime_iterable(it, options):
return dict(it)
def _side_input_data(self) -> SideInputData:
return SideInputData(common_urns.side_inputs.ITERABLE.urn, self._window_mapping_fn, dict)
|
Marker specifying a PCollection to be used as an indexable side input.
Intended for use in side-argument specification---the same places where
AsSingleton and AsIter are used, but returns an interface that allows
key lookup.
Args:
pcoll: Input pcollection. All elements should be key-value pairs (i.e.
2-tuples) with unique keys.
Returns:
An AsDict-wrapper around a PCollection whose one element is a dict with
entries for uniquely-keyed pairs in pcoll.
|
github-repos
|
def GetDevicePath(device_handle):
io_service_obj = iokit.IOHIDDeviceGetService(device_handle)
str_buffer = ctypes.create_string_buffer(DEVICE_PATH_BUFFER_SIZE)
iokit.IORegistryEntryGetPath(io_service_obj, K_IO_SERVICE_PLANE, str_buffer)
return str_buffer.value
|
Obtains the unique path for the device.
Args:
device_handle: reference to the device
Returns:
A unique path for the device, obtained from the IO Registry
|
juraj-google-style
|
def _get_path_for_op_id(self, id: str) -> Optional[str]:
for (path_key, path_value) in self._get_spec()['paths'].items():
for method in self.METHODS:
if (method in path_value):
if (self.OPERATION_ID_KEY in path_value[method]):
if (path_value[method][self.OPERATION_ID_KEY] == id):
return path_key
return None
|
Searches the spec for a path matching the operation id.
Args:
id: operation id
Returns:
path to the endpoint, or None if not found
|
codesearchnet
|
def _update_linear_bucket_count(a_float, dist):
buckets = dist.linearBuckets
if buckets is None:
raise ValueError(_BAD_UNSET_BUCKETS % (u'linear buckets'))
bucket_counts = dist.bucketCounts
num_finite_buckets = buckets.numFiniteBuckets
if len(bucket_counts) < num_finite_buckets + 2:
raise ValueError(_BAD_LOW_BUCKET_COUNT)
width = buckets.width
lower = buckets.offset
upper = lower + (num_finite_buckets * width)
if a_float < lower:
index = 0
elif a_float >= upper:
index = num_finite_buckets + 1
else:
index = 1 + int(((a_float - lower) / width))
bucket_counts[index] += 1
_logger.debug(u'upper:%f, lower:%f, width:%f, sample:%f, index:%d',
upper, lower, width, a_float, index)
|
Adds `a_float` to `dist`, updating the its linear buckets.
Args:
a_float (float): a new value
dist (:class:`endpoints_management.gen.servicecontrol_v1_messages.Distribution`):
the Distribution being updated
Raises:
ValueError: if `dist` does not already have linear buckets defined
ValueError: if there are not enough bucket count fields in `dist`
|
juraj-google-style
|
def learn(self, features, labels):
labels = np.ravel(labels)
self.__learn_labels(labels)
if (len(labels) == 0):
return
labels = self.labels.transform(labels)
if ((self.feature_length > 0) and hasattr(self.clf, 'partial_fit')):
self.clf = self.clf.partial_fit(features, labels)
else:
self.clf = self.clf.fit(features, labels)
self.feature_length = len(features[0])
|
Fits the classifier
If it's state is empty, the classifier is fitted, if not
the classifier is partially fitted.
See sklearn's SGDClassifier fit and partial_fit methods.
Args:
features (:obj:`list` of :obj:`list` of :obj:`float`)
labels (:obj:`list` of :obj:`str`): Labels for each set of features.
New features are learnt.
|
codesearchnet
|
def copy(reader, writer, start, stop, insertLocation=None, tsCol=None):
assert stop >= start
startRows = []
copyRows = []
ts = None
inc = None
if tsCol is None:
tsCol = reader.getTimestampFieldIdx()
for i, row in enumerate(reader):
if ts is None:
ts = row[tsCol]
elif inc is None:
inc = row[tsCol] - ts
if i >= start and i <= stop:
copyRows.append(row)
startRows.append(row)
if insertLocation is None:
insertLocation = stop + 1
startRows[insertLocation:insertLocation] = copyRows
for row in startRows:
row[tsCol] = ts
writer.appendRecord(row)
ts += inc
|
Copies a range of values to a new location in the data set.
Args:
reader: A FileRecordStream object with input data.
writer: A FileRecordStream object to write output data to.
start: The first row in the range to copy.
stop: The last row in the range to copy.
insertLocation: The location to insert the copied range. If not specified,
the range is inserted immediately following itself.
|
juraj-google-style
|
def longest_one_seg_prefix(self, word):
match = self.seg_regex.match(word)
if match:
return match.group(0)
else:
return ''
|
Return longest IPA Unicode prefix of `word`
Args:
word (unicode): word as IPA string
Returns:
unicode: longest single-segment prefix of `word`
|
juraj-google-style
|
def __init__(self, data=None):
if data is None:
data = {}
self._data = data
self._len = 0
|
Instantiate the histogram.
Args:
data (Mapping[str, int]): The data strucure to be used to store
the underlying data. The default is an empty dictionary.
This can be set to a dictionary-like object if required
(for example, if a special object is needed for
concurrency reasons).
|
juraj-google-style
|
def offset(self, num_to_skip):
query = query_mod.Query(self)
return query.offset(num_to_skip)
|
Skip to an offset in a query with this collection as parent.
See
:meth:`~.firestore_v1beta1.query.Query.offset` for
more information on this method.
Args:
num_to_skip (int): The number of results to skip at the beginning
of query results. (Must be non-negative.)
Returns:
~.firestore_v1beta1.query.Query: An offset query.
|
juraj-google-style
|
def add_middleware(middleware: EFBMiddleware):
global middlewares
if isinstance(middleware, EFBMiddleware):
middlewares.append(middleware)
else:
raise TypeError('Middleware instance is expected')
|
Register a middleware with the coordinator.
Args:
middleware (EFBMiddleware): Middleware to register
|
codesearchnet
|
def _TerminateProcess(self, process):
pid = process.pid
logger.warning('Terminating process: (PID: {0:d}).'.format(pid))
process.terminate()
process.join(timeout=self._PROCESS_JOIN_TIMEOUT)
if process.is_alive():
logger.warning('Killing process: (PID: {0:d}).'.format(pid))
self._KillProcess(pid)
|
Terminate a process.
Args:
process (MultiProcessBaseProcess): process to terminate.
|
juraj-google-style
|
def create_cloudwatch_event(app_name, env, region, rules):
session = boto3.Session(profile_name=env, region_name=region)
cloudwatch_client = session.client('events')
rule_name = rules.get('rule_name')
schedule = rules.get('schedule')
rule_description = rules.get('rule_description')
json_input = rules.get('json_input', {})
if schedule is None:
LOG.critical('Schedule is required and no schedule is defined!')
raise InvalidEventConfiguration('Schedule is required and no schedule is defined!')
if rule_name is None:
LOG.critical('Rule name is required and no rule_name is defined!')
raise InvalidEventConfiguration('Rule name is required and no rule_name is defined!')
else:
LOG.info('%s and %s', app_name, rule_name)
rule_name = "{}_{}".format(app_name, rule_name.replace(' ', '_'))
if rule_description is None:
rule_description = "{} - {}".format(app_name, rule_name)
lambda_arn = get_lambda_arn(app=app_name, account=env, region=region)
account_id = get_env_credential(env=env)['accountId']
principal = "events.amazonaws.com"
statement_id = '{}_cloudwatch_{}'.format(app_name, rule_name)
source_arn = 'arn:aws:events:{}:{}:rule/{}'.format(region, account_id, rule_name)
add_lambda_permissions(
function=lambda_arn,
statement_id=statement_id,
action='lambda:InvokeFunction',
principal=principal,
source_arn=source_arn,
env=env,
region=region, )
cloudwatch_client.put_rule(
Name=rule_name,
ScheduleExpression=schedule,
State='ENABLED',
Description=rule_description, )
targets = []
json_payload = '{}'.format(json.dumps(json_input))
target = {
"Id": app_name,
"Arn": lambda_arn,
"Input": json_payload,
}
targets.append(target)
put_targets_response = cloudwatch_client.put_targets(Rule=rule_name, Targets=targets)
LOG.debug('Cloudwatch put targets response: %s', put_targets_response)
LOG.info('Created Cloudwatch event "%s" with schedule: %s', rule_name, schedule)
|
Create cloudwatch event for lambda from rules.
Args:
app_name (str): name of the lambda function
env (str): Environment/Account for lambda function
region (str): AWS region of the lambda function
rules (dict): Trigger rules from the settings
|
juraj-google-style
|
def GetMACBRepresentation(self, event):
data_type = getattr(event, 'data_type', None)
if (not data_type):
return '....'
if (data_type == 'fs:stat'):
descriptions = event.timestamp_desc.split(';')
return_characters = ['.', '.', '.', '.']
for description in descriptions:
if (description in ('mtime', definitions.TIME_DESCRIPTION_MODIFICATION)):
return_characters[0] = 'M'
elif (description in ('atime', definitions.TIME_DESCRIPTION_LAST_ACCESS)):
return_characters[1] = 'A'
elif (description in ('ctime', definitions.TIME_DESCRIPTION_CHANGE)):
return_characters[2] = 'C'
elif (description in ('crtime', definitions.TIME_DESCRIPTION_CREATION)):
return_characters[3] = 'B'
return ''.join(return_characters)
if (event.timestamp_desc in [definitions.TIME_DESCRIPTION_LAST_ACCESS, definitions.TIME_DESCRIPTION_ACCOUNT_CREATED, definitions.TIME_DESCRIPTION_LAST_VISITED, definitions.TIME_DESCRIPTION_START, definitions.TIME_DESCRIPTION_LAST_SHUTDOWN, definitions.TIME_DESCRIPTION_LAST_LOGIN, definitions.TIME_DESCRIPTION_LAST_PASSWORD_RESET, definitions.TIME_DESCRIPTION_LAST_CONNECTED, definitions.TIME_DESCRIPTION_LAST_RUN, definitions.TIME_DESCRIPTION_LAST_PRINTED]):
return '.A..'
if (event.timestamp_desc in [definitions.TIME_DESCRIPTION_MODIFICATION, definitions.TIME_DESCRIPTION_WRITTEN, definitions.TIME_DESCRIPTION_DELETED]):
return 'M...'
if (event.timestamp_desc in [definitions.TIME_DESCRIPTION_CREATION, definitions.TIME_DESCRIPTION_ADDED, definitions.TIME_DESCRIPTION_FILE_DOWNLOADED, definitions.TIME_DESCRIPTION_FIRST_CONNECTED]):
return '...B'
if (event.timestamp_desc in [definitions.TIME_DESCRIPTION_CHANGE, definitions.TIME_DESCRIPTION_ENTRY_MODIFICATION]):
return '..C.'
return '....'
|
Retrieves the MACB representation.
Args:
event (EventObject): event.
Returns:
str: MACB representation.
|
codesearchnet
|
def decode(self, decoder_input_ids, encoder_outputs, encoder_attention_mask: Optional[jnp.ndarray]=None, decoder_attention_mask: Optional[jnp.ndarray]=None, decoder_position_ids: Optional[jnp.ndarray]=None, past_key_values: Optional[dict]=None, output_attentions: Optional[bool]=None, output_hidden_states: Optional[bool]=None, return_dict: Optional[bool]=None, train: bool=False, params: Optional[dict]=None, dropout_rng: PRNGKey=None):
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
output_hidden_states = output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
return_dict = return_dict if return_dict is not None else self.config.return_dict
encoder_hidden_states = encoder_outputs[0]
if encoder_attention_mask is None:
batch_size, sequence_length = encoder_hidden_states.shape[:2]
encoder_attention_mask = jnp.ones((batch_size, sequence_length))
batch_size, sequence_length = decoder_input_ids.shape
if decoder_attention_mask is None:
decoder_attention_mask = jnp.ones((batch_size, sequence_length))
if decoder_position_ids is None:
if past_key_values is not None:
raise ValueError('Make sure to provide `decoder_position_ids` when passing `past_key_values`.')
decoder_position_ids = jnp.broadcast_to(jnp.arange(sequence_length)[None, :], (batch_size, sequence_length))
rngs = {}
if dropout_rng is not None:
rngs['dropout'] = dropout_rng
inputs = {'params': params or self.params}
if past_key_values:
inputs['cache'] = past_key_values
mutable = ['cache']
else:
mutable = False
def _decoder_forward(module, decoder_input_ids, decoder_attention_mask, decoder_position_ids, **kwargs):
decoder_module = module._get_decoder_module()
outputs = decoder_module(decoder_input_ids, decoder_attention_mask, decoder_position_ids, **kwargs)
hidden_states = outputs[0]
if self.config.tie_word_embeddings:
shared_embedding = module.model.variables['params']['shared']['embedding']
lm_logits = module.lm_head.apply({'params': {'kernel': shared_embedding.T}}, hidden_states)
else:
lm_logits = module.lm_head(hidden_states)
lm_logits += module.final_logits_bias.astype(self.dtype)
return (lm_logits, outputs)
outputs = self.module.apply(inputs, decoder_input_ids=jnp.array(decoder_input_ids, dtype='i4'), decoder_attention_mask=jnp.array(decoder_attention_mask, dtype='i4'), decoder_position_ids=jnp.array(decoder_position_ids, dtype='i4'), encoder_hidden_states=encoder_hidden_states, encoder_attention_mask=jnp.array(encoder_attention_mask, dtype='i4'), output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict, deterministic=not train, rngs=rngs, mutable=mutable, method=_decoder_forward)
if past_key_values is None:
lm_logits, decoder_outputs = outputs
else:
(lm_logits, decoder_outputs), past = outputs
if return_dict:
outputs = FlaxCausalLMOutputWithCrossAttentions(logits=lm_logits, hidden_states=decoder_outputs.hidden_states, attentions=decoder_outputs.attentions, cross_attentions=decoder_outputs.cross_attentions)
else:
outputs = (lm_logits,) + decoder_outputs[1:]
if past_key_values is not None and return_dict:
outputs['past_key_values'] = unfreeze(past['cache'])
return outputs
elif past_key_values is not None and (not return_dict):
outputs = outputs[:1] + (unfreeze(past['cache']),) + outputs[1:]
return outputs
|
Returns:
Example:
```python
>>> from transformers import AutoTokenizer, FlaxMBartForConditionalGeneration
>>> model = FlaxMBartForConditionalGeneration.from_pretrained("facebook/mbart-large-cc25")
>>> tokenizer = AutoTokenizer.from_pretrained("facebook/mbart-large-cc25")
>>> text = "My friends are cool but they eat too many carbs."
>>> inputs = tokenizer(text, max_length=1024, return_tensors="jax")
>>> encoder_outputs = model.encode(**inputs)
>>> decoder_start_token_id = model.config.decoder_start_token_id
>>> decoder_input_ids = jnp.ones((inputs.input_ids.shape[0], 1), dtype="i4") * decoder_start_token_id
>>> outputs = model.decode(decoder_input_ids, encoder_outputs)
>>> logits = outputs.logits
```
|
github-repos
|
def prune(self, regex='.*'):
return filetree(self.root, ignore=self.ignore, regex=regex)
|
Prune leaves of filetree according to specified
regular expression.
Args:
regex (str): Regular expression to use in pruning tree.
|
codesearchnet
|
def pred_to_prob(Y_h, k):
Y_h = Y_h.clone()
if Y_h.dim() > 1:
Y_h = Y_h.squeeze()
assert Y_h.dim() == 1
assert (Y_h >= 1).all()
assert (Y_h <= k).all()
n = Y_h.shape[0]
Y_s = torch.zeros((n, k), dtype=Y_h.dtype, device=Y_h.device)
for i, j in enumerate(Y_h):
Y_s[i, j - 1] = 1.0
return Y_s
|
Converts a 1D tensor of predicted labels into a 2D tensor of probabilistic labels
Args:
Y_h: an [n], or [n,1] tensor of predicted (int) labels in {1,...,k}
k: the largest possible label in Y_h
Returns:
Y_s: a torch.FloatTensor of shape [n, k] where Y_s[i, j-1] is the probabilistic
label for item i and label j
|
juraj-google-style
|
def _openfile(instance, filething, filename, fileobj, writable, create):
assert not create or writable
if isinstance(filething, FileThing):
filename = filething.filename
fileobj = filething.fileobj
filething = None
if filething is not None:
if is_fileobj(filething):
fileobj = filething
elif hasattr(filething, "__fspath__"):
filename = filething.__fspath__()
if not isinstance(filename, (bytes, text_type)):
raise TypeError("expected __fspath__() to return a filename")
else:
filename = filething
if instance is not None:
if not writable:
instance.filename = filename
elif filename is None:
filename = getattr(instance, "filename", None)
if fileobj is not None:
verify_fileobj(fileobj, writable=writable)
yield FileThing(fileobj, filename, filename or fileobj_name(fileobj))
elif filename is not None:
verify_filename(filename)
inmemory_fileobj = False
try:
fileobj = open(filename, "rb+" if writable else "rb")
except IOError as e:
if writable and e.errno == errno.EOPNOTSUPP:
try:
with open(filename, "rb") as fileobj:
fileobj = BytesIO(fileobj.read())
except IOError as e2:
raise MutagenError(e2)
inmemory_fileobj = True
elif create and e.errno == errno.ENOENT:
assert writable
try:
fileobj = open(filename, "wb+")
except IOError as e2:
raise MutagenError(e2)
else:
raise MutagenError(e)
with fileobj as fileobj:
yield FileThing(fileobj, filename, filename)
if inmemory_fileobj:
assert writable
data = fileobj.getvalue()
try:
with open(filename, "wb") as fileobj:
fileobj.write(data)
except IOError as e:
raise MutagenError(e)
else:
raise TypeError("Missing filename or fileobj argument")
|
yields a FileThing
Args:
filething: Either a file name, a file object or None
filename: Either a file name or None
fileobj: Either a file object or None
writable (bool): if the file should be opened
create (bool): if the file should be created if it doesn't exist.
implies writable
Raises:
MutagenError: In case opening the file failed
TypeError: in case neither a file name or a file object is passed
|
juraj-google-style
|
def add_http_endpoint(self, url, request_handler):
self.app.router.add_route('*', url, request_handler)
|
This method provides a programatic way of added invidual routes
to the http server.
Args:
url (str): the url to be handled by the request_handler
request_handler (nautilus.network.RequestHandler): The request handler
|
codesearchnet
|
def unzip(input_layer, split_dim=0, num_splits=2):
shape = input_layer.shape
_check_split_dims(num_splits, split_dim, shape)
splits = functions.unzip(input_layer, split_dim, shape[split_dim], num_splits)
return input_layer.with_sequence(splits)
|
Unzips this Tensor along the split_dim into num_splits Equal chunks.
Examples:
* `[1, 2, 3, 4] -> [1, 3], [2, 4]`
* `[[1, 1], [2, 2], [3, 3], [4, 4]] -> [[1, 1], [3, 3]], [[2, 2], [4, 4]]`
Args:
input_layer: The chainable object, supplied.
split_dim: The dimension to split along. Defaults to batch.
num_splits: The number of splits.
Returns:
A list of PrettyTensors.
Raises:
ValueError: If split_dim is out of range or isn't divided evenly by
num_splits.
|
codesearchnet
|
def Trim(self, flags):
logger.info('Trimming!')
flags = bytearray(flags)
length = (1 << (self.Depth - 1))
while (len(flags) < length):
flags.append(0)
MerkleTree._TrimNode(self.Root, 0, self.Depth, flags)
|
Trim the nodes from the tree keeping only the root hash.
Args:
flags: "0000" for trimming, any other value for keeping the nodes.
|
codesearchnet
|
def _get_graph(self):
with self._lock:
return self._graph
|
Returns pydot.Dot object for the pipeline graph.
The purpose of this method is to avoid accessing the graph while it is
updated. No one except for this method should be accessing _graph directly.
Returns:
(pydot.Dot)
|
github-repos
|
def stChromagram(signal, fs, win, step, PLOT=False):
win = int(win)
step = int(step)
signal = numpy.double(signal)
signal = signal / (2.0 ** 15)
DC = signal.mean()
MAX = (numpy.abs(signal)).max()
signal = (signal - DC) / (MAX - DC)
N = len(signal)
cur_p = 0
count_fr = 0
nfft = int(win / 2)
nChroma, nFreqsPerChroma = stChromaFeaturesInit(nfft, fs)
chromaGram = numpy.array([], dtype=numpy.float64)
while (cur_p + win - 1 < N):
count_fr += 1
x = signal[cur_p:cur_p + win]
cur_p = cur_p + step
X = abs(fft(x))
X = X[0:nfft]
X = X / len(X)
chromaNames, C = stChromaFeatures(X, fs, nChroma, nFreqsPerChroma)
C = C[:, 0]
if count_fr == 1:
chromaGram = C.T
else:
chromaGram = numpy.vstack((chromaGram, C.T))
FreqAxis = chromaNames
TimeAxis = [(t * step) / fs for t in range(chromaGram.shape[0])]
if (PLOT):
fig, ax = plt.subplots()
chromaGramToPlot = chromaGram.transpose()[::-1, :]
Ratio = int(chromaGramToPlot.shape[1] / (3*chromaGramToPlot.shape[0]))
if Ratio < 1:
Ratio = 1
chromaGramToPlot = numpy.repeat(chromaGramToPlot, Ratio, axis=0)
imgplot = plt.imshow(chromaGramToPlot)
fstep = int(nfft / 5.0)
ax.set_yticks(range(int(Ratio / 2), len(FreqAxis) * Ratio, Ratio))
ax.set_yticklabels(FreqAxis[::-1])
TStep = int(count_fr / 3)
TimeTicks = range(0, count_fr, TStep)
TimeTicksLabels = ['%.2f' % (float(t * step) / fs) for t in TimeTicks]
ax.set_xticks(TimeTicks)
ax.set_xticklabels(TimeTicksLabels)
ax.set_xlabel('time (secs)')
imgplot.set_cmap('jet')
plt.colorbar()
plt.show()
return (chromaGram, TimeAxis, FreqAxis)
|
Short-term FFT mag for spectogram estimation:
Returns:
a numpy array (nFFT x numOfShortTermWindows)
ARGUMENTS:
signal: the input signal samples
fs: the sampling freq (in Hz)
win: the short-term window size (in samples)
step: the short-term window step (in samples)
PLOT: flag, 1 if results are to be ploted
RETURNS:
|
juraj-google-style
|
def from_file(cls, path, fields=None, encoding='utf-8'):
path = _table_filename(path)
if (fields is None):
fields = _get_relation_from_table_path(path)
table = cls(fields)
table.attach(path, encoding=encoding)
return table
|
Instantiate a Table from a database file.
This method instantiates a table attached to the file at *path*.
The file will be opened and traversed to determine the number of
records, but the contents will not be stored in memory unless
they are modified.
Args:
path: the path to the table file
fields: the Relation schema for the table (loaded from the
relations file in the same directory if not given)
encoding: the character encoding of the file at *path*
|
codesearchnet
|
def _MergeOptional(self, a, b):
if (a and b):
if (a != b):
raise MergeError(("values must be identical if both specified ('%s' vs '%s')" % (transitfeed.EncodeUnicode(a), transitfeed.EncodeUnicode(b))))
return (a or b)
|
Tries to merge two values which may be None.
If both values are not None, they are required to be the same and the
merge is trivial. If one of the values is None and the other is not None,
the merge results in the one which is not None. If both are None, the merge
results in None.
Args:
a: The first value.
b: The second value.
Returns:
The merged value.
Raises:
MergeError: If both values are not None and are not the same.
|
codesearchnet
|
def get_catalog(self, catalog_id):
return self._load_data(self.CATALOGS_ENDPOINT, default=[], resource_id=catalog_id)
|
Return specified course catalog.
Returns:
dict: catalog details if it is available for the user.
|
codesearchnet
|
async def _auth_login(self, username, password):
mechanism = 'LOGIN'
(code, message) = (await self.do_cmd('AUTH', mechanism, SMTP.b64enc(username), success=(334,)))
try:
(code, message) = (await self.do_cmd(SMTP.b64enc(password), success=(235, 503)))
except SMTPCommandFailedError as e:
raise SMTPAuthenticationError(e.code, e.message, mechanism)
return (code, message)
|
Performs an authentication attempt using the LOGIN mechanism.
Protocol:
1. The username is base64-encoded ;
2. The string 'AUTH LOGIN' and a space character are prepended to
the base64-encoded username and sent to the server ;
3. If the server replies with a 334 return code, we can go on:
1) The password is base64-encoded and sent to the server ;
2) If the server replies with a 235 return code, the user is
authenticated.
Args:
username (str): Identifier of the user trying to authenticate.
password (str): Password for the user.
Raises:
ConnectionResetError: If the connection with the server is
unexpectedely lost.
SMTPAuthenticationError: If the authentication attempt fails.
Returns:
(int, str): A (code, message) 2-tuple containing the server
response.
|
codesearchnet
|
def _create_interval_filter(interval):
def filter_fn(value):
if ((not isinstance(value, six.integer_types)) and (not isinstance(value, float))):
raise error.HParamsError(('Cannot use an interval filter for a value of type: %s, Value: %s' % (type(value), value)))
return ((interval.min_value <= value) and (value <= interval.max_value))
return filter_fn
|
Returns a function that checkes whether a number belongs to an interval.
Args:
interval: A tensorboard.hparams.Interval protobuf describing the interval.
Returns:
A function taking a number (a float or an object of a type in
six.integer_types) that returns True if the number belongs to (the closed)
'interval'.
|
codesearchnet
|
def find_distinct(self, collection, key):
obj = getattr(self.db, collection)
result = obj.distinct(key)
return result
|
Search a collection for the distinct key values provided.
Args:
collection: The db collection. See main class documentation.
key: The name of the key to find distinct values. For example with
the indicators collection, the key could be "type".
Returns:
List of distinct values.
|
juraj-google-style
|
def __init__(self, fn, fullargspec=None):
if not callable(fn):
raise TypeError('Expected a callable object instead of: %r' % fn)
self._fn = fn
self._fullargspec = fullargspec
if isinstance(fn, (types.BuiltinFunctionType, types.MethodType, types.FunctionType)):
self.process = fn
else:
self.process = lambda element: fn(element)
super().__init__()
|
Initializes a CallableWrapperDoFn object wrapping a callable.
Args:
fn: A callable object.
Raises:
TypeError: if fn parameter is not a callable type.
|
github-repos
|
def _GetLines(line_strings):
lines = []
for line_string in line_strings:
line = list(map(int, line_string.split('-', 1)))
if line[0] < 1:
raise errors.YapfError('invalid start of line range: %r' % line)
if line[0] > line[1]:
raise errors.YapfError('end comes before start in line range: %r' % line)
lines.append(tuple(line))
return lines
|
Parses the start and end lines from a line string like 'start-end'.
Arguments:
line_strings: (array of string) A list of strings representing a line
range like 'start-end'.
Returns:
A list of tuples of the start and end line numbers.
Raises:
ValueError: If the line string failed to parse or was an invalid line range.
|
github-repos
|
def get_cluster_interfaces(cluster, extra_cond=(lambda nic: True)):
nics = get_nics(cluster)
nics = [(nic['device'], nic['name']) for nic in nics if (nic['mountable'] and (nic['interface'] == 'Ethernet') and (not nic['management']) and extra_cond(nic))]
nics = sorted(nics)
return nics
|
Get the network interfaces names corresponding to a criteria.
Note that the cluster is passed (not the individual node names), thus it is
assumed that all nodes in a cluster have the same interface names same
configuration. In addition to ``extra_cond``, only the mountable and
Ehernet interfaces are returned.
Args:
cluster(str): the cluster to consider
extra_cond(lambda): boolean lambda that takes the nic(dict) as
parameter
|
codesearchnet
|
def __init__(self, forward_core, backward_core, name="bidir_rnn"):
super(BidirectionalRNN, self).__init__(name=name)
self._forward_core = forward_core
self._backward_core = backward_core
def _is_recurrent(core):
has_rnn_core_interface = (hasattr(core, "initial_state") and
hasattr(core, "output_size") and
hasattr(core, "state_size"))
return isinstance(core, rnn_core.RNNCore) or has_rnn_core_interface
if not(_is_recurrent(forward_core) and _is_recurrent(backward_core)):
raise ValueError("Forward and backward cores must both be instances of"
"RNNCore.")
|
Construct a Bidirectional RNN core.
Args:
forward_core: callable RNNCore module that computes forward states.
backward_core: callable RNNCore module that computes backward states.
name: name of the module.
Raises:
ValueError: if not all the modules are recurrent.
|
juraj-google-style
|
def _from_components(self, components):
raise NotImplementedError('%s._from_components()' % type(self).__name__)
|
Reconstructs a value from a nested structure of Tensor/CompositeTensor.
Args:
components: A nested structure of `tf.Tensor` or `tf.CompositeTensor`,
compatible with `self._component_specs`. (Caller is responsible for
ensuring compatibility.)
Returns:
A value that is compatible with this `TypeSpec`.
|
github-repos
|
def helper_list(access_token, oid, path):
if (oid != ''):
path = ''.join([path, "('", oid, "')"])
endpoint = ''.join([ams_rest_endpoint, path])
return do_ams_get(endpoint, path, access_token)
|
Helper Function to list a URL path.
Args:
access_token (str): A valid Azure authentication token.
oid (str): An OID.
path (str): A URL Path.
Returns:
HTTP response. JSON body.
|
codesearchnet
|
def unstage_signature(vcs, signature):
evidence_path = _get_staged_history_path(vcs)
staged = get_staged_signatures(vcs)
if signature not in staged:
raise NotStagedError
staged.remove(signature)
string = '\n'.join(staged)
with open(evidence_path, 'w') as f:
f.write(string)
|
Remove `signature` from the list of staged signatures
Args:
vcs (easyci.vcs.base.Vcs)
signature (basestring)
Raises:
NotStagedError
|
juraj-google-style
|
def get_object(cls, api_token, id):
load_balancer = cls(token=api_token, id=id)
load_balancer.load()
return load_balancer
|
Class method that will return a LoadBalancer object by its ID.
Args:
api_token (str): DigitalOcean API token
id (str): Load Balancer ID
|
juraj-google-style
|
def __init__(self, message):
super(CryptographicFailure, self).__init__(
reason=enums.ResultReason.CRYPTOGRAPHIC_FAILURE,
message=message
)
|
Create a CryptographicFailure exception.
Args:
message (string): A string containing information about the error.
|
juraj-google-style
|
def element(self, using, value):
return self._execute(Command.FIND_CHILD_ELEMENT, {
'using': using,
'value': value
})
|
find an element in the current element.
Support:
Android iOS Web(WebView)
Args:
using(str): The element location strategy.
value(str): The value of the location strategy.
Returns:
WebElement Object.
Raises:
WebDriverException.
|
juraj-google-style
|
def get_pending_reboot():
checks = (get_pending_update, get_pending_file_rename, get_pending_servermanager, get_pending_component_servicing, get_reboot_required_witnessed, get_pending_computer_name, get_pending_domain_join)
for check in checks:
if check():
return True
return False
|
Determine whether there is a reboot pending.
.. versionadded:: 2016.11.0
Returns:
bool: ``True`` if the system is pending reboot, otherwise ``False``
CLI Example:
.. code-block:: bash
salt '*' system.get_pending_reboot
|
codesearchnet
|
def _BuildIntersection(self, type_list):
type_list = tuple(type_list)
if len(type_list) == 1:
return type_list[0]
else:
return ' and '.join(type_list)
|
Builds a intersection of the types in type_list.
Args:
type_list: A list of strings representing types.
Returns:
A string representing the intersection of the types in type_list.
Simplifies Intersection[X] to X and Intersection[X, None] to Optional[X].
|
github-repos
|
def get_watermarks(self, applied_ptransform: AppliedPTransform) -> '_TransformWatermarks':
while applied_ptransform.parts:
applied_ptransform = applied_ptransform.parts[-1]
return self._transform_to_watermarks[applied_ptransform]
|
Gets the input and output watermarks for an AppliedPTransform.
If the applied_ptransform has not processed any elements, return a
watermark with minimum value.
Args:
applied_ptransform: AppliedPTransform to get the watermarks for.
Returns:
A snapshot (TransformWatermarks) of the input watermark and output
watermark for the provided transform.
|
github-repos
|
def _AssertProtoDictEquals(self, expected_dict, actual_dict, verbose=False, update_goldens=False, additional_missing_object_message='', api_version=2):
diffs = []
verbose_diffs = []
expected_keys = set(expected_dict.keys())
actual_keys = set(actual_dict.keys())
only_in_expected = expected_keys - actual_keys
only_in_actual = actual_keys - expected_keys
all_keys = expected_keys | actual_keys
updated_keys = []
for key in all_keys:
diff_message = ''
verbose_diff_message = ''
if key in only_in_expected:
diff_message = 'Object %s expected but not found (removed). %s' % (key, additional_missing_object_message)
verbose_diff_message = diff_message
elif key in only_in_actual:
diff_message = 'New object %s found (added).' % key
verbose_diff_message = diff_message
else:
self.maxDiff = None
try:
self.assertProtoEquals(expected_dict[key], actual_dict[key])
except AssertionError as e:
updated_keys.append(key)
diff_message = 'Change detected in python object: %s.' % key
verbose_diff_message = str(e)
if diff_message:
diffs.append(diff_message)
verbose_diffs.append(verbose_diff_message)
if diffs:
diff_count = len(diffs)
logging.error(self._test_readme_message)
logging.error('%d differences found between API and golden.', diff_count)
if update_goldens:
logging.warning(self._update_golden_warning)
for key in only_in_expected:
filepath = _KeyToFilePath(key, api_version)
file_io.delete_file(filepath)
for key in only_in_actual | set(updated_keys):
filepath = _KeyToFilePath(key, api_version)
file_io.write_string_to_file(filepath, text_format.MessageToString(actual_dict[key]))
else:
for d, verbose_d in zip(diffs, verbose_diffs):
logging.error(' %s', d)
logging.error(' %s', verbose_d)
self.fail('%d differences found between API and golden.' % diff_count)
else:
logging.info('No differences found between API and golden.')
|
Diff given dicts of protobufs and report differences a readable way.
Args:
expected_dict: a dict of TFAPIObject protos constructed from golden files.
actual_dict: a dict of TFAPIObject protos constructed by reading from the
TF package linked to the test.
verbose: Whether to log the full diffs, or simply report which files were
different.
update_goldens: Whether to update goldens when there are diffs found.
additional_missing_object_message: Message to print when a symbol is
missing.
api_version: TensorFlow API version to test.
|
github-repos
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.