code stringlengths 20 4.93k | docstring stringlengths 33 1.27k | source stringclasses 3
values |
|---|---|---|
def _CreateEventTag(self, event, comment, labels):
event_identifier = event.GetIdentifier()
event_tag = events.EventTag(comment=comment)
event_tag.SetEventIdentifier(event_identifier)
event_tag.AddLabels(labels)
event_identifier_string = event_identifier.CopyToString()
logger.debug('Created even... | Creates an event tag.
Args:
event (EventObject): event to tag.
comment (str): event tag comment.
labels (list[str]): event tag labels.
Returns:
EventTag: the event tag. | codesearchnet |
def add_droplets(self, droplet_ids):
return self.get_data(('load_balancers/%s/droplets/' % self.id), type=POST, params={'droplet_ids': droplet_ids}) | Assign a LoadBalancer to a Droplet.
Args:
droplet_ids (obj:`list` of `int`): A list of Droplet IDs | codesearchnet |
def extend(self, records):
fields = self.fields
for record in records:
record = _cast_record_to_str_tuple(record, fields)
self._records.append(record) | Add each record in *records* to the end of the table.
Args:
record: an iterable of :class:`Record` or other iterables
containing column values | juraj-google-style |
async def update_pairing_method(self, pairing: Pairing):
do_sequential_pairing = pairing == Pairing.sequential
await self.update(sequential_pairings=do_sequential_pairing) | |methcoro|
Args:
pairing:
Raises:
APIException | juraj-google-style |
def member_update(self, repl_id, member_id, params):
repl = self[repl_id]
result = repl.member_update(member_id, params)
self[repl_id] = repl
return result | apply new params to replica set member
Args:
repl_id - replica set identity
member_id - member index
params - new member's params
return True if operation success otherwise False | juraj-google-style |
def get_attribute(self, obj, attr):
if attr == '*':
return obj
if isinstance(obj, Mapping):
return obj.get(attr, None)
return getattr(obj, attr, None) | Get attribute of given object instance.
Reason for existence of this method is the fact that 'attribute' can
be also object's key from if is a dict or any other kind of mapping.
Note: it will return None if attribute key does not exist
Args:
obj (object): internal object to retrieve data from
Returns:
internal obj... | juraj-google-style |
def with_output_types(self, type_hint):
type_hint = native_type_compatibility.convert_to_beam_type(type_hint)
validate_composite_type_param(type_hint, 'Type hints for a PTransform')
return super().with_output_types(type_hint) | Annotates the output type of a :class:`PTransform` with a type-hint.
Args:
type_hint (type): An instance of an allowed built-in type, a custom class,
or a :class:`~apache_beam.typehints.typehints.TypeConstraint`.
Raises:
TypeError: If **type_hint** is not a valid type-hint. See
:obj:`~apache_beam.typehints.typehints.... | github-repos |
def write_uint8(self, value, little_endian=True):
if little_endian:
endian = "<"
else:
endian = ">"
return self.pack('%sB' % endian, value) | Pack the value as an unsigned byte and write 1 byte to the stream.
Args:
value:
little_endian (bool): specify the endianness. (Default) Little endian.
Returns:
int: the number of bytes written. | juraj-google-style |
def init_algebra(*, default_hs_cls='LocalSpace'):
from qnet.algebra.core.hilbert_space_algebra import LocalSpace
from qnet.algebra.core.abstract_quantum_algebra import QuantumExpression
default_hs_cls = getattr(importlib.import_module('qnet'), default_hs_cls)
if issubclass(default_hs_cls, LocalSpac... | Initialize the algebra system
Args:
default_hs_cls (str): The name of the :class:`.LocalSpace` subclass
that should be used when implicitly creating Hilbert spaces, e.g.
in :class:`.OperatorSymbol` | juraj-google-style |
def _InternalUnpackAny(msg):
from google.protobuf import symbol_database
factory = symbol_database.Default()
type_url = msg.type_url
if not type_url:
return None
type_name = type_url.split('/')[-1]
descriptor = factory.pool.FindMessageTypeByName(type_name)
if descriptor is Non... | Unpacks Any message and returns the unpacked message.
This internal method is different from public Any Unpack method which takes
the target message as argument. _InternalUnpackAny method does not have
target message type and need to find the message type in descriptor pool.
Args:
msg: An Any message to be unpacked.
... | juraj-google-style |
def split(self):
assert (self.status == SolverStatus.exhausted)
scopes = []
next_scopes = []
split_i = None
for (i, scope) in enumerate(self.scopes):
if (split_i is None):
r = scope.split()
if (r is not None):
(scope_, next_scope) = r
s... | Split the phase.
When a phase is exhausted, it gets split into a pair of phases to be
further solved. The split happens like so:
1) Select the first unsolved package scope.
2) Find some common dependency in the first N variants of the scope.
3) Split the scope into two: [:N] and [N:].
4) Create two copies of the phase... | codesearchnet |
def add(self, X):
for each in X:
self.dpp_vector[each] = X[each]
self.fit(self.dpp_vector.reshape(1, (- 1))) | Add data about known pipeline and scores.
Updates ``dpp_vector`` and refits model with all data.
Args:
X (dict): mapping of pipeline indices to scores. Keys must correspond to the index of a
column in ``dpp_matrix`` and values are the corresponding score for pipeline on
the dataset. | codesearchnet |
def DEFINE_spaceseplist(name, default, help, comma_compat=False, flag_values=_flagvalues.FLAGS, **args):
parser = _argument_parser.WhitespaceSeparatedListParser(comma_compat=comma_compat)
serializer = _argument_parser.ListSerializer(' ')
DEFINE(parser, name, default, help, flag_values, serializer, **args) | Registers a flag whose value is a whitespace-separated list of strings.
Any whitespace can be used as a separator.
Args:
name: str, the flag name.
default: list|str|None, the default value of the flag.
help: str, the help message.
comma_compat: bool - Whether to support comma as an additional separator.
If false then... | codesearchnet |
def __init__(self, original_embedding: nn.Embedding, assistant_overlap_token_ids):
super().__init__()
self.original_embedding = original_embedding
self.weight = original_embedding.weight
self.assistant_overlap_token_ids = assistant_overlap_token_ids
self.map = False | Wraps an existing embedding layer and remaps token IDs before lookup.
Args:
original_embedding (nn.Embedding): Pre-trained or existing embedding layer.
assistant_overlap_token_ids (dict): Mapping from original token IDs to new token IDs.
Example: {old_id: new_id} | github-repos |
def reflection_matrix_pow(reflection_matrix: np.ndarray, exponent: float):
squared_phase = np.dot(reflection_matrix[:, 0],
reflection_matrix[0, :])
phase = complex(np.sqrt(squared_phase))
i = np.eye(reflection_matrix.shape[0]) * phase
pos_part = (i + reflectio... | Raises a matrix with two opposing eigenvalues to a power.
Args:
reflection_matrix: The matrix to raise to a power.
exponent: The power to raise the matrix to.
Returns:
The given matrix raised to the given power. | juraj-google-style |
def contains_call_signature(caller, key):
try:
args = inspect.signature(caller).parameters
except AttributeError:
args = inspect.getargspec(caller).args
return (key in args) | Check if a function or method call signature contains a specific
argument.
Args:
caller (Callable):
Method or function to check if signature is contain in.
key (str):
Signature to look for.
Returns:
True if ``key`` exits in ``caller`` call signature.
Examples:
>>> def foo(param): pass
>>> contains_call_signature(foo... | codesearchnet |
def get_table_columns(metadata):
cols = OrderedDict()
for col in metadata.c:
name = str(col).rpartition(".")[2]
cols[name] = col.type.python_type.__name__
return cols | Extract columns names and python typos from metadata
Args:
metadata: Table metadata
Returns:
dict with columns names and python types | juraj-google-style |
def accept_prompt(self, text=None, response=None, wait=None):
with self.driver.accept_modal('prompt', text=text, response=response, wait=wait):
(yield) | Execute the wrapped code, accepting a prompt, optionally responding to the prompt.
Args:
text (str | RegexObject, optional): Text to match against the text in the modal.
response (str, optional): Response to provide to the prompt.
wait (int | float, optional): Maximum time to wait for the modal to appear after
executi... | codesearchnet |
def encoder_vgg(x, enc_final_size, reuse=False, scope_prefix='', hparams=None, is_training=True):
with tf.variable_scope((scope_prefix + 'encoder'), reuse=reuse):
x *= 256
x = (x - COLOR_NORMALIZATION_VECTOR)
with arg_scope(vgg.vgg_arg_scope()):
x = tf.pad(x, [[0, 0], [0, (VGG_IM... | VGG network to use as encoder without the top few layers.
Can be pretrained.
Args:
x: The image to encode. In the range 0 to 1.
enc_final_size: The desired size of the encoding.
reuse: To reuse in variable scope or not.
scope_prefix: The prefix before the scope name.
hparams: The python hparams.
is_training: boolean ... | codesearchnet |
def get_effect_class(self, effect_name: str, package_name: str = None) -> Type['Effect']:
return self._project.get_effect_class(effect_name, package_name=package_name) | Get an effect class by the class name
Args:
effect_name (str): Name of the effect class
Keyword Args:
package_name (str): The package the effect belongs to. This is optional and only
needed when effect class names are not unique.
Returns:
:py:class:`Effect` class | juraj-google-style |
def __is_function_action(self, action_function):
is_function_action = True
if (not hasattr(action_function, '__call__')):
return False
try:
for (end_string, context) in action_function():
if (not isinstance(end_string, basestring)):
self.log_error('Action function... | Detect if given function is really an action function.
Args:
action_function: Function to test.
Note:
We don't care if the variable refer to a function but rather if it is callable or not. | codesearchnet |
def get_gan_loss(self, true_frames, gen_frames, name):
with tf.variable_scope("%s_discriminator" % name, reuse=tf.AUTO_REUSE):
gan_d_loss, _, fake_logits_stop = self.d_step(
true_frames, gen_frames)
with tf.variable_scope("%s_discriminator" % name, reuse=True):
gan_g_loss_p... | Get the discriminator + generator loss at every step.
This performs an 1:1 update of the discriminator and generator at every
step.
Args:
true_frames: 5-D Tensor of shape (num_steps, batch_size, H, W, C)
Assumed to be ground truth.
gen_frames: 5-D Tensor of shape (num_steps, batch_size, H, W, C)
Assumed to be fake.
n... | juraj-google-style |
def __init__(self, subscription_path, deduplicate=None, expansion_service=None):
if deduplicate is None:
deduplicate = False
if expansion_service is None:
expansion_service = _default_io_expansion_service()
super().__init__('beam:transform:org.apache.beam:pubsublite_read:v1', NamedTupleBased... | Initializes a read operation from Pub/Sub Lite, returning the serialized
bytes of SequencedMessage protos.
Args:
subscription_path: A Pub/Sub Lite Subscription path.
deduplicate: Whether to deduplicate messages based on the value of
the 'x-goog-pubsublite-dataflow-uuid' attribute. | github-repos |
def get_workunit(self, ignore_list=None):
if ignore_list is None:
ignore_list = []
potential_files = self.get_potential_files(ignore_list)
while len(potential_files) > 0:
potential_file = self.select_potential_file(potential_files)
potential_files.r... | Gets a new unit of work.
Args:
ignore_list: list(str)
A list of filenames which should be ignored. Defaults to None.
Returns:
new_workunit: WorkUnit
A new unit of work that has not yet been processed. A lock on
it has been acquired.
Raises:
NoAvailableWorkException
There is no more work available. | juraj-google-style |
def get_branch_length(self, age=None, pos=0):
if (age is None):
age = self.age
return (self.length * pow(self.branches[pos][0], age)) | Get the length of a branch.
This method calculates the length of a branch in specific age.
The used formula: length * scale^age.
Args:
age (int): The age, for which you want to know the branch length.
Returns:
float: The length of the branch | codesearchnet |
def get_shreds(self, feature_extractors, sheet_name):
if self._shreds is None:
shreds = []
_, contours, _ = cv2.findContours(self._foreground_mask,
cv2.RETR_EXTERNAL,
cv2.CHAIN_APPROX_SIMPLE)
... | Detects shreds in the current sheet and constructs Shred instances.
Caches the results for further invocations.
Args:
feature_extractors: iterable of AbstractShredFeature instances to
use for shreds feature assignment.
sheet_name: string, included in shred attributes.
Returns:
list of Shred instances. | juraj-google-style |
def create_token_type_ids_from_sequences(self, token_ids_0: List[int], token_ids_1: Optional[List[int]]=None) -> List[int]:
sep = [self.sep_token_id]
cls = [self.cls_token_id]
if token_ids_1 is None:
return len(cls + token_ids_0 + sep) * [0]
return len(cls + token_ids_0 + sep + sep + token_ids_1... | Creates a mask from the two sequences passed to be used in a sequence-pair classification task. MPNet does not
make use of token type ids, therefore a list of zeros is returned.
Args:
token_ids_0 (`List[int]`):
List of ids.
token_ids_1 (`List[int]`, *optional*):
Optional second list of IDs for sequence pairs.
Returns... | github-repos |
class FlavaProcessor(ProcessorMixin):
attributes = ['image_processor', 'tokenizer']
image_processor_class = 'FlavaImageProcessor'
tokenizer_class = ('BertTokenizer', 'BertTokenizerFast')
def __init__(self, image_processor=None, tokenizer=None, **kwargs):
feature_extractor = None
if 'fea... | Constructs a FLAVA processor which wraps a FLAVA image processor and a FLAVA tokenizer into a single processor.
[`FlavaProcessor`] offers all the functionalities of [`FlavaImageProcessor`] and [`BertTokenizerFast`]. See the
[`~FlavaProcessor.__call__`] and [`~FlavaProcessor.decode`] for more information.
Args:
image_... | github-repos |
def store_sample(self, input_bytes, filename, type_tag):
if type_tag == 'unknown':
print 'Info: Unknown File -- Trying to Determine Type...'
type_tag = self.guess_type_tag(input_bytes, filename)
if type_tag == 'lz4':
input_bytes = lz4.load... | Store a sample into the DataStore.
Args:
input_bytes: the actual bytes of the sample e.g. f.read()
filename: name of the file (used purely as meta data not for lookup)
type_tag: ('exe','pcap','pdf','json','swf', or ...)
Returns:
the md5 of the sample. | juraj-google-style |
def score_task(self, X, Y, t=0, metric="accuracy", verbose=True, **kwargs):
Y = self._to_numpy(Y)
Y_tp = self.predict_task(X, t=t, **kwargs)
probs = self.predict_proba(X)[t]
score = metric_score(
Y[t], Y_tp, metric, ignore_in_gold=[0], probs=probs, **kwargs
)... | Scores the predictive performance of the Classifier on task t
Args:
X: The input for the predict_task method
Y: A [n] or [n, 1] np.ndarray or torch.Tensor of gold labels in
{1,...,K_t}
t: The task index to score
metric: The metric with which to score performance on this task
Returns:
The (float) score of the Classifie... | juraj-google-style |
def _map_args(self, node: cfg.CFGNode, args: function.Args) -> tuple[list[tuple[str, _base.BaseValue]], dict[str, cfg.Variable]]:
formal_args: list[tuple[str, _base.BaseValue]] = [(p.name, self.signature.annotations[p.name]) for p in self.pytd_sig.params]
arg_dict: dict[str, cfg.Variable] = {}
for name, arg... | Map the passed arguments to a name->binding dictionary.
Args:
node: The current node.
args: The passed arguments.
Returns:
A tuple of:
a list of formal arguments, each a (name, abstract value) pair;
a name->variable dictionary of the passed arguments.
Raises:
InvalidParameters: If the passed arguments don't match th... | github-repos |
def attention_lm_small():
hparams = attention_lm_base()
hparams.num_hidden_layers = 4
hparams.hidden_size = 512
hparams.filter_size = 2048
hparams.layer_prepostprocess_dropout = 0.5
return hparams | Cheap model.
on lm1b_32k:
45M params
2 steps/sec on [GeForce GTX TITAN X]
Returns:
an hparams object. | codesearchnet |
def HandleForwardedIps(self, interface, forwarded_ips, interface_ip=None):
desired = self.ip_forwarding_utils.ParseForwardedIps(forwarded_ips)
configured = self.ip_forwarding_utils.GetForwardedIps(
interface, interface_ip)
to_add = sorted(set(desired) - set(configured))
to_remove = sorted(s... | Handle changes to the forwarded IPs on a network interface.
Args:
interface: string, the output device to configure.
forwarded_ips: list, the forwarded IP address strings desired.
interface_ip: string, current interface ip address. | juraj-google-style |
def ready(self, cluster):
ready_nodes = set()
next_ready_check = 9999999.99
unknown_leaders_exist = False
now = time.time()
exhausted = bool((self._free.queued() > 0))
partitions = list(self._batches.keys())
for tp in partitions:
leader = cluster.leader_for_partition(tp)
if (... | Get a list of nodes whose partitions are ready to be sent, and the
earliest time at which any non-sendable partition will be ready;
Also return the flag for whether there are any unknown leaders for the
accumulated partition batches.
A destination node is ready to send if:
* There is at least one partition that is no... | codesearchnet |
def get(self, public_key, spent=None, headers=None):
return self.transport.forward_request(method='GET', path=self.path, params={'public_key': public_key, 'spent': spent}, headers=headers) | Get transaction outputs by public key. The public_key parameter
must be a base58 encoded ed25519 public key associated with
transaction output ownership.
Args:
public_key (str): Public key for which unfulfilled
conditions are sought.
spent (bool): Indicate if the result set should include only spent
or only unspent ou... | codesearchnet |
def _get_block_sizes(resnet_size):
choices = {18: [2, 2, 2, 2], 34: [3, 4, 6, 3], 50: [3, 4, 6, 3], 101: [3, 4, 23, 3], 152: [3, 8, 36, 3], 200: [3, 24, 36, 3]}
try:
return choices[resnet_size]
except KeyError:
err = 'Could not find layers for selected Resnet size.\nSize received: {}; sizes ... | Retrieve the size of each block_layer in the ResNet model.
The number of block layers used for the Resnet model varies according
to the size of the model. This helper grabs the layer set we want, throwing
an error if a non-standard size has been selected.
Args:
resnet_size: The number of convolutional layers needed i... | codesearchnet |
def create_new(cls, mapreduce_id, shard_number):
shard_id = cls.shard_id_from_number(mapreduce_id, shard_number)
state = cls(key_name=shard_id, mapreduce_id=mapreduce_id)
return state | Create new shard state.
Args:
mapreduce_id: unique mapreduce id as string.
shard_number: shard number for which to create shard state.
Returns:
new instance of ShardState ready to put into datastore. | codesearchnet |
def ignore_path(path):
ignore = False
for name in ['.tox', 'dist', 'build', 'node_modules', 'htmlcov']:
if path.find(name) >= 0:
ignore = True
break
return ignore | Verify whether to ignore a path.
Args:
path (str): path to check.
Returns:
bool: True when to ignore given path. | juraj-google-style |
def all_near_zero(a: Union[float, complex, Iterable[float], np.ndarray],
*,
atol: float = 1e-8) -> bool:
return np.all(np.less_equal(np.abs(a), atol)) | Checks if the tensor's elements are all near zero.
Args:
a: Tensor of elements that could all be near zero.
atol: Absolute tolerance. | juraj-google-style |
def connect_all(state):
hosts = [
host for host in state.inventory
if state.is_host_in_limit(host)
]
greenlet_to_host = {
state.pool.spawn(host.connect, state): host
for host in hosts
}
with progress_spinner(greenlet_to_host.values()) as progress:
for ... | Connect to all the configured servers in parallel. Reads/writes state.inventory.
Args:
state (``pyinfra.api.State`` obj): the state containing an inventory to connect to | juraj-google-style |
def load_audio(audio: Union[str, np.ndarray], sampling_rate=16000, timeout=None) -> np.ndarray:
requires_backends(load_audio, ['librosa'])
if isinstance(audio, str):
if audio.startswith('http:
audio = librosa.load(BytesIO(requests.get(audio, timeout=timeout).content), sr=sampling_rate)[0]
... | Loads `audio` to an np.ndarray object.
Args:
audio (`str` or `np.ndarray`):
The audio to be loaded to the numpy array format.
sampling_rate (`int`, *optional*, defaults to 16000):
The sampling rate to be used when loading the audio. It should be same as the
sampling rate the model you will be using further was trained... | github-repos |
def spherical_to_cartesian(r,theta,phi):
x = r * np.sin(phi) * np.cos(theta)
y = r * np.sin(phi) * np.sin(theta)
z = r * np.cos(phi)
return (x,y,z) | Simple conversion of spherical to cartesian coordinates
Args:
r,theta,phi = scalar spherical coordinates
Returns:
x,y,z = scalar cartesian coordinates | juraj-google-style |
def update_network_asset(self, asset_id, name, asset_type):
self.update_asset('NETWORK', asset_id, name, asset_type) | Updates a Network Asset
Args:
name: The name provided to the network asset
asset_type: The type provided to the network asset
asset_id:
Returns: | juraj-google-style |
def set_seat_logical_name(self, seat):
rc = self._libinput.libinput_device_set_seat_logical_name(self._handle, seat.encode())
assert (rc == 0), 'Cannot assign device to {}'.format(seat) | Change the logical seat associated with this device by removing
the device and adding it to the new seat.
This command is identical to physically unplugging the device, then
re-plugging it as a member of the new seat. libinput will generate
a :attr:`~libinput.constant.EventType.DEVICE_REMOVED` event and this
:class:`D... | codesearchnet |
def get_unique_families(hkls):
def is_perm(hkl1, hkl2):
h1 = np.abs(hkl1)
h2 = np.abs(hkl2)
return all([i == j for i, j in zip(sorted(h1), sorted(h2))])
unique = collections.defaultdict(list)
for hkl1 in hkls:
found = False
for hkl2 in unique.keys():
... | Returns unique families of Miller indices. Families must be permutations
of each other.
Args:
hkls ([h, k, l]): List of Miller indices.
Returns:
{hkl: multiplicity}: A dict with unique hkl and multiplicity. | juraj-google-style |
def __init__(self, start_at):
super().__init__()
self._timeout = start_at
self._timeout_triggered = False | Creates a timeout behaviour, which is run at start_at
Args:
start_at (datetime.datetime): when to start the behaviour | juraj-google-style |
def fram_wave(waveform: np.array, hop_length: int=160, fft_window_size: int=400, center: bool=True):
warnings.warn('The function `fram_wave` is deprecated and will be removed in version 4.31.0 of Transformers', FutureWarning)
frames = []
for i in range(0, waveform.shape[0] + 1, hop_length):
if cente... | In order to compute the short time fourier transform, the waveform needs to be split in overlapping windowed
segments called `frames`.
The window length (window_length) defines how much of the signal is contained in each frame, while the hop length
defines the step between the beginning of each new frame.
Args:
wave... | github-repos |
def get_appliance(self, id_or_uri, fields=''):
uri = self.URI + '/image-streamer-appliances/' + extract_id_from_uri(id_or_uri)
if fields:
uri += '?fields=' + fields
return self._client.get(uri) | Gets the particular Image Streamer resource based on its ID or URI.
Args:
id_or_uri:
Can be either the Os Deployment Server ID or the URI
fields:
Specifies which fields should be returned in the result.
Returns:
dict: Image Streamer resource. | juraj-google-style |
def processor_groups(mesh_shape, group_dims):
group_numbers = [pnum_to_group(mesh_shape, group_dims, pnum) for pnum in xrange(mesh_shape.size)]
ret = []
for (pnum, g) in enumerate(group_numbers):
while (len(ret) <= g):
ret.append([])
ret[g].append(pnum)
return ret | Groups of processors which differ only in the given dimensions.
Args:
mesh_shape: a Shape
group_dims: a list of integers
Returns:
a list of lists of integers (processor numbers) | codesearchnet |
def get_unique_variable(name):
candidates = tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, name)
if (not candidates):
raise ValueError(('Couldnt find variable %s' % name))
for candidate in candidates:
if (candidate.op.name == name):
return candidate
raise ValueError('Variab... | Gets the variable uniquely identified by that name.
Args:
name: a name that uniquely identifies the variable.
Returns:
a tensorflow variable.
Raises:
ValueError: if no variable uniquely identified by the name exists. | codesearchnet |
def export_artifacts(self, processed_artifacts, sketch_id):
for timeline_name, artifact_path in processed_artifacts:
print('Uploading {0:s} to timeline {1:s}'.format(
artifact_path, timeline_name))
new_timeline_id = self.upload_timeline(timeline_name, artifact_path)
self.add_t... | Upload provided artifacts to specified, or new if non-existent, sketch.
Args:
processed_artifacts: List of (timeline_name, artifact_path) tuples
sketch_id: ID of sketch to append the timeline to
Returns:
int: ID of sketch. | juraj-google-style |
def set_match_statements(self, name, action, seqno, statements):
try:
current_statements = self.get(name)[action][seqno]['match']
except:
current_statements = []
commands = list()
for entry in set(current_statements).difference(statements):
commands.append(('route-map %s %s %s' %... | Configures the match statements within the routemap clause.
The final configuration of match statements will reflect the list
of statements passed into the statements attribute. This implies
match statements found in the routemap that are not specified in the
statements attribute will be removed.
Args:
name (string): ... | codesearchnet |
def idle(self, stop_signals: tuple = (SIGINT, SIGTERM, SIGABRT)):
def signal_handler(*args):
self.is_idle = False
for s in stop_signals:
signal(s, signal_handler)
self.is_idle = True
while self.is_idle:
time.sleep(1)
self.stop() | Blocks the program execution until one of the signals are received,
then gently stop the Client by closing the underlying connection.
Args:
stop_signals (``tuple``, *optional*):
Iterable containing signals the signal handler will listen to.
Defaults to (SIGINT, SIGTERM, SIGABRT). | juraj-google-style |
def _publish_scan_response(self, client):
devices = self._manager.scanned_devices
converted_devs = []
for uuid, info in devices.items():
slug = self._build_device_slug(uuid)
message = {}
message['uuid'] = uuid
if uuid in self._connectio... | Publish a scan response message
The message contains all of the devices that are currently known
to this agent. Connection strings for direct connections are
translated to what is appropriate for this agent.
Args:
client (string): A unique id for the client that made this request | juraj-google-style |
def get_saved_model_tag_sets(saved_model_dir):
saved_model = read_saved_model(saved_model_dir)
all_tags = []
for meta_graph_def in saved_model.meta_graphs:
all_tags.append(list(meta_graph_def.meta_info_def.tags))
return all_tags | Retrieves all the tag-sets available in the SavedModel.
Args:
saved_model_dir: Directory containing the SavedModel.
Returns:
List of all tag-sets in the SavedModel, where a tag-set is represented as a
list of strings. | github-repos |
def render_wrapper(self, region='us-east-1'):
base = self.settings['pipeline']['base']
if self.base:
base = self.base
email = self.settings['pipeline']['notifications']['email']
slack = self.settings['pipeline']['notifications']['slack']
baking_process = se... | Generate the base Pipeline wrapper.
This renders the non-repeatable stages in a pipeline, like jenkins, baking, tagging and notifications.
Args:
region (str): AWS Region.
Returns:
dict: Rendered Pipeline wrapper. | juraj-google-style |
def GetDataStream(self, name, case_sensitive=True):
if not isinstance(name, py2to3.STRING_TYPES):
raise ValueError('Name is not a string.')
name_lower = name.lower()
matching_data_stream = None
for data_stream in self._GetDataStreams():
if data_stream.name == name:
return data... | Retrieves a data stream by name.
Args:
name (str): name of the data stream.
case_sensitive (Optional[bool]): True if the name is case sensitive.
Returns:
DataStream: a data stream or None if not available.
Raises:
ValueError: if the name is not string. | juraj-google-style |
def embedding_lookup(self, features: Any, weights: Optional[Any]=None) -> Any:
if not self._built:
self.build()
nest.assert_same_structure(features, self._feature_config)
flat_inputs = nest.flatten(features)
flat_weights = [None] * len(flat_inputs)
if weights is not None:
nest.assert... | Apply embedding lookup on TPUs using Tensorcore.
Note that all the sparse and ragged tensors will be converted to dense
tensors on CPU and then passed to the TPU to do embedding look up. Large
embedding lookup is not supported by this API, use the TPUEmbedding mid
level api instead.
Args:
features: a nested structure... | github-repos |
def update(self, domain, type_name, search_command, body):
return self._request(domain, type_name, search_command, 'PUT', body) | Update entry in ThreatConnect Data Store
Args:
domain (string): One of 'local', 'organization', or 'system'.
type_name (string): This is a free form index type name. The ThreatConnect API will use
this resource verbatim.
search_command (string): Search command to pass to ES.
body (str): JSON body | codesearchnet |
def get_token(self, text, start=0):
best_class = best_match = None
for token_class, match in self.matching_tokens(text):
if best_match and best_match.end() >= match.end():
continue
best_match = match
best_class = token_class
return b... | Retrieve the next token from some text.
Args:
text (str): the text from which tokens should be extracted
Returns:
(token_kind, token_text): the token kind and its content. | juraj-google-style |
def index_2d(seqs: List[List[Any]], target: Any) -> Tuple[(int, int)]:
for i in range(len(seqs)):
for j in range(len(seqs[i])):
if (seqs[i][j] == target):
return (i, j)
raise ValueError('Item not present.') | Finds the first index of a target item within a list of lists.
Args:
seqs: The list of lists to search.
target: The item to find.
Raises:
ValueError: Item is not present. | codesearchnet |
def _ParseCommentRecord(self, structure):
comment = structure[1]
if comment.startswith('Version'):
(_, _, self._version) = comment.partition(':')
elif comment.startswith('Software'):
(_, _, self._software) = comment.partition(':')
elif comment.startswith('Time'):
(_, _, time_form... | Parse a comment and store appropriate attributes.
Args:
structure (pyparsing.ParseResults): parsed log line. | codesearchnet |
def mset(self, values):
for (key, value) in values.items():
self.set(key, value) | Set the value of several keys at once.
Args:
values (dict): maps a key to its value. | codesearchnet |
def stream_sample(self, md5, kwargs=None):
max_rows = kwargs.get('max_rows', None) if kwargs else None
sample = self.get_sample(md5)['sample']
raw_bytes = sample['raw_bytes']
type_tag = sample['type_tag']
if type_tag == 'bro':
br... | Stream the sample by giving back a generator, typically used on 'logs'.
Args:
md5: the md5 of the sample
kwargs: a way of specifying subsets of samples (None for all)
max_rows: the maximum number of rows to return
Returns:
A generator that yields rows of the file/log | juraj-google-style |
def index_library_datasets(self, tick_f=None):
dataset_n = 0
partition_n = 0
def tick(d, p):
if tick_f:
tick_f('datasets: {} partitions: {}'.format(d, p))
for dataset in self.library.datasets:
if self.backend.dataset_index.index_one(da... | Indexes all datasets of the library.
Args:
tick_f (callable, optional): callable of one argument. Gets string with index state. | juraj-google-style |
def fswap(p, q):
(yield (cirq.ISWAP(q, p), (cirq.Z(p) ** 1.5)))
(yield (cirq.Z(q) ** 1.5)) | Decompose the Fermionic SWAP gate into two single-qubit gates and
one iSWAP gate.
Args:
p: the id of the first qubit
q: the id of the second qubit | codesearchnet |
def inner_text(node):
from lxml import etree
parts = [node.text]
for child in node.getchildren():
parts.append(etree.tostring(child, encoding="utf-8", method="text"))
parts.append(child.tail)
return "".join(map(decode_bytes, filter(None, parts))) | Returns the inner text of a given XML node, excluding tags.
Args:
node: (lxml.etree.Element): The node whose inner text is desired.
Returns:
str: The inner text of the node. | juraj-google-style |
def _parse_domain_id(self, config):
match = re.search('domain-id (.+)$', config)
value = (match.group(1) if match else None)
return dict(domain_id=value) | Scans the config block and parses the domain-id value
Args:
config (str): The config block to scan
Returns:
dict: A dict object that is intended to be merged into the
resource dict | codesearchnet |
def get(self, key):
''
value = self.child_datastore.get(key)
return self.deserializedValue(value) | Return the object named by key or None if it does not exist.
Retrieves the value from the ``child_datastore``, and de-serializes
it on the way out.
Args:
key: Key naming the object to retrieve
Returns:
object or None | codesearchnet |
def datasets_update(self, dataset_name, dataset_info):
url = Api._ENDPOINT + (Api._DATASETS_PATH % dataset_name)
return datalab.utils.Http.request(url, method='PUT', data=dataset_info,
credentials=self._credentials) | Updates the Dataset info.
Args:
dataset_name: the name of the dataset to update as a tuple of components.
dataset_info: the Dataset resource with updated fields. | juraj-google-style |
class AltCLIPEncoder(nn.Module):
def __init__(self, config: AltCLIPConfig):
super().__init__()
self.config = config
self.layers = nn.ModuleList([AltCLIPEncoderLayer(config) for _ in range(config.num_hidden_layers)])
self.gradient_checkpointing = False
def forward(self, inputs_e... | Transformer encoder consisting of `config.num_hidden_layers` self attention layers. Each layer is a
[`AltCLIPEncoderLayer`].
Args:
config: AltCLIPConfig | github-repos |
def _verify_watches(self, watch_opts, expected_output_slot, expected_debug_ops, expected_debug_urls):
node_names = []
for watch in watch_opts:
node_names.append(watch.node_name)
if watch.node_name == '*':
self.assertEqual(-1, watch.output_slot)
self.assertEqual(expected_d... | Verify a list of debug tensor watches.
This requires all watches in the watch list have exactly the same
output_slot, debug_ops and debug_urls.
Args:
watch_opts: Repeated protobuf field of DebugTensorWatch.
expected_output_slot: Expected output slot index, as an integer.
expected_debug_ops: Expected debug ops, as a l... | github-repos |
def create(self, vectors):
if (type(vectors) is dict):
vectors = [vectors]
for vector in vectors:
if (not ('properties' in list(vector.keys()))):
raise Exception('Vector does not contain "properties" field.')
if (not ('item_type' in list(vector['properties'].keys()))):
... | Create a vectors in the vector service.
Args:
vectors: A single geojson vector or a list of geojson vectors. Item_type and ingest_source are required.
Returns:
(list): IDs of the vectors created
Example:
>>> vectors.create(
... {
... "type": "Feature",
... "geometry": {
... "type": "P... | codesearchnet |
def add_permissions(self, grp_name, resource, permissions):
self.service.add_permissions(grp_name, resource, permissions, self.url_prefix, self.auth, self.session, self.session_send_opts) | Add additional permissions for the group associated with the given resource.
Args:
grp_name (string): Name of group.
resource (intern.resource.boss.BossResource): Identifies which data model object to operate on.
permissions (list): List of permissions to add to the given resource.
Raises:
requests.HTTPError on failu... | codesearchnet |
def GetHTTPHeaders(self):
http_headers = self._adwords_client.oauth2_client.CreateHttpHeader()
if self.enable_compression:
http_headers['accept-encoding'] = 'gzip'
http_headers.update(self.custom_http_headers)
return http_headers | Returns the HTTP headers required for request authorization.
Returns:
A dictionary containing the required headers. | codesearchnet |
def to_json_str(value: Any, *, json_indent=None, **kwargs) -> str:
def _encode_int_keys(v):
if isinstance(v, dict):
return {f'n_:{k}' if isinstance(k, int) else k: _encode_int_keys(v) for k, v in v.items()}
elif isinstance(v, list):
return [_encode_int_keys(v) for v in v]
... | Serializes a (maybe) symbolic value into a JSON string.
Example::
@pg.members([
('x', pg.typing.Any())
])
class A(pg.Object):
pass
a1 = A(1)
json_str = a1.to_json_str()
a2 = pg.from_json_str(json_str)
assert pg.eq(a1, a2)
Args:
value: Value to serialize.
json_indent: The size of indentation for JSON format.
**kwarg... | github-repos |
def cross_section(verts, tris, plane_orig, plane_normal, **kwargs):
mesh = TriangleMesh(verts, tris)
plane = Plane(plane_orig, plane_normal)
return cross_section_mesh(mesh, plane, **kwargs) | Compute the planar cross section of a mesh. This returns a set of
polylines.
Args:
verts: Nx3 array of the vertices position
faces: Nx3 array of the faces, containing vertex indices
plane_orig: 3-vector indicating the plane origin
plane_normal: 3-vector indicating the plane normal
Returns:
A list of Nx3 arrays, each ... | juraj-google-style |
def get_guild_info(self, id: str) -> Dict[(str, Any)]:
return self._query(f'guilds/{id}', 'GET') | Get a guild's information by its id
Args:
id: snowflake id of the guild
Returns:
Dictionary data for the guild API object
Example:
{
"id": "41771983423143937",
"name": "Discord Developers",
"icon": "SEkgTU9NIElUUyBBTkRSRUkhISEhISEh",
"splash": null,
"owner_id": "80351110224678912",
"region": "us-east",
"afk_channel_... | codesearchnet |
def prepare_soap_envelope(self, prepared_soap_header, prepared_soap_body):
soap_env_template = (
'<?xml version="1.0"?>'
'<s:Envelope xmlns:s="http:
' s:encodingStyle="http:
'{soap_header}'
'<s:Body>'
... | Prepare the SOAP Envelope for sending.
Args:
prepared_soap_header (str): A SOAP Header prepared by
`prepare_soap_header`
prepared_soap_body (str): A SOAP Body prepared by
`prepare_soap_body`
Returns:
str: A prepared SOAP Envelope | juraj-google-style |
def create_and_fill_np_array(start_or_end_logits, dataset, max_len):
step = 0
logits_concat = np.full((len(dataset), max_len), -100, dtype=np.float64)
for i, output_logit in enumerate(start_or_end_logits):
batch_size = output_logit.shape[0]
cols = output_logit.shape[1]
if step + batc... | Create and fill numpy array of size len_of_validation_data * max_length_of_output_tensor
Args:
start_or_end_logits(:obj:`tensor`):
This is the output predictions of the model. We can only enter either start or end logits.
eval_dataset: Evaluation dataset
max_len(:obj:`int`):
The maximum length of the output tensor. ( ... | github-repos |
def copy_remote_file(web_file, destination):
size = 0
dir_name = os.path.dirname(destination)
if (not os.path.exists(dir_name)):
os.makedirs(dir_name)
with open(destination, 'wb') as file_:
chunk_size = (8 * 1024)
for chunk in web_file.iter_content(chunk_size=chunk_size):
... | Check if exist the destination path, and copy the online resource
file to local.
Args:
:web_file: reference to online file resource to take.
:destination: path to store the file. | codesearchnet |
def cancel(self, job_ids):
statuses = []
for job_id in job_ids:
try:
self.delete_instance(job_id)
statuses.append(True)
self.provisioned_blocks -= 1
except Exception:
statuses.append(False)
return st... | Cancels the resources identified by the job_ids provided by the user.
Args:
- job_ids (list): A list of job identifiers
Returns:
- A list of status from cancelling the job which can be True, False
Raises:
- ExecutionProviderException or its subclasses | juraj-google-style |
def validate_config_has_one_of(config, one_of_keys):
intersection = set(config).intersection(one_of_keys)
if (len(intersection) > 1):
raise Exception(('Only one of the values in "%s" is needed' % ', '.join(intersection)))
if (len(intersection) == 0):
raise Exception(('One of the values in "%... | Validate a config dictionary to make sure it has one and only one
key in one_of_keys.
Args:
config: the config to validate.
one_of_keys: the list of possible keys that config can have one and only one.
Raises:
Exception if the config does not have any of them, or multiple of them. | codesearchnet |
def deserialize(config, custom_objects=None):
from tensorflow.python.keras.mixed_precision import loss_scale_optimizer
all_classes = {'adadelta': adadelta_v2.Adadelta, 'adagrad': adagrad_v2.Adagrad, 'adam': adam_v2.Adam, 'adamax': adamax_v2.Adamax, 'nadam': nadam_v2.Nadam, 'rmsprop': rmsprop_v2.RMSprop, 'sgd': ... | Inverse of the `serialize` function.
Args:
config: Optimizer configuration dictionary.
custom_objects: Optional dictionary mapping names (strings) to custom
objects (classes and functions) to be considered during deserialization.
Returns:
A Keras Optimizer instance. | github-repos |
def ValidatePassword(self, password):
password = to_aes_key(password)
return (hashlib.sha256(password).digest() == self.LoadStoredData('PasswordHash')) | Validates if the provided password matches with the stored password.
Args:
password (string): a password.
Returns:
bool: the provided password matches with the stored password. | codesearchnet |
def _validate_alias_name(alias_name):
if not alias_name:
raise CLIError(EMPTY_ALIAS_ERROR)
if not re.match('^[a-zA-Z]', alias_name):
raise CLIError(INVALID_STARTING_CHAR_ERROR.format(alias_name[0])) | Check if the alias name is valid.
Args:
alias_name: The name of the alias to validate. | juraj-google-style |
def __gt__(self, other):
if not isinstance(other, interface.DateTimeValues):
raise ValueError('Other not an instance of DateTimeValues')
return not isinstance(other, Never) | Determines if the date time values are greater than other.
Args:
other (DateTimeValues): date time values to compare against.
Returns:
bool: True if the date time values are greater than other.
Raises:
ValueError: if other is not an instance of DateTimeValues. | juraj-google-style |
def GetSubNodeByLocation(self, location):
for sub_node in self.sub_nodes:
sub_node_location = getattr(sub_node.path_spec, 'location', None)
if location == sub_node_location:
return sub_node
return None | Retrieves a sub scan node based on the location.
Args:
location (str): location that should match the location of the path
specification of a sub scan node.
Returns:
SourceScanNode: sub scan node or None if not available. | juraj-google-style |
def files(self, request, id):
gist = self.send(request, id).json()
return gist['files'] | Returns a list of files in the gist
Arguments:
request: an initial request object
id: the gist identifier
Returns:
A list of the files | codesearchnet |
def detect_mbr(self, filename, offset, fs_id):
self.logger.debug('Detecting MBR partition type')
if fs_id not in self.__mbr_plugins:
return None
else:
plugins = self.__mbr_plugins.get(fs_id)
for plugin in plugins:
if plugin.detect(fil... | Used by rawdisk.session.Session to match mbr partitions against
filesystem plugins.
Args:
filename: device or file that it will read in order to detect
the filesystem fs_id: filesystem id to match (ex. 0x07)
offset: offset for the filesystem that is being matched
Returns:
Volume object supplied by matched plugin.
If ... | juraj-google-style |
def _validate_write(self, address):
if (not any((address.startswith(ns) for ns in self._write_list))):
raise AuthorizationException(address=address) | Raises an exception if the address is not allowed to be set
in this context, based on txn outputs.
Notes:
Checks that the address is either listed fully as one of the
outputs, or some portion of the address is listed as a namespace
in the outputs of the txn.
Args:
address (str): The address to be validated. The conte... | codesearchnet |
def get_vocabulary(self, include_special_tokens=True):
return self._lookup_layer.get_vocabulary(include_special_tokens) | Returns the current vocabulary of the layer.
Args:
include_special_tokens: If `True`, the returned vocabulary
will include the padding and OOV tokens,
and a term's index in the vocabulary will equal
the term's index when calling the layer. If `False`, the
returned vocabulary will not include any padding
or OOV tokens. | github-repos |
def infer(self, **kwargs) -> Any: | Returns the inferred value.
Args:
**kwargs: Optional keyword arguments for inference, which are usually
inferential subclass specific.
Returns:
Inferred value.
Raises:
AttributeError: If the value cannot be inferred. | github-repos |
def __init__(self, config: FastSpeech2ConformerConfig, num_layers=2, num_chans=384, kernel_size=3, dropout_rate=0.5):
super().__init__()
self.conv_layers = nn.ModuleList()
for idx in range(num_layers):
input_channels = config.hidden_size if idx == 0 else num_chans
layer = FastSpeech2Conforme... | Initialize variance predictor module.
Args:
input_dim (`int`): Input dimension.
num_layers (`int`, *optional*, defaults to 2): Number of convolutional layers.
num_chans (`int`, *optional*, defaults to 384): Number of channels of convolutional layers.
kernel_size (`int`, *optional*, defaults to 3): Kernel size of convo... | github-repos |
def NodeName(node):
if node.type < 256:
return token.tok_name[node.type]
else:
return pygram.python_grammar.number2symbol[node.type] | Produce a string name for a given node.
For a Leaf this is the token name, and for a Node this is the type.
Arguments:
node: a tree node
Returns:
Name as a string. | github-repos |
def permute(self, ordering: np.ndarray, *, axis: int) -> None:
if (axis == 0):
self.values = self.values[(ordering, :)]
elif (axis == 1):
self.values = self.values[(:, ordering)]
else:
raise ValueError('axis must be 0 or 1') | Permute the layer along an axis
Args:
axis: The axis to permute (0, permute the rows; 1, permute the columns)
ordering: The permutation vector | codesearchnet |
def _pipeline_cell(args, cell_body):
name = args.get('name')
if name is None:
raise Exception('Pipeline name was not specified.')
import google.datalab.utils as utils
bq_pipeline_config = utils.commands.parse_config(
cell_body, utils.commands.notebook_environment())
try:
a... | Implements the pipeline subcommand in the %%bq magic.
Args:
args: the arguments following '%%bq pipeline'.
cell_body: Cell contents. | juraj-google-style |
def DownloadDir(aff4_path, output_dir, bufsize=8192, preserve_path=True):
if (not os.path.isdir(output_dir)):
os.makedirs(output_dir)
fd = aff4.FACTORY.Open(aff4_path)
for child in fd.OpenChildren():
if preserve_path:
full_dir = utils.JoinPath(output_dir, child.urn.Path())
... | Take an aff4 path and download all files in it to output_dir.
Args:
aff4_path: Any aff4 path as a string
output_dir: A local directory to write to, will be created if not there.
bufsize: Buffer size to use.
preserve_path: If set all paths will be created. Note that this works for
collections as well. It will download... | codesearchnet |
def __init__(self, target_shape, **kwargs):
super(Reshape, self).__init__(**kwargs)
self.target_shape = tuple(target_shape) | Creates a `tf.keras.layers.Reshape` layer instance.
Args:
target_shape: Target shape. Tuple of integers, does not include the
samples dimension (batch size).
**kwargs: Any additional layer keyword arguments. | github-repos |
def setup_build(self):
if not self.make_imports_dir():
return set()
default_output = self.write_default_pyi()
self.write_ninja_preamble()
files = set()
module_to_imports_map = {}
module_to_output = {}
for module, action, deps, stage in self.yield_sorted_modules():
if files >=... | Write out the full build.ninja file.
Returns:
All files with build statements. | github-repos |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.