code stringlengths 20 4.93k | docstring stringlengths 33 1.27k | source stringclasses 3
values |
|---|---|---|
def evaluate(self, expression):
dump_tensors_iter = re.finditer(_DUMP_TENSOR_PATTERN, expression)
rewritten_expression = expression
for match in reversed(list(dump_tensors_iter)):
tensor_name = match.group(0)[1:-1].strip()
device_name, node_name, output_slot, debug_op, exec_index = _parse_de... | Parse an expression.
Args:
expression: the expression to be parsed.
Returns:
The result of the evaluation.
Raises:
ValueError: If the value of one or more of the debug tensors in the
expression are not available. | github-repos |
def replace_drive_enclosure(self, information):
uri = '{}/replaceDriveEnclosure'.format(self.data['uri'])
result = self._helper.create(information, uri)
self.refresh()
return result | When a drive enclosure has been physically replaced, initiate the replacement operation that enables the
new drive enclosure to take over as a replacement for the prior drive enclosure. The request requires
specification of both the serial numbers of the original drive enclosure and its replacement to be provided.
Arg... | codesearchnet |
def get_parsed_context(pipeline, context_in_string):
logger.debug('starting')
if ('context_parser' in pipeline):
parser_module_name = pipeline['context_parser']
logger.debug(f'context parser found: {parser_module_name}')
parser_module = pypyr.moduleloader.get_module(parser_module_name)
... | Execute get_parsed_context handler if specified.
Dynamically load the module specified by the context_parser key in pipeline
dict and execute the get_parsed_context function on that module.
Args:
pipeline: dict. Pipeline object.
context_in_string: string. Argument string used to initialize context.
Returns:
pypyr.co... | codesearchnet |
def patch_on_type(src: symbolic.Symbolic, value_type: Union[Type[Any], Tuple[Type[Any], ...]], value: Any=None, value_fn: Optional[Callable[[Any], Any]]=None, skip_notification: Optional[bool]=None) -> Any:
return _conditional_patch(src, lambda k, v, p: isinstance(v, value_type), value, value_fn, skip_notification) | Recursively patch values on matched types.
Example::
d = pg.Dict(a={'x': 1}, b=2)
print(pg.patching.patch_on_type(d, int, value_fn=lambda x: x * 2))
# {a={x=2}, b=4}
Args:
src: symbolic value to patch.
value_type: Value type to match.
value: New value for field that satisfy `condition`.
value_fn: Callable object tha... | github-repos |
def create_van_der_corput_samples(idx, number_base=2):
assert number_base > 1
idx = numpy.asarray(idx).flatten() + 1
out = numpy.zeros(len(idx), dtype=float)
base = float(number_base)
active = numpy.ones(len(idx), dtype=bool)
while numpy.any(active):
out[active] += (idx[active] % ... | Van der Corput samples.
Args:
idx (int, numpy.ndarray):
The index of the sequence. If array is provided, all values in
array is returned.
number_base (int):
The numerical base from where to create the samples from.
Returns (float, numpy.ndarray):
Van der Corput samples. | juraj-google-style |
def anti_clobber_dir_path(dir_path, suffix='.d'):
dir_path = os.path.normpath(dir_path)
parts = dir_path.split(os.sep)
for index in range(len(parts)):
test_path = os.sep.join(parts[:(index + 1)])
if os.path.isfile(test_path):
parts[index] += suffix
return os.sep.join(... | Return a directory path free of filenames.
Args:
dir_path (str): A directory path.
suffix (str): The suffix to append to the part of the path that is
a file.
Returns:
str | codesearchnet |
def _watch(self, primals, tangents):
def _watch(primal, tangent):
if not primal.dtype.is_floating:
logging.log_first_n(logging.WARN, 'The dtype of the watched primal must be floating (e.g. tf.float32), got %r', 5, primal.dtype)
tangent = ops.convert_to_tensor(tangent, dtype=primal.dtype... | Ensures that `primals` are being traced by this accumulator.
Mathematically, `tangents` is a vector right-multiplying the Jacobian matrix
(a Jacobian-vector product) for the function computed while this accumulator
is active. Since JVPs are computed in forward mode as the computation
happens, this vector must be suppl... | github-repos |
def download(self, temp_ver, store_metadata=True):
dest = self._prefixed(temp_ver.name)
temp_dest = ('%s.tmp' % dest)
with utils.LockFile((dest + '.lock')):
if os.path.exists(dest):
return
temp_ver.download(temp_dest)
if store_metadata:
with open(('%s.metadata... | Retrieve the given template version
Args:
temp_ver (TemplateVersion): template version to retrieve
store_metadata (bool): If set to ``False``, will not refresh the
local metadata with the retrieved one
Returns:
None | codesearchnet |
def fit(weights: Array, train_dataset: Dataset, iters: int, learning_rate: float, log_span: int, val_dataset: typing.Optional[Dataset]=None) -> Array:
grad_loss = jit(grad(cross_entropy_loss, argnums=0))
for t in range(iters):
weights = weights - learning_rate * grad_loss(weights, train_dataset.X, train... | Updates the weights with the given dataset.
Args:
weights: A weight vector.
train_dataset: A train dataset.
iters: A number of iterations.
learning_rate: A learning rate.
log_span: A span to log metrics.
val_dataset: A validation dataset (optional).
Returns:
An updated weight vector. | github-repos |
def run_conditional_decorators(self, context):
logger.debug('starting')
run_me = context.get_formatted_as_type(self.run_me, out_type=bool)
skip_me = context.get_formatted_as_type(self.skip_me, out_type=bool)
swallow_me = context.get_formatted_as_type(self.swallow_me, out_type=bool)
if run_me:
... | Evaluate the step decorators to decide whether to run step or not.
Use pypyr.dsl.Step.run_step if you intend on executing the step the
same way pypyr does.
Args:
context: (pypyr.context.Context) The pypyr context. This arg will
mutate. | codesearchnet |
def add_input(self, **kwargs):
self._closed()
def _get_item(args):
'Get a single item from args.'
if (not args):
raise ValueError('No parameter specified.')
item = args.popitem()
if args:
raise ValueError('Too many parameters, not clear what to do with {}... | Add workflow input.
Args:
kwargs (dict): A dict with a `name: type` item
and optionally a `default: value` item, where name is the
name (id) of the workflow input (e.g., `dir_in`) and type is
the type of the input (e.g., `'Directory'`).
The type of input parameter can be learned from
`step.inputs(step_name=input_name)... | codesearchnet |
def flowshow(flow, win_name='', wait_time=0):
flow = flowread(flow)
flow_img = flow2rgb(flow)
imshow(rgb2bgr(flow_img), win_name, wait_time) | Show optical flow.
Args:
flow (ndarray or str): The optical flow to be displayed.
win_name (str): The window name.
wait_time (int): Value of waitKey param. | juraj-google-style |
def unstem(self, term):
originals = []
for i in self.terms[term]:
originals.append(self.tokens[i]['unstemmed'])
mode = Counter(originals).most_common(1)
return mode[0][0] | Given a stemmed term, get the most common unstemmed variant.
Args:
term (str): A stemmed term.
Returns:
str: The unstemmed token. | juraj-google-style |
def find_invalid_filenames(filenames, repository_root):
errors = []
for filename in filenames:
if (not os.path.abspath(filename).startswith(repository_root)):
errors.append((filename, ('Error: File %s does not belong to repository %s' % (filename, repository_root))))
if (not os.path.... | Find files that does not exist, are not in the repo or are directories.
Args:
filenames: list of filenames to check
repository_root: the absolute path of the repository's root.
Returns: A list of errors. | codesearchnet |
def __init__(self, **kwargs) -> 'PygalleBaseClass':
self.options = kwargs
self.init_properties() \
.set_uid() \
.set_class_name() \
.set_category() | Create a new instance of :class:`PygalleBaseClass`
# Arguments
args:
kwargs:
# Returns:
PygalleBaseClass: An instance of :class:`PygalleBaseClass` | juraj-google-style |
def reciprocal_lattice_from_outcar( filename ):
outcar = open(filename, "r").read()
recLat = re.findall(r"reciprocal\s*lattice\s*vectors\s*([-.\s\d]*)",
outcar)[-1]
recLat = recLat.split()
recLat = np.array(recLat, dtype=float)
recLat.shape = (3, 6)
recLat... | Finds and returns the reciprocal lattice vectors, if more than
one set present, it just returns the last one.
Args:
filename (Str): The name of the outcar file to be read
Returns:
List(Float): The reciprocal lattice vectors. | juraj-google-style |
class Speech2Text2Processor(ProcessorMixin):
feature_extractor_class = 'AutoFeatureExtractor'
tokenizer_class = 'Speech2Text2Tokenizer'
def __init__(self, feature_extractor, tokenizer):
super().__init__(feature_extractor, tokenizer)
self.current_processor = self.feature_extractor
se... | Constructs a Speech2Text2 processor which wraps a Speech2Text2 feature extractor and a Speech2Text2 tokenizer into
a single processor.
[`Speech2Text2Processor`] offers all the functionalities of [`AutoFeatureExtractor`] and [`Speech2Text2Tokenizer`].
See the [`~Speech2Text2Processor.__call__`] and [`~Speech2Text2Proce... | github-repos |
def report_filter(config, auth, body, filters):
new_body = body.copy()
for f, d in filters.items():
for v in get_rows(config, auth, d):
new_body['params'].setdefault('filters', []).append({'type': f, 'value': v})
return new_body | Adds filters to a report body
Filters cannot be easily added to the reports without templateing, this allows
filters to be passed as lists.
Values are specified using get_rows(...) helper, see
starthinker/util/data/__init__.py.
To specify a filter, use the official filter name and a list of values.
For exmaple:
```
... | github-repos |
def get_percentage_volume_change(self):
initial_vol = self.initial.lattice.volume
final_vol = self.final.lattice.volume
return ((final_vol / initial_vol) - 1) | Returns the percentage volume change.
Returns:
Volume change in percentage, e.g., 0.055 implies a 5.5% increase. | codesearchnet |
def stat(self, follow_symlinks=True):
if follow_symlinks:
if self._statresult_symlink is None:
file_object = self._filesystem.resolve(self.path)
if self._filesystem.is_windows_fs:
file_object.st_nlink = 0
self._statresult_s... | Return a stat_result object for this entry.
Args:
follow_symlinks: If False and the entry is a symlink, return the
result for the symlink, otherwise for the object it points to. | juraj-google-style |
def build_model(self, token_encoder_model, trainable_embeddings=True, output_activation='softmax'):
if (not isinstance(token_encoder_model, SequenceEncoderBase)):
raise ValueError('`token_encoder_model` should be an instance of `{}`'.format(SequenceEncoderBase))
if ((not token_encoder_model.allows_dynam... | Builds a model using the given `text_model`
Args:
token_encoder_model: An instance of `SequenceEncoderBase` for encoding all the tokens within a document.
This encoding is then fed into a final `Dense` layer for classification.
trainable_embeddings: Whether or not to fine tune embeddings.
output_activation: The output... | codesearchnet |
def where(self, predicate):
if self.closed():
raise ValueError('Attempt to call where() on a closed Queryable.')
if (not is_callable(predicate)):
raise TypeError('where() parameter predicate={predicate} is not callable'.format(predicate=repr(predicate)))
return self._create(ifilter(predicate... | Filters elements according to whether they match a predicate.
Note: This method uses deferred execution.
Args:
predicate: A unary function which is applied to each element in the
source sequence. Source elements for which the predicate
returns True will be present in the result.
Returns:
A Queryable over those eleme... | codesearchnet |
def call(self, *args, **kwargs):
if (not self.is_connected()):
if self.autoconnect:
return self._call_with_autoconnect(*args, **kwargs)
else:
error = ConnectionError('you are not connected and autoconnect=False')
return tornado.gen.maybe_future(error)
return s... | Calls a redis command and returns a Future of the reply.
Args:
*args: full redis command as variable length argument list or
a Pipeline object (as a single argument).
**kwargs: internal private options (do not use).
Returns:
a Future with the decoded redis reply as result (when available) or
a ConnectionError object ... | codesearchnet |
def patch_addPadding(self, patches):
paddingLength = self.Patch_Margin
nullPadding = ""
for x in range(1, paddingLength + 1):
nullPadding += chr(x)
for patch in patches:
patch.start1 += paddingLength
patch.start2 += paddingLength
patch = patches[0]
diffs = patc... | Add some padding on text start and end so that edges can match
something. Intended to be called only from within patch_apply.
Args:
patches: Array of Patch objects.
Returns:
The padding string added to each side. | juraj-google-style |
def _parse_flowcontrol_receive(self, config):
value = 'off'
match = re.search(r'flowcontrol receive (\w+)$', config, re.M)
if match:
value = match.group(1)
return dict(flowcontrol_receive=value) | Scans the config block and returns the flowcontrol receive value
Args:
config (str): The interface config block to scan
Returns:
dict: Returns a dict object with the flowcontrol receive value
retrieved from the config block. The returned dict object
is intended to be merged into the interface resource dict | juraj-google-style |
def plot(self, tag, mpl_plt, step=None, close_plot=True):
if (step is None):
step = self._step
else:
self._step = step
fig = mpl_plt.get_current_fig_manager()
(img_w, img_h) = fig.canvas.get_width_height()
image_buf = io.BytesIO()
mpl_plt.savefig(image_buf, format='png')
imag... | Saves matplotlib plot output to summary image.
Args:
tag: str: label for this data
mpl_plt: matplotlib stateful pyplot object with prepared plotting state
step: int: training step
close_plot: bool: automatically closes plot | codesearchnet |
def uncompress(element, output_spec):
flat_types = structure.get_flat_tensor_types(output_spec)
flat_shapes = structure.get_flat_tensor_shapes(output_spec)
tensor_list = ged_ops.uncompress_element(element, output_types=flat_types, output_shapes=flat_shapes)
return structure.from_tensor_list(output_spec,... | Uncompress a compressed dataset element.
Args:
element: A scalar variant tensor to uncompress. The element should have been
created by calling `compress`.
output_spec: A nested structure of `tf.TypeSpec` representing the type(s) of
the uncompressed element.
Returns:
The uncompressed element. | github-repos |
def get_mim_genes(genemap_lines, mim2gene_lines):
LOG.info("Get the mim genes")
genes = {}
hgnc_genes = {}
gene_nr = 0
no_hgnc = 0
for entry in parse_mim2gene(mim2gene_lines):
if 'gene' in entry['entry_type']:
mim_nr = entry['mim_number']
gene_... | Get a dictionary with genes and their omim information
Args:
genemap_lines(iterable(str))
mim2gene_lines(iterable(str))
Returns.
hgnc_genes(dict): A dictionary with hgnc_symbol as keys | juraj-google-style |
def are_values_same_type(first_val, second_val):
first_val_type = type(first_val)
second_val_type = type(second_val)
if (isinstance(first_val, string_types) and isinstance(second_val, string_types)):
return True
if (isinstance(first_val, bool) or isinstance(second_val, bool)):
return (fi... | Method to verify that both values belong to same type. Float and integer are
considered as same type.
Args:
first_val: Value to validate.
second_Val: Value to validate.
Returns:
Boolean: True if both values belong to same type. Otherwise False. | codesearchnet |
def _url_dirname(self, url_or_path):
return os.path.dirname(url_or_path) | Pass through to os.path.dirname.
This version uses os.path instead of posixpath to be compatible with the
host OS.
Args:
url_or_path: A string in the form of /some/path. | github-repos |
def __getattr__(self, name: str) -> column_expression_builder.ColumnExpressionBuilder:
lookup = name[:-1] if name.endswith('_') and keyword.iskeyword(name[:-1]) else name
expression = None
if self._fields:
for field in self._fields:
if field.column_name == lookup:
express... | Used to support building expressions directly off of the base view.
See the class-level documentation for guidance on use.
Args:
name: the name of the FHIR field to start with in the builder.
Returns:
A ColumnExpressionBuilder for the field in question | github-repos |
def _cumprod(l):
ret = [1]
for item in l:
ret.append(ret[-1] * item)
return ret | Cumulative product of a list.
Args:
l: a list of integers
Returns:
a list with one more element (starting with 1) | juraj-google-style |
def put_many(self, type: Type[T], items: Iterable[T], context: PipelineContext = None) -> None:
pass | Puts multiple objects of the same type into the data sink.
Args:
type: The type of the objects being inserted.
items: The objects to be inserted.
context: The context of the insertion (mutable). | juraj-google-style |
def export_as_tfhub_module(model_name, hparams, decode_hparams, problem, checkpoint_path, export_dir):
def hub_module_fn():
'Creates the TF graph for the hub module.'
model_fn = t2t_model.T2TModel.make_estimator_model_fn(model_name, hparams, decode_hparams=decode_hparams, use_tpu=FLAGS.use_tpu)
... | Exports the last checkpoint from the directory as tfhub module.
It creates the Module spec and signature (based on T2T problem information),
which is later used to create and export the hub module.
Module will be saved inside the ckpt_dir.
Args:
model_name: name of the model to be exported.
hparams: T2T parameters, m... | codesearchnet |
def to_dict(self):
return {'all_set': self._is_all_set(), 'progress': self.progress(), 'values': {property_name: (getattr(self, property_name) or []) for property_name in worker_mapping().keys()}} | This method is used in with connection to REST API. It basically
converts all important properties to dictionary, which may be used by
frontend.
Returns:
dict: ``{"all_set": bool, "progress": [int(done), int(how_many)], \
"values": {"property": [values], ..}}`` | codesearchnet |
def get_output(self):
template_function = TEMPLATE_WRAPPER.format(function_name=self.js_function_name, template_code=self.output.getvalue()).strip()
module_format = JS_MODULE_FORMATS[self.js_module_format]
return module_format(self.dependencies, template_function) | Returns the generated JavaScript code.
Returns:
str | codesearchnet |
def fix_docstring(obj: Any, old_doc_args: str, new_doc_args: str):
source, line_number = inspect.getsourcelines(obj)
idx = 0
while idx < len(source) and _re_args.search(source[idx]) is None:
idx += 1
if idx == len(source):
return
indent = find_indent(source[idx])
idx += 1
sta... | Fixes the docstring of an object by replacing its arguments documentation by the one matched with the signature.
Args:
obj (`Any`):
The object whose dostring we are fixing.
old_doc_args (`str`):
The current documentation of the parameters of `obj` in the docstring (as returned by
`match_docstring_with_signature`).
new... | github-repos |
def create_summary_metadata(hparams_plugin_data_pb):
if not isinstance(hparams_plugin_data_pb, plugin_data_pb2.HParamsPluginData):
raise TypeError('Needed an instance of plugin_data_pb2.HParamsPluginData.'
' Got: %s' % type(hparams_plugin_data_pb))
content = plugin_data_pb2.HParamsPluginD... | Returns a summary metadata for the HParams plugin.
Returns a summary_pb2.SummaryMetadata holding a copy of the given
HParamsPluginData message in its plugin_data.content field.
Sets the version field of the hparams_plugin_data_pb copy to
PLUGIN_DATA_VERSION.
Args:
hparams_plugin_data_pb: the HParamsPluginData protobu... | juraj-google-style |
def construct_lanczos_params(self):
self.min_eigen_vec = autograph.to_graph(utils.tf_lanczos_smallest_eigval)
def _m_vector_prod_fn(x):
return self.get_psd_product(x, dtype=self.lanczos_dtype)
def _h_vector_prod_fn(x):
return self.get_h_product(x, dtype=self.lanczos_dtype)
... | Computes matrices T and V using the Lanczos algorithm.
Args:
k: number of iterations and dimensionality of the tridiagonal matrix
Returns:
eig_vec: eigen vector corresponding to min eigenvalue | juraj-google-style |
def IsDevice(self):
if (self._stat_object is None):
self._stat_object = self._GetStat()
if (self._stat_object is not None):
self.entry_type = self._stat_object.type
return (self.entry_type == definitions.FILE_ENTRY_TYPE_DEVICE) | Determines if the file entry is a device.
Returns:
bool: True if the file entry is a device. | codesearchnet |
class GeneratorEnqueuer(SequenceEnqueuer):
def __init__(self, generator, use_multiprocessing=False, random_seed=None):
super(GeneratorEnqueuer, self).__init__(generator, use_multiprocessing)
self.random_seed = random_seed
def _get_executor_init(self, workers):
def pool_fn(seq... | Builds a queue out of a data generator.
The provided generator can be finite in which case the class will throw
a `StopIteration` exception.
Args:
generator: a generator function which yields data
use_multiprocessing: use multiprocessing if True, otherwise threading
random_seed: Initial seed for workers,
will be incr... | github-repos |
def __init__(self, obj):
if distob.engine is None:
setup_engines()
if isinstance(obj, Ref):
self._ref = obj
self.is_local = (self._ref.id.engine is distob.engine.eid)
else:
self._ref = Ref(obj)
self.is_local = True
if s... | Set up the Remote* proxy object to access an already-existing object,
which may be local or remote.
Args:
obj (Ref or object): either a Ref reference to the (possibly remote)
object to be controlled, or else an actual (local) object to be
controlled. | juraj-google-style |
async def update_state(self, short_name, state):
if (short_name not in self.services):
raise ArgumentError('Service name is unknown', short_name=short_name)
if (state not in states.KNOWN_STATES):
raise ArgumentError('Invalid service state', state=state)
serv = self.services[short_name]['stat... | Set the current state of a service.
If the state is unchanged from a previous attempt, this routine does
nothing.
Args:
short_name (string): The short name of the service
state (int): The new stae of the service | codesearchnet |
def add_institute(self, institute_obj):
internal_id = institute_obj['internal_id']
display_name = institute_obj['internal_id']
if self.institute(institute_id=internal_id):
raise IntegrityError("Institute {0} already exists in database"
... | Add a institute to the database
Args:
institute_obj(Institute) | juraj-google-style |
def load(self, key_filter=None, header_preproc=None):
df = pd.read_csv(self.input_file, sep='\t', dtype=object)
if (key_filter is not None):
df = df[df[df.columns[0]].str.match(key_filter)]
meta_col = df.columns[0]
df[meta_col] = df[meta_col].str.split(',').str[(- 1)]
for col_name in df.colu... | Load data table from tsv file, from default location
Args:
key_filter (str): additional filter for key column - regex matching
key values to include; None for no filter
header_preproc (func): function to apply to column headers to extract year numbers (as strings)
Returns:
pd.DataFrame: data | codesearchnet |
def json_to_url(json, symbol):
start = json[0]['date']
end = json[(- 1)]['date']
diff = (end - start)
periods = [300, 900, 1800, 7200, 14400, 86400]
diffs = {}
for p in periods:
diffs[p] = abs((1 - (p / (diff / len(json)))))
period = min(diffs, key=diffs.get)
url = 'https:
re... | Converts a JSON to a URL by the Poloniex API
Args:
json: JSON data as a list of dict dates, where the keys are
the raw market statistics.
symbol: String of currency pair, like a ticker symbol.
Returns:
String URL to Poloniex API representing the given JSON. | codesearchnet |
def validate_filename(filename, white_list_formats):
return filename.lower().endswith(white_list_formats) and os.path.isfile(filename) | Check if a filename refers to a valid file.
Args:
filename: String, absolute path to a file
white_list_formats: Set, allowed file extensions
Returns:
A boolean value indicating if the filename is valid or not | github-repos |
def CopyToDateTimeStringISO8601(self):
date_time_string = self.CopyToDateTimeString()
if date_time_string:
date_time_string = date_time_string.replace(' ', 'T')
date_time_string = '{0:s}Z'.format(date_time_string)
return date_time_string | Copies the date time value to an ISO 8601 date and time string.
Returns:
str: date and time value formatted as an ISO 8601 date and time string or
None if the timestamp cannot be copied to a date and time string. | codesearchnet |
def loadfile(method=True, writable=False, create=False):
def convert_file_args(args, kwargs):
filething = args[0] if args else None
filename = kwargs.pop("filename", None)
fileobj = kwargs.pop("fileobj", None)
return filething, filename, fileobj, args[1:], kwargs
def wrap(... | A decorator for functions taking a `filething` as a first argument.
Passes a FileThing instance as the first argument to the wrapped function.
Args:
method (bool): If the wrapped functions is a method
writable (bool): If a filename is passed opens the file readwrite, if
passed a file object verifies that it is writab... | juraj-google-style |
def _ParseKeywordArgs(args, fn_spec):
kwargs = {}
remaining_kwargs = []
remaining_args = []
fn_keywords = fn_spec.varkw
fn_args = fn_spec.args + fn_spec.kwonlyargs
if not args:
return (kwargs, remaining_kwargs, remaining_args)
skip_argument = False
for index, argument in enumerat... | Parses the supplied arguments for keyword arguments.
Given a list of arguments, finds occurrences of --name value, and uses 'name'
as the keyword and 'value' as the value. Constructs and returns a dictionary
of these keyword arguments, and returns a list of the remaining arguments.
Only if fn_keywords is None, this o... | github-repos |
def get_instance(self):
return Instance(self.rest_client.make_request(self.instance), self.rest_client) | Get the Streams instance that owns this view.
Returns:
Instance: Streams instance owning this view. | codesearchnet |
def get_adif_id(self, callsign, timestamp=timestamp_now):
return self.get_all(callsign, timestamp)[const.ADIF] | Returns ADIF id of a callsign's country
Args:
callsign (str): Amateur Radio callsign
timestamp (datetime, optional): datetime in UTC (tzinfo=pytz.UTC)
Returns:
int: containing the country ADIF id
Raises:
KeyError: No Country found for callsign | juraj-google-style |
def check_output(self, want, got, optionflags):
if got and (not want):
return True
if want is None:
want = ''
if want == got:
return True
want = self._ADDRESS_RE.sub('at ...>', want)
want, want_changed = self._tf_tensor_numpy_output(want)
if want_changed:
got, _ =... | Compares the docstring output to the output gotten by running the code.
Python addresses in the output are replaced with wildcards.
Float values in the output compared as using `np.allclose`:
* Float values are extracted from the text and replaced with wildcards.
* The wildcard text is compared to the actual output.... | github-repos |
def suggest(self, query):
res, suggest = self.search(query, results=1, suggestion=True)
try:
title = suggest or res[0]
except IndexError:
title = None
return title | Gather suggestions based on the provided title or None if no
suggestions found
Args:
query (str): Page title
Returns:
String or None: Suggested page title or **None** if no \
suggestion found | juraj-google-style |
def _QueryProcessStatus(self, process):
process_is_alive = process.is_alive()
if process_is_alive:
rpc_client = self._rpc_clients_per_pid.get(process.pid, None)
process_status = rpc_client.CallFunction()
else:
process_status = None
return process_status | Queries a process to determine its status.
Args:
process (MultiProcessBaseProcess): process to query for its status.
Returns:
dict[str, str]: status values received from the worker process. | juraj-google-style |
def get_end_start_epochs(year, month, day, direction, unit, count):
if (year or month or day):
if (not year):
year = 2017
if (not month):
month = 1
if (not day):
day = 1
initial_delorean = date_to_delorean(year, month, day)
else:
count ... | Gets epoch from a start date and epoch from a shifted date
Args:
year: Int between 1 and 9999.
month: Int between 1 and 12.
day: Int between 1 and 31.
direction: String to shift time forwards or backwards.
Valid values: 'last', 'next'.
unit: String of time period unit for count argument.
How far back to check historic... | codesearchnet |
def _MakeServiceDescriptor(self, service_proto, service_index, scope, package, file_desc):
if package:
service_name = '.'.join((package, service_proto.name))
else:
service_name = service_proto.name
methods = [self._MakeMethodDescriptor(method_proto, service_name, package, scope, index) for (... | Make a protobuf ServiceDescriptor given a ServiceDescriptorProto.
Args:
service_proto: The descriptor_pb2.ServiceDescriptorProto protobuf message.
service_index: The index of the service in the File.
scope: Dict mapping short and full symbols to message and enum types.
package: Optional package name for the new messag... | codesearchnet |
def _GetContainerTypes(self):
self._cursor.execute(self._TABLE_NAMES_QUERY)
table_names = [row[0] for row in self._cursor.fetchall()]
return [table_name for table_name in self._CONTAINER_TYPES if (table_name in table_names)] | Retrieves the container types to merge.
Container types not defined in _CONTAINER_TYPES are ignored and not merged.
Specific container types reference other container types, such
as event referencing event data. The names are ordered to ensure the
attribute containers are merged in the correct order.
Returns:
list[s... | codesearchnet |
def squeeze_batch_dims(inp, op, inner_rank):
with ops.name_scope_v2('squeeze_batch_dims'):
shape = inp.shape
inner_shape = shape[-inner_rank:]
if not inner_shape.is_fully_defined():
inner_shape = array_ops.shape(inp)[-inner_rank:]
batch_shape = shape[:-inner_rank]
... | Returns `unsqueeze_batch(op(squeeze_batch(inp)))`.
Where `squeeze_batch` reshapes `inp` to shape
`[prod(inp.shape[:-inner_rank])] + inp.shape[-inner_rank:]`
and `unsqueeze_batch` does the reverse reshape but on the output.
Args:
inp: A tensor with dims `batch_shape + inner_shape` where `inner_shape`
is length `inner_... | github-repos |
def _set_initial_contents(self, contents):
contents = self._encode_contents(contents)
changed = self._byte_contents != contents
st_size = len(contents)
if self._byte_contents:
self.size = 0
current_size = self.st_size or 0
self.filesystem.change_disk... | Sets the file contents and size.
Called internally after initial file creation.
Args:
contents: string, new content of file.
Returns:
True if the contents have been changed.
Raises:
IOError: if the st_size is not a non-negative integer,
or if st_size exceeds the available file system space | juraj-google-style |
def attach(self, droplet_id, region):
return self.get_data(('volumes/%s/actions/' % self.id), type=POST, params={'type': 'attach', 'droplet_id': droplet_id, 'region': region}) | Attach a Volume to a Droplet.
Args:
droplet_id: int - droplet id
region: string - slug identifier for the region | codesearchnet |
def read(file_path):
actual_file_path = os.path.expanduser(file_path)
with open(actual_file_path, 'r') as f:
lines = f.readlines()
gmt = []
for (line_num, line) in enumerate(lines):
fields = line.split('\t')
assert (len(fields) > 2), ('Each line must have at least 3 tab-delimited... | Read a gmt file at the path specified by file_path.
Args:
file_path (string): path to gmt file
Returns:
gmt (GMT object): list of dicts, where each dict corresponds to one
line of the GMT file | codesearchnet |
def __init__(self, estimator, logdir=None):
threading.Thread.__init__(self)
self.event = threading.Event()
self.estimator = estimator
self.logdir = logdir or tempfile.mkdtemp() | Initialize ``Tensorboard`` instance.
Args:
estimator (sagemaker.estimator.Framework): A SageMaker ``Estimator``.
logdir (str): Directory for logs (default: None). If not specified, a temporary directory is made. | juraj-google-style |
def dp020(self, value=None):
if value is not None:
try:
value = float(value)
except ValueError:
raise ValueError('value {} need to be of type float '
'for field `dp020`'.format(value))
self._dp020 = value | Corresponds to IDD Field `dp020`
Dew-point temperature corresponding to 2.0% annual cumulative frequency of occurrence
Args:
value (float): value for IDD Field `dp020`
Unit: C
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... | juraj-google-style |
def array(self, dimensions=None):
if (dimensions is None):
dims = [d for d in (self.kdims + self.vdims)]
else:
dims = [self.get_dimension(d, strict=True) for d in dimensions]
(columns, types) = ([], [])
for dim in dims:
column = self.dimension_values(dim)
columns.append(c... | Convert dimension values to columnar array.
Args:
dimensions: List of dimensions to return
Returns:
Array of columns corresponding to each dimension | codesearchnet |
def _find_cellid(self, code):
from difflib import SequenceMatcher
maxvalue = 0.
maxid = None
for cellid, c in self.cellids.items():
matcher = SequenceMatcher(a=c, b=code)
ratio = matcher.quick_ratio()
if ratio > maxvalue and ratio > 0... | Determines the most similar cell (if any) to the specified code. It
must have at least 50% overlap ratio and have been a loop-intercepted
cell previously.
Args:
code (str): contents of the code cell that were executed. | juraj-google-style |
def add_input(self, *args, **kwargs):
return self._inputs.add(*args, **kwargs) | Add a wrapped input argument to the hint.
Args:
*args: The input tensor.
**kwargs:
"name" label
"tag" a tag to group multiple arguments that will be aggregated. I.e.
a string like 'cool_input'. Basically multiple inputs can be added
to the same hint for parallel operations that will eventually be
combined. An example ... | github-repos |
def fullpath(self):
return str(os.path.join(self.path, self.directory)) | Full path to the Mackup configuration files.
The full path to the directory when Mackup is storing the configuration
files.
Returns:
str | codesearchnet |
def absolute_url(self):
if self.is_root():
return utils.concat_urls(self.url)
return utils.concat_urls(self.parent.absolute_url, self.url) | Get the absolute url of ``self``.
Returns:
str: the absolute url. | codesearchnet |
def extract_github_repo_owner_and_name(url):
_check_github_url_is_supported(url)
parts = get_parts_of_url_path(url)
repo_owner = parts[0]
repo_name = parts[1]
return repo_owner, _strip_trailing_dot_git(repo_name) | Given an URL, return the repo name and who owns it.
Args:
url (str): The URL to the GitHub repository
Raises:
ValueError: on url that aren't from github
Returns:
str, str: the owner of the repository, the repository name | juraj-google-style |
def restore_collection(backup):
for k, v in six.iteritems(backup):
del tf.get_collection_ref(k)[:]
tf.get_collection_ref(k).extend(v) | Restore from a collection backup.
Args:
backup (dict): | juraj-google-style |
def fragment_search(self, fragement:str) -> List[dict]:
fragement = self.extract_fragment(fragement)
ilx_rows = self.fragment2rows.get(fragement)
if not ilx_rows:
return None
else:
return ilx_rows | Returns the rows in InterLex associated with the fragment
Note:
Pressumed to have duplicate fragements in InterLex
Args:
fragment: The fragment_id of the curie pertaining to the ontology
Returns:
None or List[dict] | juraj-google-style |
def predict_proba(self, x, y=None, **kwargs):
if (self.clf is None):
raise ValueError('Model has to be trained before making predictions.')
if (x is pandas.Series):
input_ = self.featurize_row(x.iloc[0], x.iloc[1]).reshape((1, (- 1)))
elif (x is pandas.DataFrame):
input_ = np.array([... | Predict the causal score using a trained RCC model
Args:
x (numpy.array or pandas.DataFrame or pandas.Series): First variable or dataset.
args (numpy.array): second variable (optional depending on the 1st argument).
Returns:
float: Causation score (Value : 1 if a->b and -1 if b->a) | codesearchnet |
def round_f1(y_true, y_predicted):
try:
predictions = [np.round(x) for x in y_predicted]
except TypeError:
predictions = y_predicted
return f1_score(y_true, predictions) | Calculates F1 (binary) measure.
Args:
y_true: list of true values
y_predicted: list of predicted values
Returns:
F1 score | juraj-google-style |
def StaticAdd(cls, queue_urn, rdf_value, mutation_pool=None):
if (not isinstance(rdf_value, cls.rdf_type)):
raise ValueError(('This collection only accepts values of type %s.' % cls.rdf_type.__name__))
if (mutation_pool is None):
raise ValueError("Mutation pool can't be none.")
timestamp = r... | Adds an rdf value the queue.
Adds an rdf value to a queue. Does not require that the queue be locked, or
even open. NOTE: The caller is responsible for ensuring that the queue
exists and is of the correct type.
Args:
queue_urn: The urn of the queue to add to.
rdf_value: The rdf value to add to the queue.
mutation_p... | codesearchnet |
def _VerifyValues(self, image, ksizes, strides, rates, padding, patches):
ksizes = [1] + ksizes + [1]
strides = [1] + strides + [1]
rates = [1] + rates + [1]
for dtype in [np.float16, np.float32, np.float64, dtypes.bfloat16.as_numpy_dtype]:
out_tensor = array_ops.extract_image_patches(constant_o... | Tests input-output pairs for the ExtractImagePatches op.
Args:
image: Input tensor with shape: [batch, in_rows, in_cols, depth].
ksizes: Patch size specified as: [ksize_rows, ksize_cols].
strides: Output strides, specified as [stride_rows, stride_cols].
rates: Atrous rates, specified as [rate_rows, rate_cols].
padding... | github-repos |
def assert_rank(x, rank, data=None, summarize=None, message=None, name=None):
with ops.name_scope(name, 'assert_rank', (x, rank) + tuple(data or [])):
if not isinstance(x, sparse_tensor.SparseTensor):
x = ops.convert_to_tensor(x, name='x')
rank = ops.convert_to_tensor(rank, name='rank')
... | Assert `x` has rank equal to `rank`.
Example of adding a dependency to an operation:
```python
with tf.control_dependencies([tf.compat.v1.assert_rank(x, 2)]):
output = tf.reduce_sum(x)
```
Args:
x: Numeric `Tensor`.
rank: Scalar integer `Tensor`.
data: The tensors to print out if the condition is False. Defaults... | github-repos |
def anti_join(df, other, **kwargs):
(left_on, right_on, suffixes) = get_join_parameters(kwargs)
if (not right_on):
right_on = [col_name for col_name in df.columns.values.tolist() if (col_name in other.columns.values.tolist())]
left_on = right_on
elif (not isinstance(right_on, (list, tuple)))... | Returns all of the rows in the left DataFrame that do not have a
match in the right DataFrame.
Args:
df (pandas.DataFrame): Left DataFrame (passed in via pipe)
other (pandas.DataFrame): Right DataFrame
Kwargs:
by (str or list): Columns to join on. If a single string, will join
on that column. If a list of lists which... | codesearchnet |
def get_config(filepath=None, default_loader=None, on_missing=None):
cache_key = (filepath, default_loader, on_missing)
if (CACHE.get(cache_key) is not None):
return CACHE.get(cache_key)
logger = logging.getLogger('birding')
if (filepath is None):
filepath = BIRDING_CONF
if (default_... | Get a dict for the current birding configuration.
The resulting dictionary is fully populated with defaults, such that all
valid keys will resolve to valid values. Invalid and extra values in the
configuration result in an exception.
See :ref:`config` (module-level docstring) for discussion on how birding
configurati... | codesearchnet |
def cancelRealTimeBars(self, bars: RealTimeBarList):
self.client.cancelRealTimeBars(bars.reqId)
self.wrapper.endSubscription(bars) | Cancel the realtime bars subscription.
Args:
bars: The bar list that was obtained from ``reqRealTimeBars``. | juraj-google-style |
def getConfigPath(configFileName=None):
paths = {}
applicationPath = './'
if (sys.platform == 'win32'):
applicationPath = os.path.expanduser(os.path.join('~\\', 'OSRFramework'))
else:
applicationPath = os.path.expanduser(os.path.join('~/', '.config', 'OSRFramework'))
paths = {'appPat... | Auxiliar function to get the configuration paths depending on the system
Args:
-----
configFileName: TODO.
Returns:
--------
A dictionary with the following keys: appPath, appPathDefaults,
appPathTransforms, appPathPlugins, appPathPatterns, appPathPatterns. | codesearchnet |
def summarize(self, geom, stat=None):
if not hasattr(geom, 'num_coords'):
raise TypeError('Need OGR or GEOS geometry, %s found' % type(geom))
clone = self._clone()
for obj in clone:
arr = obj.array(geom)
if arr is not None:
if stat:
... | Returns a new RasterQuerySet with subsetted/summarized ndarrays.
Arguments:
geom -- geometry for masking or spatial subsetting
Keyword args:
stat -- any numpy summary stat method as str (min/max/mean/etc) | juraj-google-style |
def save_with_exif_info(img, *args, **kwargs):
if ('exif' in kwargs):
exif = kwargs.pop('exif')
else:
exif = img.info.get('exif')
img.save(*args, exif=exif, **kwargs) | Saves an image using PIL, preserving the exif information.
Args:
img (PIL.Image.Image):
*args: The arguments for the `save` method of the Image class.
**kwargs: The keywords for the `save` method of the Image class. | codesearchnet |
def Shell(self, command, timeout_ms=None):
return self.protocol_handler.Command(
self._handle, service=b'shell', command=command,
timeout_ms=timeout_ms) | Run command on the device, returning the output.
Args:
command: Shell command to run
timeout_ms: Maximum time to allow the command to run. | juraj-google-style |
def _write_reqs(amend: bool=False, stage: bool=False):
LOGGER.info('writing requirements')
base_cmd = 'pipenv lock -r'
_write_reqs_file(f'{base_cmd}', 'requirements.txt')
_write_reqs_file(f'{base_cmd} -d', 'requirements-dev.txt')
files_to_add = ['Pipfile', 'requirements.txt', 'requirements-dev.txt']... | Writes the requirement files
Args:
amend: amend last commit with changes
stage: stage changes | codesearchnet |
def _HashRow(cls, row):
values = []
for value in row:
try:
value = '{0!s}'.format(value)
except UnicodeDecodeError:
value = repr(value)
values.append(value)
return hash(' '.join(values)) | Hashes the given row.
Args:
row (sqlite3.Row): row.
Returns:
int: hash value of the given row. | juraj-google-style |
def apply(self, var, props, reverse=False):
vs, vid = sort_vid_split(var)
if reverse:
tms = []
else:
tms = [(a, op, b) for a, op, b in self._typemap if op in _LR_OPS]
for src, op, tgt in tms:
if _valmatch([vs], src, o... | Apply the VPM to variable *var* and properties *props*.
Args:
var: a variable
props: a dictionary mapping properties to values
reverse: if `True`, apply the rules in reverse (e.g. from
grammar-external to grammar-internal forms)
Returns:
a tuple (v, p) of the mapped variable and properties | juraj-google-style |
def _IsIdentifier(cls, string):
return (string and (not string[0].isdigit()) and all(((character.isalnum() or (character == '_')) for character in string))) | Checks if a string contains an identifier.
Args:
string (str): string to check.
Returns:
bool: True if the string contains an identifier, False otherwise. | codesearchnet |
def flatten(repertoire, big_endian=False):
if repertoire is None:
return None
order = 'C' if big_endian else 'F'
return repertoire.squeeze().ravel(order=order) | Flatten a repertoire, removing empty dimensions.
By default, the flattened repertoire is returned in little-endian order.
Args:
repertoire (np.ndarray or None): A repertoire.
Keyword Args:
big_endian (boolean): If ``True``, flatten the repertoire in big-endian
order.
Returns:
np.ndarray: The flattened repertoire. | juraj-google-style |
def _faster_to_representation(self, instance):
ret = {}
fields = self._readable_fields
is_fast = isinstance(instance, prefetch.FastObject)
id_fields = self._readable_id_fields
for field in fields:
attribute = None
if ... | Modified to_representation with optimizations.
1) Returns a plain old dict as opposed to OrderedDict.
(Constructing ordered dict is ~100x slower than `{}`.)
2) Ensure we use a cached list of fields
(this optimization exists in DRF 3.2 but not 3.1)
Arguments:
instance: a model instance or data object
Returns:
Dict of ... | juraj-google-style |
def _CreateIndexIfNotExists(self, index_name, mappings):
try:
if not self._client.indices.exists(index_name):
self._client.indices.create(
body={'mappings': mappings}, index=index_name)
except elasticsearch.exceptions.ConnectionError as exception:
raise RuntimeError(
... | Creates an Elasticsearch index if it does not exist.
Args:
index_name (str): mame of the index.
mappings (dict[str, object]): mappings of the index.
Raises:
RuntimeError: if the Elasticsearch index cannot be created. | juraj-google-style |
def make_flat_list_of_images(images: Union[list[ImageInput], ImageInput]) -> ImageInput:
if isinstance(images, (list, tuple)) and all((isinstance(images_i, (list, tuple)) for images_i in images)) and all((is_valid_list_of_images(images_i) for images_i in images)):
return [img for img_list in images for img ... | Ensure that the output is a flat list of images. If the input is a single image, it is converted to a list of length 1.
If the input is a nested list of images, it is converted to a flat list of images.
Args:
images (`Union[List[ImageInput], ImageInput]`):
The input image.
Returns:
list: A list of images or a 4d array ... | github-repos |
def run(self, gin):
with ScratchDir('.'):
p = subprocess.Popen(self._gulp_cmd, stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.PIPE)
(out, err) = p.communicate(bytearray(gin, 'utf-8'))
out = out.decode('utf-8')
err = err.decode('utf-8')
if (('Error' in err) o... | Run GULP using the gin as input
Args:
gin: GULP input string
Returns:
gout: GULP output string | codesearchnet |
def freeze(self, permanent_value: Any=utils.MISSING_VALUE, apply_before_use: bool=True) -> 'ValueSpec': | Sets the default value using a permanent value and freezes current spec.
A frozen value spec will not accept any value that is not the default
value. A frozen value spec is useful when a subclass fixes the value of a
symoblic attribute and want to prevent it from being modified.
Args:
permanent_value: A permanent val... | github-repos |
def _fork_children_processes(name, successors):
logging.info('Process "%s" started, PID: %d!', name, os.getpid())
children_process = [multiprocessing.Process(target=_fork_children_processes, args=args) for args in successors]
for child_process in children_process:
child_process.start()
if 'child... | Forks children processes and its descendants recursively.
Args:
name: The name of this process.
successors: The args for the descendant processes. | github-repos |
def _check_error(self, response, json_response=None):
if (response.status_code >= 400):
json_response = (json_response or self._get_json_response(response))
err_cls = self._check_http_error_code(response.status_code)
try:
raise err_cls(('%s error: %s' % (response.status_code, jso... | Check for HTTP error code from the response, raise exception if there's any
Args:
response (object): Object returned by requests' `get` and `post`
methods
json_response (dict): JSON response, if applicable
Raises:
HTTPError: If the status code of response is either 4xx or 5xx
Returns:
True if status code is not err... | codesearchnet |
def resolve_one_of(tags, at_least_one):
if (len(tags) < len(at_least_one)):
return None
for possible_resolution in choose_1_from_each(at_least_one):
resolution = {}
pr = possible_resolution[:]
for entity_type in pr:
last_end_index = (- 1)
if (entity_type i... | This searches tags for Entites in at_least_one and returns any match
Args:
tags(list): List of tags with Entities to search for Entities
at_least_one(list): List of Entities to find in tags
Returns:
object: returns None if no match is found but returns any match as an object | codesearchnet |
def _shape_invariant_to_type_spec(var, shape=None):
var = _convert_tensorarray_to_flow(var)
if shape is None:
return type_spec.type_spec_from_value(var)
elif isinstance(shape, type_spec.TypeSpec):
if not shape.is_compatible_with(var):
raise TypeError('TypeSpec %r is not compatibl... | Converts a shape invariant to a TypeSpec.
If `var` is a TensorArray, it will first be converted to its flow.
Args:
var: The tensor, tensor array or composite tensor whose shape is described
by the shape invariant.
shape: A `TypeSpec` or `TensorShape`. If `shape` is already a `TypeSpec`,
then it is simply returned as... | github-repos |
def _collect_feature_info(self, candidate_feature_diffs):
project_root = self.project.path
for diff in candidate_feature_diffs:
path = diff.b_path
modname = relpath_to_modname(path)
modpath = project_root.joinpath(path)
importer = partial(import_module_at_path, modname, modpath)
... | Collect feature info
Args:
candidate_feature_diffs (List[git.diff.Diff]): list of Diffs
corresponding to admissible file changes compared to
comparison ref
Returns:
List[Tuple]: list of tuple of importer, module name, and module
path. The "importer" is a callable that returns a module | codesearchnet |
def query_blockchain_events(
web3: Web3,
contract_manager: ContractManager,
contract_address: Address,
contract_name: str,
topics: List,
from_block: BlockNumber,
to_block: BlockNumber,
) -> List[Dict]:
filter_params = {
'fromBlock': from_block,
... | Returns events emmitted by a contract for a given event name, within a certain range.
Args:
web3: A Web3 instance
contract_manager: A contract manager
contract_address: The address of the contract to be filtered, can be `None`
contract_name: The name of the contract
topics: The topics to filter for
from_block: The blo... | juraj-google-style |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.