code stringlengths 20 4.93k | docstring stringlengths 33 1.27k | source stringclasses 3
values |
|---|---|---|
def flatlist_dropdup(list_of_lists):
return list(set([str(item) for sublist in list_of_lists for item in sublist])) | Make a single list out of a list of lists, and drop all duplicates.
Args:
list_of_lists: List of lists.
Returns:
list: List of single objects. | juraj-google-style |
def __init__(self, iterator_resource, initializer, output_types, output_shapes, output_classes):
self._iterator_resource = iterator_resource
self._initializer = initializer
if output_types is None or output_shapes is None or output_classes is None:
raise ValueError(f'All of `output_types`, `output_s... | Creates a new iterator from the given iterator resource.
Note: Most users will not call this initializer directly, and will
instead use `Dataset.make_initializable_iterator()` or
`Dataset.make_one_shot_iterator()`.
Args:
iterator_resource: A `tf.resource` scalar `tf.Tensor` representing the
iterator.
initializer: A `... | github-repos |
class Monitor(object):
def __init__(self, namespace: str, name_prefix: str) -> None:
self.namespace = namespace
self.name_prefix = name_prefix
self.doFn = MonitorDoFn(namespace, name_prefix) | A monitor of elements with support for later retrieving their metrics
monitor objects contains a doFn to record metrics
Args:
namespace: the namespace all metrics within this Monitor uses
name_prefix: a prefix for this Monitor's metrics' names, intended to
be unique in per-monitor basis in pipeline | github-repos |
def remove_hairs_decorator(fn=None, hairs=HAIRS):
def decorator_wrapper(fn):
@wraps(fn)
def decorator(*args, **kwargs):
out = fn(*args, **kwargs)
return remove_hairs(out, hairs)
return decorator
if fn:
return decorator_wrapper(fn)
return decor... | Parametrized decorator wrapping the :func:`remove_hairs` function.
Args:
hairs (str, default HAIRS): List of characters which should be removed.
See :attr:`HAIRS` for details. | juraj-google-style |
def get_tqdm_kwargs(**kwargs):
default = dict(
smoothing=0.5,
dynamic_ncols=True,
ascii=True,
bar_format='{l_bar}{bar}|{n_fmt}/{total_fmt}[{elapsed}<{remaining},{rate_noinv_fmt}]'
)
try:
interval = float(os.environ['TENSORPACK_PROGRESS_REFRESH'])
ex... | Return default arguments to be used with tqdm.
Args:
kwargs: extra arguments to be used.
Returns:
dict: | juraj-google-style |
def add_business_days(self, date_tensor, num_days, roll_convention=constants.BusinessDayConvention.NONE):
control_deps = []
if roll_convention == constants.BusinessDayConvention.NONE:
message = 'Some dates in date_tensor are not business days. Please specify the roll_convention argument.'
is_bus... | Adds given number of business days to given dates.
Note that this is different from calling `add_period_and_roll` with
PeriodType.DAY. For example, adding 5 business days to Monday gives the next
Monday (unless there are holidays on this week or next Monday). Adding 5
days and rolling means landing on Saturday and the... | github-repos |
def Readdir(self, path, fh=None):
if self.DataRefreshRequired(path):
self._RunAndWaitForVFSFileUpdate(path)
return super(GRRFuse, self).Readdir(path, fh=None) | Updates the directory listing from the client.
Args:
path: The path to the directory to update. Client is inferred from this.
fh: A file handler. Not used.
Returns:
A list of filenames. | codesearchnet |
def parse_config_input_output(args=sys.argv):
parser = argparse.ArgumentParser(
description='Process the input files using the given config')
parser.add_argument(
'config_file',
help='Configuration file.',
metavar='FILE', type=extant_file)
parser.add_argument(
'i... | Parse the args using the config_file, input_dir, output_dir pattern
Args:
args: sys.argv
Returns:
The populated namespace object from parser.parse_args().
Raises:
TBD | juraj-google-style |
def underlying_variable_ref(t):
while (t.op.type in ['Identity', 'ReadVariableOp', 'Enter']):
t = t.op.inputs[0]
op_type = t.op.type
if (('Variable' in op_type) or ('VarHandle' in op_type)):
return t
else:
return None | Find the underlying variable ref.
Traverses through Identity, ReadVariableOp, and Enter ops.
Stops when op type has Variable or VarHandle in name.
Args:
t: a Tensor
Returns:
a Tensor that is a variable ref, or None on error. | codesearchnet |
def save_results(vcs, signature, result_path, patterns):
results_directory = _get_results_directory(vcs, signature)
if not os.path.exists(results_directory):
os.makedirs(results_directory)
with open(os.path.join(results_directory, 'patterns'), 'w') as f:
f.write('\n'.join(patterns))
... | Save results matching `patterns` at `result_path`.
Args:
vcs (easyci.vcs.base.Vcs) - the VCS object for the actual project
(not the disposable copy)
signature (str) - the project state signature
result_path (str) - the path containing the result, usually
a disposable copy of the project
patterns (str) - `rsync`-compat... | juraj-google-style |
def findLabel(self, query, create=False):
if isinstance(query, six.string_types):
query = query.lower()
for label in self._labels.values():
if ((isinstance(query, six.string_types) and (query == label.name.lower())) or (isinstance(query, Pattern) and query.search(label.name))):
retur... | Find a label with the given name.
Args:
name (Union[_sre.SRE_Pattern, str]): A str or regular expression to match against the name.
create (bool): Whether to create the label if it doesn't exist (only if name is a str).
Returns:
Union[gkeepapi.node.Label, None]: The label. | codesearchnet |
def GetIndentLevel(line):
indent = Match('^( *)\\S', line)
if indent:
return len(indent.group(1))
else:
return 0 | Return the number of leading spaces in line.
Args:
line: A string to check.
Returns:
An integer count of leading spaces, possibly zero. | codesearchnet |
def GetServiceAccount(self, request, global_params=None):
config = self.GetMethodConfig('GetServiceAccount')
return self._RunMethod(config, request, global_params=global_params) | Returns the email address of the service account for your project used for interactions with Google Cloud KMS.
Args:
request: (BigqueryProjectsGetServiceAccountRequest) input message
global_params: (StandardQueryParameters, default: None) global arguments
Returns:
(GetServiceAccountResponse) The response message. | github-repos |
def GetKeyByPath(self, key_path):
root_key_path, _, key_path = key_path.partition(
definitions.KEY_PATH_SEPARATOR)
root_key_path = root_key_path.upper()
root_key_path = self._ROOT_KEY_ALIASES.get(root_key_path, root_key_path)
if root_key_path not in self._ROOT_KEYS:
raise Runti... | Retrieves the key for a specific path.
Args:
key_path (str): Windows Registry key path.
Returns:
WinRegistryKey: Windows Registry key or None if not available.
Raises:
RuntimeError: if the root key is not supported. | juraj-google-style |
def of(cls, msg_header: MessageHeader) -> 'MessageDecoder':
cte_hdr = msg_header.parsed.content_transfer_encoding
return cls.of_cte(cte_hdr) | Return a decoder from the message header object.
See Also:
:meth:`.of_cte`
Args:
msg_header: The message header object. | codesearchnet |
def _run_benchmarks(regex):
registry = list(GLOBAL_BENCHMARK_REGISTRY)
selected_benchmarks = []
for benchmark in registry:
benchmark_name = '%s.%s' % (benchmark.__module__, benchmark.__name__)
attrs = dir(benchmark)
benchmark_instance = None
for attr in attrs:
if ... | Run benchmarks that match regex `regex`.
This function goes through the global benchmark registry, and matches
benchmark class and method names of the form
`module.name.BenchmarkClass.benchmarkMethod` to the given regex.
If a method matches, it is run.
Args:
regex: The string regular expression to match Benchmark cla... | github-repos |
def info(self, **kwargs):
path = self._get_series_id_season_number_path('info')
response = self._GET(path, kwargs)
self._set_attrs_to_values(response)
return response | Get the primary information about a TV season by its season number.
Args:
language: (optional) ISO 639 code.
append_to_response: (optional) Comma separated, any TV series
method.
Returns:
A dict respresentation of the JSON returned from the API. | codesearchnet |
def ws45(msg):
d = hex2bin(data(msg))
if (d[3] == '0'):
return None
ws = bin2int(d[4:6])
return ws | Wind shear.
Args:
msg (String): 28 bytes hexadecimal message string
Returns:
int: Wind shear level. 0=NIL, 1=Light, 2=Moderate, 3=Severe | codesearchnet |
def get_custom_object_name(obj):
if hasattr(obj, 'name'):
return obj.name
elif hasattr(obj, '__name__'):
return obj.__name__
elif hasattr(obj, '__class__'):
return generic_utils.to_snake_case(obj.__class__.__name__)
else:
return None | Returns the name to use for a custom loss or metric callable.
Args:
obj: Custom loss of metric callable
Returns:
Name to use, or `None` if the object was not recognized. | github-repos |
def _add_loss_summaries(total_loss):
loss_averages = tf.train.ExponentialMovingAverage(0.9, name='avg')
losses = tf.get_collection('losses')
loss_averages_op = loss_averages.apply(losses + [total_loss])
for l in losses + [total_loss]:
tf.summary.scalar(l.op.name + ' (raw)', l)
tf.... | Add summaries for losses in CIFAR-10 model.
Generates moving average for all losses and associated summaries for
visualizing the performance of the network.
Args:
total_loss: Total loss from loss().
Returns:
loss_averages_op: op for generating moving averages of losses. | juraj-google-style |
def _CreateStopsFolder(self, schedule, doc):
if not schedule.GetStopList():
return None
stop_folder = self._CreateFolder(doc, 'Stops')
stop_folder_selection = self._StopFolderSelectionMethod(stop_folder)
stop_style_selection = self._StopStyleSelectionMethod(doc)
stops = list(schedule.GetS... | Create a KML Folder containing placemarks for each stop in the schedule.
If there are no stops in the schedule then no folder is created.
Args:
schedule: The transitfeed.Schedule instance.
doc: The KML Document ElementTree.Element instance.
Returns:
The Folder ElementTree.Element instance or None if there are no sto... | juraj-google-style |
def sia(transition, direction=Direction.BIDIRECTIONAL):
validate.direction(direction, allow_bi=True)
log.info('Calculating big-alpha for %s...', transition)
if (not transition):
log.info('Transition %s is empty; returning null SIA immediately.', transition)
return _null_ac_sia(transition, di... | Return the minimal information partition of a transition in a specific
direction.
Args:
transition (Transition): The candidate system.
Returns:
AcSystemIrreducibilityAnalysis: A nested structure containing all the
data from the intermediate calculations. The top level contains the
basic irreducibility information for... | codesearchnet |
def set_maintainer(self, maintainer):
if isinstance(maintainer, hdx.data.user.User) or isinstance(maintainer, dict):
if 'id' not in maintainer:
maintainer = hdx.data.user.User.read_from_hdx(maintainer['name'], configuration=self.configuration)
maintainer... | Set the dataset's maintainer.
Args:
maintainer (Union[User,Dict,str]): Either a user id or User metadata from a User object or dictionary.
Returns:
None | juraj-google-style |
def from_respecth(cls, filename_xml, file_author='', file_author_orcid=''):
properties = ReSpecTh_to_ChemKED(filename_xml, file_author, file_author_orcid, validate=False)
return cls(dict_input=properties) | Construct a ChemKED instance directly from a ReSpecTh file.
Arguments:
filename_xml (`str`): Filename of the ReSpecTh-formatted XML file to be imported
file_author (`str`, optional): File author to be added to the list generated from the
XML file
file_author_orcid (`str`, optional): ORCID for the file author being add... | codesearchnet |
def update_firmware(self, firmware_information, force=False):
firmware_uri = "{}/firmware".format(self.data["uri"])
result = self._helper.update(firmware_information, firmware_uri, force=force)
self.refresh()
return result | Installs firmware to the member interconnects of a SAS Logical Interconnect.
Args:
firmware_information: Options to install firmware to a SAS Logical Interconnect.
force: If sets to true, the operation completes despite any problems with the network connectivy
or the erros on the resource itself.
Returns:
dict: SAS Lo... | juraj-google-style |
def GetArtifactPathDependencies(rdf_artifact):
deps = set()
for source in rdf_artifact.sources:
for arg, value in iteritems(source.attributes):
paths = []
if arg in ["path", "query"]:
paths.append(value)
if arg == "key_value_pairs":
paths.extend([x["key"] for x in v... | Return a set of knowledgebase path dependencies.
Args:
rdf_artifact: RDF artifact object.
Returns:
A set of strings for the required kb objects e.g.
["users.appdata", "systemroot"] | juraj-google-style |
def generate_plaintext_random(plain_vocab, distribution, train_samples,
length):
if distribution is not None:
assert len(distribution) == len(plain_vocab)
train_indices = np.random.choice(
range(len(plain_vocab)), (train_samples, length), p=distribution)
return train_i... | Generates samples of text from the provided vocabulary.
Args:
plain_vocab: vocabulary.
distribution: distribution.
train_samples: samples for training.
length: length.
Returns:
train_indices (np.array of Integers): random integers for training.
shape = [num_samples, length]
test_indices (np.array of Integers): random... | juraj-google-style |
def filter_error(self, error):
if error.filename != self._filename or error.line is None:
return True
if error.name == 'bad-return-type' and error.opcode_name in ('RETURN_VALUE', 'RETURN_CONST') and (error.line not in self.return_lines):
_, end = self._function_ranges.find_outermost(error.line)
... | Return whether the error should be logged.
This method is suitable for use as an error filter.
Args:
error: An error._Error object.
Returns:
True iff the error should be included in the log. | github-repos |
def add_space(self, line):
if (not isinstance(self.last_item, Space)):
space = Space(self._structure)
self._structure.append(space)
self.last_item.add_line(line)
return self | Add a Space object to the section
Used during initial parsing mainly
Args:
line (str): one line that defines the space, maybe whitespaces | codesearchnet |
def __init__(self, message):
super(ItemNotFound, self).__init__(
reason=enums.ResultReason.ITEM_NOT_FOUND,
message=message
) | Create an ItemNotFound exception.
Args:
message (string): A string containing information about the error. | juraj-google-style |
def IsDeletedOrDefault(clean_lines, linenum):
open_paren = clean_lines.elided[linenum].find('(')
if (open_paren < 0):
return False
(close_line, _, close_paren) = CloseExpression(clean_lines, linenum, open_paren)
if (close_paren < 0):
return False
return Match('\\s*=\\s*(?:delete|defa... | Check if current constructor or operator is deleted or default.
Args:
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
Returns:
True if this is a deleted or default constructor. | codesearchnet |
def get_ggt(self, n, u):
gk = self[0].einsum_sequence([n, u, n, u])
result = ((- ((((2 * gk) * np.outer(u, u)) + self[0].einsum_sequence([n, n])) + self[1].einsum_sequence([n, u, n, u]))) / (2 * gk))
return result | Gets the Generalized Gruneisen tensor for a given
third-order elastic tensor expansion.
Args:
n (3x1 array-like): normal mode direction
u (3x1 array-like): polarization direction | codesearchnet |
def build_bird_configuration(config):
bird_configuration = {}
if config.getboolean('daemon', 'ipv4'):
if os.path.islink(config.get('daemon', 'bird_conf')):
config_file = os.path.realpath(config.get('daemon', 'bird_conf'))
print("'bird_conf' is set to a symbolic link ({s} ->... | Build bird configuration structure.
First it performs a sanity check against bird settings and then builds a
dictionary structure with bird configuration per IP version.
Arguments:
config (obj): A configparser object which holds our configuration.
Returns:
A dictionary
Raises:
ValueError if sanity check fails. | juraj-google-style |
def set_boolean(self, option, value):
if not isinstance(value, bool):
raise TypeError("%s must be a boolean" % option)
self.options[option] = str(value).lower() | Set a boolean option.
Args:
option (str): name of option.
value (bool): value of the option.
Raises:
TypeError: Value must be a boolean. | juraj-google-style |
def __init__(self, timestamp=None):
super(DelphiDateTime, self).__init__()
self._precision = definitions.PRECISION_1_MILLISECOND
self._timestamp = timestamp | Initializes a Delphi TDateTime timestamp.
Args:
timestamp (Optional[float]): Delphi TDateTime timestamp. | juraj-google-style |
def _get_metrics_from_layers(layers):
metrics = []
layers = layer_utils.filter_empty_layer_containers(layers)
for layer in layers:
if isinstance(layer, Model):
metrics.extend(layer._metrics)
metrics.extend(_get_metrics_from_layers(layer.layers))
else:
metr... | Returns list of metrics from the given layers.
This will not include the `compile` metrics of a model layer.
Args:
layers: List of layers.
Returns:
List of metrics. | github-repos |
def image(self, tag, image, step=None):
image = onp.array(image)
if step is None:
step = self._step
else:
self._step = step
if len(onp.shape(image)) == 2:
image = image[:, :, onp.newaxis]
if onp.shape(image)[-1] == 1:
image = onp.repeat(image, 3, axis=-1)
image_strio... | Saves RGB image summary from onp.ndarray [H,W], [H,W,1], or [H,W,3].
Args:
tag: str: label for this data
image: ndarray: [H,W], [H,W,1], [H,W,3] save image in greyscale or colors/
step: int: training step | juraj-google-style |
def launchctl(sub_cmd, *args, **kwargs):
return_stdout = kwargs.pop('return_stdout', False)
cmd = ['launchctl', sub_cmd]
cmd.extend(args)
kwargs['python_shell'] = False
kwargs = salt.utils.args.clean_kwargs(**kwargs)
ret = __salt__['cmd.run_all'](cmd, **kwargs)
error = _check_launchctl_stder... | Run a launchctl command and raise an error if it fails
Args: additional args are passed to launchctl
sub_cmd (str): Sub command supplied to launchctl
Kwargs: passed to ``cmd.run_all``
return_stdout (bool): A keyword argument. If true return the stdout of
the launchctl command
Returns:
bool: ``True`` if successful
st... | codesearchnet |
def match_docstring_with_signature(obj: Any) -> Optional[Tuple[str, str]]:
if len(getattr(obj, '__doc__', '')) == 0:
return
try:
source, _ = inspect.getsourcelines(obj)
except OSError:
source = []
idx = 0
while idx < len(source) and '"""' not in source[idx]:
idx += 1
... | Matches the docstring of an object with its signature.
Args:
obj (`Any`): The object to process.
Returns:
`Optional[Tuple[str, str]]`: Returns `None` if there is no docstring or no parameters documented in the
docstring, otherwise returns a tuple of two strings: the current documentation of the arguments in the
docst... | github-repos |
def is_outlier(df, item_id, segment_id, price):
if ((segment_id, item_id) not in df.index):
return False
mean = df.loc[(segment_id, item_id)]['mean']
std = df.loc[(segment_id, item_id)]['std']
return gaussian_outlier.is_outlier(x=price, mean=mean, standard_deviation=std) | Verify if a item is an outlier compared to the
other occurrences of the same item, based on his price.
Args:
item_id: idPlanilhaItens
segment_id: idSegmento
price: VlUnitarioAprovado | codesearchnet |
def add_transcript(self, transcript):
logger.debug("Adding transcript {0} to variant {1}".format(
transcript, self['variant_id']))
self['transcripts'].append(transcript) | Add the information transcript
This adds a transcript dict to variant['transcripts']
Args:
transcript (dict): A transcript dictionary | juraj-google-style |
def get_airports(self, country):
url = AIRPORT_BASE.format(country.replace(" ", "-"))
return self._fr24.get_airports_data(url) | Returns a list of all the airports
For a given country this returns a list of dicts, one for each airport, with information like the iata code of the airport etc
Args:
country (str): The country for which the airports will be fetched
Example::
from pyflightdata import FlightData
f=FlightData()
f.get_airports('India'... | juraj-google-style |
def download(self, resource_id):
self.resource_id(str(resource_id))
self._request_uri = '{}/download'.format(self._request_uri) | Update the request URI to download the document for this resource.
Args:
resource_id (integer): The group id. | juraj-google-style |
def GetClientURNsForHostnames(hostnames, token=None):
if data_store.RelationalDBEnabled():
index = ClientIndex()
else:
index = CreateClientIndex(token=token)
keywords = set()
for hostname in hostnames:
if hostname.startswith('host:'):
keywords.add(hostname)
el... | Gets all client_ids for a given list of hostnames or FQDNS.
Args:
hostnames: A list of hostnames / FQDNs.
token: An ACL token.
Returns:
A dict with a list of all known GRR client_ids for each hostname. | codesearchnet |
def _process_config_item(item, dirname):
item = copy.deepcopy(item)
html = item.get('html', None)
if (not html):
raise UserWarning(("Can't find HTML source for item:\n%s" % str(item)))
link = (html if (':
del item['html']
for (key, val) in item.items():
if ('notfoundmsg' in val):... | Process one item from the configuration file, which contains multiple items
saved as dictionary.
This function reads additional data from the config and do some
replacements - for example, if you specify url, it will download data
from this url and so on.
Args:
item (dict): Item, which will be processed.
Note:
Retur... | codesearchnet |
def ParseDom(self, dom, feed):
shape_num = 0
for node in dom.getElementsByTagName('Placemark'):
p = self.ParsePlacemark(node)
if p.IsPoint():
(lon, lat) = p.coordinates[0]
m = self.stopNameRe.search(p.name)
feed.AddStop(lat, lon, m.group(1))
elif p.IsL... | Parses the given kml dom tree and updates the Google transit feed object.
Args:
dom - kml dom tree
feed - an instance of Schedule class to be updated | codesearchnet |
def makeDoubleLinked(dom, parent=None):
dom.parent = parent
for child in dom.childs:
child.parent = dom
makeDoubleLinked(child, dom) | Standard output from `dhtmlparser` is single-linked tree. This will make it
double-linked.
Args:
dom (obj): :class:`.HTMLElement` instance.
parent (obj, default None): Don't use this, it is used in recursive
call. | juraj-google-style |
def decision_points(self) -> List[DecisionPoint]:
return self._decision_points | Returns all decision points in their declaration order.
Returns:
All decision points in current space. For multi-choices, the sub-choice
objects will be returned. Users can call `spec.parent_choice` to access
the parent multi-choice node. | github-repos |
def modify_binding(site, binding, hostheader=None, ipaddress=None, port=None, sslflags=None):
if ((sslflags is not None) and (sslflags not in _VALID_SSL_FLAGS)):
message = "Invalid sslflags '{0}' specified. Valid sslflags range: {1}..{2}".format(sslflags, _VALID_SSL_FLAGS[0], _VALID_SSL_FLAGS[(- 1)])
... | Modify an IIS Web Binding. Use ``site`` and ``binding`` to target the
binding.
.. versionadded:: 2017.7.0
Args:
site (str): The IIS site name.
binding (str): The binding to edit. This is a combination of the
IP address, port, and hostheader. It is in the following format:
ipaddress:port:hostheader. For example, ``*:8... | codesearchnet |
def get_pattern_additional_cycles(self, patternnumber):
_checkPatternNumber(patternnumber)
address = _calculateRegisterAddress('cycles', patternnumber)
return self.read_register(address) | Get the number of additional cycles for a given pattern.
Args:
patternnumber (integer): 0-7
Returns:
The number of additional cycles (int). | codesearchnet |
def list_depth(list_, func=max, _depth=0):
depth_list = [list_depth(item, func=func, _depth=_depth + 1)
for item in list_ if util_type.is_listlike(item)]
if len(depth_list) > 0:
return func(depth_list)
else:
return _depth | Returns the deepest level of nesting within a list of lists
Args:
list_ : a nested listlike object
func : depth aggregation strategy (defaults to max)
_depth : internal var
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_list import * # NOQA
>>> list_ = [[[[[1]]], [3]], [[1], [3]], [[1], [3]]]
>>> result = (lis... | juraj-google-style |
def encode(self, s):
if s.endswith('.mp3'):
out_filepath = (s[:(- 4)] + '.wav')
call(['sox', '--guard', s, '-r', '16k', '-b', '16', '-c', '1', out_filepath])
s = out_filepath
elif (not s.endswith('.wav')):
out_filepath = (s + '.wav')
if (not os.path.exists(out_filepath)):... | Transform a string with a filename into a list of float32.
Args:
s: path to the file with a waveform.
Returns:
samples: list of int16s | codesearchnet |
def _create_triangular_filter_bank(fft_freqs: np.ndarray, filter_freqs: np.ndarray) -> np.ndarray:
filter_diff = np.diff(filter_freqs)
slopes = np.expand_dims(filter_freqs, 0) - np.expand_dims(fft_freqs, 1)
down_slopes = -slopes[:, :-2] / filter_diff[:-1]
up_slopes = slopes[:, 2:] / filter_diff[1:]
... | Creates a triangular filter bank.
Adapted from *torchaudio* and *librosa*.
Args:
fft_freqs (`np.ndarray` of shape `(num_frequency_bins,)`):
Discrete frequencies of the FFT bins in Hz.
filter_freqs (`np.ndarray` of shape `(num_mel_filters,)`):
Center frequencies of the triangular filters to create, in Hz.
Returns:
`n... | github-repos |
def delete_case(self, case):
mongo_case = self.case(case)
if not mongo_case:
raise CaseError("Tried to delete case {0} but could not find case".format(
case.get('case_id')
))
LOG.info("Removing case {0} from database".format(
mongo_ca... | Delete case from the database
Delete a case from the database
Args:
case (dict): A case dictionary | juraj-google-style |
def serialize_example(transformed_json_data, info_dict):
import six
import tensorflow as tf
def _make_int64_list(x):
return tf.train.Feature(int64_list=tf.train.Int64List(value=x))
def _make_bytes_list(x):
return tf.train.Feature(bytes_list=tf.train.BytesList(value=x))
def _make_f... | Makes a serialized tf.example.
Args:
transformed_json_data: dict of transformed data.
info_dict: output of feature_transforms.get_transfrormed_feature_info()
Returns:
The serialized tf.example version of transformed_json_data. | 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_pos_d, gan_g_loss... | 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... | codesearchnet |
def RemoveScanNode(self, path_spec):
scan_node = self._scan_nodes.get(path_spec, None)
if (not scan_node):
return None
if scan_node.sub_nodes:
raise RuntimeError('Scan node has sub nodes.')
parent_scan_node = scan_node.parent_node
if parent_scan_node:
parent_scan_node.sub_nod... | Removes a scan node of a certain path specification.
Args:
path_spec (PathSpec): path specification.
Returns:
SourceScanNode: parent scan node or None if not available.
Raises:
RuntimeError: if the scan node has sub nodes. | codesearchnet |
def getFingerprintsForTexts(self, strings, sparsity=1.0):
body = [{"text": s} for s in strings]
return self._text.getRepresentationsForBulkText(self._retina, json.dumps(body), sparsity) | Bulk get Fingerprint for text.
Args:
strings, list(str): A list of texts to be evaluated (required)
sparsity, float: Sparsify the resulting expression to this percentage (optional)
Returns:
list of Fingerprint
Raises:
CorticalioException: if the request was not successful | juraj-google-style |
def _EvaluateExpressions(self, frame):
return [self._FormatExpression(frame, expression) for expression in
self._definition.get('expressions') or []] | Evaluates watched expressions into a string form.
If expression evaluation fails, the error message is used as evaluated
expression string.
Args:
frame: Python stack frame of breakpoint hit.
Returns:
Array of strings where each string corresponds to the breakpoint
expression with the same index. | juraj-google-style |
def scalar_pb(tag, data, description=None):
arr = np.array(data)
if arr.shape != ():
raise ValueError('Expected scalar shape for tensor, got shape: %s.'
% arr.shape)
if arr.dtype.kind not in ('b', 'i', 'u', 'f'):
raise ValueError('Cast %s to float is not supported' % arr.dtype.na... | Create a scalar summary_pb2.Summary protobuf.
Arguments:
tag: String tag for the summary.
data: A 0-dimensional `np.array` or a compatible python number type.
description: Optional long-form description for this summary, as a
`str`. Markdown is supported. Defaults to empty.
Raises:
ValueError: If the type or shape of... | juraj-google-style |
def arcsinh(x):
if any_symbolic_tensors((x,)):
return Arcsinh().symbolic_call(x)
return backend.numpy.arcsinh(x) | Inverse hyperbolic sine, element-wise.
Arguments:
x: Input tensor.
Returns:
Output tensor of same shape as `x`.
Example:
>>> x = keras.ops.convert_to_tensor([1, -1, 0])
>>> keras.ops.arcsinh(x)
array([0.88137364, -0.88137364, 0.0], dtype=float32) | github-repos |
def decrypt_block(self, cipherText):
if (not self.initialized):
raise TypeError('CamCrypt object has not been initialized')
if (len(cipherText) != BLOCK_SIZE):
raise ValueError(('cipherText must be %d bytes long (received %d bytes)' % (BLOCK_SIZE, len(cipherText))))
plain = ctypes.create_str... | Decrypt a 16-byte block of data.
NOTE: This function was formerly called `decrypt`, but was changed when
support for decrypting arbitrary-length strings was added.
Args:
cipherText (str): 16-byte data.
Returns:
16-byte str.
Raises:
TypeError if CamCrypt object has not been initialized.
ValueError if `cipherText` is... | codesearchnet |
def commit(self, sourcedir, targetdir, abs_config, abs_sourcedir, abs_targetdir):
(config_path, config_filename) = os.path.split(abs_config)
if (not os.path.exists(config_path)):
os.makedirs(config_path)
if (not os.path.exists(abs_sourcedir)):
os.makedirs(abs_sourcedir)
if (not os.path.e... | Commit project structure and configuration file
Args:
sourcedir (string): Source directory path.
targetdir (string): Compiled files target directory path.
abs_config (string): Configuration file absolute path.
abs_sourcedir (string): ``sourcedir`` expanded as absolute path.
abs_targetdir (string): ``targetdir`` expand... | codesearchnet |
def layout(mtf_graph, mesh_shape, mtf_outputs=()):
mesh_shape = mtf.convert_to_shape(mesh_shape)
estimator = memory_estimator.MemoryEstimator(mtf_graph, mesh_shape,
mtf_outputs)
optimizer = layout_optimizer.LayoutOptimizer(estimator)
return mtf.convert_to_layout... | Compute layout rules based on a computational graph and mesh shape.
Args:
mtf_graph: a mtf.Graph.
mesh_shape: an mtf.Shape, str, or listlike of mtf.Dimension.
mtf_outputs: an optional iterable of mtf.Tensor, representing the outputs
of the computation.
Returns:
a mtf.LayoutRules | juraj-google-style |
def _execute_with_retries(conn, function, **kwargs):
r = {}
max_attempts = 18
max_retry_delay = 10
for attempt in range(max_attempts):
log.info('attempt: %s function: %s', attempt, function)
try:
fn = getattr(conn, function)
r['result'] = fn(**kwargs)
... | Retry if we're rate limited by AWS or blocked by another call.
Give up and return error message if resource not found or argument is invalid.
conn
The connection established by the calling method via _get_conn()
function
The function to call on conn. i.e. create_stream
**kwargs
Any kwargs required by the above funct... | codesearchnet |
def isValidUnit(self, w):
bad = set(['point', 'a'])
if w in bad:
return False
try:
pq.Quantity(0.0, w)
return True
except:
return w == '/' | Checks if a string represents a valid quantities unit.
Args:
w (str): A string to be tested against the set of valid
quantities units.
Returns:
True if the string can be used as a unit in the quantities
module. | juraj-google-style |
def _constrain_L2_grad(op, grad):
inp = op.inputs[0]
inp_norm = tf.norm(inp)
unit_inp = (inp / inp_norm)
grad_projection = dot(unit_inp, grad)
parallel_grad = (unit_inp * grad_projection)
is_in_ball = tf.less_equal(inp_norm, 1)
is_pointed_inward = tf.less(grad_projection, 0)
allow_grad =... | Gradient for constrained optimization on an L2 unit ball.
This function projects the gradient onto the ball if you are on the boundary
(or outside!), but leaves it untouched if you are inside the ball.
Args:
op: the tensorflow op we're computing the gradient for.
grad: gradient we need to backprop
Returns:
(projecte... | codesearchnet |
def retrieve_instance_links(self):
instance_links = {}
self.log.debug('LINKS IS %s', LINKS)
for (key, value) in LINKS.items():
if (value not in self.pipeline_config['instance_links'].values()):
instance_links[key] = value
return instance_links | Appends on existing instance links
Returns:
instance_links: A dictionary containing all the instance links in LINKS and not in pipeline_config | codesearchnet |
def authenticate(self, request):
request = request._request
user = getattr(request, 'user', None)
if ((not user) or user.is_anonymous):
return None
self.enforce_csrf(request)
return (user, None) | Authenticate the user, requiring a logged-in account and CSRF.
This is exactly the same as the `SessionAuthentication` implementation,
with the `user.is_active` check removed.
Args:
request (HttpRequest)
Returns:
Tuple of `(user, token)`
Raises:
PermissionDenied: The CSRF token check failed. | codesearchnet |
def decode(self, audio_codes: torch.Tensor, audio_scales: torch.Tensor, padding_mask: Optional[torch.Tensor]=None, return_dict: Optional[bool]=None) -> Union[Tuple[torch.Tensor, torch.Tensor], EncodecDecoderOutput]:
return_dict = return_dict if return_dict is not None else self.config.return_dict
chunk_length =... | Decodes the given frames into an output audio waveform.
Note that the output might be a bit bigger than the input. In that case, any extra steps at the end can be
trimmed.
Args:
audio_codes (`torch.LongTensor` of shape `(batch_size, nb_chunks, chunk_length)`, *optional*):
Discret code embeddings computed using `mode... | github-repos |
def to_env_vars(self):
env = {'hosts': self.hosts, 'network_interface_name': self.network_interface_name, 'hps': self.hyperparameters, 'user_entry_point': self.user_entry_point, 'framework_params': self.additional_framework_parameters, 'resource_config': self.resource_config, 'input_data_config': self.input_data_co... | Environment variable representation of the training environment
Returns:
dict: an instance of dictionary | codesearchnet |
def GetMap(self, map_name, since=None, location=None):
if map_name == config.MAP_PASSWORD:
return self.GetPasswdMap(since)
elif map_name == config.MAP_SSHKEY:
return self.GetSshkeyMap(since)
elif map_name == config.MAP_GROUP:
return self.GetGroupMap(since)
elif map_name == config... | Get a specific map from this source.
Args:
map_name: A string representation of the map you want
since: optional timestamp for incremental query
location: optional field used by automounts to indicate a specific map
Returns:
A Map child class for the map requested.
Raises:
UnsupportedMap: for unknown source maps | github-repos |
def recipe_manual(config, auth_read):
hello(config, {'auth': auth_read, 'hour': [], 'say': 'Hello Manual', 'sleep': 0}) | Used by tests.
Args:
auth_read (authentication) - Credentials used for reading data. | github-repos |
def can_acomp(cat_id):
url = 'https:
auth = Auth()
r = _req_with_retries(auth.gbdx_connection, url)
try:
data = r.json()
return data['acompVersion'] is not None
except:
return False | Checks to see if a CatalogID can be atmos. compensated or not.
Args:
catalogID (str): The catalog ID from the platform catalog.
Returns:
available (bool): Whether or not the image can be acomp'd | juraj-google-style |
def appliance_node_information(self):
if (not self.__appliance_node_information):
self.__appliance_node_information = ApplianceNodeInformation(self.__connection)
return self.__appliance_node_information | Gets the ApplianceNodeInformation API client.
Returns:
ApplianceNodeInformation: | codesearchnet |
def _make_headers(self, method, path, query={}, headers={}):
date = datetime.datetime.utcnow().strftime('%a, %d %b %Y %H:%M:%S GMT')
nonce = self._make_nonce()
ctype = headers.get('Content-Type') if headers.get('Content-Type') else 'application/json'
auth = self._make_auth(met... | Creates a headers object to sign the request
Args:
- method (str): HTTP method
- path (str): Request path, e.g. /api/documents. No query string
- query (dict, default={}): Query string in key-value format
- headers (dict, default={}): Other headers to pass in
Returns:
- dict: Dictionary containing all headers | juraj-google-style |
def _CanProcessKeyWithPlugin(self, registry_key, plugin):
for registry_key_filter in plugin.FILTERS:
if getattr(registry_key_filter, 'key_paths', []):
continue
if registry_key_filter.Match(registry_key):
return True
return False | Determines if a plugin can process a Windows Registry key or its values.
Args:
registry_key (dfwinreg.WinRegistryKey): Windows Registry key.
plugin (WindowsRegistryPlugin): Windows Registry plugin.
Returns:
bool: True if the Registry key can be processed with the plugin. | codesearchnet |
def _acquire_given_subnet(self, uuid_path, subnet):
lease = self.create_lease_object_from_subnet(subnet)
self._take_lease(lease, uuid_path)
return lease.to_ip_network() | Try to create a lease for subnet
Args:
uuid_path (str): Path to the uuid file of a :class:`lago.Prefix`
subnet (str): dotted ipv4 subnet
(for example ```192.168.200.0```)
Returns:
netaddr.IPNetwork: Which represents the selected subnet
Raises:
LagoSubnetLeaseException: If the requested subnet is not in the
range of ... | juraj-google-style |
def __mod__(self, other):
other = as_dimension(other)
if self._value is None or other.value is None:
return Dimension(None)
else:
return Dimension(self._value % other.value) | Returns `self` modulo `other`.
Dimension modulo are computed as follows:
```python
tf.compat.v1.Dimension(m) % tf.compat.v1.Dimension(n) ==
tf.compat.v1.Dimension(m % n)
tf.compat.v1.Dimension(m) % tf.compat.v1.Dimension(None) # equiv. to
tf.compat.v1.Dimension(None)
tf.compat.v1.Dimension(None) % tf.compa... | github-repos |
def AnalyzeEvents(self):
session = engine.BaseEngine.CreateSession(command_line_arguments=self._command_line_arguments, preferred_encoding=self.preferred_encoding)
storage_reader = storage_factory.StorageFactory.CreateStorageReaderForFile(self._storage_file_path)
if (not storage_reader):
logger.erro... | Analyzes events from a plaso storage file and generate a report.
Raises:
BadConfigOption: when a configuration parameter fails validation.
RuntimeError: if a non-recoverable situation is encountered. | codesearchnet |
def most_uncertain_by_mask(self, mask, y):
idxs = np.where(mask)[0]
return idxs[np.argsort(np.abs((self.probs[(idxs, y)] - (1 / self.num_classes))))[:4]] | Extracts the first 4 most uncertain indexes from the ordered list of probabilities
Arguments:
mask (numpy.ndarray): the mask of probabilities specific to the selected class; a boolean array with shape (num_of_samples,) which contains True where class==selected_class, and False everywhere else
y (int): the selected cla... | codesearchnet |
def create_state(self, state_manager):
pass | Uses the `state_manager` to create state for the FeatureColumn.
Args:
state_manager: A `StateManager` to create / access resources such as
lookup tables and variables. | github-repos |
def build_and_pickle_dump(self, abivalidate=False):
self.build()
if (not abivalidate):
return self.pickle_dump()
(isok, errors) = self.abivalidate_inputs()
if isok:
return self.pickle_dump()
errlines = []
for (i, e) in enumerate(errors):
errlines.append(('[%d] %s' % (i, e... | Build dirs and file of the `Flow` and save the object in pickle format.
Returns 0 if success
Args:
abivalidate: If True, all the input files are validate by calling
the abinit parser. If the validation fails, ValueError is raise. | codesearchnet |
def to_matrix(xx, yy, zz, xy, yz, xz):
matrix = np.array([[xx, xy, xz], [xy, yy, yz], [xz, yz, zz]])
return matrix | Convert a list of matrix components to a symmetric 3x3 matrix.
Inputs should be in the order xx, yy, zz, xy, yz, xz.
Args:
xx (float): xx component of the matrix.
yy (float): yy component of the matrix.
zz (float): zz component of the matrix.
xy (float): xy component of the matrix.
yz (float): yz component of the matr... | codesearchnet |
def dynamics(start, end=None):
def _(sequence):
if (start in _dynamic_markers_to_velocity):
start_velocity = _dynamic_markers_to_velocity[start]
start_marker = start
else:
raise ValueError(('Unknown start dynamic: %s, must be in %s' % (start, _dynamic_markers_to_... | Apply dynamics to a sequence. If end is specified, it will crescendo or diminuendo linearly from start to end dynamics.
You can pass any of these strings as dynamic markers: ['pppppp', 'ppppp', 'pppp', 'ppp', 'pp', 'p', 'mp', 'mf', 'f', 'ff', 'fff', ''ffff]
Args:
start: beginning dynamic marker, if no end is specifie... | codesearchnet |
def permutation_matrix(permutation):
assert check_permutation(permutation)
n = len(permutation)
op_matrix = np_zeros((n, n), dtype=int)
for (i, j) in enumerate(permutation):
op_matrix[(j, i)] = 1
return Matrix(op_matrix) | r"""Return orthogonal permutation matrix for permutation tuple
Return an orthogonal permutation matrix :math:`M_\sigma`
for a permutation :math:`\sigma` defined by the image tuple
:math:`(\sigma(1), \sigma(2),\dots \sigma(n))`,
such that
.. math::
M_\sigma \vec{e}_i = \vec{e}_{\sigma(i)}
where :math:`\vec{e}_k` is ... | codesearchnet |
def _get_value_from_match(self, key, match):
value = match.groups(1)[0]
clean_value = str(value).lstrip().rstrip()
if (clean_value == 'true'):
self._log.info('Got value of "%s" as boolean true.', key)
return True
if (clean_value == 'false'):
self._log.info('Got value of "%s" as b... | Gets the value of the property in the given MatchObject.
Args:
key (str): Key of the property looked-up.
match (MatchObject): The matched property.
Return:
The discovered value, as a string or boolean. | codesearchnet |
def get_key(key, data_structure):
if (key == '/'):
return data_structure
path = key.split('/')
(path[0] or path.pop(0))
current_value = data_structure
while path:
current_key = path.pop(0)
try:
current_key = int(current_key)
except ValueError:
... | Helper method for extracting values from a nested data structure.
Args:
key (str): The path to the vales (a series of keys and indexes
separated by '/')
data_structure (dict or list): The data structure from which the
value will be extracted.
Returns:
str: The values associated with key | codesearchnet |
def FromId(architecture_id, error_on_unknown=True):
if not architecture_id:
return None
for arch in Architecture._ALL:
if arch.id == architecture_id:
return arch
if error_on_unknown:
raise InvalidEnumValue(architecture_id, 'Architecture', [value.id for value in Architectu... | Gets the enum corresponding to the given architecture id.
Args:
architecture_id: str, The architecture id to parse
error_on_unknown: bool, True to raise an exception if the id is unknown,
False to just return None.
Raises:
InvalidEnumValue: If the given value cannot be parsed.
Returns:
ArchitectureTuple, One of the ... | github-repos |
def register_with_password(self, username, password):
response = self.api.register(
auth_body={"type": "m.login.dummy"},
kind='user',
username=username,
password=password,
)
return self._post_registration(response) | Register for a new account on this HS.
Args:
username (str): Account username
password (str): Account password
Returns:
str: Access Token
Raises:
MatrixRequestError | juraj-google-style |
def partial_derivative_mu(mu, sigma, low, high, data):
pd_mu = (np.sum((data - mu)) / (sigma ** 2))
pd_mu -= (len(data) * ((norm.pdf(low, mu, sigma) - norm.pdf(high, mu, sigma)) / (norm.cdf(high, mu, sigma) - norm.cdf(low, mu, sigma))))
return (- pd_mu) | The partial derivative with respect to the mean.
Args:
mu (float): the mean of the truncated normal
sigma (float): the std of the truncated normal
low (float): the lower truncation bound
high (float): the upper truncation bound
data (ndarray): the one dimension list of data points for which we want to calculate the li... | codesearchnet |
def increment(self, size: int):
assert size >= 0, size
self.files += 1
self.size += size
self.bandwidth_meter.feed(size) | Increment the number of files downloaded.
Args:
size: The size of the file | juraj-google-style |
def experimental_run_functions_eagerly(run_eagerly):
return run_functions_eagerly(run_eagerly) | Enables / disables eager execution of `tf.function`s.
Calling `tf.config.experimental_run_functions_eagerly(True)` will make all
invocations of `tf.function` run eagerly instead of running as a traced graph
function.
See `tf.config.run_functions_eagerly` for an example.
Note: This flag has no effect on functions pas... | github-repos |
def find_divisors(n):
if (not isinstance(n, int)):
raise TypeError('Expecting a strictly positive integer')
if (n <= 0):
raise ValueError('Expecting a strictly positive integer')
for i in range(1, (int((n ** 0.5)) + 1)):
if ((n % i) == 0):
divisors = {i, (n
f... | Find all the positive divisors of the given integer n.
Args:
n (int): strictly positive integer
Returns:
A generator of all the positive divisors of n
Raises:
TypeError: if n is not an integer
ValueError: if n is negative | codesearchnet |
def _extend_op(values, leaf_op, empty_st_op=None):
if not isinstance(values, Sequence):
raise ValueError('Expected a list')
if not values:
raise ValueError('List cannot be empty')
if empty_st_op is None:
empty_st_op = empty_st_op_like_zeros(leaf_op)
value = values[0]
if isins... | Extend an op from RaggedTensor and Tensor to StructuredTensor.
Visits all children of the structured tensor, and children of children,
applying leaf_op whenever it reaches a leaf, and empty_st_op whenever
it reaches an internal node without children.
Args:
values: a list of structured tensors, ragged tensors, or tens... | github-repos |
def read_classification_results(storage_client, file_path):
if storage_client:
success = False
retry_count = 0
while (retry_count < 4):
try:
blob = storage_client.get_blob(file_path)
if (not blob):
return {}
if (... | Reads classification results from the file in Cloud Storage.
This method reads file with classification results produced by running
defense on singe batch of adversarial images.
Args:
storage_client: instance of CompetitionStorageClient or None for local file
file_path: path of the file with results
Returns:
diction... | codesearchnet |
def load_mutation_rates(path=None):
if path is None:
path = resource_filename(__name__, "data/rates.txt")
rates = []
with open(path) as handle:
for line in handle:
if line.startswith("from"):
continue
line = [ x.encode('utf... | load sequence context-based mutation rates
Args:
path: path to table of sequence context-based mutation rates. If None,
this defaults to per-trinucleotide rates provided by Kaitlin Samocha
(Broad Institute).
Returns:
list of [initial, changed, rate] lists e.g. [['AGA', 'ATA', '5e-8']] | juraj-google-style |
def set_server_def(self, server_def, keep_alive_secs=_KEEP_ALIVE_SECS):
if not server_def:
raise ValueError('server_def is None.')
self._server_def = server_def
if self._context_handle:
server_def_str = server_def.SerializeToString()
pywrap_tfe.TFE_ContextSetServerDef(self._context_h... | Allow setting a server_def on the context.
When a server def is replaced, it effectively clears a bunch of caches
within the context. If you attempt to use a tensor object that was pointing
to a tensor on the remote device, it will raise an error.
Args:
server_def: A tensorflow::ServerDef proto. Enables execution on ... | github-repos |
def find(self, *index):
assert (self.wrapFunction is not None)
if ((len(index) == 1) and isinstance(index[0], (tuple, list))):
index = index[0]
it = self._impl.find(Tuple(index)._impl)
if (it == self._impl.end()):
return None
else:
return self.wrapFunction(it) | Searches the current entity for an instance with the specified index.
Returns:
The wanted instance if found, otherwise it returns `None`. | codesearchnet |
def recursive_import(root):
for _, name, _ in pkgutil.walk_packages(root.__path__, prefix=root.__name__ + '.'):
try:
importlib.import_module(name)
except (AttributeError, ImportError):
pass | Recursively imports all the sub-modules under a root package.
Args:
root: A python package. | github-repos |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.