code stringlengths 20 4.93k | docstring stringlengths 33 1.27k | source stringclasses 3
values |
|---|---|---|
def sget_voltage(self, cycle, step, set_number=None):
time_00 = time.time()
set_number = self._validate_dataset_number(set_number)
if set_number is None:
self._report_empty_dataset()
return
cycle_index_header = self.headers_normal.cycle_index_txt
... | Returns voltage for cycle, step.
Convinience function; same as issuing
dfdata[(dfdata[cycle_index_header] == cycle) &
(dfdata[step_index_header] == step)][voltage_header]
Args:
cycle: cycle number
step: step number
set_number: the dataset number (automatic selection if None)
Returns:
pandas.Series or None if empty | juraj-google-style |
def add_constant(self, stream, value):
if stream in self.constant_database:
raise ArgumentError("Attempted to set the same constant twice", stream=stream, old_value=self.constant_database[stream], new_value=value)
self.constant_database[stream] = value | Store a constant value for use in this sensor graph.
Constant assignments occur after all sensor graph nodes have been
allocated since they must be propogated to all appropriate virtual
stream walkers.
Args:
stream (DataStream): The constant stream to assign the value to
value (int): The value to assign. | juraj-google-style |
def GrabObject(self, identifier):
if identifier not in self._values:
raise KeyError('Missing cached object for identifier: {0:s}'.format(
identifier))
cache_value = self._values[identifier]
if not cache_value:
raise RuntimeError('Missing cache value for identifier: {0:s}'.format(... | Grabs a cached object based on the identifier.
This method increments the cache value reference count.
Args:
identifier (str): VFS object identifier.
Raises:
KeyError: if the VFS object is not found in the cache.
RuntimeError: if the cache value is missing. | juraj-google-style |
def get_average_record(self, n):
history_deque = collections.deque()
averages = []
for d in self.data_points:
history_deque.appendleft(d)
if (len(history_deque) > n):
history_deque.pop()
avg = (sum(history_deque) / len(history_deque))
averages.append(round(avg, se... | Returns a list of average current numbers, each representing the
average over the last n data points.
Args:
n: Number of data points to average over.
Returns:
A list of average current values. | codesearchnet |
class PatchTSMixerPatchify(nn.Module):
def __init__(self, config: PatchTSMixerConfig):
super().__init__()
self.sequence_length = config.context_length
self.patch_length = config.patch_length
self.patch_stride = config.patch_stride
if self.sequence_length <= self.patch_length... | A class to patchify the time series sequence into different patches
Returns:
`torch.Tensor` of shape `(batch_size, num_channels, num_patches, patch_length)` | github-repos |
def get_data_xls(file_name, file_contents=None, on_demand=False):
def tuple_to_iso_date(tuple_date):
"\n Turns a gregorian (year, month, day, hour, minute, nearest_second) into a\n standard YYYY-MM-DDTHH:MM:SS ISO date. If the date part is all zeros, it's\n assumed to be a time; if th... | Loads the old excel format files. New format files will automatically
get loaded as well.
Args:
file_name: The name of the local file, or the holder for the
extension type when the file_contents are supplied.
file_contents: The file-like object holding contents of file_name.
If left as None, then file_name is directly... | codesearchnet |
def IsDefault(self):
if ((not self._tsk_attribute) or (not self._file_system)):
return True
if self._file_system.IsHFS():
attribute_type = getattr(self._tsk_attribute.info, 'type', None)
return (attribute_type in (pytsk3.TSK_FS_ATTR_TYPE_HFS_DEFAULT, pytsk3.TSK_FS_ATTR_TYPE_HFS_DATA))
... | Determines if the data stream is the default data stream.
Returns:
bool: True if the data stream is the default data stream, false if not. | codesearchnet |
def _GetProcessedStorageFilePath(self, task):
filename = '{0:s}.plaso'.format(task.identifier)
return os.path.join(self._processed_task_storage_path, filename) | Retrieves the path of a task storage file in the processed directory.
Args:
task (Task): task.
Returns:
str: path of a task storage file in the processed directory. | codesearchnet |
def _process_worker(call_queue, result_queue, initializer, initargs, processes_management_lock, timeout, worker_exit_lock, current_depth):
if (initializer is not None):
try:
initializer(*initargs)
except BaseException:
_base.LOGGER.critical('Exception in initializer:', exc_in... | Evaluates calls from call_queue and places the results in result_queue.
This worker is run in a separate process.
Args:
call_queue: A ctx.Queue of _CallItems that will be read and
evaluated by the worker.
result_queue: A ctx.Queue of _ResultItems that will written
to by the worker.
initializer: A callable initializer... | codesearchnet |
def compose_path(pub, uuid_url=False):
if uuid_url:
return join(
"/",
UUID_DOWNLOAD_KEY,
str(pub.uuid)
)
return join(
"/",
DOWNLOAD_KEY,
basename(pub.file_pointer),
basename(pub.filename)
) | Compose absolute path for given `pub`.
Args:
pub (obj): :class:`.DBPublication` instance.
uuid_url (bool, default False): Compose URL using UUID.
Returns:
str: Absolute url-path of the publication, without server's address \
and protocol.
Raises:
PrivatePublicationError: When the `pub` is private publication. | juraj-google-style |
def ExpandSubClasses(self, t):
queue = [t]
seen = set()
while queue:
item = queue.pop()
if item not in seen:
seen.add(item)
queue.extend(self._subclasses[item])
return seen | Generate a set of all (known) subclasses for a type.
Arguments:
t: A type. E.g. NamedType("int").
Returns:
A set of types. This set includes t as well as all its subclasses. For
example, this will return "int" and "bool" for "int". | github-repos |
def victim(self, name, owner=None, **kwargs):
return Victim(self.tcex, name, owner=owner, **kwargs) | Create the Victim TI object.
Args:
owner:
name:
**kwargs:
Return: | codesearchnet |
def rh45(msg):
d = hex2bin(data(msg))
if (d[38] == '0'):
return None
rh = (bin2int(d[39:51]) * 16)
return rh | Radio height.
Args:
msg (String): 28 bytes hexadecimal message string
Returns:
int: radio height in ft | codesearchnet |
async def invoke(self, context):
try:
tasks = (await self._run_cancellable(claim_work(context)))
if ((not tasks) or (not tasks.get('tasks', []))):
(await self._run_cancellable(asyncio.sleep(context.config['poll_interval'])))
return None
status = None
for task_... | Claims and processes Taskcluster work.
Args:
context (scriptworker.context.Context): context of worker
Returns: status code of build | codesearchnet |
def event_stream(self, from_token, timeout=30000):
warnings.warn("event_stream is deprecated. Use sync instead.",
DeprecationWarning)
path = "/events"
return self._send(
"GET", path, query_params={
"timeout": timeout,
"fr... | Deprecated. Use sync instead.
Performs /events
Args:
from_token (str): The 'from' query parameter.
timeout (int): Optional. The 'timeout' query parameter. | juraj-google-style |
def get_nested_dmaps(dmap):
if not isinstance(dmap, DynamicMap):
return []
dmaps = [dmap]
for o in dmap.callback.inputs:
dmaps.extend(get_nested_dmaps(o))
return list(set(dmaps)) | Recurses DynamicMap to find DynamicMaps inputs
Args:
dmap: DynamicMap to recurse to look for DynamicMap inputs
Returns:
List of DynamicMap instances that were found | juraj-google-style |
def __init__(self, weight_shape: Sequence[int], same_scale_op: str) -> None:
self.filters = np.random.uniform(low=-1.0, high=1.0, size=weight_shape)
self.same_scale_op = same_scale_op | Initializes a MatmulModel.
Args:
weight_shape: Shape of the weight tensor.
same_scale_op: Name of the same-scale op to be tested. Raises error
when an unknown name is given. | github-repos |
def extract_all_content(
self,
path=None,
payload=None,
objectInput=None,
pretty_print=False,
convert_to_obj=False,
):
f = file_path(path, payload, objectInput)
switches = ["-J", "-t", "-r", f]
if not pretty_print:
switches... | This function returns a JSON of all contents and
metadata of passed file
Args:
path (string): Path of file to analyze
payload (string): Payload base64 to analyze
objectInput (object): file object/standard input to analyze
pretty_print (boolean): If True adds newlines and whitespace,
for better readability
convert_to_o... | juraj-google-style |
def process_layer(layer_data):
layer_name = layer_data['name']
if 'module' not in layer_data:
layer = saving_utils.model_from_config(layer_data, custom_objects=custom_objects)
else:
layer = serialization_lib.deserialize_keras_object(layer_data, custom_objects=custom_objects)
if not isins... | Deserializes a layer and index its inbound nodes.
Args:
layer_data: layer config dict. | github-repos |
def node_info(self, args, screen_info=None):
_ = screen_info
parsed = self._arg_parsers['node_info'].parse_args(args)
node_name, unused_slot = debug_graphs.parse_node_or_tensor_name(parsed.node_name)
if not self._debug_dump.node_exists(node_name):
output = cli_shared.error('There is no node name... | Command handler for node_info.
Query information about a given node.
Args:
args: Command-line arguments, excluding the command prefix, as a list of
str.
screen_info: Optional dict input containing screen information such as
cols.
Returns:
Output text lines as a RichTextLines object. | github-repos |
def _example_from_complex_def(self, prop_spec):
if 'schema' not in prop_spec:
return [{}]
elif 'type' not in prop_spec['schema']:
definition_name = self.get_definition_name_from_ref(prop_spec['schema']['$ref'])
if self.build_one_definition_example(definition_... | Get an example from a property specification.
In case there is no "type" key in the root of the dictionary.
Args:
prop_spec: property specification you want an example of.
Returns:
An example. | juraj-google-style |
def _load_config_section(self, section_name):
if self._config.has_section(section_name):
section = dict(self._config.items(section_name))
elif self._config.has_section('Default'):
section = dict(self._config.items('Default'))
else:
raise KeyError(("'{}' was not found in the configura... | Method to load the specific Service section from the config file if it
exists, or fall back to the default
Args:
section_name (str): The desired service section name
Returns:
(dict): the section parameters | codesearchnet |
def assemble_concatenated_meta(concated_meta_dfs, remove_all_metadata_fields):
if remove_all_metadata_fields:
for df in concated_meta_dfs:
df.drop(df.columns, axis=1, inplace=True)
all_concated_meta_df = pd.concat(concated_meta_dfs, axis=0)
n_rows = all_concated_meta_df.shape[0]
logg... | Assemble the concatenated metadata dfs together. For example,
if horizontally concatenating, the concatenated metadata dfs are the
column metadata dfs. Both indices are sorted.
Args:
concated_meta_dfs (list of pandas dfs)
Returns:
all_concated_meta_df_sorted (pandas df) | codesearchnet |
def inspect_distribution(self, image, auth_config=None):
(registry, _) = auth.resolve_repository_name(image)
headers = {}
if (auth_config is None):
header = auth.get_config_header(self, registry)
if header:
headers['X-Registry-Auth'] = header
else:
log.debug('Sending ... | Get image digest and platform information by contacting the registry.
Args:
image (str): The image name to inspect
auth_config (dict): Override the credentials that are found in the
config for this request. ``auth_config`` should contain the
``username`` and ``password`` keys to be valid.
Returns:
(dict): A dict con... | codesearchnet |
def parameterized_codec(raw, b64):
if isinstance(raw, bytes):
raw = raw.decode('utf-8')
result = _parameterize_string(raw)
return (Base64(result.data) if b64 else result) | Parameterize a string, possibly encoding it as Base64 afterwards
Args:
raw (`str` | `bytes`): String to be processed. Byte strings will be
interpreted as UTF-8.
b64 (`bool`): Whether to wrap the output in a Base64 CloudFormation
call
Returns:
:class:`troposphere.AWSHelperFn`: output to be included in a
CloudFormation... | codesearchnet |
def backward(ctx, grad_at_output: torch.Tensor):
multiplier, selected_experts, masked_gates = ctx.saved_tensors
grad_at_output = grad_at_output * multiplier
grad_at_scores_expanded = masked_gates * grad_at_output.mul(-1)
grad_at_scores_expanded.scatter_add_(dim=-1, index=selected_experts, src=grad_at_ou... | Backward pass for the custom autograd function.
Args:
ctx: Context object with saved tensors from the forward pass.
grad_at_output (torch.Tensor): Gradient at the output.
Returns:
Tuple[torch.Tensor, None, None, None, None]: Gradients for the inputs. | github-repos |
def get_container_details(self, container_id_or_name: str) -> dict:
container = self._client.containers.get(container_id_or_name)
return container.attrs | Get details of a container.
Args:
container_id_or_name (string): docker container id or name
Returns:
dict, details of the container | juraj-google-style |
def validate(obj, schema):
if isinstance(obj, str):
obj = json.loads(obj)
return JsonValidator(schema)._validate(obj) | Validate an object against a schema
Args:
obj (dict):
schema (dict): | juraj-google-style |
def CheckForNonConstReference(filename, clean_lines, linenum, nesting_state, error):
line = clean_lines.elided[linenum]
if ('&' not in line):
return
if IsDerivedFunction(clean_lines, linenum):
return
if IsOutOfLineMethodDefinition(clean_lines, linenum):
return
if (linenum > 1... | Check for non-const references.
Separate from CheckLanguage since it scans backwards from current
line, instead of scanning forward.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
nesting_state: A NestingState instance... | codesearchnet |
def call(self, input_ids: TFModelInputType | None=None, attention_mask: np.ndarray | tf.Tensor | None=None, token_type_ids: np.ndarray | tf.Tensor | None=None, position_ids: np.ndarray | tf.Tensor | None=None, head_mask: np.ndarray | tf.Tensor | None=None, inputs_embeds: np.ndarray | tf.Tensor | None=None, output_atten... | Returns:
Examples:
```python
>>> from transformers import AutoTokenizer, TapasModel
>>> import pandas as pd
>>> tokenizer = AutoTokenizer.from_pretrained("google/tapas-base")
>>> model = TapasModel.from_pretrained("google/tapas-base")
>>> data = {
... "Actors": ["Brad Pitt", "Leonardo Di Caprio", "George Cloone... | github-repos |
def validate(self):
if (not isinstance(self.value, bytes)):
raise TypeError('secret value must be bytes')
elif (not isinstance(self.data_type, enums.SecretDataType)):
raise TypeError('secret data type must be a SecretDataType enumeration')
mask_count = len(self.cryptographic_usage_masks)
... | Verify that the contents of the SecretData object are valid.
Raises:
TypeError: if the types of any SecretData attributes are invalid. | codesearchnet |
def intersection(self, other):
if not hasattr(other, "__iter__"):
other = [other]
bounds = self.bounds
for range in other:
bounds = self._intersection(bounds, range.bounds)
if not bounds:
return None
range = VersionRange(None... | AND together version ranges.
Calculates the intersection of this range with one or more other ranges.
Args:
other: VersionRange object (or list of) to AND with.
Returns:
New VersionRange object representing the intersection, or None if
no ranges intersect. | juraj-google-style |
def get_version(
here_path,
default_version=DEFAULT_VERSION,
):
if 'site-packages' in here_path:
return _version_from_file(here_path)
if os.environ.get('TRAVIS_TAG'):
if not TEST_MODE:
return os.environ.get('TRAVIS_TAG').replace('v', '')
... | tries to resolve version number
Args:
here_path (str): path to project local dir
default_version (str): what version to return if all else fails
Returns:
str: semantic_version information for library | juraj-google-style |
def get_oxi_state_decorated_structure(self, structure):
s = structure.copy()
if s.is_ordered:
valences = self.get_valences(s)
s.add_oxidation_state_by_site(valences)
else:
valences = self.get_valences(s)
s = add_oxidation_state_by_site_fraction(s, valences)
return s | Get an oxidation state decorated structure. This currently works only
for ordered structures only.
Args:
structure: Structure to analyze
Returns:
A modified structure that is oxidation state decorated.
Raises:
ValueError if the valences cannot be determined. | codesearchnet |
def restore_component(self, component_name, save_path):
component = self.get_component(component_name=component_name)
self._validate_savable(component=component, component_name=component_name)
component.restore(sess=self.session, save_path=save_path) | Restores a component's parameters from a save location.
Args:
component_name: The component to restore.
save_path: The save location. | juraj-google-style |
def rest_error(self):
error_json = self.__format_error('errors')
return json.dumps(error_json, indent=1, sort_keys=True) | Format this error into a response to a REST request.
Returns:
A string containing the reformatted error response. | codesearchnet |
def InitPrivateKey(self):
if self.private_key:
try:
self.common_name = rdf_client.ClientURN.FromPrivateKey(self.private_key)
logging.info('Starting client %s', self.common_name)
return self.private_key
except type_info.TypeValueError:
pass
key = rd... | Makes sure this client has a private key set.
It first tries to load an RSA key from the certificate.
If no certificate is found, or it is invalid, we make a new random RSA key,
and store it as our certificate.
Returns:
An RSA key - either from the certificate or a new random key. | codesearchnet |
def create_leaflet_viewer(self, idaho_image_results, filename):
description = self.describe_images(idaho_image_results)
if (len(description) > 0):
functionstring = ''
for (catid, images) in description.items():
for (partnum, part) in images['parts'].items():
num_image... | Create a leaflet viewer html file for viewing idaho images.
Args:
idaho_image_results (dict): IDAHO image result set as returned from
the catalog.
filename (str): Where to save output html file. | codesearchnet |
def _infer_graph(self, inputs, clusters):
assert isinstance(inputs, list)
scores = self._distance_graph(inputs, clusters, self._distance_metric)
output = []
if self._distance_metric == COSINE_DISTANCE and (not self._clusters_l2_normalized()):
with ops.colocate_with(clusters, ignore_existing=True... | Maps input to closest cluster and the score.
Args:
inputs: list of input Tensors.
clusters: Tensor of cluster centers.
Returns:
List of tuple, where each value in tuple corresponds to a value in inp.
The tuple has following three elements:
all_scores: distance of each input to each cluster center.
score: distance of ... | github-repos |
class SimpleSlidingQuantileTracker(WindowedTracker, QuantileTracker):
def __init__(self, window_size, q):
super().__init__(window_mode=WindowMode.SLIDING, window_size=window_size)
QuantileTracker.__init__(self, q)
def get(self):
with warnings.catch_warnings(record=False):
... | Sliding window quantile tracker using NumPy.
This tracker uses NumPy's `nanquantile` function to calculate the specified
quantile of the values currently in the sliding window. It's a simple,
non-incremental approach.
Args:
window_size: The size of the sliding window.
q: The quantile to calculate, a float between 0 a... | github-repos |
def removeTags(dom):
try:
string_type = basestring
except NameError:
string_type = str
element_stack = None
if type(dom) in [list, tuple]:
element_stack = dom
elif isinstance(dom, HTMLElement):
element_stack = dom.childs if dom.isTag() else [dom]
e... | Remove all tags from `dom` and obtain plaintext representation.
Args:
dom (str, obj, array): str, HTMLElement instance or array of elements.
Returns:
str: Plain string without tags. | juraj-google-style |
def radar_xsect(scatterer, h_pol=True):
Z = scatterer.get_Z()
if h_pol:
return 2 * np.pi * \
(Z[0,0] - Z[0,1] - Z[1,0] + Z[1,1])
else:
return 2 * np.pi * \
(Z[0,0] + Z[0,1] + Z[1,0] + Z[1,1]) | Radar cross section for the current setup.
Args:
scatterer: a Scatterer instance.
h_pol: If True (default), use horizontal polarization.
If False, use vertical polarization.
Returns:
The radar cross section. | juraj-google-style |
def _status(self):
job_id_list = ' '.join(self.resources.keys())
jobs_missing = list(self.resources.keys())
retcode, stdout, stderr = self.channel.execute_wait("qstat {0}".format(job_id_list), 3)
for line in stdout.split('\n'):
parts = line.split()
if ... | Internal: Do not call. Returns the status list for a list of job_ids
Args:
self
Returns:
[status...] : Status list of all jobs | juraj-google-style |
def state_nums():
st_nums = {}
fname = pkg_resources.resource_filename(__name__, 'resources/States.csv')
with open(fname, 'rU') as csvfile:
reader = csv.reader(csvfile, delimiter=',')
i = 0
for row in reader:
st_nums[row[0]] = i
i = (i + 1)
return st_nums | Get a dictionary of state names mapped to their 'legend' value.
Returns:
dictionary of state names mapped to their numeric value | codesearchnet |
def _get_model_field(self, name: str):
field_name = self._normalize_field_name(name)
if ((field_name == 'pk') and self.query.model._meta.pk):
return self.query.model._meta.pk
for field in self.query.model._meta.local_concrete_fields:
if ((field.name == field_name) or (field.column == field_n... | Gets the field on a model with the specified name.
Arguments:
name:
The name of the field to look for.
This can be both the actual field name, or
the name of the column, both will work :)
Returns:
The field with the specified name or None if
no such field exists. | codesearchnet |
def select(self, inputs: List[Any], global_state: pg.geno.AttributeDict, step: int) -> List[Any]: | Select a list of outputs from the inputs.
A selector has two use cases:
* Used as parents selector, which selects individuals from the population
as parents for recombination. It will be called before the recombination
step within the :meth:`pyglove.evolution.Evolution.propose` method.
* Used as a population updater... | github-repos |
def save_pickle(obj, outfile, protocol=2):
with open(outfile, 'wb') as f:
pickle.dump(obj, f, protocol=protocol)
return outfile | Save the object as a pickle file
Args:
outfile (str): Filename
protocol (int): Pickle protocol to use. Default is 2 to remain compatible with Python 2
Returns:
str: Path to pickle file | codesearchnet |
def seq_int_arr(seqs):
return np.array([[NT_TO_INT[c] for c in x.upper()] for x in seqs]) | Convert list of ACGT strings to matix of 1-4 ints
Args:
seqs (list of str): nucleotide sequences with only 'ACGT' characters
Returns:
numpy.array of int: matrix of integers from 1 to 4 inclusive representing A, C, G, and T
str: nucleotide sequence string | juraj-google-style |
def load_settings(self, path):
if not os.path.exists(path):
raise exceptions.ConfigurationError(
"The server configuration file ('{0}') could not be "
"located.".format(path)
)
self._logger.info(
"Loading server configuration ... | Load configuration settings from the file pointed to by path.
This will overwrite all current setting values.
Args:
path (string): The path to the configuration file containing
the settings to load. Required.
Raises:
ConfigurationError: Raised if the path does not point to an
existing file or if a setting value is in... | juraj-google-style |
def swap_gain(mapping, node_id1, mapping_id1, node_id2, mapping_id2, weight_dict, match_num):
new_mapping_list = mapping[:]
new_mapping_list[node_id1] = mapping_id2
new_mapping_list[node_id2] = mapping_id1
if tuple(new_mapping_list) in match_triple_dict:
return match_triple_dict[t... | Compute the triple match number gain from the swapping
Arguments:
mapping: current node mapping list
node_id1: node 1 index in AMR 1
mapping_id1: the node index in AMR 2 node 1 maps to (in the current mapping)
node_id2: node 2 index in AMR 1
mapping_id2: the node index in AMR 2 node 2 maps to (in the current mapping)
w... | juraj-google-style |
def replace_dimensions(cls, dimensions, overrides):
from .dimension import Dimension
replaced = []
for d in dimensions:
if (d.name in overrides):
override = overrides[d.name]
elif (d.label in overrides):
override = overrides[d.label]
else:
override... | Replaces dimensions in list with dictionary of overrides.
Args:
dimensions: List of dimensions
overrides: Dictionary of dimension specs indexed by name
Returns:
list: List of dimensions with replacements applied | codesearchnet |
def prep_itasser_modeling(self, itasser_installation, itlib_folder, runtype, create_in_dir=None, execute_from_dir=None, print_exec=False, **kwargs):
if (not create_in_dir):
if (not self.structure_dir):
raise ValueError('Output directory must be specified')
self.homology_models_dir = op.j... | Prepare to run I-TASSER homology modeling for the representative sequence.
Args:
itasser_installation (str): Path to I-TASSER folder, i.e. ``~/software/I-TASSER4.4``
itlib_folder (str): Path to ITLIB folder, i.e. ``~/software/ITLIB``
runtype: How you will be running I-TASSER - local, slurm, or torque
create_in_dir (st... | codesearchnet |
def convert_graphdef(input_data, input_tensors, output_tensors, **kwargs):
model_flags = build_model_flags(**kwargs)
conversion_flags = build_conversion_flags(**kwargs)
saved_model_dir = kwargs.get('saved_model_dir', None)
input_shapes = kwargs.get('input_shapes', None)
quantized_input_stats = kwarg... | Convert a frozen GraphDef model using the TF Lite converter.
Conversion can be customized by providing arguments that are forwarded to
`build_model_flags` and `build_conversion_flags` (see documentation).
Args:
input_data: Input data (i.e. often `sess.graph_def`),
input_tensors: List of input tensors. Type and shape ... | github-repos |
def table_update(self, table_name, table_info):
url = (Api._ENDPOINT + (Api._TABLES_PATH % table_name))
return datalab.utils.Http.request(url, method='PUT', data=table_info, credentials=self._credentials) | Updates the Table info.
Args:
table_name: the name of the table to update as a tuple of components.
table_info: the Table resource with updated fields. | codesearchnet |
def inject_positional_args(self, method):
inspect = self._modules['inspect']
argspec = inspect.getargspec(method)
keyword_arg_index = ((- 1) * len((argspec.defaults or [])))
arg_names = argspec.args[:(keyword_arg_index or None)]
kwarg_names = argspec.args[len(arg_names):]
functools = self._modul... | Decorator for injecting positional arguments from the configuration.
This decorator wraps the given method, so that any positional arguments are
passed with corresponding values from the configuration. The name of the
positional argument must match the configuration key.
Keyword arguments are *NEVER* modified, even ... | codesearchnet |
def process_latest_result(self, latest_results, current_time_ms, recognize_element):
if latest_results.shape[0] != self._label_count:
raise ValueError('The results for recognition should contain {} elements, but there are {} produced'.format(self._label_count, latest_results.shape[0]))
if self._previous... | Smoothing the results in average window when a new result is added in.
Receive a new result from inference and put the founded command into
a RecognizeResult instance after the smoothing procedure.
Args:
latest_results: A list containing the confidences of all labels.
current_time_ms: The start timestamp of the input... | github-repos |
def min(cls, x: 'TensorFluent', y: 'TensorFluent') -> 'TensorFluent':
return cls._binary_op(x, y, tf.minimum, tf.float32) | Returns a TensorFluent for the minimum function.
Args:
x: The first operand.
y: The second operand.
Returns:
A TensorFluent wrapping the minimum function. | juraj-google-style |
def sanitize_filename(filename):
sanitized_filename = re.sub('[/\\\\:*?"<>|]', '-', filename)
sanitized_filename = sanitized_filename.replace('&', 'and')
sanitized_filename = sanitized_filename.replace('"', '')
sanitized_filename = sanitized_filename.replace("'", '')
sanitized_filename = sanitized_f... | Make sure filenames are valid paths.
Returns:
str: | codesearchnet |
def recursively_convert_to_json_serializable(test_obj):
try:
if not isinstance(test_obj, list) and np.isnan(test_obj):
return None
except TypeError:
pass
except ValueError:
pass
if isinstance(test_obj, (string_types, inte... | Helper function to convert a dict object to one that is serializable
Args:
test_obj: an object to attempt to convert a corresponding json-serializable object
Returns:
(dict) A converted test_object
Warning:
test_obj may also be converted in place. | juraj-google-style |
def validate_gcs_path(path, require_object):
(bucket, key) = datalab.storage._bucket.parse_name(path)
if (bucket is None):
raise Exception(('Invalid GCS path "%s"' % path))
if (require_object and (key is None)):
raise Exception(('It appears the GCS path "%s" is a bucket path but not an objec... | Check whether a given path is a valid GCS path.
Args:
path: the config to check.
require_object: if True, the path has to be an object path but not bucket path.
Raises:
Exception if the path is invalid | codesearchnet |
def get_correct_answer(question, default=None, required=False, answer=None, is_answer_correct=None):
while 1:
if (default is None):
msg = u' - No Default Available'
else:
msg = u'\n[DEFAULT] -> {}\nPress Enter To Use Default'.format(default)
prompt = ((question + msg)... | u"""Ask user a question and confirm answer
Args:
question (str): Question to ask user
default (str): Default answer if no input from user
required (str): Require user to input answer
answer (str): Used for testing
is_answer_correct (str): Used for testing | codesearchnet |
def _ParseAttribute(self, file_object):
file_offset = file_object.tell()
attribute_map = self._GetDataTypeMap('cups_ipp_attribute')
try:
attribute, _ = self._ReadStructureFromFileObject(
file_object, file_offset, attribute_map)
except (ValueError, errors.ParseError) as exception:
... | Parses a CUPS IPP attribute from a file-like object.
Args:
file_object (dfvfs.FileIO): file-like object.
Returns:
tuple[str, object]: attribute name and value.
Raises:
ParseError: if the attribute cannot be parsed. | juraj-google-style |
def _get_val_from_ddb_data(data, keylist):
next_type = None
for k in keylist:
for k1 in k:
if next_type is None:
data = data[k[k1]]
else:
temp_dict = data[next_type]
data = temp_dict[k[k1]]
next_type = k1
i... | Given a dictionary of dynamodb data (including the datatypes) and a
properly structured keylist, it will return the value of the lookup
Args:
data (dict): the raw dynamodb data
keylist(list): a list of keys to lookup. This must include the
datatype
Returns:
various: It returns the value from the dynamodb record, and ... | juraj-google-style |
def next(self):
self._set_consumer_timeout_start()
while True:
try:
return six.next(self._get_message_iterator())
except StopIteration:
self._reset_message_iterator()
self._check_consumer_timeout() | Return the next available message
Blocks indefinitely unless consumer_timeout_ms > 0
Returns:
a single KafkaMessage from the message iterator
Raises:
ConsumerTimeout after consumer_timeout_ms and no message
Note:
This is also the method called internally during iteration | codesearchnet |
def List(self, request, global_params=None):
config = self.GetMethodConfig('List')
return self._RunMethod(config, request, global_params=global_params) | Lists all row access policies on the specified table.
Args:
request: (BigqueryRowAccessPoliciesListRequest) input message
global_params: (StandardQueryParameters, default: None) global arguments
Returns:
(ListRowAccessPoliciesResponse) The response message. | github-repos |
def username(self, value):
self._username = value
self._connectionXML.set('username', value) | Set the connection's username property.
Args:
value: New username value. String.
Returns:
Nothing. | juraj-google-style |
def CheckMySQLConnection(db_options):
for tries_left in range(_MYSQL_MAX_RETRIES, -1, -1):
try:
connection_options = dict(
host=db_options["Mysql.host"],
port=db_options["Mysql.port"],
db=db_options["Mysql.database_name"],
user=db_options["Mysql.database_username"]... | Checks whether a connection can be established to MySQL.
Args:
db_options: A dict mapping GRR MySQL config options to their values.
Returns:
A boolean indicating whether a connection could be made to a MySQL server
instance with the given options. | juraj-google-style |
def is_test_executed(self, test_name):
for record in self.executed:
if record.test_name == test_name:
return True
return False | Checks if a specific test has been executed.
Args:
test_name: string, the name of the test to check.
Returns:
True if the test has been executed according to the test result,
False otherwise. | juraj-google-style |
def Matches(self, file_entry):
if not self._date_time_ranges:
return None
for date_time_range in self._date_time_ranges:
time_attribute = self._TIME_VALUE_MAPPINGS.get(
date_time_range.time_value, None)
if not time_attribute:
continue
timestamp = getattr(file_ent... | Compares the file entry against the filter.
Args:
file_entry (dfvfs.FileEntry): file entry to compare.
Returns:
bool: True if the file entry matches the filter, False if not or
None if the filter does not apply. | juraj-google-style |
def list(self):
self._initialize_list()
interested = True
response = self._cloudFormation.list_stacks()
print('Stack(s):')
while interested:
if 'StackSummaries' in response:
for stack in response['StackSummaries']:
stack_s... | List the existing stacks in the indicated region
Args:
None
Returns:
True if True
Todo:
Figure out what could go wrong and take steps
to hanlde problems. | juraj-google-style |
def wait_for_compilation_job(self, job, poll=5):
desc = _wait_until((lambda : _compilation_job_status(self.sagemaker_client, job)), poll)
self._check_job_status(job, desc, 'CompilationJobStatus')
return desc | Wait for an Amazon SageMaker Neo compilation job to complete.
Args:
job (str): Name of the compilation job to wait for.
poll (int): Polling interval in seconds (default: 5).
Returns:
(dict): Return value from the ``DescribeCompilationJob`` API.
Raises:
ValueError: If the compilation job fails. | codesearchnet |
def transform(self, col):
out = pd.DataFrame()
out[self.col_name] = self.safe_datetime_cast(col)
out[self.col_name] = self.to_timestamp(out)
return out | Prepare the transformer to convert data and return the processed table.
Args:
col(pandas.DataFrame): Data to transform.
Returns:
pandas.DataFrame | juraj-google-style |
def prefer_static_broadcast_shape(shape1,
shape2,
name="prefer_static_broadcast_shape"):
with tf.name_scope(name):
def make_shape_tensor(x):
return tf.convert_to_tensor(value=x, name="shape", dtype=tf.int32)
def get_tensor_shape(s)... | Convenience function which statically broadcasts shape when possible.
Args:
shape1: `1-D` integer `Tensor`. Already converted to tensor!
shape2: `1-D` integer `Tensor`. Already converted to tensor!
name: A string name to prepend to created ops.
Returns:
The broadcast shape, either as `TensorShape` (if broadcast ... | juraj-google-style |
def workspace_from_url(self, mets_url, dst_dir=None, clobber_mets=False, mets_basename=None, download=False, baseurl=None):
if (dst_dir and (not dst_dir.startswith('/'))):
dst_dir = abspath(dst_dir)
if (mets_url is None):
if (baseurl is None):
raise Exception('Must pass mets_url and/... | Create a workspace from a METS by URL.
Sets the mets.xml file
Arguments:
mets_url (string): Source mets URL
dst_dir (string, None): Target directory for the workspace
clobber_mets (boolean, False): Whether to overwrite existing mets.xml. By default existing mets.xml will raise an exception.
download (boolean, False):... | codesearchnet |
def message_index(index_url):
idx = csv.reader(urllib2.urlopen(index_url), delimiter=':')
messages = []
for line in idx:
messages.append(line)
return messages | get message index of components for urllib2.
Args:
url(string):
Returns:
list: messages | codesearchnet |
def batch_predict_async(training_dir, prediction_input_file, output_dir, mode, batch_size=16, shard_files=True, output_format='csv', cloud=False):
import google.datalab.utils as du
with warnings.catch_warnings():
warnings.simplefilter('ignore')
if cloud:
runner_results = cloud_batch_... | Local and cloud batch prediction.
Args:
training_dir: The output folder of training.
prediction_input_file: csv file pattern to a file. File must be on GCS if
running cloud prediction
output_dir: output location to save the results. Must be a GSC path if
running cloud prediction.
mode: 'evaluation' or 'prediction'. If... | codesearchnet |
def get_q2(self, thetas=None, phis=None):
if ((thetas is not None) and (phis is not None)):
self.compute_trigonometric_terms(thetas, phis)
nnn = len(self._pow_sin_t[1])
nnn_range = range(nnn)
sqrt_15_2pi = sqrt((15.0 / (2.0 * pi)))
sqrt_5_pi = sqrt((5.0 / pi))
pre_y_2_2 = [((0.25 * sqrt_... | Calculates the value of the bond orientational order parameter of
weight l=2. If the function is called with non-empty lists of
polar and azimuthal angles the corresponding trigonometric terms
are computed afresh. Otherwise, it is expected that the
compute_trigonometric_terms function has been just called.
Args:
the... | codesearchnet |
def cast_vdata(vdata=None, vtype='REG_SZ'):
registry = Registry()
vtype_value = registry.vtype[vtype]
if (vtype_value in [win32con.REG_SZ, win32con.REG_EXPAND_SZ]):
return _to_unicode(vdata)
elif (vtype_value == win32con.REG_BINARY):
if isinstance(vdata, six.text_type):
retur... | Cast the ``vdata` value to the appropriate data type for the registry type
specified in ``vtype``
Args:
vdata (str, int, list, bytes): The data to cast
vtype (str):
The type of data to be written to the registry. Must be one of the
following:
- REG_BINARY
- REG_DWORD
- REG_EXPAND_SZ
- REG_MULTI_SZ
- REG_QWORD
- REG... | codesearchnet |
def _get_resource(self, label: str, source: dict, resource_type: str):
try:
return source[label]
except KeyError:
raise ValueError("Cannot find {0} with label '{1}'.\nExisting {0} labels: {2}".format(
resource_type, label, list(source.keys()))) | Generic resoure fetcher handling errors.
Args:
label (str): The label to fetch
source (dict): The dictionary to look up the label
resource_type str: The display name of the resource type (used in errors) | juraj-google-style |
def __init__(
self, resolver_context, file_system, path_spec, is_root=False,
is_virtual=False):
compressed_stream = resolver.Resolver.OpenFileObject(
path_spec, resolver_context=resolver_context)
if not compressed_stream:
raise errors.BackEndError(
'Unable to open compre... | Initializes a file entry.
Args:
resolver_context (Context): resolver context.
file_system (FileSystem): file system.
path_spec (PathSpec): path specification.
is_root (Optional[bool]): True if the file entry is the root file entry
of the corresponding file system.
is_virtual (Optional[bool]): True if the file entry is... | juraj-google-style |
def get_aws_session(account):
from cloud_inquisitor.config import dbconfig
from cloud_inquisitor.plugins.types.accounts import AWSAccount
if (not isinstance(account, AWSAccount)):
raise InquisitorError('Non AWSAccount passed to get_aws_session, got {}'.format(account.__class__.__name__))
session... | Function to return a boto3 Session based on the account passed in the first argument.
Args:
account (:obj:`Account`): Account to create the session object for
Returns:
:obj:`boto3:boto3.session.Session` | codesearchnet |
def join(self):
c_api.TF_ServerJoin(self._server) | Blocks until the server has shut down.
This method currently blocks forever.
Raises:
tf.errors.OpError: Or one of its subclasses if an error occurs while
joining the TensorFlow server. | github-repos |
def response_list(data, key):
if (key not in data):
return None
if isinstance(data[key], list):
return data[key]
else:
return [data[key]] | Obtain the relevant response data in a list.
If the response does not already contain the result in a list, a new one
will be created to ease iteration in the parser methods.
Args:
data (dict): API response.
key (str): Attribute of the response that contains the result values.
Returns:
List of response items (usuall... | codesearchnet |
def initialize_plugs(self, plug_types=None):
types = plug_types if plug_types is not None else self._plug_types
for plug_type in types:
plug_logger = self.logger.getChild(plug_type.__name__)
if plug_type in self._plugs_by_type:
continue
try:
if not issubclass... | Instantiate required plugs.
Instantiates plug types and saves the instances in self._plugs_by_type for
use in provide_plugs().
Args:
plug_types: Plug types may be specified here rather than passed
into the constructor (this is used primarily for unit testing
phases). | juraj-google-style |
def AddFiles(self, hash_id_metadatas):
for hash_id, metadata in iteritems(hash_id_metadatas):
self.AddFile(hash_id, metadata) | Adds multiple files to the file store.
Args:
hash_id_metadatas: A dictionary mapping hash ids to file metadata (a tuple
of hash client path and blob references). | juraj-google-style |
def create_cloudwatch_event(app_name, env, region, rules):
session = boto3.Session(profile_name=env, region_name=region)
cloudwatch_client = session.client('events')
rule_name = rules.get('rule_name')
schedule = rules.get('schedule')
rule_description = rules.get('rule_description')
json_input = ... | Create cloudwatch event for lambda from rules.
Args:
app_name (str): name of the lambda function
env (str): Environment/Account for lambda function
region (str): AWS region of the lambda function
rules (dict): Trigger rules from the settings | codesearchnet |
def __init__(self, _args):
super(TcExRun, self).__init__(_args)
self._signal_handler_init()
self._config = None
self._profile = {}
self._staging_data = None
self.container = None
self.reports = Reports()
self.tcex = None
self.doc... | Initialize Class properties.
Args:
_args (namespace): The argparser args Namespace. | juraj-google-style |
def reschedule(cls,
mapreduce_state,
mapreduce_spec,
serial_id,
queue_name=None):
task_name = ControllerCallbackHandler.get_task_name(
mapreduce_spec, serial_id)
task_params = ControllerCallbackHandler.controller_parameters(
... | Schedule new update status callback task.
Args:
mapreduce_state: mapreduce state as model.MapreduceState
mapreduce_spec: mapreduce specification as MapreduceSpec.
serial_id: id of the invocation as int.
queue_name: The queue to schedule this task on. Will use the current
queue of execution if not supplied. | juraj-google-style |
def apply(self, func, *args, **kwargs):
ret = func(self._t, *args, **kwargs)
return LinearWrap(ret) | Apply a function on the wrapped tensor.
Returns:
LinearWrap: ``LinearWrap(func(self.tensor(), *args, **kwargs))``. | codesearchnet |
def collect_trajectories(env, policy_fun, num_trajectories=1, policy='greedy', max_timestep=None, epsilon=0.1):
trajectories = []
for t in range(num_trajectories):
t_start = time.time()
rewards = []
actions = []
done = False
observation = env.reset()
observation_h... | Collect trajectories with the given policy net and behaviour.
Args:
env: A gym env interface, for now this is not-batched.
policy_fun: observations(B,T+1) -> log-probabs(B,T+1, A) callable.
num_trajectories: int, number of trajectories.
policy: string, "greedy", "epsilon-greedy", or "categorical-sampling" i.e.
how to ... | codesearchnet |
def __init__(self, resolver_context):
super(APFSFileSystem, self).__init__(resolver_context)
self._fsapfs_volume = None | Initializes an APFS file system.
Args:
resolver_context (Context): resolver context. | juraj-google-style |
def validate_signature(self, signature, data, encoding='utf8'):
if isinstance(data, string_types):
data = bytearray(data, encoding)
if isinstance(signature, string_types):
signature = bytearray(signature, encoding)
secret_key = bytearray(self.secret_key, 'utf8')
hashed = hmac.new(secret_... | Validate the signature for the provided data.
Args:
signature (str or bytes or bytearray): Signature that was provided
for the request.
data (str or bytes or bytearray): Data string to validate against
the signature.
encoding (str, optional): If a string was provided for ``data`` or
``signature``, this is the characte... | codesearchnet |
def add_nodes(self, root_id, current_node, indent=1):
if not current_node.children:
return
config.LOGGER.info("({count} of {total} uploaded) {indent}Processing {title} ({kind})".format(
count=self.node_count_dict['upload_count'],
total=self.node_cou... | add_nodes: adds processed nodes to tree
Args:
root_id (str): id of parent node on Kolibri Studio
current_node (Node): node to publish children
indent (int): level of indentation for printing
Returns: link to uploadedchannel | juraj-google-style |
def run(self, dag):
num_dag_qubits = sum([qreg.size for qreg in dag.qregs.values()])
if num_dag_qubits > self.coupling_map.size():
raise TranspilerError('Number of qubits greater than device.')
best_sub = self._best_subset(num_dag_qubits)
layout = Layout()
ma... | Pick a convenient layout depending on the best matching
qubit connectivity, and set the property `layout`.
Args:
dag (DAGCircuit): DAG to find layout for.
Raises:
TranspilerError: if dag wider than self.coupling_map | juraj-google-style |
def flatten(structure):
return tree_impl.flatten(structure) | Flattens a possibly nested structure into a list.
In the case of dict instances, the sequence consists of the values,
sorted by key to ensure deterministic behavior. However, instances of
`collections.OrderedDict` are handled differently: their sequence order is
used instead of the sorted keys. The same convention is ... | github-repos |
def _read_messages_until_true(self, predicate, timeout):
while (not predicate()):
self._message_received.acquire()
if self._reader_lock.acquire(False):
try:
self._message_received.release()
if predicate():
return
self._h... | Read a message from this stream and handle it.
This method tries to read a message from this stream, blocking until a
message is read. Once read, it will handle it accordingly by calling
self._handle_message().
This is repeated as long as predicate() returns False. There is some
locking used internally here so that... | codesearchnet |
def assert_is_compatible_with(self, other):
if not self.is_compatible_with(other):
raise ValueError('Dimensions %s and %s are not compatible' % (self, other)) | Raises an exception if `other` is not compatible with this Dimension.
Args:
other: Another Dimension.
Raises:
ValueError: If `self` and `other` are not compatible (see
is_compatible_with). | github-repos |
def _IsBase64(cls, s):
try:
if base64.b64encode(base64.b64decode(s)).decode('utf-8') == s:
return True
except (TypeError, binascii.Error):
pass
return False | An imperfect but decent method for determining if a string is base64.
Args:
s: A string with the data to test.
Returns:
True if s is base64, else False. | juraj-google-style |
def loss_l2(self, l2=0):
if isinstance(l2, (int, float)):
D = (l2 * torch.eye(self.d))
else:
D = torch.diag(torch.from_numpy(l2))
return (torch.norm((D @ (self.mu - self.mu_init))) ** 2) | L2 loss centered around mu_init, scaled optionally per-source.
In other words, diagonal Tikhonov regularization,
||D(\mu-\mu_{init})||_2^2
where D is diagonal.
Args:
- l2: A float or np.array representing the per-source regularization
strengths to use | codesearchnet |
def get_table(e: exp.Expression) -> str:
table = e.find(exp.Table).args['this'].args['this']
if table in table_dataset_map:
table = table_dataset_map[table]
return table | Get the table name from an expression.
Args:
e (Expression): The expression containing table information.
Returns:
str: The table name. | github-repos |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.