code stringlengths 20 4.93k | docstring stringlengths 33 1.27k | source stringclasses 3
values |
|---|---|---|
def expected_rs(n):
front = (n - 0.5) / n
i = np.arange(1,n)
back = np.sum(np.sqrt((n - i) / i))
if n <= 340:
middle = math.gamma((n-1) * 0.5) / math.sqrt(math.pi) / math.gamma(n * 0.5)
else:
middle = 1.0 / math.sqrt(n * math.pi * 0.5)
return front * middle * back | Calculates the expected (R/S)_n for white noise for a given n.
This is used as a correction factor in the function hurst_rs. It uses the
formula of Anis-Lloyd-Peters (see [h_3]_).
Args:
n (int):
the value of n for which the expected (R/S)_n should be calculated
Returns:
float:
expected (R/S)_n for white noise | juraj-google-style |
def sample_variants(self, variants, sample_name, category='snv'):
LOG.info('Retrieving variants for subject : {0}'.format(sample_name))
has_allele = re.compile('1|2')
query = {'$and': [{'_id': {'$in': variants}}, {'category': category}, {'samples': {'$elemMatch': {'display_name': sample_name, 'genotype_call... | Given a list of variants get variant objects found in a specific patient
Args:
variants(list): a list of variant ids
sample_name(str): a sample display name
category(str): 'snv', 'sv' ..
Returns:
result(iterable(Variant)) | codesearchnet |
def AddrStrToScriptHash(address):
data = b58decode(address)
if (len(data) != 25):
raise ValueError('Not correct Address, wrong length.')
if (data[0] != settings.ADDRESS_VERSION):
raise ValueError('Not correct Coin Version')
checksum = Crypto.Default().Hash256(data[:21])[:4]
if (check... | Convert a public address to a script hash.
Args:
address (str): base 58 check encoded public address.
Raises:
ValueError: if the address length of address version is incorrect.
Exception: if the address checksum fails.
Returns:
UInt160: | codesearchnet |
def query(self, s):
s1 = np.sort([self.order[token] for token in s if (token in self.order)])
logging.debug('{} original tokens and {} tokens after applying frequency order.'.format(len(s), len(s1)))
prefix = self._get_prefix(s1)
candidates = set([i for (p1, token) in enumerate(prefix) for (i, p2) in se... | Query the search index for sets similar to the query set.
Args:
s (Iterable): the query set.
Returns (list): a list of tuples `(index, similarity)` where the index
is the index of the matching sets in the original list of sets. | codesearchnet |
def inv(a):
amean = gvar.mean(a)
if ((amean.ndim != 2) or (amean.shape[0] != amean.shape[1])):
raise ValueError(('bad matrix shape: ' + str(a.shape)))
da = (a - amean)
ainv = numpy.linalg.inv(amean)
return (ainv - ainv.dot(da.dot(ainv))) | Inverse of matrix ``a``.
Args:
a: Two-dimensional, square matrix/array of numbers
and/or :class:`gvar.GVar`\s.
Returns:
The inverse of matrix ``a``.
Raises:
ValueError: If matrix is not square and two-dimensional. | codesearchnet |
def mimic_adam_with_adafactor(hparams):
assert "adam" in hparams.optimizer
hparams.optimizer = "adafactor"
hparams.optimizer_adafactor_beta1 = hparams.optimizer_adam_beta1
hparams.optimizer_adafactor_beta2 = hparams.optimizer_adam_beta2
hparams.optimizer_adafactor_multiply_by_parameter_scale = False
hpar... | Switch from Adam to Adafactor, approximating the behavior of Adam.
Some minor things may be different, like epsilon and beta1 correction.
Args:
hparams: model hyperparameters where "adam" in hparams.optimizer | juraj-google-style |
def __init__(self, artifacts_registry, knowledge_base):
super(ArtifactDefinitionsFilterHelper, self).__init__()
self._artifacts_registry = artifacts_registry
self._knowledge_base = knowledge_base
self.file_system_artifact_names = set()
self.file_system_find_specs = []
self.registry_artifac... | Initializes an artifact definitions filter helper.
Args:
artifacts_registry (artifacts.ArtifactDefinitionsRegistry): artifact
definitions registry.
knowledge_base (KnowledgeBase): contains information from the source
data needed for filtering. | juraj-google-style |
def __init__(self, select2attrs=None, *args, **kwargs):
self.select2attrs = select2attrs or {}
assert_msg = "select2attrs attribute must be dict, not {}"
assert isinstance(self.select2attrs, dict), assert_msg.format(
self.select2attrs.__class__.__name__
)
... | Initialize default select2 attributes.
If width is not provided, sets Select2 width to 250px.
Args:
select2attrs: a dictionary, which then passed to
Select2 constructor function as options. | juraj-google-style |
def __init__(self, columns: list[str], name: Optional[str]=None):
self.name = name
super().__init__(columns) | Deduplicates each row (0th dimension) of the provided tensor.
Args:
columns: A list of the columns to apply the transformation on.
name: optional. A name for this operation. | github-repos |
def add_resource(self, feature_column, resource_name, resource):
self._cols_to_resources_map[feature_column][resource_name] = resource
if self._layer is not None and isinstance(resource, trackable.Trackable):
if feature_column.name not in self._layer._resources:
self._layer._resources[featur... | Creates a new resource.
Resources can be things such as tables, variables, trackables, etc.
Args:
feature_column: A `FeatureColumn` object this resource corresponds to.
resource_name: Name of the resource.
resource: The resource.
Returns:
The created resource. | github-repos |
def ExtractEvents(self, parser_mediator, registry_key, **kwargs):
version_value = registry_key.GetValueByName('Version')
count_subkey = registry_key.GetSubkeyByName('Count')
if not version_value:
parser_mediator.ProduceExtractionWarning('missing version value')
return
if not version_v... | Extracts events from a Windows Registry key.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
registry_key (dfwinreg.WinRegistryKey): Windows Registry key. | juraj-google-style |
def add_state(self, name: str, state: State, initial: bool=False):
if (not issubclass(state.__class__, State)):
raise AttributeError('state must be subclass of spade.behaviour.State')
self._states[name] = state
if initial:
self.current_state = name | Adds a new state to the FSM.
Args:
name (str): the name of the state, which is used as its identifier.
state (spade.behaviour.State): The state class
initial (bool, optional): wether the state is the initial state or not. (Only one initial state is allowed) (Default value = False) | codesearchnet |
def plot_internal_energy(self, tmin, tmax, ntemp, ylim=None, **kwargs):
temperatures = np.linspace(tmin, tmax, ntemp)
if self.structure:
ylabel = r"$\Delta E$ (kJ/mol)"
else:
ylabel = r"$\Delta E$ (kJ/mol-c)"
fig = self._plot_thermo(self.dos.internal_en... | Plots the vibrational internal energy in a temperature range.
Args:
tmin: minimum temperature
tmax: maximum temperature
ntemp: number of steps
ylim: tuple specifying the y-axis limits.
kwargs: kwargs passed to the matplotlib function 'plot'.
Returns:
matplotlib figure | juraj-google-style |
def _checkResponseRegisterAddress(payload, registeraddress):
_checkString(payload, minlength=2, description='payload')
_checkRegisteraddress(registeraddress)
BYTERANGE_FOR_STARTADDRESS = slice(0, 2)
bytesForStartAddress = payload[BYTERANGE_FOR_STARTADDRESS]
receivedStartAddress = _twoByteStri... | Check that the start adress as given in the response is correct.
The first two bytes in the payload holds the address value.
Args:
* payload (string): The payload
* registeraddress (int): The register address (use decimal numbers, not hex).
Raises:
TypeError, ValueError | juraj-google-style |
def create_graph_from_data(self, data):
self.arguments['{SCORE}'] = self.scores[self.score]
self.arguments['{VERBOSE}'] = str(self.verbose).upper()
results = self._run_gies(data, verbose=self.verbose)
return nx.relabel_nodes(nx.DiGraph(results), {idx: i for (idx, i) in enumerate(data.columns)}) | Run the GIES algorithm.
Args:
data (pandas.DataFrame): DataFrame containing the data
Returns:
networkx.DiGraph: Solution given by the GIES algorithm. | codesearchnet |
def add_perm(self, subj_str, perm_str):
self._assert_valid_permission(perm_str)
self._perm_dict.setdefault(perm_str, set()).add(subj_str) | Add a permission for a subject.
Args:
subj_str : str
Subject for which to add permission(s)
perm_str : str
Permission to add. Implicitly adds all lower permissions. E.g., ``write``
will also add ``read``. | juraj-google-style |
def scan(self, folder, sub=None, next_=None):
if (not sub):
sub = ''
assert isinstance(sub, string_types)
assert (isinstance(next_, int) or (next_ is None))
return self.post('scan', params={'folder': folder, 'sub': sub, 'next': next_}) | Request immediate rescan of a folder, or a specific path within a
folder.
Args:
folder (str): Folder ID.
sub (str): Path relative to the folder root. If sub is omitted
the entire folder is scanned for changes, otherwise only
the given path children are scanned.
next_ (int): Delays Syncthing's automated rescan interval... | codesearchnet |
def load_yaml(path):
with open(path, 'rt') as f:
yamldict = yaml.load(f.read(), Loader=yamlloader.ordereddict.CSafeLoader)
if (not yamldict):
raise LoadError(('YAML file: %s is empty!' % path))
return yamldict | Load YAML file into an ordered dictionary
Args:
path (str): Path to YAML file
Returns:
OrderedDict: Ordered dictionary containing loaded YAML file | codesearchnet |
def create_slot(primary, val, name, colocate_with_primary=True, *, copy_xla_sharding=False):
validate_shape = val.get_shape().is_fully_defined()
if isinstance(primary, variables.Variable):
prefix = primary._shared_name
else:
prefix = primary.op.name
with variable_scope.variable_scope(Non... | Create a slot initialized to the given value.
The type of the slot is determined by the given value.
Args:
primary: The primary `Variable` or `Tensor`.
val: A `Tensor` specifying the initial value of the slot.
name: Name to use for the slot variable.
colocate_with_primary: Boolean. If True the slot is located
on the... | github-repos |
def annotate(label, since, current, extra_message, custom_message=None):
warning_message = _WarningMessage(label=label, since=since, current=current, extra_message=extra_message, custom_message=custom_message)
def _annotate(fnc):
if inspect.isclass(fnc):
old_new = fnc.__new__
d... | Decorates an API with a deprecated or experimental annotation.
Args:
label: the kind of annotation ('deprecated' or 'experimental').
since: the version that causes the annotation.
current: the suggested replacement function.
extra_message: an optional additional message.
custom_message: if the default message does not... | github-repos |
def resources(self, absolute_url=None):
if absolute_url:
return Resources(mode="server", root_url=absolute_url + self._prefix, path_versioner=StaticHandler.append_version)
return Resources(mode="server", root_url=self._prefix, path_versioner=StaticHandler.append_version) | Provide a :class:`~bokeh.resources.Resources` that specifies where
Bokeh application sessions should load BokehJS resources from.
Args:
absolute_url (bool):
An absolute URL prefix to use for locating resources. If None,
relative URLs are used (default: None) | 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):
... | 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. | juraj-google-style |
def _get_status_code(self, http_status):
try:
return int(http_status.split(' ', 1)[0])
except TypeError:
_logger.warning('Unable to find status code in HTTP status %r.', http_status)
return 500 | Get the HTTP status code from an HTTP status string.
Args:
http_status: A string containing a HTTP status code and reason.
Returns:
An integer with the status code number from http_status. | codesearchnet |
def __init__(self, project, query, checksum, timeout_secs=0):
if bigquery is None:
raise ImportError('Bigquery dependencies are not installed.')
if not query or not isinstance(query, str):
raise ValueError('Invalid argument: query. Please use non-empty string')
if not checksum or not isinsta... | Initialize BigQueryMatcher object.
Args:
project: The name (string) of the project.
query: The query (string) to perform.
checksum: SHA-1 hash generated from a sorted list of lines
read from expected output.
timeout_secs: Duration to retry query until checksum matches. This
is useful for DF streaming pipelines or BQ st... | github-repos |
def reshape_data(tensor, per_example_length=1):
dims = [1, 0]
for i in xrange(2, tensor.get_shape().ndims):
dims.append(i)
return pt.wrap(tf.transpose(tensor, dims)).reshape([(- 1), per_example_length]) | Reshapes input so that it is appropriate for sequence_lstm..
The expected format for sequence lstms is
[timesteps * batch, per_example_length] and the data produced by the utilities
is [batch, timestep, *optional* expected_length]. The result can be cleaved
so that there is a Tensor per timestep.
Args:
tensor: The t... | codesearchnet |
def _Scroll(self, lines=None):
if lines is None:
lines = self._cli_lines
if lines < 0:
self._displayed -= self._cli_lines
self._displayed += lines
if self._displayed < 0:
self._displayed = 0
self._lines_to_show = self._cli_lines
else:
self._lines_to_show = l... | Set attributes to scroll the buffer correctly.
Args:
lines: An int, number of lines to scroll. If None, scrolls
by the terminal length. | juraj-google-style |
def __init__(self, config, http_client_session=None):
self.verify = config.get("verify", True)
self.output = config.get("output", [])
self.validation_results = []
config_variables = config.get("variables", {})
testcase_setup_hooks = config.get("setup_hooks", []... | run testcase or testsuite.
Args:
config (dict): testcase/testsuite config dict
{
"name": "ABC",
"variables": {},
"setup_hooks", [],
"teardown_hooks", []
}
http_client_session (instance): requests.Session(), or locust.client.Session() instance. | juraj-google-style |
def parse_commit_message(commit_message: str) -> Dict[str, bool]:
if commit_message is None:
return {'skip': False, 'no_filter': False, 'test_all': False}
command_search = re.search('\\[([^\\]]*)\\]', commit_message)
if command_search is not None:
command = command_search.groups()[0]
... | Parses the commit message to detect if a command is there to skip, force all or part of the CI.
Args:
commit_message (`str`): The commit message of the current commit.
Returns:
`Dict[str, bool]`: A dictionary of strings to bools with keys the following keys: `"skip"`,
`"test_all_models"` and `"test_all"`. | github-repos |
def html2text(__html: str, *, width: int = 80,
ascii_replacements: bool = False) -> str:
html2.BODY_WIDTH = width
html2.UNICODE_SNOB = ascii_replacements
return html2.html2text(__html).strip() | HTML to plain text renderer.
See also: :pypi:`html2text`
Args:
__html: Text to process
width: Paragraph width
ascii_replacements: Use pseudo-ASCII replacements for Unicode
Returns:
Rendered text | juraj-google-style |
def get_parent(self, tree, alt=None):
parent = self.parent_db.get(tree.path)
if not parent:
return alt
return list(parent)[0] | Get parent for given `tree` or `alt` if not found.
Args:
tree (obj): :class:`.Tree` instance, which is already stored in DB.
alt (obj, default None): Alternative value returned when `tree` is
not found.
Returns:
obj: :class:`.Tree` parent to given `tree`. | juraj-google-style |
def minimum_eigen_vector(x, num_steps, learning_rate, vector_prod_fn):
x = tf.nn.l2_normalize(x)
for _ in range(num_steps):
x = eig_one_step(x, learning_rate, vector_prod_fn)
return x | Computes eigenvector which corresponds to minimum eigenvalue.
Args:
x: initial value of eigenvector.
num_steps: number of optimization steps.
learning_rate: learning rate.
vector_prod_fn: function which takes x and returns product H*x.
Returns:
approximate value of eigenvector.
This function finds approximate value ... | codesearchnet |
def _parse_ospf_process_id(self, config):
match = re.search(r'^router ospf (\d+)', config)
return dict(ospf_process_id=int(match.group(1))) | Parses config file for the OSPF proc ID
Args:
config(str): Running configuration
Returns:
dict: key: ospf_process_id (int) | juraj-google-style |
def apply_formatting_dict(obj: Any, formatting: Dict[(str, Any)]) -> Any:
new_obj = obj
if isinstance(obj, str):
if ('$' not in obj):
new_obj = string.Formatter().vformat(obj, (), formatting_dict(**formatting))
elif isinstance(obj, dict):
new_obj = {}
for (k, v) in obj.it... | Recursively apply a formatting dict to all strings in a configuration.
Note that it skips applying the formatting if the string appears to contain latex (specifically,
if it contains an "$"), since the formatting fails on nested brackets.
Args:
obj: Some configuration object to recursively applying the formatting to.... | codesearchnet |
def apply_cut(self, cut):
return Subsystem(self.network, self.state, self.node_indices,
cut=cut, mice_cache=self._mice_cache) | Return a cut version of this |Subsystem|.
Args:
cut (Cut): The cut to apply to this |Subsystem|.
Returns:
Subsystem: The cut subsystem. | juraj-google-style |
def filter_dict(d, exclude):
ret = {}
for (key, value) in d.items():
if (key not in exclude):
ret.update({key: value})
return ret | Return a new dict with specified keys excluded from the origional dict
Args:
d (dict): origional dict
exclude (list): The keys that are excluded | codesearchnet |
def ParseFileObject(self, parser_mediator, file_object):
esedb_file = pyesedb.file()
try:
esedb_file.open_file_object(file_object)
except IOError as exception:
parser_mediator.ProduceExtractionWarning('unable to open file with error: {0!s}'.format(exception))
return
cache = ESEDB... | Parses an ESE database file-like object.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
file_object (dfvfs.FileIO): file-like object. | codesearchnet |
def prepare_run_debug_urls(self, fetches, feed_dict):
self._run_counter_lock.acquire()
run_dir = os.path.join(self._session_root, 'run_%d_%d' % (int(time.time() * 1000000.0), self._run_counter))
self._run_counter += 1
self._run_counter_lock.release()
gfile.MkDir(run_dir)
fetches_event = event_pb... | Implementation of abstract method in superclass.
See doc of `NonInteractiveDebugWrapperSession.prepare_run_debug_urls()`
for details. This implementation creates a run-specific subdirectory under
self._session_root and stores information regarding run `fetches` and
`feed_dict.keys()` in the subdirectory.
Args:
fetche... | github-repos |
def get_class_weights(y, smooth_factor=0):
from collections import Counter
counter = Counter(y)
if (smooth_factor > 0):
p = (max(counter.values()) * smooth_factor)
for k in counter.keys():
counter[k] += p
majority = max(counter.values())
return {cls: float((majority / cou... | Returns the weights for each class based on the frequencies of the samples.
Args:
y: A list of true labels (the labels must be hashable).
smooth_factor: A factor that smooths extremely uneven weights.
Returns:
A dictionary with the weight for each class. | codesearchnet |
def BuildFilterFindSpecs(self, artifact_definitions_path, custom_artifacts_path, knowledge_base_object, artifact_filter_names=None, filter_file_path=None):
environment_variables = knowledge_base_object.GetEnvironmentVariables()
find_specs = None
if artifact_filter_names:
logger.debug('building find ... | Builds find specifications from artifacts or filter file if available.
Args:
artifact_definitions_path (str): path to artifact definitions file.
custom_artifacts_path (str): path to custom artifact definitions file.
knowledge_base_object (KnowledgeBase): knowledge base.
artifact_filter_names (Optional[list[str]]): nam... | codesearchnet |
def convert_dt_time(duration, return_iter=False):
try:
days, hours, minutes, seconds = convert_timedelta(duration)
if return_iter:
return days, hours, minutes, seconds
if days > 0:
format_string = (
'{} day{}, {} hour{}'.format(
... | Summary:
convert timedelta objects to human readable output
Args:
:duration (datetime.timedelta): time duration to convert
:return_iter (tuple): tuple containing time sequence
Returns:
days, hours, minutes, seconds | TYPE: tuple (integers), OR
human readable, notated units | TYPE: string | juraj-google-style |
def preds(self, nodeids=None):
if nodeids is None: nodeids = self._nodeids
_eps = self._eps
return [_eps[nid][1] for nid in nodeids] | Return the Pred objects for *nodeids*, or all Preds.
Args:
nodeids: an iterable of nodeids of predications to return
Preds from; if `None`, return all Preds | juraj-google-style |
def dataflow_to_dataset(df, types):
assert isinstance(df, DataFlow), df
assert isinstance(types, (list, tuple)), types
df = MapData(df, (lambda dp: tuple(dp)))
df.reset_state()
ds = tf.data.Dataset.from_generator(df.get_data, tuple(types))
return ds | Wrap a dataflow to tf.data.Dataset.
This function will also reset the dataflow.
If the dataflow itself is finite, the returned dataset is also finite.
Therefore, if used for training, you'll need to add `.repeat()` on the returned
dataset.
Args:
df (DataFlow): a dataflow which produces lists
types([tf.DType]): list o... | codesearchnet |
def get_entry_type(self, tag):
if tag.findParent().get('kind') in ['class', 'struct']:
return u'Method'
return super(functionTagProcessor, self).get_entry_type(tag) | Override that returns u'Method' for class/struct methods.
Override as necessary.
Args:
tag: A BeautifulSoup Tag for a function.
Returns:
If this is a class/struct method, returns u'Method', otherwise
returns the value from the inherited implementation of
get_entry_type (which should be u'Function'). | juraj-google-style |
def fill_memory_slot(memory, value, index):
mask = tf.to_float(tf.one_hot(index, tf.shape(memory)[0])[(:, None, None, None)])
fill_memory = (((1 - mask) * memory) + (mask * value[(None, ...)]))
return fill_memory | Fills the memory slot at a particular index with the given value.
Args:
memory: a 4-d tensor [memory_size, batch, length, channel] containing
the state of all steps
value: a 3-d tensor [batch, length, channel] as the sate
index: integer in [0, memory_size)
Returns:
filled memory | codesearchnet |
def evalAsync(self, amplstatements, callback, **kwargs):
if self._langext is not None:
amplstatements = self._langext.translate(amplstatements, **kwargs)
def async_call():
self._lock.acquire()
try:
self._impl.eval(amplstatements)
... | Interpret the given AMPL statement asynchronously.
Args:
amplstatements: A collection of AMPL statements and declarations to
be passed to the interpreter.
callback: Callback to be executed when the statement has been
interpreted.
Raises:
RuntimeError: if the input is not a complete AMPL statement (e.g.
if it does no... | juraj-google-style |
def set(self, key, value):
data = self._load_file()
data[key] = value
self._save_file(data) | Set the value of a key
Args:
key (string): The key used to store this value
value (string): The value to store | juraj-google-style |
def RegisterPlugin(cls, plugin_class):
plugin_name = plugin_class.NAME.lower()
if (plugin_name in cls._plugin_classes):
raise KeyError('Plugin class already set for name: {0:s}.'.format(plugin_class.NAME))
cls._plugin_classes[plugin_name] = plugin_class | Registers a plugin class.
The plugin classes are identified based on their lower case name.
Args:
plugin_class (type): class of the plugin.
Raises:
KeyError: if plugin class is already set for the corresponding name. | codesearchnet |
def precipitable_water(self, value=999.0):
if value is not None:
try:
value = float(value)
except ValueError:
raise ValueError(
'value {} need to be of type float '
'for field `precipitable_water`'.format(va... | Corresponds to IDD Field `precipitable_water`
Args:
value (float): value for IDD Field `precipitable_water`
Unit: mm
Missing value: 999.0
if `value` is None it will not be checked against the
specification and is assumed to be a missing value
Raises:
ValueError: if `value` is not a valid value | juraj-google-style |
def case(self, case_id=None):
cases = self.cases()
if case_id:
for case in cases:
if case.case_id == case_id:
return case
else:
if cases:
return cases[0]
return None | Return a Case object
If no case_id is given return one case
Args:
case_id (str): A case id
Returns:
case(Case): A Case object | juraj-google-style |
def class_logit(layer, label):
def inner(T):
if isinstance(label, int):
class_n = label
else:
class_n = T('labels').index(label)
logits = T(layer)
logit = tf.reduce_sum(logits[(:, class_n)])
return logit
return inner | Like channel, but for softmax layers.
Args:
layer: A layer name string.
label: Either a string (refering to a label in model.labels) or an int
label position.
Returns:
Objective maximizing a logit. | codesearchnet |
def configure_attributes(self, json_data):
env = boto3.session.Session(profile_name=self.env, region_name=self.region)
elbclient = env.client('elb')
elb_settings = self.properties['elb']
LOG.debug('Block ELB Settings Pre Configure Load Balancer Attributes:\n%s', pformat(elb_set... | Configure load balancer attributes such as idle timeout, connection draining, etc
Args:
json_data (json): return data from ELB upsert | juraj-google-style |
def get_features(self, tokenizer, max_length=None, pad_on_left=False, pad_token=0, mask_padding_with_zero=True, return_tensors=None):
if max_length is None:
max_length = tokenizer.max_len
label_map = {label: i for i, label in enumerate(self.labels)}
all_input_ids = []
for ex_index, example in en... | Convert examples in a list of `InputFeatures`
Args:
tokenizer: Instance of a tokenizer that will tokenize the examples
max_length: Maximum example length
pad_on_left: If set to `True`, the examples will be padded on the left rather than on the right (default)
pad_token: Padding token
mask_padding_with_zero: If set to ... | github-repos |
def display_task_progress(self, instance, project, region, request_id=None, user=None, poll_interval=60):
total_completed = 0
while True:
task_results = self.client.get_task_data(instance, project, region, request_id=request_id, user=user)
tasks = {task['id']: task for task in task_results}
... | Displays the overall progress of tasks in a Turbinia job.
Args:
instance (string): The name of the Turbinia instance
project (string): The project containing the disk to process
region (string): Region where turbinia is configured.
request_id (string): The request ID provided by Turbinia.
user (string): The username t... | codesearchnet |
def VerifyStructure(self, parser_mediator, line):
try:
structure = self._LINE.parseString(line)
except pyparsing.ParseException:
logger.debug('Not a SkyDrive old log file')
return False
(day_of_month, month, year, hours, minutes, seconds, milliseconds) = structure.date_time
time_... | Verify that this file is a SkyDrive old log file.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
line (str): line from a text file.
Returns:
bool: True if the line is in the expected format, False if not. | codesearchnet |
def for_executor(cls, executor: Optional[Executor]) -> 'Subsystem':
if isinstance(executor, ThreadPoolExecutor):
return _ThreadingSubsystem(executor)
elif executor is None:
return _AsyncioSubsystem()
else:
raise TypeError(executor) | Return a subsystem based on the given executor. If ``executor`` is
None, use :mod:`asyncio`. If ``executor`` is a
:class:`concurrent.futures.ThreadPoolExecutor`, use :mod:`threading`.
Args:
executor: The executor in use, if any. | juraj-google-style |
def start(self, hostname=None, port=None, templates_path=None):
self.hostname = hostname if hostname else "localhost"
if port:
self.port = port
elif not self.port:
self.port = unused_port(self.hostname)
if templates_path:
self.loaders.insert(0... | Starts the web interface.
Args:
hostname (str, optional): host name to listen from. (Default value = None)
port (int, optional): port to listen from. (Default value = None)
templates_path (str, optional): path to look for templates. (Default value = None) | juraj-google-style |
def _call_and_return_none_on_error(func: Callable[[], NotNoneT], error_msg: str) -> Optional[NotNoneT]:
try:
return func()
except Exception as ex:
traceback.print_exception(ex)
logging.error(error_msg)
return None | Calls `func` and returns `None` on error.
This is used to gracefully return the 'error status' represented as `None`, as
raising exceptions from `PyFunctionLibrary` methods crashes the program.
Args:
func: The function to run. The function should be a callable returning a
non-None value.
error_msg: The error message ... | github-repos |
def get_next_as_optional(iterator):
return iterator.get_next_as_optional() | Returns a `tf.experimental.Optional` with the next element of the iterator.
If the iterator has reached the end of the sequence, the returned
`tf.experimental.Optional` will have no value.
Args:
iterator: A `tf.data.Iterator`.
Returns:
A `tf.experimental.Optional` object which either contains the next element
of the... | github-repos |
def segs(self, word):
return [m.group('all') for m in self.seg_regex.finditer(word)] | Returns a list of segments from a word
Args:
word (unicode): input word as Unicode IPA string
Returns:
list: list of strings corresponding to segments found in `word` | codesearchnet |
def alt40fms(msg):
d = hex2bin(data(msg))
if d[13] == '0':
return None
alt = bin2int(d[14:26]) * 16
return alt | Selected altitude, FMS
Args:
msg (String): 28 bytes hexadecimal message (BDS40) string
Returns:
int: altitude in feet | juraj-google-style |
def __init__(self, regularizer=None, activity_regularizer=None, use_operator=False, var_name='v', **kwargs):
self._regularizer = regularizer
if isinstance(regularizer, dict):
self._regularizer = regularizers.deserialize(regularizer, custom_objects=globals())
self._activity_regularizer = activity_reg... | Initializes the MultiplyLayer.
Args:
regularizer: The weight regularizer on the scalar variable.
activity_regularizer: The activity regularizer.
use_operator: If True, add using the * operator. If False, add using
tf.multiply.
var_name: The name of the variable. It can be useful to pass a name other
than 'v', to test ... | github-repos |
def create(self, params):
sh_id = params.get('id', str(uuid4()))
if sh_id in self:
raise ShardedClusterError(
"Sharded cluster with id %s already exists." % sh_id)
params['id'] = sh_id
cluster = ShardedCluster(params)
self[cluster.id] = cluste... | create new ShardedCluster
Args:
params - dictionary with specific params for instance
Return cluster_id
where cluster_id - id which can use to take the cluster from servers collection | juraj-google-style |
def set_hook_data(self, key, data):
if (not isinstance(data, collections.Mapping)):
raise ValueError(('Hook (key: %s) data must be an instance of collections.Mapping (a dictionary for example).' % key))
if (key in self.hook_data):
raise KeyError('Hook data for key %s already exists, each hook mu... | Set hook data for the given key.
Args:
key(str): The key to store the hook data in.
data(:class:`collections.Mapping`): A dictionary of data to store,
as returned from a hook. | codesearchnet |
def usermacro_get(macro=None, hostids=None, templateids=None, hostmacroids=None, globalmacroids=None, globalmacro=False, **kwargs):
conn_args = _login(**kwargs)
ret = {}
try:
if conn_args:
method = 'usermacro.get'
params = {'output': 'extend', 'filter': {}}
if mac... | Retrieve user macros according to the given parameters.
Args:
macro: name of the usermacro
hostids: Return macros for the given hostids
templateids: Return macros for the given templateids
hostmacroids: Return macros with the given hostmacroids
globalmacroids: Return macros with the given globalma... | codesearchnet |
def dump(self, format='ttl'):
return self.rdf.graph.serialize(format=format).decode('utf-8') | Convenience method to return RDF data for resource,
optionally selecting serialization format.
Inspired by .dump from Samvera.
Args:
format (str): expecting serialization formats accepted by rdflib.serialization(format=) | codesearchnet |
def realtime(widget, url_name=None, url_regex=None, time_interval=None):
if not hasattr(widget, 'get_updated_content'):
raise AttributeError('Widget %s must implement get_updated_content '
'method.' % widget)
elif not callable(widget.get_updated_content):
raise ... | Return a widget as real-time.
Args:
widget (Widget): the widget to register and return as real-time.
url_name (str): the URL name to call to get updated content.
url_regex (regex): the URL regex to be matched.
time_interval (int): the interval of refreshment in milliseconds.
Returns:
Widget: the "real-timed" widget. | juraj-google-style |
def discount_rate(self, date: Optional[types.DateTensor]=None, time: Optional[types.FloatTensor]=None, context=None) -> tf.Tensor:
pass | Returns the discount rates to a specified set of dates.
Args:
date: A `DateTensor` specifying the dates at which to evaluate the
discount rates. The function expects either `date` or `time` to be
specified.
time: A real `Tensor` specifying the times at which to evaluate the
discount rates. The function expects either ... | github-repos |
def seek(self, offset, whence=os.SEEK_SET):
if not self._is_open:
raise IOError('Not opened.')
if self._current_offset < 0:
raise IOError(
'Invalid current offset: {0:d} value less than zero.'.format(
self._current_offset))
if whence == os.SEEK_CUR:
offset +=... | Seeks to an offset within the file-like object.
Args:
offset (int): offset to seek to.
whence (Optional(int)): value that indicates whether offset is an absolute
or relative position within the file.
Raises:
IOError: if the seek failed.
OSError: if the seek failed. | juraj-google-style |
def _CanSkipContentExtraction(self, file_entry):
location = getattr(file_entry.path_spec, 'location', None)
if not location:
return False
data_stream_name = getattr(file_entry.path_spec, 'data_stream', None)
if data_stream_name:
return False
file_system = file_entry.GetF... | Determines if content extraction of a file entry can be skipped.
Args:
file_entry (dfvfs.FileEntry): file entry of which to determine content
extraction can be skipped.
Returns:
bool: True if content extraction can be skipped. | juraj-google-style |
def _filter_var(self, node, var):
bindings = var.Bindings(node) if len(var.bindings) > 1 else var.bindings
if not bindings:
return None
if len(bindings) == len(var.bindings) and (not any((isinstance(b.data, abstract.TypeParameterInstance) for b in bindings))):
return var
ret = self.ctx.p... | Filter the variable by the node.
Filters the variable data, including recursively expanded type parameter
instances, by visibility at the node. A type parameter instance needs to be
filtered at the moment of access because its value may change later.
Args:
node: The current node.
var: A variable to filter.
Returns:
... | github-repos |
def _resolve_path(obj, path=None):
if path:
for attr_name in path.split('__'):
obj = getattr(obj, attr_name)
return obj | Resolve django-like path eg. object2__object3 for object
Args:
obj: The object the view is displaying.
path (str, optional): Description
Returns:
A oject at end of resolved path | juraj-google-style |
def replace_nones(list_, repl=(- 1)):
repl_list = [(repl if (item is None) else (replace_nones(item, repl) if isinstance(item, list) else item)) for item in list_]
return repl_list | r"""
Recursively removes Nones in all lists and sublists and replaces them with
the repl variable
Args:
list_ (list):
repl (obj): replacement value
Returns:
list
CommandLine:
python -m utool.util_list --test-replace_nones
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_list import * # NOQA
>>> # build test data
... | codesearchnet |
def __init__(self, replicaset=None, ssl=None, login=None, password=None,
ca_cert=None, certfile=None, keyfile=None,
keyfile_passphrase=None, crlfile=None, **kwargs):
super().__init__(**kwargs)
self.replicaset = replicaset or bigchaindb.config['database'].get('... | Create a new Connection instance.
Args:
replicaset (str, optional): the name of the replica set to
connect to.
**kwargs: arbitrary keyword arguments provided by the
configuration's ``database`` settings | juraj-google-style |
def report_sink_lineage(path):
FileSystems.get_filesystem(path).report_lineage(path, Lineage.sinks()) | Report sink :class:`~apache_beam.metrics.metric.Lineage`.
Args:
path: string path to be reported. | github-repos |
def _ParseEntry(self, key, val):
if (key in self._repeated):
setting = self.section.setdefault(key, [])
setting.extend(val)
else:
self.section.setdefault(key, val) | Adds an entry for a configuration setting.
Args:
key: The name of the setting.
val: The value of the setting. | codesearchnet |
def cumulative_distribution(self, X, U=0):
self.check_fit()
low_bounds = self.model.dataset.mean() - (5 * self.model.dataset.std())
return self.model.integrate_box_1d(low_bounds, X) - U | Computes the integral of a 1-D pdf between two bounds
Args:
X(float): a datapoint.
U(float): cdf value in [0,1], only used in get_ppf
Returns:
float: estimated cumulative distribution. | juraj-google-style |
def dense_shape_and_type(matrix):
if not isinstance(matrix, tensor_lib.Tensor):
raise TypeError('matrix should be a tensor, but saw: %s' % (matrix,))
if matrix.dtype != dtypes.variant:
raise TypeError('expected matrix to be type tf.variant, but saw: %s' % (matrix.dtype,))
handle_data = _get_... | Get dense shape and dtype of the tf.Tensor containing the matrix.
Args:
matrix: A `tf.Tensor` of type `tf.variant` storing a sparse matrix.
Returns:
An instance of `ShapeAndType` with properties `shape` (a `tf.TensorShape`)
and `dtype` (a `tf.DType`).
Raises:
TypeError: if `matrix` is not a tensor or its dtype is no... | github-repos |
def convert_lrelu(params, w_name, scope_name, inputs, layers, weights, names):
print('Converting lrelu ...')
if (names == 'short'):
tf_name = ('lRELU' + random_string(3))
elif (names == 'keep'):
tf_name = w_name
else:
tf_name = (w_name + str(random.random()))
leakyrelu = kera... | Convert leaky relu layer.
Args:
params: dictionary with layer parameters
w_name: name prefix in state_dict
scope_name: pytorch scope name
inputs: pytorch node inputs
layers: dictionary with keras tensors
weights: pytorch state_dict
names: use short names for keras layers | codesearchnet |
def main(params=None):
if params == None:
parser = getParser()
args = parser.parse_args(params)
else:
args = params
print(general.title(banner.text))
extraWords = args.extra_words
try:
if args.name == None and args.surname1 == None and args.surname2 == None an... | Main function to launch alias_generator.
Args:
-----
params: A list with the parameters as grabbed by the terminal. It is
None when this is called by an entry_point. If it is called by osrf
the data is already parsed. | juraj-google-style |
def diff_text2(self, diffs):
text = []
for (op, data) in diffs:
if op != self.DIFF_DELETE:
text.append(data)
return "".join(text) | Compute and return the destination text (all equalities and insertions).
Args:
diffs: Array of diff tuples.
Returns:
Destination text. | juraj-google-style |
def datetimeobj_YmdHMS(value):
i = int(value)
S = i
M = S
H = M
d = H
m = d
Y = m
return datetime.datetime(
Y % 10000, m % 100, d % 100, H % 100, M % 100, S % 100, tzinfo=TZ_GMT
) | Convert timestamp string to a datetime object.
Timestamps strings like '20130618120000' are able to be converted by this
function.
Args:
value: A timestamp string in the format '%Y%m%d%H%M%S'.
Returns:
A datetime object.
Raises:
ValueError: If timestamp is invalid.
Note: The timezone is assumed to be UTC/GMT. | juraj-google-style |
def zip_ll(data, means, M):
genes, cells = data.shape
clusters = means.shape[1]
ll = np.zeros((cells, clusters))
d0 = (data==0)
d1 = (data>0)
for i in range(clusters):
means_i = np.tile(means[:,i], (cells, 1))
means_i = means_i.transpose()
L_i = np.tile(M[:,i], (cell... | Calculates the zero-inflated Poisson log-likelihood.
Args:
data (array): genes x cells
means (array): genes x k
M (array): genes x k - this is the zero-inflation parameter.
Returns:
cells x k array of log-likelihood for each cell/cluster pair. | juraj-google-style |
def text(self, x, y, text):
for i, char in enumerate(text):
self.point(x + i, y, char) | Print a text on ASCII canvas.
Args:
x (int): x coordinate where the text should start.
y (int): y coordinate where the text should start.
text (str): string that should be printed. | juraj-google-style |
def git_ls_remote(self, uri, ref):
logger.debug('Invoking git to retrieve commit id for repo %s...', uri)
lsremote_output = subprocess.check_output(['git', 'ls-remote', uri, ref])
if (b'\t' in lsremote_output):
commit_id = lsremote_output.split(b'\t')[0]
logger.debug('Matching commit id foun... | Determine the latest commit id for a given ref.
Args:
uri (string): git URI
ref (string): git ref
Returns:
str: A commit id | codesearchnet |
def value_splitter(self, reference, prop, value, mode):
items = []
if (mode == 'json-list'):
try:
items = json.loads(value)
except json.JSONDecodeError as e:
print(value)
msg = "Reference '{ref}' raised JSON decoder error when splitting values from '{prop}': {... | Split a string into a list items.
Default behavior is to split on white spaces.
Arguments:
reference (string): Reference name used when raising possible
error.
prop (string): Property name used when raising possible error.
value (string): Property value to split.
mode (string): Splitter mode. Default should come fro... | codesearchnet |
def append_transformation(self, transformation, return_alternatives=False, clear_redo=True):
if clear_redo:
self._undone = []
if (return_alternatives and transformation.is_one_to_many):
ranked_list = transformation.apply_transformation(self.final_structure, return_ranked_list=return_alternatives... | Appends a transformation to the TransformedStructure.
Args:
transformation: Transformation to append
return_alternatives: Whether to return alternative
TransformedStructures for one-to-many transformations.
return_alternatives can be a number, which stipulates the
total number of structures to return.
clear_redo: Bool... | codesearchnet |
def concatenate(self, other):
other = as_shape(other)
if self.dims is None or other.dims is None:
return unknown_shape()
else:
return TensorShape(self.dims + other.dims) | Returns the concatenation of the dimension in `self` and `other`.
*N.B.* If either `self` or `other` is completely unknown,
concatenation will discard information about the other shape. In
future, we might support concatenation that preserves this
information for use with slicing.
Args:
other: Another `TensorShape`.
... | github-repos |
def _bbox(nodes):
(left, bottom) = np.min(nodes, axis=1)
(right, top) = np.max(nodes, axis=1)
return (left, right, bottom, top) | Get the bounding box for set of points.
.. note::
There is also a Fortran implementation of this function, which
will be used if it can be built.
Args:
nodes (numpy.ndarray): A set of points.
Returns:
Tuple[float, float, float, float]: The left, right,
bottom and top bounds for the box. | codesearchnet |
def _assert_same_base_type(items, expected_type=None):
original_expected_type = expected_type
mismatch = False
for item in items:
if (item is not None):
item_type = base_dtype(item.dtype)
if (not expected_type):
expected_type = item_type
elif (expe... | r"""Asserts all items are of the same base type.
Args:
items: List of graph items (e.g., `Variable`, `Tensor`, `SparseTensor`,
`Operation`, or `IndexedSlices`). Can include `None` elements, which
will be ignored.
expected_type: Expected type. If not specified, assert all items are
of the same base type.
Returns:
Vali... | codesearchnet |
def intersect(df, other, index=False, keep='first'):
validate_set_ops(df, other)
if index:
df_reset_index = df.reset_index()
other_reset_index = other.reset_index()
index_cols = [col for col in df_reset_index.columns if (col not in df.columns)]
df_index_names = df.index.names
... | Returns rows that appear in both DataFrames.
Args:
df (pandas.DataFrame): data passed in through the pipe.
other (pandas.DataFrame): other DataFrame to use for set operation with
the first.
Kwargs:
index (bool): Boolean indicating whether to consider the pandas index
as part of the set operation (default `False`).
ke... | codesearchnet |
def wait(timeout=None, flush=True):
if (timeout is not None):
timeout = (timeout + _time.clock())
while True:
if _eventQueue:
return _eventQueue.pop(0)
if flush:
_tdl.flush()
if (timeout and (_time.clock() >= timeout)):
return None
_tim... | Wait for an event.
Args:
timeout (Optional[int]): The time in seconds that this function will
wait before giving up and returning None.
With the default value of None, this will block forever.
flush (bool): If True a call to :any:`tdl.flush` will be made before
listening for events.
Returns: Type[Event]: An event, o... | codesearchnet |
def rescale(self, image: 'torch.Tensor', scale: float, offset: Optional[bool]=True, **kwargs) -> 'torch.Tensor':
rescaled_image = image * scale
if offset:
rescaled_image -= 1
return rescaled_image | Rescale an image by a scale factor.
If `offset` is `True`, the image has its values rescaled by `scale` and then offset by 1. If `scale` is
1/127.5, the image is rescaled between [-1, 1].
image = image * scale - 1
If `offset` is `False`, and `scale` is 1/255, the image is rescaled between [0, 1].
image = image * scal... | github-repos |
def get_variable(mesh, name, shape, dtype=tf.float32, master_dtype=None, slice_dtype=None, activation_dtype=None, initializer=None, trainable=True, **kwargs):
if (dtype is None):
dtype = VariableDType(master_dtype, slice_dtype, activation_dtype)
elif isinstance(dtype, tf.DType):
dtype = Variable... | Create a new variable or retrieve an already-created one.
Args:
mesh: a Mesh
name: a string (uses the existing tf.variable_scope())
shape: a Shape
dtype: a VariableDType or a tf.DType
master_dtype: an optional tf.DType (deprecated - use dtype arg)
slice_dtype: an optional tf.DType (deprecated - use dtype arg)
activati... | codesearchnet |
def incrementKeySequenceCounter(self, iIncrementValue=1):
print '%s call incrementKeySequenceCounter' % self.port
print iIncrementValue
currentKeySeq = ''
try:
currentKeySeq = self.getKeySequenceCounter()
keySequence = int(currentKeySeq, 10) + iIncrementV... | increment the key sequence with a given value
Args:
iIncrementValue: specific increment value to be added
Returns:
True: successful to increment the key sequence with a given value
False: fail to increment the key sequence with a given value | juraj-google-style |
def __init__(self, rs_params):
self.server_map = {}
self.auth_key = rs_params.get('auth_key', None)
self.login = rs_params.get('login', '')
self.auth_source = rs_params.get('authSource', 'admin')
self.password = rs_params.get('password', '')
self.admin_added = Fa... | create replica set according members config
Args:
rs_params - replica set configuration | juraj-google-style |
def _generate_graph_update_dicts(self):
transform_dict = {}
pcoll_dict = {}
for transform_id, transform_proto in self._top_level_transforms():
transform_dict[transform_proto.unique_name] = {'required': transform_id in self._required_transforms}
for pcoll_id in transform_proto.outputs.values(... | Generate updates specific to interactive pipeline.
Returns:
vertex_dict: (Dict[str, Dict[str, str]]) maps vertex name to attributes
edge_dict: (Dict[str, Dict[str, str]]) maps vertex name to attributes | github-repos |
def format_level_1_memory(memory):
formatted_memory = _list_to_complex_array(memory)
if (not (1 <= len(formatted_memory.shape) <= 2)):
raise QiskitError('Level one memory is not of correct shape.')
return formatted_memory | Format an experiment result memory object for measurement level 1.
Args:
memory (list): Memory from experiment with `meas_level==1`. `avg` or
`single` will be inferred from shape of result memory.
Returns:
np.ndarray: Measurement level 1 complex numpy array
Raises:
QiskitError: If the returned numpy array does not h... | codesearchnet |
def __getattr__(self, item):
if item in self.METHOD_NO_PROXY:
return super(AuthProxy, self).__getattr__(item)
attr = getattr(self.proxy_class, item)
if callable(attr):
return self.auth_proxy(attr) | Override attribute getter to act as a proxy for``proxy_class``.
If ``item`` is contained in ``METHOD_NO_PROXY``, it will not be
proxied to the ``proxy_class`` and will instead return the attribute
on this object.
Args:
item (str): Name of attribute to get. | juraj-google-style |
def get_el_amount(self, element):
return sum([self._all_comp[i][element] * abs(self._coeffs[i])
for i in range(len(self._all_comp))]) / 2 | Returns the amount of the element in the reaction.
Args:
element (Element/Specie): Element in the reaction
Returns:
Amount of that element in the reaction. | juraj-google-style |
def to_file(self, filename):
d = {'mass_info': self.mass_info, 'nonbond_coeffs': self.nonbond_coeffs, 'topo_coeffs': self.topo_coeffs}
yaml = YAML(typ='safe')
with open(filename, 'w') as f:
yaml.dump(d, f) | Saves object to a file in YAML format.
Args:
filename (str): Filename. | codesearchnet |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.