code stringlengths 20 4.93k | docstring stringlengths 33 1.27k | source stringclasses 3
values |
|---|---|---|
def heightmap_lerp_hm(
hm1: np.ndarray, hm2: np.ndarray, hm3: np.ndarray, coef: float
) -> None:
lib.TCOD_heightmap_lerp_hm(
_heightmap_cdata(hm1),
_heightmap_cdata(hm2),
_heightmap_cdata(hm3),
coef,
) | Perform linear interpolation between two heightmaps storing the result
in ``hm3``.
This is the same as doing ``hm3[:] = hm1[:] + (hm2[:] - hm1[:]) * coef``
Args:
hm1 (numpy.ndarray): The first heightmap.
hm2 (numpy.ndarray): The second heightmap to add to the first.
hm3 (numpy.ndarray): A destination heightmap to sto... | juraj-google-style |
def replace_punctuation(self, text, excluded=None, replacement=''):
if (excluded is None):
excluded = set()
elif (not isinstance(excluded, set)):
excluded = set(excluded)
punct = ''.join(self.__punctuation.difference(excluded))
return self.replace_characters(text, characters=punct, repla... | Replace punctuation symbols in text.
Removes punctuation from input text or replaces them with a
string if specified. Characters replaced will be those
in string.punctuation.
Args:
text: The text to be processed.
excluded: Set of characters to exclude.
replacement: New text that will replace punctuation.
Returns:
Th... | codesearchnet |
def __init__(self, type_, value):
self.type_ = type_
self.value = value
super(CastError, self).__init__(
'Unable to cast "{}" to {}.'.format(value, type_.__name__)) | Instantiate the exception with a descriptive message.
Args:
type_: The type to which the cast was attempting to convert the
value.
value: The value that was attempted to be cast. | juraj-google-style |
def add_dspam_headers(self, results):
for header in self.headers:
hname = (self.header_prefix + header)
if (header.lower() in results):
hvalue = results[header.lower()]
logger.debug('<{}> Adding header {}: {}'.format(self.id, hname, hvalue))
self.addheader(hname, ... | Format DSPAM headers with passed results, and add them to the message.
Args:
results -- A results dictionary from DspamClient. | codesearchnet |
def __init__(self, trainer_id):
if not trainer_id:
raise ValueError('tf.data service cross-trainer cache requires a non-empty trainer ID.')
self.trainer_id = trainer_id | Constructs a CrossTrainerCache.
Args:
trainer_id: Each training job has a unique ID. Once a job has consumed
data, the data remains in the cache and is re-used by jobs with different
`trainer_id`s. Requests with the same `trainer_id` do not re-use data.
Raises:
ValueError if `trainer_id` is empty. | github-repos |
def __init__(self, add_tag_methods=None):
super(PacketTags, self).__init__()
self.tag_methods = [PacketTags._tag_net_direction, PacketTags._tag_nxdomain]
if add_tag_methods:
self.tag_methods += add_tag_methods
self.output_stream = self.ta... | Initialize PacketTags Class
Args:
add_tag_methods: a list of additional tag methods (optional, defaults to None))
Note: all methods must take the data dictionary as an argmument (e.g. tag_method(data)) | juraj-google-style |
def _shadow_model_variables(shadow_vars):
G = tf.get_default_graph()
curr_shadow_vars = set([v.name for v in shadow_vars])
model_vars = tf.model_variables()
shadow_model_vars = []
for v in model_vars:
assert v.name.startswith('tower'), 'Found some MODEL_VARIABLES created outside of the tower... | Create shadow vars for model_variables as well, and add to the list of ``shadow_vars``.
Returns:
list of (shadow_model_var, local_model_var) used for syncing. | codesearchnet |
def to_view(self, view_name):
from . import _view
return _view.View(view_name, self._context).create(self._sql) | Create a View from this Query.
Args:
view_name: the name of the View either as a string or a 3-part tuple
(projectid, datasetid, name).
Returns:
A View for the Query. | codesearchnet |
def trace_set_buffer_capacity(self, size):
cmd = enums.JLinkTraceCommand.SET_CAPACITY
data = ctypes.c_uint32(size)
res = self._dll.JLINKARM_TRACE_Control(cmd, ctypes.byref(data))
if (res == 1):
raise errors.JLinkException('Failed to set trace buffer size.')
return None | Sets the capacity for the trace buffer.
Args:
self (JLink): the ``JLink`` instance.
size (int): the new capacity for the trace buffer.
Returns:
``None`` | codesearchnet |
def get_attribute_from_config(config, section, attribute):
section = config.get(section)
if section:
option = section.get(attribute)
if option:
return option
raise ConfigurationError("Config file badly formed!\nFailed to get attribute '{}' from section '{}'!".format(attribute, se... | Try to parse an attribute of the config file.
Args:
config (defaultdict): A defaultdict.
section (str): The section of the config file to get information from.
attribute (str): The attribute of the section to fetch.
Returns:
str: The string corresponding to the section and attribute.
Raises:
ConfigurationError | codesearchnet |
def Verify(self, mempool):
logger.info("Verifying transaction: %s " % self.Hash.ToBytes())
return Helper.VerifyScripts(self) | Verify the transaction.
Args:
mempool:
Returns:
bool: True if verified. False otherwise. | juraj-google-style |
def record_factory(app, fields=None):
record = Record(app, {
'$type': Record._type,
'isNew': True,
'applicationId': app.id,
'comments': {
'$type': 'System.Collections.Generic.Dictionary`2[[System.String, mscorlib],[System.Collections.Generic.List`1[[Core.Models.... | Return a temporary Record instance to be used for field validation and value parsing
Args:
app (App): Target App to create a transient Record instance for
fields (dict): Optional dict of fields and values to set on new Record instance before returning
Returns:
Record: Unsaved Record instance to be used for validation... | juraj-google-style |
def parse_binary_descriptor(bindata):
func_names = {0: 'copy_latest_a', 1: 'average_a', 2: 'copy_all_a', 3: 'sum_a', 4: 'copy_count_a', 5: 'trigger_streamer', 6: 'call_rpc', 7: 'subtract_afromb'}
if (len(bindata) != 20):
raise ArgumentError('Invalid binary node descriptor with incorrect size', size=len(... | Convert a binary node descriptor into a string descriptor.
Binary node descriptor are 20-byte binary structures that encode all
information needed to create a graph node. They are used to communicate
that information to an embedded device in an efficent format. This
function exists to turn such a compressed node des... | codesearchnet |
def server_hardware_types(self):
if (not self.__server_hardware_types):
self.__server_hardware_types = ServerHardwareTypes(self.__connection)
return self.__server_hardware_types | Gets the ServerHardwareTypes API client.
Returns:
ServerHardwareTypes: | codesearchnet |
def parse_int(value: Any) -> Numeric:
return int(value) | Attempts to parse a valid integer value from the provided value.
Args:
* value: of Any type
Returns:
* int value: if valid
Raises:
* ValueError: if parsing failed | github-repos |
def _get_context_name(self, app=None):
elements = [self.__class__.__name__, 'context', text_type(id(self))]
if app:
elements.append(text_type(id(app)))
else:
try:
elements.append(text_type(id(self.app)))
except RuntimeError:
pass
return '_'.join(elements) | Generate the name of the context variable for this component & app.
Because we store the ``context`` in a Local so the component
can be used across multiple apps, we cannot store the context on the
instance itself. This function will generate a unique and predictable
key in which to store the context.
Returns:
str: T... | codesearchnet |
def match_rules_context(tree, rules, parent_context={}):
for template, match_rules in rules.items():
context = parent_context.copy()
if match_template(tree, template, context):
for key, child_rules in match_rules.items():
child_context = match_rules_context(context[k... | Recursively matches a Tree structure with rules and returns context
Args:
tree (Tree): Parsed tree structure
rules (dict): See match_rules
parent_context (dict): Context of parent call
Returns:
dict: Context matched dictionary of matched rules or
None if no match | juraj-google-style |
def _get_members(self, class_obj, member_type, include_in_public=None):
try:
app = self.state.document.settings.env.app
except AttributeError:
app = None
if (not include_in_public):
include_in_public = []
all_members = []
for member_name in dir(class_obj):
try:
... | Return class members of the specified type.
class_obj: Class object.
member_type: Member type ('method' or 'attribute').
include_in_public: set/list/tuple with member names that should be
included in public members in addition to the public names (those
starting without underscore).
Returns:
tuple(public_members, a... | codesearchnet |
def group_protos(cls, proto_list: List[types.ProtobufBaseType], **kwargs) -> Dict[str, List[types.ProtobufBaseType]]:
del proto_list, kwargs
return [] | Creates a dict of batchable protos.
For a list of protos, generates a dictionary `{key: grouped_protos}` such
that the `grouped_protos` can be batched together.
Args:
proto_list: A list of `Instrument` protos.
**kwargs: Any extra arguments. E.g., pricing configuration.
Returns:
A dictionary of grouped protos. | github-repos |
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 n... | juraj-google-style |
def determine_action(self, issue):
resource_type = self.resource_types[issue.resource.resource_type_id]
issue_alert_schedule = (self.alert_schedule[resource_type] if (resource_type in self.alert_schedule) else self.alert_schedule['*'])
action_item = {'action': None, 'action_description': None, 'last_alert':... | Determine the action we should take for the issue
Args:
issue: Issue to determine action for
Returns:
`dict` | codesearchnet |
def __init__(self, *timeslots: List[Timeslot]):
self._table = defaultdict(list)
for slot in timeslots:
for interval in self._table[slot.channel]:
if slot.interval.has_overlap(interval):
raise PulseError("Cannot create TimeslotCollection from over... | Create a new time-slot collection.
Args:
*timeslots: list of time slots
Raises:
PulseError: when overlapped time slots are specified | juraj-google-style |
def wait_for_bq_job(self, job_reference, sleep_duration_sec=5, max_retries=0):
retry = 0
while True:
retry += 1
job = self.get_job(job_reference.projectId, job_reference.jobId, job_reference.location)
_LOGGER.info('Job %s status: %s', job.id, job.status.state)
if job.status.state... | Poll job until it is DONE.
Args:
job_reference: bigquery.JobReference instance.
sleep_duration_sec: Specifies the delay in seconds between retries.
max_retries: The total number of times to retry. If equals to 0,
the function waits forever.
Raises:
`RuntimeError`: If the job is FAILED or the number of retries has bee... | github-repos |
def _create_state_graph(self, name):
import_collections = [tf_v1.GraphKeys.GLOBAL_VARIABLES, tf_v1.GraphKeys.MODEL_VARIABLES, tf_v1.GraphKeys.TABLE_INITIALIZERS, tf_v1.GraphKeys.ASSET_FILEPATHS, tf_v1.GraphKeys.COND_CONTEXT, tf_v1.GraphKeys.WHILE_CONTEXT]
if self._trainable:
import_collections.extend([t... | Creates the graph nodes that hold the state of the Module.
Args:
name: name scope to create the state graph in.
Returns:
A tuple consisting of:
variables_tensor_map: a map from tensor names in the original graph def
to the created Variables objects.
state_map: a map from tensors names in the original graph def to the... | codesearchnet |
def _order_pases(self, passes):
passes = set(passes)
pass_deps = {}
for opt in passes:
(_, before, after) = self._known_passes[opt]
if (opt not in pass_deps):
pass_deps[opt] = set()
for after_pass in after:
pass_deps[opt].add(after_pass)
for other in b... | Topologically sort optimization passes.
This ensures that the resulting passes are run in order
respecting before/after constraints.
Args:
passes (iterable): An iterable of pass names that should
be included in the optimization passes run. | codesearchnet |
def listdir(self, target_directory):
target_directory = self.resolve_path(target_directory, allow_fd=True)
directory = self.confirmdir(target_directory)
directory_contents = directory.contents
return list(directory_contents.keys()) | Return a list of file names in target_directory.
Args:
target_directory: Path to the target directory within the
fake filesystem.
Returns:
A list of file names within the target directory in arbitrary
order.
Raises:
OSError: if the target is not a directory. | juraj-google-style |
def AddSubkey(self, registry_key):
name = registry_key.name.upper()
if name in self._subkeys:
raise KeyError(
'Subkey: {0:s} already exists.'.format(registry_key.name))
self._subkeys[name] = registry_key
key_path = self._JoinKeyPath([self._key_path, registry_key.name])
registr... | Adds a subkey.
Args:
registry_key (WinRegistryKey): Windows Registry subkey.
Raises:
KeyError: if the subkey already exists. | juraj-google-style |
def init_op(self):
return self._init_op | Return the Init Op used by the supervisor.
Returns:
An Op or `None`. | github-repos |
def match_criterion(self, tag):
return tag.name == self.reference_tag_name and \
tag.attrs.get('kind', '') == self.reference_tag_kind | Override. Determine if a tag has the desired name and kind attribute
value.
Args:
tag: A BeautifulSoup Tag.
Returns:
True if tag has the desired name and kind, otherwise False. | juraj-google-style |
def _pad_modernbert_output(inputs: torch.Tensor, indices: torch.Tensor, batch: int, seqlen: int) -> torch.Tensor:
if inputs.dim() == 1:
output = torch.zeros(batch * seqlen, dtype=inputs.dtype, device=inputs.device)
output[indices] = inputs
padded_inputs = output.view(batch, seqlen)
else:... | Add padding to sequences.
Args:
inputs: (total_nnz, ...) or (total_nnz,), where total_nnz = number of tokens selected in attention_mask.
indices: (total_nnz)
batch: int, batch size
seqlen: int, max sequence length
Returns:
padded_inputs: (batch, seqlen, ...) or (batch, seqlen) | github-repos |
def is_generic_union(type_: Type) -> bool:
if hasattr(typing, '_GenericAlias'):
return (isinstance(type_, typing._GenericAlias) and
type_.__origin__ is Union)
else:
if hasattr(typing, '_Union'):
return isinstance(type_, typing._Union) ... | Determines whether a type is a Union[...].
How to do this varies for different Python versions, due to the
typing library not having a stable API. This functions smooths
over the differences.
Args:
type_: The type to check.
Returns:
True iff it's a Union[...something...]. | juraj-google-style |
def FromEncoded(cls, bindata):
if (len(bindata) != 8):
raise ArgumentError('Invalid binary slot descriptor with invalid length', length=len(bindata), expected=8, data=bindata)
(slot, match_op) = struct.unpack('<B6xB', bindata)
match_name = cls.KNOWN_MATCH_CODES.get(match_op)
if (match_name is No... | Create a slot identifier from an encoded binary descriptor.
These binary descriptors are used to communicate slot targeting
to an embedded device. They are exactly 8 bytes in length.
Args:
bindata (bytes): The 8-byte binary descriptor.
Returns:
SlotIdentifier | codesearchnet |
def _push_frontier(self, early_frontier: Dict[(ops.Qid, int)], late_frontier: Dict[(ops.Qid, int)], update_qubits: Iterable[ops.Qid]=None) -> Tuple[(int, int)]:
if (update_qubits is None):
update_qubits = set(early_frontier).difference(late_frontier)
n_new_moments = (max(((early_frontier.get(q, 0) - lat... | Inserts moments to separate two frontiers.
After insertion n_new moments, the following holds:
for q in late_frontier:
early_frontier[q] <= late_frontier[q] + n_new
for q in update_qubits:
early_frontier[q] the identifies the same moment as before
(but whose index may have changed if this moment is after
those inserte... | codesearchnet |
def run(self, resources):
hwman = resources['connection']
con = hwman.hwman.controller()
test_interface = con.test_interface()
try:
test_interface.synchronize_clock()
print('Time currently set at %s' % test_interface.current_time_str())
except:
... | Sets the RTC timestamp to UTC.
Args:
resources (dict): A dictionary containing the required resources that
we needed access to in order to perform this step. | juraj-google-style |
def _get_data_buffer_time_limit_ms(experiments):
for experiment in experiments:
if re.match('data_buffer_time_limit_ms=', experiment):
return int(re.match('data_buffer_time_limit_ms=(?P<data_buffer_time_limit_ms>.*)', experiment).group('data_buffer_time_limit_ms'))
return 0 | Defines the time limt of the outbound data buffering.
Note: data_buffer_time_limit_ms is an experimental flag and might
not be available in future releases.
Returns:
an int indicating the time limit in milliseconds of the outbound
data buffering. Default is 0 (disabled) | github-repos |
def sample_with_temperature(x, dim, temperature=1.0, dtype=tf.int32, name=None):
dim = convert_to_dimension(dim)
with tf.name_scope(name, default_name="sample_with_temperature"):
if temperature != 0.0:
tiny_val = 1e-9
g = -log(-log(
random_uniform(
... | Either argmax or random sampling.
Args:
x: a Tensor.
dim: a Dimension in x.shape.dims
temperature: a float 0.0=argmax 1.0=random
dtype: a tf.dtype (for the output)
name: an optional string
Returns:
a Tensor with type dtype. | juraj-google-style |
def _process_celeba_config_file(self, file_path):
with tf.io.gfile.GFile(file_path) as f:
data_raw = f.read()
lines = data_raw.split("\n")
keys = lines[1].strip().split()
values = {}
for line in lines[2:-1]:
row_values = line.strip().split()
values[row_values[0]] ... | Unpack the celeba config file.
The file starts with the number of lines, and a header.
Afterwards, there is a configuration for each file: one per line.
Args:
file_path: Path to the file with the configuration.
Returns:
keys: names of the attributes
values: map from the file name to the list of attribute values for
... | juraj-google-style |
def _align_monomer(self, monomer, mon_vector, move_direction):
axis = np.cross(mon_vector, move_direction)
origin = monomer[self.start].coords
angle = get_angle(mon_vector, move_direction)
op = SymmOp.from_origin_axis_angle(origin, axis, angle)
monomer.apply_operation(op... | rotate the monomer so that it is aligned along the move direction
Args:
monomer (Molecule)
mon_vector (numpy.array): molecule vector that starts from the
start atom index to the end atom index
move_direction (numpy.array): the direction of the polymer chain
extension | juraj-google-style |
def Matches(self, file_entry):
if not self._file_scanner or not file_entry.IsFile():
return None
file_object = file_entry.GetFileObject()
if not file_object:
return False
try:
scan_state = pysigscan.scan_state()
self._file_scanner.scan_file_object(scan_state, file_object)
... | Compares the file entry against the filter.
Args:
file_entry (dfvfs.FileEntry): file entry to compare.
Returns:
bool: True if the file entry matches the filter, False if not or
None if the filter does not apply. | juraj-google-style |
def _to_backend_layout(tensor_layout):
if tensor_layout.device_mesh is None:
raise ValueError('Cannot create sharding when device mesh is not set for TensorLayout.')
sharding_specs = [axis if axis else dtensor.UNSHARDED for axis in tensor_layout.axes]
dtensor_mesh = tensor_layout.device_mesh.backend... | Convert the TensorLayout to Tensorflow backend specific Sharding.
Args:
tensor_layout: TensorLayout instance to convert.
Returns:
A `tf.dtensor.Layout` instance. | github-repos |
def rtt_get_num_down_buffers(self):
cmd = enums.JLinkRTTCommand.GETNUMBUF
dir = ctypes.c_int(enums.JLinkRTTDirection.DOWN)
return self.rtt_control(cmd, dir) | After starting RTT, get the current number of down buffers.
Args:
self (JLink): the ``JLink`` instance
Returns:
The number of configured down buffers on the target.
Raises:
JLinkRTTException if the underlying JLINK_RTTERMINAL_Control call fails. | juraj-google-style |
def _check_lambda_alias(self):
aliases = self.lambda_client.list_aliases(FunctionName=self.app_name)
matched_alias = False
for alias in aliases['Aliases']:
if (alias['Name'] == self.env):
LOG.info('Found alias %s for function %s', self.env, self.app_name)
matched_alias = True... | Check if lambda alias exists.
Returns:
True if alias exists
False if alias does not exist | codesearchnet |
def _build_projection_expression(clean_table_keys):
projection_expression = ''
for key in clean_table_keys[:-1]:
projection_expression += ('{},').format(key)
projection_expression += clean_table_keys[-1]
return projection_expression | Given cleaned up keys, this will return a projection expression for
the dynamodb lookup.
Args:
clean_table_keys (dict): keys without the data types attached
Returns:
str: A projection expression for the dynamodb lookup. | juraj-google-style |
def xsrf_secret_key():
secret = memcache.get(XSRF_MEMCACHE_ID, namespace=OAUTH2CLIENT_NAMESPACE)
if (not secret):
model = SiteXsrfSecretKey.get_or_insert(key_name='site')
if (not model.secret):
model.secret = _generate_new_xsrf_secret_key()
model.put()
secret = mo... | Return the secret key for use for XSRF protection.
If the Site entity does not have a secret key, this method will also create
one and persist it.
Returns:
The secret key. | codesearchnet |
def derive_temporary_python2_environment(
destination_directory: str,
python3_environment: PreparedEnv,
verbose: bool,
env_name: str = '.test_virtualenv_py2',
python_path: str = "/usr/bin/python2.7") -> PreparedEnv:
shutil.rmtree(destination_directory)
input_directo... | Creates a python 2.7 environment starting from a prepared python 3 one.
Args:
destination_directory: Where to put the python 2 environment.
python3_environment: The prepared environment to start from.
verbose: When set, more progress output is produced.
env_name: The name to use for the virtualenv directory.
python_pa... | juraj-google-style |
def _reset_offset(self, partition):
timestamp = self._subscriptions.assignment[partition].reset_strategy
if (timestamp is OffsetResetStrategy.EARLIEST):
strategy = 'earliest'
elif (timestamp is OffsetResetStrategy.LATEST):
strategy = 'latest'
else:
raise NoOffsetForPartitionError... | Reset offsets for the given partition using the offset reset strategy.
Arguments:
partition (TopicPartition): the partition that needs reset offset
Raises:
NoOffsetForPartitionError: if no offset reset strategy is defined | codesearchnet |
def get_highest_values(self, count):
count = int(count)
assert (count <= len(self._values)), 'count must be smaller than or equal to values length. {} > {}.'.format(count, len(self._values))
assert (count > 0), 'count must be greater than 0. Got {}.'.format(count)
highest_values = sorted(self._values, r... | Get a list of the the x highest values of the Data Collection and their indices.
This is useful for situations where one needs to know the times of
the year when the largest values of a data collection occur. For example,
there is a European dayight code that requires an analysis for the hours
of the year with the gr... | codesearchnet |
def _validate_testbed_configs(testbed_configs):
seen_names = set()
for config in testbed_configs:
name = config[keys.Config.key_testbed_name.value]
_validate_testbed_name(name)
if name in seen_names:
raise MoblyConfigError('Duplicate testbed name %s found.' % name)
se... | Validates the testbed configurations.
Args:
testbed_configs: A list of testbed configuration dicts.
Raises:
MoblyConfigError: Some parts of the configuration is invalid. | github-repos |
def _WriteTimestamp(self, timestamp, filename):
try:
os.makedirs(self.timestamp_dir)
except OSError as e:
if e.errno == errno.EEXIST and os.path.isdir(self.timestamp_dir):
pass
else:
raise
filedesc, temp_filename = tempfile.mkstemp(prefix='nsscache-update-', d... | Write a given timestamp out to a file, converting to the ISO-8601
format.
We convert internal timestamp format (epoch) to ISO-8601 format, i.e.
YYYY-MM-DDThh:mm:ssZ which is basically UTC time, then write it out to a
file.
Args:
timestamp: A String in nss_cache internal timestamp format, aka time_t.
filename: A Strin... | github-repos |
def human_timestamp(__timestamp: datetime.datetime) -> str:
numstr = '. a two three four five six seven eight nine ten'.split()
matches = [(((60 * 60) * 24) * 365), (((60 * 60) * 24) * 28), (((60 * 60) * 24) * 7), ((60 * 60) * 24), (60 * 60), 60, 1]
match_names = ['year', 'month', 'week', 'day', 'hour', 'mi... | Format a relative time.
Args:
__timestamp: Event to generate relative timestamp against
Returns:
Human readable date and time offset | codesearchnet |
def ParseChat(self, parser_mediator, query, row, **unused_kwargs):
query_hash = hash(query)
participants = self._GetRowValue(query_hash, row, 'participants')
author = self._GetRowValue(query_hash, row, 'author')
dialog_partner = self._GetRowValue(query_hash, row, 'dialog_partner')
from_displayname =... | Parses a chat message.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
query (str): query that created the row.
row (sqlite3.Row): row resulting from query. | codesearchnet |
def __driver_helper(self, line):
if (line.strip() == '?'):
self.stdout.write('\n')
self.stdout.write(self.doc_string())
else:
toks = shlex.split(line[:(- 1)])
try:
msg = self.__get_help_message(toks)
except Exception as e:
self.stderr.write('\n')
... | Driver level helper method.
1. Display help message for the given input. Internally calls
self.__get_help_message() to obtain the help message.
2. Re-display the prompt and the input line.
Arguments:
line: The input line.
Raises:
Errors from helper methods print stack trace without terminating
this shell. Other ex... | codesearchnet |
def are_checksums_equal(checksum_a_pyxb, checksum_b_pyxb):
if (checksum_a_pyxb.algorithm != checksum_b_pyxb.algorithm):
raise ValueError('Cannot compare checksums calculated with different algorithms. a="{}" b="{}"'.format(checksum_a_pyxb.algorithm, checksum_b_pyxb.algorithm))
return (checksum_a_pyxb.va... | Determine if checksums are equal.
Args:
checksum_a_pyxb, checksum_b_pyxb: PyXB Checksum objects to compare.
Returns:
bool
- **True**: The checksums contain the same hexadecimal values calculated with
the same algorithm. Identical checksums guarantee (for all practical
purposes) that the checksums were calculated from... | codesearchnet |
def UpdateIncludeState(filename, include_dict, io=codecs):
headerfile = None
try:
headerfile = io.open(filename, 'r', 'utf8', 'replace')
except IOError:
return False
linenum = 0
for line in headerfile:
linenum += 1
clean_line = CleanseComments(line)
match = _R... | Fill up the include_dict with new includes found from the file.
Args:
filename: the name of the header to read.
include_dict: a dictionary in which the headers are inserted.
io: The io factory to use to read the file. Provided for testability.
Returns:
True if a header was successfully added. False otherwise. | codesearchnet |
def ExtractCredentialsFromPathSpec(self, path_spec):
credentials = manager.CredentialsManager.GetCredentials(path_spec)
for identifier in credentials.CREDENTIALS:
value = getattr(path_spec, identifier, None)
if (value is None):
continue
self.SetCredential(path_spec, identifie... | Extracts credentials from a path specification.
Args:
path_spec (PathSpec): path specification to extract credentials from. | codesearchnet |
def clip_boxes(box, box_size: Tuple[int, int]):
assert torch.isfinite(box).all(), 'Box tensor contains infinite or NaN!'
height, width = box_size
x1 = box[:, 0].clamp(min=0, max=width)
y1 = box[:, 1].clamp(min=0, max=height)
x2 = box[:, 2].clamp(min=0, max=width)
y2 = box[:, 3].clamp(min=0, max=... | Clip the boxes by limiting x coordinates to the range [0, width]
and y coordinates to the range [0, height].
Args:
box (Tensor): The box to be clipped.
box_size (height, width): The clipping box's size. | github-repos |
def get_header_from_ops_and_kernels(ops_and_kernels, include_all_ops_and_kernels):
ops_and_kernels = sorted(ops_and_kernels)
ops = set((op for op, _ in ops_and_kernels))
result_list = []
def append(s):
result_list.append(s)
_, script_name = os.path.split(sys.argv[0])
append('
append... | Returns a header for use with tensorflow SELECTIVE_REGISTRATION.
Args:
ops_and_kernels: a set of (op_name, kernel_class_name) pairs to include.
include_all_ops_and_kernels: if True, ops_and_kernels is ignored and all op
kernels are included.
Returns:
the string of the header that should be written as ops_to_register.... | github-repos |
def input_fn(filenames, tf_transform_output, batch_size=200):
transformed_feature_spec = tf_transform_output.transformed_feature_spec().copy()
transformed_features = tf.contrib.learn.io.read_batch_features(filenames, batch_size, transformed_feature_spec, reader=_gzip_reader_fn)
return (transformed_features,... | Generates features and labels for training or evaluation.
Args:
filenames: [str] list of CSV files to read data from.
tf_transform_output: A TFTransformOutput.
batch_size: int First dimension size of the Tensors returned by input_fn
Returns:
A (features, indices) tuple where features is a dictionary of
Tensors, and i... | github-repos |
def load(self, sess, tags, import_scope=None, **saver_kwargs):
saved_model_proto = parse_saved_model(self._export_dir)
metrics.IncrementReadApi(_LOADER_LABEL)
with sess.graph.as_default():
saver, _ = self.load_graph(sess.graph, tags, import_scope, **saver_kwargs)
self.restore_variables(sess,... | Load the MetaGraphDef graph and restore variable values into the session.
Args:
sess: tf.compat.v1.Session to restore variable values.
tags: a set of string tags identifying a MetaGraphDef.
import_scope: Optional `string` -- if specified, prepend this string
followed by '/' to all loaded tensor names. This scope is ap... | github-repos |
def _build_migrated_variables(checkpoint_reader, name_value_fn):
names_to_shapes = checkpoint_reader.get_variable_to_shape_map()
new_name_to_variable = {}
name_to_new_name = {}
for name in names_to_shapes:
value = checkpoint_reader.get_tensor(name)
(new_name, new_value) = name_value_fn(n... | Builds the TensorFlow variables of the migrated checkpoint.
Args:
checkpoint_reader: A `tf.train.NewCheckPointReader` of the checkpoint to
be read from.
name_value_fn: Function taking two arguments, `name` and `value`, which
returns the pair of new name and value for that a variable of that name.
Returns:
Tuple of a ... | codesearchnet |
def start_of_chunk(prev_tag, tag, prev_type, type_):
chunk_start = False
if (tag == 'B'):
chunk_start = True
if (tag == 'S'):
chunk_start = True
if ((prev_tag == 'E') and (tag == 'E')):
chunk_start = True
if ((prev_tag == 'E') and (tag == 'I')):
chunk_start = True
... | Checks if a chunk started between the previous and current word.
Args:
prev_tag: previous chunk tag.
tag: current chunk tag.
prev_type: previous type.
type_: current type.
Returns:
chunk_start: boolean. | codesearchnet |
def Tensors(self, run, tag):
accumulator = self.GetAccumulator(run)
return accumulator.Tensors(tag) | Retrieve the tensor events associated with a run and tag.
Args:
run: A string name of the run for which values are retrieved.
tag: A string name of the tag for which values are retrieved.
Raises:
KeyError: If the run is not found, or the tag is not available for
the given run.
Returns:
An array of `event_accumulator... | juraj-google-style |
def build(self, backend=None):
n_total = len(self.data.index)
if len(self.completes):
completes = [set(x) for x in sum(self.completes, [])]
completes = set.intersection(*completes)
else:
completes = [x for x in range(len(self.data.index))]
... | Set up the model for sampling/fitting.
Performs any steps that require access to all model terms (e.g., scaling priors
on each term), then calls the BackEnd's build() method.
Args:
backend (str): The name of the backend to use for model fitting.
Currently, 'pymc' and 'stan' are supported. If None, assume
that fit() h... | juraj-google-style |
def GetIamPolicy(self, request, global_params=None):
config = self.GetMethodConfig('GetIamPolicy')
return self._RunMethod(config, request, global_params=global_params) | Gets the access control policy for a resource. Returns an empty policy if the resource exists and does not have a policy set.
Args:
request: (BigqueryTablesGetIamPolicyRequest) input message
global_params: (StandardQueryParameters, default: None) global arguments
Returns:
(Policy) The response message. | github-repos |
def receiveds_format(receiveds):
log.debug("Receiveds for this email are parsed")
output = []
counter = Counter()
for i in receiveds[::-1]:
j = {k: v.strip() for k, v in i.items() if v}
j["hop"] = counter["hop"] + 1
if i.get("date"):
... | Given a list of receiveds hop, adds metadata and reformat
field values
Args:
receiveds (list): list of receiveds hops already formatted
Returns:
list of receiveds reformated and with new fields | juraj-google-style |
def users_getPresence(self, *, user: str, **kwargs) -> SlackResponse:
kwargs.update({"user": user})
return self.api_call("users.getPresence", http_verb="GET", params=kwargs) | Gets user presence information.
Args:
user (str): User to get presence info on. Defaults to the authed user.
e.g. 'W1234567890' | juraj-google-style |
def chown(self, path, uid, gid, dir_fd=None, follow_symlinks=None):
if (follow_symlinks is None):
follow_symlinks = True
elif (sys.version_info < (3, 3)):
raise TypeError("chown() got an unexpected keyword argument 'follow_symlinks'")
path = self._path_with_dir_fd(path, self.chown, dir_fd)
... | Set ownership of a faked file.
Args:
path: (str) Path to the file or directory.
uid: (int) Numeric uid to set the file or directory to.
gid: (int) Numeric gid to set the file or directory to.
dir_fd: (int) If not `None`, the file descriptor of a directory,
with `path` being relative to this directory.
New in Python 3.... | codesearchnet |
def parse(self, message, schema):
func = {
'audit-log': self._parse_audit_log_msg,
'event': self._parse_event_msg,
}[schema]
return func(message) | Parse message according to schema.
`message` should already be validated against the given schema.
See :ref:`schemadef` for more information.
Args:
message (dict): message data to parse.
schema (str): valid message schema.
Returns:
(dict): parsed message | juraj-google-style |
def get_adversary_phone_asset(self, main_type, sub_type, unique_id, asset_id, params=None):
return self.adversary_phone_asset(main_type, sub_type, unique_id, asset_id, params=params) | Args:
main_type:
sub_type:
unique_id:
asset_id:
params:
Return: | juraj-google-style |
def should_use_network(self, request):
return (self.networking and all((fn(request) for fn in self.network_filters))) | Verifies if real networking mode should be used for the given
request, passing it to the registered network filters.
Arguments:
request (pook.Request): outgoing HTTP request to test.
Returns:
bool | codesearchnet |
def _parse_publisher(details):
publisher = _get_td_or_none(
details,
"ctl00_ContentPlaceHolder1_tblRowNakladatel"
)
if not publisher:
return None
publisher = dhtmlparser.removeTags(publisher).strip()
if not publisher:
return None
return publishe... | Parse publisher of the book.
Args:
details (obj): HTMLElement containing slice of the page with details.
Returns:
str/None: Publisher's name as string or None if not found. | juraj-google-style |
def _extract_field_with_regex(self, field):
matched = re.search(field, self.text)
if (not matched):
err_msg = u'Failed to extract data with regex! => {}\n'.format(field)
err_msg += u'response body: {}\n'.format(self.text)
logger.log_error(err_msg)
raise exceptions.ExtractFailure(... | extract field from response content with regex.
requests.Response body could be json or html text.
Args:
field (str): regex string that matched r".*\(.*\).*"
Returns:
str: matched content.
Raises:
exceptions.ExtractFailure: If no content matched with regex.
Examples:
>>> # self.text: "LB123abcRB789"
>>> filed = "LB... | codesearchnet |
def __tf_unflatten__(cls, metadata, components): | Create a user-defined object from (metadata, components).
Args:
metadata: a custom Python object that stands for the static config for
reconstructing a new object of the current class.
components: a `tuple` that contains the dynamic data fields of the current
class, for object reconstruction.
Returns:
The user-define... | github-repos |
def set_signal_type(self, sig_type):
if isinstance(sig_type, str):
sig_type = [sig_type]
self.snr_input.signal_type = sig_type
return | Set the signal type of interest.
Sets the signal type for which the SNR is calculated.
This means inspiral, merger, and/or ringdown.
Args:
sig_type (str or list of str): Signal type desired by user.
Choices are `ins`, `mrg`, `rd`, `all` for circular waveforms created with PhenomD.
If eccentric waveforms are used, mus... | codesearchnet |
def _summarize_eager(tensor, summarize=None):
if summarize is None:
summarize = 3
elif summarize < 0:
summarize = array_ops.size(tensor)
if tensor._rank():
flat = tensor.numpy().reshape((-1,))
lst = [str(x) for x in flat[:summarize]]
if len(lst) < flat.size:
... | Returns a summarized string representation of eager `tensor`.
Args:
tensor: EagerTensor to summarize
summarize: Include these many first elements of `array` | github-repos |
def register_name(self, register_index):
result = self._dll.JLINKARM_GetRegisterName(register_index)
return ctypes.cast(result, ctypes.c_char_p).value.decode() | Retrives and returns the name of an ARM CPU register.
Args:
self (JLink): the ``JLink`` instance
register_index (int): index of the register whose name to retrieve
Returns:
Name of the register. | 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... | Returns:
Example:
```python
>>> import jax.numpy as jnp
>>> from transformers import AutoTokenizer, FlaxPegasusForConditionalGeneration
>>> model = FlaxPegasusForConditionalGeneration.from_pretrained("google/pegasus-large")
>>> tokenizer = AutoTokenizer.from_pretrained("google/pegasus-large")
>>> text = "My friends... | github-repos |
def spawn_watcher(self, label, target=None, eternal=False):
if (label not in self._sources):
raise YapconfSourceError(('Cannot watch %s no source named %s' % (label, label)))
current_config = self._sources[label].get_data()
handler = ConfigChangeHandler(current_config, self, target)
return self.... | Spawns a config watcher in a separate daemon thread.
If a particular config value changes, and the item has a
``watch_target`` defined, then that method will be called.
If a ``target`` is passed in, then it will call the ``target``
anytime the config changes.
Args:
label (str): Should match a label added through ``a... | codesearchnet |
def _DepthwiseConv2dNumpy(x1, x2, strides, padding, data_format, dilations):
if data_format == 'NCHW':
x1 = np.transpose(x1, (0, 3, 1, 2))
strides = [strides[0], strides[3], strides[1], strides[2]]
if dilations:
dilations = [dilations[0], dilations[3], dilations[1], dilations[2]]... | Compute depthwise_conv2d using Numpy.
This allows use to test TensorFlow's depthwise_conv2d by comparing to the
Numpy version.
Unlike `_DepthwiseConv2dNumpyBasic`, this supports more advanced features
like padding.
Args:
x1: The input Numpy array.
x2: The filter Numpy array.
strides: A Python list of 4 elements repr... | github-repos |
def __init__(self, process: Process):
self.process = process
self.stopped_due_to_worker_shutdown = False | Constructor.
Args:
process (Process): task process | juraj-google-style |
def fetch(self, subscription_id, data={}, **kwargs):
return super(Subscription, self).fetch(subscription_id, data, **kwargs) | Fetch Subscription for given Id
Args:
subscription_id : Id for which subscription object is retrieved
Returns:
Subscription dict for given subscription Id | codesearchnet |
def convert_datetime_array(array):
if not isinstance(array, np.ndarray):
return array
try:
dt2001 = np.datetime64('2001')
legacy_datetime64 = (dt2001.astype('int64') ==
dt2001.astype('datetime64[ms]').astype('int64'))
except AttributeError as e:
... | Convert NumPy datetime arrays to arrays to milliseconds since epoch.
Args:
array : (obj)
A NumPy array of datetime to convert
If the value passed in is not a NumPy array, it will be returned as-is.
Returns:
array | juraj-google-style |
def ms_to_frames(ms, fps):
if fps <= 0:
raise ValueError("Framerate must be positive number (%f)." % fps)
return int(round((ms / 1000) * fps)) | Convert milliseconds to number of frames.
Arguments:
ms: Number of milliseconds (may be int, float or other numeric class).
fps: Framerate (must be a positive number, eg. 23.976).
Returns:
Number of frames (int).
Raises:
ValueError: fps was negative or zero. | juraj-google-style |
def context(self, name):
data = self._context(name)
context = data.get("context")
if context:
return context
assert self.load_path
context_path = os.path.join(self.load_path, "contexts", "%s.rxt" % name)
context = ResolvedContext.load(context_path)
... | Get a context.
Args:
name (str): Name to store the context under.
Returns:
`ResolvedContext` object. | juraj-google-style |
def match(self, message) -> bool:
if self.to and message.to != self.to:
return False
if self.sender and message.sender != self.sender:
return False
if self.body and message.body != self.body:
return False
if self.thread and message.thread !... | Returns wether a message matches with this message or not.
The message can be a Message object or a Template object.
Args:
message (spade.message.Message): the message to match to
Returns:
bool: wether the message matches or not | juraj-google-style |
def _GetCh(self):
fd = self._tty.fileno()
old = termios.tcgetattr(fd)
try:
tty.setraw(fd)
ch = self._tty.read(1)
if (ord(ch) == 27):
ch += self._tty.read(2)
finally:
termios.tcsetattr(fd, termios.TCSADRAIN, old)
return ch | Read a single character from the user.
Returns:
A string, the character read. | codesearchnet |
def _insert_operations(self, operations: Sequence[ops.Operation], insertion_indices: Sequence[int]) -> None:
if (len(operations) != len(insertion_indices)):
raise ValueError('operations and insertion_indices must have thesame length.')
self._moments += [ops.Moment() for _ in range(((1 + max(insertion_in... | Inserts operations at the specified moments. Appends new moments if
necessary.
Args:
operations: The operations to insert.
insertion_indices: Where to insert them, i.e. operations[i] is
inserted into moments[insertion_indices[i].
Raises:
ValueError: operations and insert_indices have different lengths.
NB: It's on t... | codesearchnet |
class TFCLIPEncoder(keras.layers.Layer):
def __init__(self, config: CLIPConfig, **kwargs):
super().__init__(**kwargs)
self.layers = [TFCLIPEncoderLayer(config, name=f'layers_._{i}') for i in range(config.num_hidden_layers)]
def call(self, hidden_states: tf.Tensor, attention_mask: tf.Tensor, ca... | Transformer encoder consisting of `config.num_hidden_layers` self attention layers. Each layer is a
[`TFCLIPEncoderLayer`].
Args:
config: CLIPConfig | github-repos |
def serialize_to_xml(root, block):
root.tag = 'ubcpi'
if block.rationale_size is not None:
if block.rationale_size.get('min'):
root.set('rationale_size_min', unicode(block.rationale_size.get('min')))
if block.rationale_size.get('max'):
root.set('rationale_size_max',... | Serialize the Peer Instruction XBlock's content to XML.
Args:
block (PeerInstructionXBlock): The peer instruction block to serialize.
root (etree.Element): The XML root node to update.
Returns:
etree.Element | juraj-google-style |
def __init__(self, project=None, deidentification_template_name=None, deidentification_config=None, inspection_template_name=None, inspection_config=None, timeout=None):
self.config = {}
self.project = project
self.timeout = timeout
if deidentification_template_name is not None and deidentification_conf... | Initializes a :class:`MaskDetectedDetails` transform.
Args:
project: Optional. GCP project name in which inspection will be performed
deidentification_template_name (str): Either this or
`deidentification_config` required. Name of
deidentification template to be used on detected sensitive information
instances in text... | github-repos |
def orient_undirected_graph(self, data, umg, alg='HC'):
warnings.warn('The pairwise GNN model is computed on each edge of the UMG to initialize the model and start CGNN with a DAG')
gnn = GNN(nh=self.nh, lr=self.lr)
og = gnn.orient_graph(data, umg, nb_runs=self.nb_runs, nb_max_runs=self.nb_runs, nb_jobs=sel... | Orient the undirected graph using GNN and apply CGNN to improve the graph.
Args:
data (pandas.DataFrame): Observational data on which causal
discovery has to be performed.
umg (nx.Graph): Graph that provides the skeleton, on which the GNN
then the CGNN algorithm will be applied.
alg (str): Exploration heuristic to use... | codesearchnet |
def _get_reference(document_path, reference_map):
try:
return reference_map[document_path]
except KeyError:
msg = _BAD_DOC_TEMPLATE.format(document_path)
raise ValueError(msg) | Get a document reference from a dictionary.
This just wraps a simple dictionary look-up with a helpful error that is
specific to :meth:`~.firestore.client.Client.get_all`, the
**public** caller of this function.
Args:
document_path (str): A fully-qualified document path.
reference_map (Dict[str, .DocumentReference]):... | codesearchnet |
def OverwriteAndClose(self, compressed_data, size):
self.Set(self.Schema.CONTENT(compressed_data))
self.Set(self.Schema.SIZE(size))
super(AFF4MemoryStreamBase, self).Close() | Directly overwrite the current contents.
Replaces the data currently in the stream with compressed_data,
and closes the object. Makes it possible to avoid recompressing
the data.
Args:
compressed_data: The data to write, must be zlib compressed.
size: The uncompressed size of the data. | juraj-google-style |
def _compile_constant_expression(self,
expr: Expression,
scope: Dict[str, TensorFluent],
batch_size: Optional[int] = None,
noise: Optional[List[tf.Tensor]] = None) -> Tenso... | Compile a constant expression `expr` into a TensorFluent
in the given `scope` with optional batch size.
Args:
expr (:obj:`rddl2tf.expr.Expression`): A RDDL constant expression.
scope (Dict[str, :obj:`rddl2tf.fluent.TensorFluent`]): A fluent scope.
batch_size (Optional[size]): The batch size.
Returns:
:obj:`rddl2tf.fl... | juraj-google-style |
def UploadFilePath(self, filepath, offset=0, amount=None):
return self._UploadChunkStream(self._streamer.StreamFilePath(filepath, offset=offset, amount=amount)) | Uploads chunks of a file on a given path to the transfer store flow.
Args:
filepath: A path to the file to upload.
offset: An integer offset at which the file upload should start on.
amount: An upper bound on number of bytes to stream. If it is `None` then
the whole file is uploaded.
Returns:
A `BlobImageDescriptor` ... | codesearchnet |
def random_sparse(strategy, prob, obj_reaction, flux_threshold):
essential = set()
deleted = set()
for (entity, deleted_reactions) in strategy.iter_tests():
if (obj_reaction in deleted_reactions):
logger.info('Marking entity {} as essential because the objective reaction depends on this ... | Find a random minimal network of model reactions.
Given a reaction to optimize and a threshold, delete entities randomly
until the flux of the reaction to optimize falls under the threshold.
Keep deleting until no more entities can be deleted. It works
with two strategies: deleting reactions or deleting genes (reactio... | codesearchnet |
def register_controller(self, module, required=True, min_number=1):
verify_controller_module(module)
module_ref_name = module.__name__.split('.')[(- 1)]
if (module_ref_name in self._controller_objects):
raise signals.ControllerError(('Controller module %s has already been registered. It cannot be re... | Loads a controller module and returns its loaded devices.
This is to be used in a mobly test class.
Args:
module: A module that follows the controller module interface.
required: A bool. If True, failing to register the specified
controller module raises exceptions. If False, the objects
failed to instantiate will be... | codesearchnet |
async def getNodeByBuid(self, buid):
node = self.livenodes.get(buid)
if node is not None:
return node
props = {}
proplayr = {}
for layr in self.layers:
layerprops = await layr.getBuidProps(buid)
props.update(layerprops)
pr... | Retrieve a node tuple by binary id.
Args:
buid (bytes): The binary ID for the node.
Returns:
Optional[s_node.Node]: The node object or None. | juraj-google-style |
def _copy_script_migrated(self, filename, id_=(- 1), file_type=SCRIPT_FILE_TYPE):
basefname = os.path.basename(filename)
resource = open(filename, 'rb')
headers = {'DESTINATION': '1', 'OBJECT_ID': str(id_), 'FILE_TYPE': file_type, 'FILE_NAME': basefname}
response = self.connection['jss'].session.post(ur... | Upload a script to a migrated JSS's database.
On a "migrated" JSS, scripts are POSTed to the JSS. Pass an id
if you wish to associate the script with an existing Script
object, otherwise, it will create a new Script object.
Args:
filename: Path to script file.
id_: Int ID of Script object to associate this file with.... | codesearchnet |
def __call__(self,
state: Sequence[tf.Tensor],
timestep: tf.Tensor) -> Sequence[tf.Tensor]:
return self._default | Returns the default action fluents regardless of the current `state` and `timestep`.
Args:
state (Sequence[tf.Tensor]): The current state fluents.
timestep (tf.Tensor): The current timestep.
Returns:
Sequence[tf.Tensor]: A tuple of action fluents. | juraj-google-style |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.