code stringlengths 20 4.93k | docstring stringlengths 33 1.27k | source stringclasses 3
values |
|---|---|---|
def __call__(self, shape, dtype=dtypes.float32, **kwargs):
self._validate_kwargs(kwargs)
dtype = dtypes.as_dtype(dtype)
if not dtype.is_numpy_compatible or dtype == dtypes.string:
raise ValueError(f'Argument `dtype` expected to be numeric or boolean. Received {dtype}.')
if _PARTITION_SHAPE in kw... | Returns a tensor object initialized as specified by the initializer.
Args:
shape: Shape of the tensor.
dtype: Optional dtype of the tensor. Only numeric or boolean dtypes are
supported.
**kwargs: Additional keyword arguments.
Raises:
ValuesError: If the dtype is not numeric or boolean. | github-repos |
class SessionRunValues(collections.namedtuple('SessionRunValues', ['results', 'options', 'run_metadata'])): | Contains the results of `Session.run()`.
In the future we may use this object to add more information about result of
run without changing the Hook API.
Args:
results: The return values from `Session.run()` corresponding to the fetches
attribute returned in the RunArgs. Note that this has the same shape as
the RunArg... | github-repos |
def write_payload(payload=None, objectInput=None):
temp = tempfile.mkstemp()[1]
log.debug("Write payload in temp file {!r}".format(temp))
with open(temp, 'wb') as f:
if payload:
payload = base64.b64decode(payload)
elif objectInput:
if six.PY3:
p... | This function writes a base64 payload or file object on disk.
Args:
payload (string): payload in base64
objectInput (object): file object/standard input to analyze
Returns:
Path of file | juraj-google-style |
def _factored_dims(self, shape):
if ((not self._factored) or (shape.ndims < 2)):
return None
sorted_dims = sorted(shape.dims, key=(lambda d: (- d.size)))
if (sorted_dims[1].size < self._min_dim_size_to_factor):
return None
return sorted_dims[:2] | Should we use a factored second moment estimator.
Based on the shape of the variable.
If we factor the accumulator, then this function returns a list of two
mtf.Dimensions to reduce over. We always pick the two largest dimensions.
If there are not two dimensions of size >= min_dim_size_to_factor, then we
do not facto... | codesearchnet |
def _set_options_from_file(self, file_handle):
options = []
line_number = 0
section = None
for line in file_handle.read().splitlines():
line_number += 1
orig_line = line
l... | Parses a unit file and updates self._data['options']
Args:
file_handle (file): a file-like object (supporting read()) containing a unit
Returns:
True: The file was successfuly parsed and options were updated
Raises:
IOError: from_file was specified and it does not exist
ValueError: The unit contents specified in fro... | juraj-google-style |
def short(cls, path):
if not path:
return path
path = str(path)
if cls.paths:
for p in cls.paths:
if p:
path = path.replace(p + "/", "")
path = path.replace(cls.home, "~")
return path | Example:
short("examined /Users/joe/foo") => "examined ~/foo"
Args:
path: Path to represent in its short form
Returns:
(str): Short form, using '~' if applicable | juraj-google-style |
def _previous_block_never_completed(self, current_block, previous_block, new_state):
if previous_block:
previously_timing_block = previous_block.status_code in _InstrumentationStatusCodeCategories.TIMING
currently_new_block = current_block.status_code == _InstrumentationStatusCodes.START or new_stat... | Checks if the previous instrumentation method block completed.
Args:
current_block: _InstrumentationBlock, the current instrumentation
block to check for being a different instrumentation test
method.
previous_block: _InstrumentationBlock, rhe previous
instrumentation block to check for an incomplete status.
new_state... | github-repos |
def binary_crossentropy(target, output, from_logits=False):
target = tf.convert_to_tensor(target)
output = tf.convert_to_tensor(output)
if len(target.shape) != len(output.shape):
raise ValueError(f'Arguments `target` and `output` must have the same rank (ndim). Received: target.shape={target.shape},... | Binary crossentropy between an output tensor and a target tensor.
Args:
target: A tensor with the same shape as `output`.
output: A tensor.
from_logits: Whether `output` is expected to be a logits tensor.
By default, we consider that `output`
encodes a probability distribution.
Returns:
A tensor. | github-repos |
def from_api_repr(cls, resource):
etag = resource.get("etag")
if etag is not None:
resource = resource.copy()
resource["etag"] = base64.b64decode(etag.encode("ascii"))
return super(Policy, cls).from_api_repr(resource) | Factory: create a policy from a JSON resource.
Overrides the base class version to store :attr:`etag` as bytes.
Args:
resource (dict): JSON policy resource returned by the
``getIamPolicy`` REST API.
Returns:
:class:`Policy`: the parsed policy | juraj-google-style |
def _get_log_file(self, handler):
if ('file_name_pattern' not in handler):
filename = '%Y-%m-%d-%H-%M-%S-{name}.pcap'
else:
filename = handler['file_name_pattern']
log_file = handler['log_dir']
if ('path' in handler):
log_file = os.path.join(log_file, handler['path'], filename)
... | Generate log file path for a given handler
Args:
handler:
The handler configuration dictionary for which a log file
path should be generated. | codesearchnet |
def no_selenium_errors(func):
def _inner(*args, **kwargs):
try:
return_val = func(*args, **kwargs)
except WebDriverException:
LOGGER.warning(u'Exception ignored during retry loop:', exc_info=True)
return False
else:
return return_val
retur... | Decorator to create an `EmptyPromise` check function that is satisfied
only when `func` executes without a Selenium error.
This protects against many common test failures due to timing issues.
For example, accessing an element after it has been modified by JavaScript
ordinarily results in a `StaleElementException`. M... | codesearchnet |
def from_file(feff_inp_file='feff.inp', ldos_file='ldos'):
header_str = Header.header_string_from_file(feff_inp_file)
header = Header.from_string(header_str)
structure = header.struct
nsites = structure.num_sites
parameters = Tags.from_file(feff_inp_file)
if "RE... | Creates LDos object from raw Feff ldos files by
by assuming they are numbered consecutively, i.e. ldos01.dat
ldos02.dat...
Args:
feff_inp_file (str): input file of run to obtain structure
ldos_file (str): output ldos file of run to obtain dos info, etc. | juraj-google-style |
def flag(self, diagnostic, thresh=None):
if thresh is None:
thresh = self.defaults[diagnostic]
result = self.results[diagnostic]
if isinstance(result, pd.DataFrame):
if diagnostic == 'CorrelationMatrix':
result = result.copy()
np.... | Returns indices of diagnostic that satisfy (return True from) the
threshold predicate. Will use class-level default threshold if
None provided.
Args:
diagnostic (str): name of the diagnostic
thresh (func): threshold function (boolean predicate) to apply to
each element | juraj-google-style |
def __init__(self, learning_rate, l1_regularization_strength=0.0, l2_regularization_strength=0.0, use_locking=False, name='ProximalGradientDescent'):
super(ProximalGradientDescentOptimizer, self).__init__(use_locking, name)
self._learning_rate = learning_rate
self._l1_regularization_strength = l1_regulariza... | Construct a new proximal gradient descent optimizer.
Args:
learning_rate: A Tensor or a floating point value. The learning
rate to use.
l1_regularization_strength: A float value, must be greater than or
equal to zero.
l2_regularization_strength: A float value, must be greater than or
equal to zero.
use_locking: If Tr... | github-repos |
def is_ordered(cat_id):
url = 'https:
auth = Auth()
r = _req_with_retries(auth.gbdx_connection, url)
if r is not None:
return r.status_code == 200
return False | Checks to see if a CatalogID has been ordered or not.
Args:
catalogID (str): The catalog ID from the platform catalog.
Returns:
ordered (bool): Whether or not the image has been ordered | juraj-google-style |
def solid_named(self, name):
check.str_param(name, 'name')
if name not in self._solid_dict:
raise DagsterInvariantViolationError(
'Pipeline {pipeline_name} has no solid named {name}.'.format(
pipeline_name=self.name, name=name
)
... | Return the solid named "name". Throws if it does not exist.
Args:
name (str): Name of solid
Returns:
SolidDefinition: SolidDefinition with correct name. | juraj-google-style |
def gpu_devices(devices=None):
return find_devices('GPU', devices) | Gets GPU devices out of `devices`.
Args:
devices: A device list (as a list of strings). If None, the list of all
available devices will be used for it.
Returns:
Those in `devices` that are GPUs. | github-repos |
def sys_save_screenshot(name: Optional[str] = None) -> None:
lib.TCOD_sys_save_screenshot(
_bytes(name) if name is not None else ffi.NULL
) | Save a screenshot to a file.
By default this will automatically save screenshots in the working
directory.
The automatic names are formatted as screenshotNNN.png. For example:
screenshot000.png, screenshot001.png, etc. Whichever is available first.
Args:
file Optional[AnyStr]: File path to save screenshot. | juraj-google-style |
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 | codesearchnet |
def change(script, layer_num=None):
if (layer_num is None):
if isinstance(script, mlx.FilterScript):
layer_num = script.last_layer()
else:
layer_num = 0
filter_xml = ''.join([' <filter name="Change the current layer">\n', ' <Param name="mesh" ', 'value="{:d}" '.format... | Change the current layer by specifying the new layer number.
Args:
script: the mlx.FilterScript object or script filename to write
the filter to.
layer_num (int): the number of the layer to change to. Default is the
last layer if script is a mlx.FilterScript object; if script is a
filename the default is the first lay... | codesearchnet |
def from_file(cls, filename):
with zopen(filename) as f:
return cls.from_string(f.read()) | Read an Fiesta input from a file. Currently tested to work with
files generated from this class itself.
Args:
filename: Filename to parse.
Returns:
FiestaInput object | codesearchnet |
def _free_array(self, handle: int):
with self._lock:
if (self._arrays[handle] is not None):
self._arrays[handle] = None
self._count -= 1 | Frees the memory for the array with the given handle.
Args:
handle: The handle of the array whose memory should be freed. This
handle must come from the _create_array method. | codesearchnet |
def _FormatSocketUnixToken(self, token_data):
protocol = bsmtoken.BSM_PROTOCOLS.get(token_data.socket_family, 'UNKNOWN')
return {
'protocols': protocol,
'family': token_data.socket_family,
'path': token_data.socket_path} | Formats an Unix socket token as a dictionary of values.
Args:
token_data (bsm_token_data_sockunix): AUT_SOCKUNIX token data.
Returns:
dict[str, str]: token values. | juraj-google-style |
def convert_elementwise_add(
params, w_name, scope_name, inputs, layers, weights, names
):
print('Converting elementwise_add ...')
if 'broadcast' in params:
model0 = layers[inputs[0]]
model1 = layers[inputs[1]]
if names == 'short':
tf_name = 'A' + random_string(7)
... | Convert elementwise addition.
Args:
params: dictionary with layer parameters
w_name: name prefix in state_dict
scope_name: pytorch scope name
inputs: pytorch node inputs
layers: dictionary with keras tensors
weights: pytorch state_dict
names: use short names for keras layers | juraj-google-style |
def disconnect_async(self, conn_id, callback):
try:
context = self.conns.get_context(conn_id)
except ArgumentError:
callback(conn_id, self.id, False, "Could not find connection information")
return
self.conns.begin_disconnection(conn_id, callback, s... | Asynchronously disconnect from a device that has previously been connected
Args:
conn_id (int): a unique identifier for this connection on the DeviceManager
that owns this adapter.
callback (callable): A function called as callback(conn_id, adapter_id, success, failure_reason)
when the disconnection finishes. Disconn... | juraj-google-style |
def create_document(self, doc: Dict, mime_type: str = None, url: str = "http:
doc_id=None, type_=None) -> Document:
return Document(self, doc, mime_type, url, doc_id=doc_id).with_type(type_) | Factory method to wrap input JSON docs in an ETK Document object.
Args:
doc (object): a JSON object containing a document in CDR format.
mime_type (str): if doc is a string, the mime_type tells what it is
url (str): if the doc came from the web, specifies the URL for it
doc_id
type_
Returns: wrapped Document | juraj-google-style |
def round(self, decimals=0):
return self.__class__(np.round(self, decimals=decimals)) | Wrapper around numpy.round to ensure object
of same type is returned
Args:
decimals :Number of decimal places to round to (default: 0).
If decimals is negative, it specifies the number of
positions to the left of the decimal point.
Returns (Tensor):
rounded tensor of same type | juraj-google-style |
def _check_disabled(self):
if self.config['check_disabled']:
if (self.config['on_disabled'] == 'withdraw'):
self.log.info('Check is disabled and ip_prefix will be withdrawn')
self.log.info('adding %s in the queue', self.ip_with_prefixlen)
self.action.put(self.del_operatio... | Check if health check is disabled.
It logs a message if health check is disabled and it also adds an item
to the action queue based on 'on_disabled' setting.
Returns:
True if check is disabled otherwise False. | codesearchnet |
def set_task(project_, task_):
global project, task
project = project_
task = task_
msg.okay("Set project name to {}.{}".format(project, task), 2) | Sets the active project and task. All subsequent logging will be saved to
the database with that project and task.
Args:
project_ (str): active project name; a project can have multiple tasks.
task_ (str): active task name. Logging is separated at the project and task
level. | juraj-google-style |
def ch_start_time(self, *channels: List[Channel]) -> int:
intervals = list(itertools.chain(*(self._table[chan] for chan in channels
if chan in self._table)))
if intervals:
return min((interval.begin for interval in intervals))
retur... | Return earliest start time in this collection.
Args:
*channels: Channels over which to obtain start_time. | juraj-google-style |
def _to_bfloat16_unbiased(x, noise):
x_sign = tf.sign(x)
x = ((x * x_sign) + 1e-30)
cand1 = tf.to_bfloat16(x)
cand1_f = tf.to_float(cand1)
cand2 = tf.to_bfloat16(tf.where(tf.greater(x, cand1_f), (cand1_f * 1.005), (cand1_f * 0.995)))
ret = _randomized_roundoff_to_bfloat16(x, noise, cand1, cand2)... | Convert a float32 to a bfloat16 using randomized roundoff.
Args:
x: A float32 Tensor.
noise: a float32 Tensor with values in [0, 1), broadcastable to tf.shape(x)
Returns:
A float32 Tensor. | codesearchnet |
def get_layer_policy(layer):
if not isinstance(layer, base_layer.Layer):
raise ValueError('get_policy can only be called on a layer, but got: %s' % (layer,))
return layer.dtype_policy | Returns the dtype policy of a layer.
Warning: This function is deprecated. Use
`tf.keras.layers.Layer.dtype_policy` instead.
Args:
layer: A `tf.keras.layers.Layer`.
Returns:
The `tf.keras.mixed_precision.Policy` of the layer. | github-repos |
def __init__(self, expression, options=None, **kwargs):
if options is None:
options = Options()
self._expression = expression
self._options = options
self._expression_parts = []
self._parsed = False
for kwarg in kwargs:
if hasatt... | Initializes a new instance of the ExpressionDescriptorclass
Args:
expression: The cron expression string
options: Options to control the output description
Raises:
WrongArgumentException: if kwarg is unknow | juraj-google-style |
def put_async(self, path, value):
request = Put(self._get_next_id(), path, value)
request.set_callback(self._q.put)
future = self._dispatch_request(request)
return future | Puts a value to a path and returns immediately
Args:
path (list): The path to put to
value (object): The value to set
Returns:
Future: A single Future which will resolve to the result | codesearchnet |
def trace_flush(self):
cmd = enums.JLinkTraceCommand.FLUSH
res = self._dll.JLINKARM_TRACE_Control(cmd, 0)
if (res == 1):
raise errors.JLinkException('Failed to flush the trace buffer.')
return None | Flushes the trace buffer.
After this method is called, the trace buffer is empty. This method is
best called when the device is reset.
Args:
self (JLink): the ``JLink`` instance.
Returns:
``None`` | codesearchnet |
def get_edgestore_handle(client: arango.client.ArangoClient, username=None, password=None, edgestore_db_name: str=edgestore_db_name, edgestore_edges_name: str=edgestore_edges_name, edgestore_nodes_name: str=edgestore_nodes_name, edgestore_pipeline_name: str=edgestore_pipeline_name, edgestore_pipeline_stats_name: str=ed... | Get Edgestore arangodb database handle
Args:
client (arango.client.ArangoClient): Description
username (None, optional): Description
password (None, optional): Description
edgestore_db_name (str, optional): Description
edgestore_edges_name (str, optional): Description
edgestore_nodes_name (str, optional): Description
... | codesearchnet |
def __setRouterSelectionJitter(self, iRouterJitter):
print 'call _setRouterSelectionJitter'
try:
cmd = 'routerselectionjitter %s' % str(iRouterJitter)
print cmd
return self.__sendCommand(cmd) == 'Done'
except Exception, e:
ModuleHelper.Wri... | set ROUTER_SELECTION_JITTER parameter for REED to upgrade to Router
Args:
iRouterJitter: a random period prior to request Router ID for REED
Returns:
True: successful to set the ROUTER_SELECTION_JITTER
False: fail to set ROUTER_SELECTION_JITTER | juraj-google-style |
def Skew(poly, dist=None, **kws):
if isinstance(poly, distributions.Dist):
x = polynomials.variable(len(poly))
(poly, dist) = (x, poly)
else:
poly = polynomials.Poly(poly)
if (poly.dim < len(dist)):
polynomials.setdim(poly, len(dist))
shape = poly.shape
poly = polynom... | Skewness operator.
Element by element 3rd order statistics of a distribution or polynomial.
Args:
poly (Poly, Dist):
Input to take skewness on.
dist (Dist):
Defines the space the skewness is taken on. It is ignored if
``poly`` is a distribution.
Returns:
(numpy.ndarray):
Element for element variance along ``poly``, ... | codesearchnet |
def fit_to_cols(what, indent='', cols=79):
lines = []
while what:
(what, next_line) = split_line(what=what, cols=cols, indent=indent)
lines.append(next_line)
return '\n'.join(lines) | Wrap the given text to the columns, prepending the indent to each line.
Args:
what(str): text to wrap.
indent(str): indentation to use.
cols(int): colt to wrap to.
Returns:
str: Wrapped text | codesearchnet |
def load_pos_model(lang="en", version="2"):
src_dir = "pos{}".format(version)
p = locate_resource(src_dir, lang)
fh = _open(p)
return dict(np.load(fh)) | Return a part of speech tagger parameters for `lang` and of version `version`
Args:
lang (string): language code.
version (string): version of the parameters to be used. | juraj-google-style |
def static_lengths(self, ragged_lengths=True):
if self.num_row_partitions == 0:
return self._static_inner_shape_as_list(False)
first_dim = self.row_partitions[0].static_nrows
if isinstance(first_dim, tensor_shape.Dimension):
first_dim = first_dim.value
rp_dims = [first_dim]
for rp in... | Returns a list of statically known axis lengths.
This represents what values are known. For each row partition, it presents
either the uniform row length (if statically known),
the list of row lengths, or none if it is not statically known.
For the inner shape, if the rank is known, then each dimension is reported
if ... | github-repos |
def set_result(self, result):
if self.done():
raise RuntimeError('set_result can only be called once.')
self._result = result
self._trigger() | Set the result of the future to the provided result.
Args:
result (Any): The result | codesearchnet |
def stream(self, report, callback=None):
conn_id = self._find_connection(self.conn_string)
if isinstance(report, BroadcastReport):
self.adapter.notify_event_nowait(self.conn_string, 'broadcast', report)
elif (conn_id is not None):
self.adapter.notify_event_nowait(self.conn_string, 'report', ... | Queue data for streaming
Args:
report (IOTileReport): A report object to stream to a client
callback (callable): An optional callback that will be called with
a bool value of True when this report actually gets streamed.
If the client disconnects and the report is dropped instead,
callback will be called with False | codesearchnet |
def _unescape_token(token):
r
def match(m):
r
if m.group(1) is None:
return u"_" if m.group(0) == u"\\u" else u"\\"
try:
return six.unichr(int(m.group(1)))
except (ValueError, OverflowError) as _:
return _UNDEFINED_UNICODE
return _UNESCAPE_REGEX.sub(match, token) | r"""Replaces escaped characters in the token with their unescaped versions.
Applies inverse transformations as _escape_token():
1. Replace "\u" with "_", and "\\" with "\".
2. Replace "\###;" with the unicode character the ### refers to.
Args:
token: escaped string
Returns:
unescaped string | juraj-google-style |
def get_sendback(self, uuid, key):
def send_back_callback(data):
self.sendResponse(serializers.serialize(data), uuid, key)
return send_back_callback | Return function for sending progress messages back to original caller.
Args:
uuid (str): UUID of the received message.
key (str): Routing key.
Returns:
fn reference: Reference to function which takes only one data \
argument. | codesearchnet |
def truncate_too_long_number(numobj):
if is_valid_number(numobj):
return True
numobj_copy = PhoneNumber()
numobj_copy.merge_from(numobj)
national_number = numobj.national_number
while not is_valid_number(numobj_copy):
national_number = national_number
numobj_c... | Truncate a number object that is too long.
Attempts to extract a valid number from a phone number that is too long
to be valid, and resets the PhoneNumber object passed in to that valid
version. If no valid number could be extracted, the PhoneNumber object
passed in will not be modified.
Arguments:
numobj -- A PhoneN... | juraj-google-style |
async def change_file(self, file_path: str, description: str = None):
with open(file_path, 'rb') as f:
await self._change(asset=f.read()) | change the file of that attachment
|methcoro|
Warning:
|unstable|
Args:
file_path: path to the file you want to add / modify
description: *optional* description for your attachment
Raises:
ValueError: file_path must not be None
APIException | juraj-google-style |
def str_delimited(results, header=None, delimiter="\t"):
returnstr = ""
if header is not None:
returnstr += delimiter.join(header) + "\n"
return returnstr + "\n".join([delimiter.join([str(m) for m in result])
for result in results]) | Given a tuple of tuples, generate a delimited string form.
>>> results = [["a","b","c"],["d","e","f"],[1,2,3]]
>>> print(str_delimited(results,delimiter=","))
a,b,c
d,e,f
1,2,3
Args:
result: 2d sequence of arbitrary types.
header: optional header
Returns:
Aligned string output in a table-like format. | juraj-google-style |
def __init__(self, current):
import sys
from pyoko.modelmeta import model_registry
out = []
for mdl_name in sys.PYOKO_LOGS.copy():
try:
mdl = model_registry.get_model(mdl_name)
except KeyError:
continue
bucket_n... | GET method handler
Args:
req: Request object.
resp: Response object. | juraj-google-style |
def get_asn_origin_whois(self, asn_registry='radb', asn=None, retry_count=3, server=None, port=43):
try:
if (server is None):
server = ASN_ORIGIN_WHOIS[asn_registry]['server']
conn = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
conn.settimeout(self.timeout)
log.debug... | The function for retrieving CIDR info for an ASN via whois.
Args:
asn_registry (:obj:`str`): The source to run the query against
(asn.ASN_ORIGIN_WHOIS).
asn (:obj:`str`): The AS number (required).
retry_count (:obj:`int`): The number of times to retry in case
socket errors, timeouts, connection resets, etc. are
encoun... | codesearchnet |
def db_wb004(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 `db_wb004`'.format(value))
self._db_wb004 = value | Corresponds to IDD Field `db_wb004`
mean coincident dry-bulb temperature to
Wet-bulb temperature corresponding to 0.4% annual cumulative frequency of occurrence
Args:
value (float): value for IDD Field `db_wb004`
Unit: C
if `value` is None it will not be checked against the
specification and is assumed to be a missing... | codesearchnet |
def collect_results(rule, max_results=500, result_stream_args=None):
if (result_stream_args is None):
logger.error('This function requires a configuration dict for the inner ResultStream object.')
raise KeyError
rs = ResultStream(rule_payload=rule, max_results=max_results, **result_stream_args)
... | Utility function to quickly get a list of tweets from a ``ResultStream``
without keeping the object around. Requires your args to be configured
prior to using.
Args:
rule (str): valid powertrack rule for your account, preferably
generated by the `gen_rule_payload` function.
max_results (int): maximum number of tweets ... | codesearchnet |
def audio_bottom(x, model_hparams, vocab_size):
del vocab_size
inputs = x
with tf.variable_scope("audio_modality"):
def xnet_resblock(x, filters, res_relu, name):
with tf.variable_scope(name):
y = common_layers.separable_conv_block(
x,
f... | Transform input from data space to model space.
Args:
x: A Tensor with shape [batch, ...]
model_hparams: HParams, model hyperparmeters.
vocab_size: int, vocabulary size.
Returns:
body_input: A Tensor with shape [batch, ?, ?,
model_hparams.hidden_size]. | juraj-google-style |
def _copy_fn(fn):
if (not callable(fn)):
raise TypeError('fn is not callable: {}'.format(fn))
return types.FunctionType(code=fn.__code__, globals=fn.__globals__, name=fn.__name__, argdefs=fn.__defaults__, closure=fn.__closure__) | Create a deep copy of fn.
Args:
fn: a callable
Returns:
A `FunctionType`: a deep copy of fn.
Raises:
TypeError: if `fn` is not a callable. | codesearchnet |
def to_json_string(self):
return json.dumps(self.__dict__, indent=2) + '\n' | Serializes this instance to a JSON formatted string.
Returns:
str: JSON formatted string representing the configuration instance. | github-repos |
def send_html(self, html, body=None, msgtype="m.text"):
return self.client.api.send_message_event(
self.room_id, "m.room.message", self.get_html_content(html, body, msgtype)) | Send an html formatted message.
Args:
html (str): The html formatted message to be sent.
body (str): The unformatted body of the message to be sent. | juraj-google-style |
def add_signature_block(src_fileobj, dest_fileobj, signing_algorithm, signature=None):
algo_id = {'sha1': 1, 'sha384': 2}[signing_algorithm]
if not signature:
signature = make_dummy_signature(algo_id)
src_fileobj.seek(0)
mardata = mar.parse_stream(src_fileobj)
header = mardata.he... | Add a signature block to marfile, a MarReader object.
Productversion and channel are preserved, but any existing signatures are overwritten.
Args:
src_fileobj (file object): The input MAR file to add a signature to
dest_fileobj (file object): File object to write new MAR file to. Must be open in w+b mode.
signing_alg... | juraj-google-style |
def from_value(cls, ion_type, value, annotations=()):
if value is None:
value = IonPyNull()
else:
args, kwargs = cls._to_constructor_args(value)
value = cls(*args, **kwargs)
value.ion_event = None
value.ion_type = ion_type
value.ion_an... | Constructs a value as a copy with an associated Ion type and annotations.
Args:
ion_type (IonType): The associated Ion type.
value (Any): The value to construct from, generally of type ``cls``.
annotations (Sequence[unicode]): The sequence Unicode strings decorating this value. | juraj-google-style |
def out_file_name(out_dir, fname, ext=None):
if (ext is None):
return os.path.join(out_dir, os.path.basename(fname))
fname = remove_ext(fname)
return os.path.join(out_dir, '{}.{}'.format(fname, ext)) | Return path of output file, given a directory, file name and extension.
If fname is a path, it is converted to its basename.
Args:
out_dir (str): path to the directory where output should be written.
fname (str): path to the input file.
ext (str): file extension of the output file (defaults to None).
Returns:
str: o... | codesearchnet |
def from_string(string):
lines = string.split("\n")
toks = lines[0].split()
lengths = [float(i) for i in toks]
toks = lines[1].split()
angles = [float(i) for i in toks[0:3]]
a = lengths.pop(-1)
lengths.insert(0, a)
alpha = angles.pop(-1)
... | Reads a string representation to a ZeoCssr object.
Args:
string: A string representation of a ZeoCSSR.
Returns:
ZeoCssr object. | juraj-google-style |
def is_registered(self, cuuid, host):
if (cuuid in self.registry) and (self.registry[cuuid]["host"] == host):
return True
else:
return False | This function will check to see if a given host with client uuid is
currently registered.
Args:
cuuid (string): The client uuid that wishes to register.
host (tuple): The (address, port) tuple of the client that is
registering.
Returns:
Will return True if the client is registered and will return False if
it is not. | juraj-google-style |
def remove_interceptor(self, name):
for index, interceptor in enumerate(self.interceptors):
matches = (
type(interceptor).__name__ == name or
getattr(interceptor, 'name') == name
)
if matches:
self.interceptors.pop(inde... | Removes a specific interceptor by name.
Arguments:
name (str): interceptor name to disable.
Returns:
bool: `True` if the interceptor was disabled, otherwise `False`. | juraj-google-style |
def pause():
t = timer()
if f.t.stopped:
raise StoppedError('Cannot pause stopped timer.')
if f.t.paused:
raise PausedError('Timer already paused.')
f.t.paused = True
f.t.tmp_total += (t - f.t.start_t)
f.t.start_t = None
f.t.last_t = None
return t | Pause the timer, preventing subsequent time from accumulating in the
total. Renders the timer inactive, disabling other timing commands.
Returns:
float: The current time.
Raises:
PausedError: If timer already paused.
StoppedError: If timer already stopped. | codesearchnet |
def write_label_list(path, label_list):
entries = []
for label in label_list:
entries.append([label.start, label.end, label.value])
textfile.write_separated_lines(path, entries, separator='\t') | Writes the given `label_list` to an audacity label file.
Args:
path (str): Path to write the file to.
label_list (audiomate.annotations.LabelList): Label list | codesearchnet |
def make_fixture(model_class, **kwargs):
all_fields = get_fields(model_class)
fields_for_random_generation = map(
lambda x: getattr(model_class, x), all_fields
)
overrides = {}
for kwarg, value in kwargs.items():
if kwarg in all_fields:
kwarg_field = getattr(model... | Take the model_klass and generate a fixure for it
Args:
model_class (MongoEngine Document): model for which a fixture
is needed
kwargs (dict): any overrides instead of random values
Returns:
dict for now, other fixture types are not implemented yet | juraj-google-style |
def _scale_size(size, scale):
(w, h) = size
return (int(((w * float(scale)) + 0.5)), int(((h * float(scale)) + 0.5))) | Rescale a size by a ratio.
Args:
size (tuple): w, h.
scale (float): Scaling factor.
Returns:
tuple[int]: scaled size. | codesearchnet |
def lookup(self, obj):
for registered in self._registry:
if isinstance(obj, registered):
return self._registry[registered]
raise LookupError(f'{type(obj)} has not been registered.') | Looks up 'obj'.
Args:
obj: The object to lookup within the registry.
Returns:
Value for 'obj' in the registry if found.
Raises:
LookupError: if 'obj' has not been registered. | github-repos |
def myRank(grade, badFormat, year, length):
return int(sorted(everyonesAverage(year, badFormat, length), reverse=True).index(grade) + 1) | rank of candidateNumber in year
Arguments:
grade {int} -- a weighted average for a specific candidate number and year
badFormat {dict} -- candNumber : [results for candidate]
year {int} -- year you are in
length {int} -- length of each row in badFormat divided by 2
Returns:
int -- rank of candidateNumber in year | juraj-google-style |
def get_version_details(self, version_name):
name = ('%s/versions/%s' % (self._full_model_name, version_name))
return self._api.projects().models().versions().get(name=name).execute() | Get details of a version.
Args:
version: the name of the version in short form, such as "v1".
Returns: a dictionary containing the version details. | juraj-google-style |
def create_temp(node, namer):
if isinstance(node, gast.Name):
name = node.id
elif isinstance(node, (gast.Attribute, gast.Subscript)):
name = node.value.id
else:
raise TypeError
temp_node = gast.Name(id=namer.temp(name), annotation=None, ctx=None)
anno.setanno(temp_node, 'temp_var', node)
retu... | Create a temporary variable.
Args:
node: Create a temporary variable to store this variable in.
namer: A naming object that guarantees the names are unique.
Returns:
node: See `create_grad`. Returns a temporary variable, which is always a
simple variable annotated with `temp_var`. | juraj-google-style |
def render_wrapper(self, region='us-east-1'):
base = self.settings['pipeline']['base']
if self.base:
base = self.base
email = self.settings['pipeline']['notifications']['email']
slack = self.settings['pipeline']['notifications']['slack']
deploy_type = self.... | Generate the base Pipeline wrapper.
This renders the non-repeatable stages in a pipeline, like jenkins, baking, tagging and notifications.
Args:
region (str): AWS Region.
Returns:
dict: Rendered Pipeline wrapper. | juraj-google-style |
def __init__(self, inputs, num_clusters, initial_clusters, distance_metric, random_seed, kmeans_plus_plus_num_retries, kmc2_chain_length, cluster_centers, cluster_centers_updated, cluster_centers_initialized):
self._inputs = inputs
self._num_clusters = num_clusters
self._initial_clusters = initial_clusters
... | Creates an op factory.
Args:
inputs: See KMeans constructor.
num_clusters: An integer Tensor providing the number of clusters.
initial_clusters: See KMeans constructor.
distance_metric: See KMeans constructor.
random_seed: See KMeans constructor.
kmeans_plus_plus_num_retries: See KMeans constructor.
kmc2_chain_length:... | github-repos |
def formula_balance(model):
compound_formula = {}
for compound in model.compounds:
if (compound.formula is not None):
try:
f = Formula.parse(compound.formula).flattened()
compound_formula[compound.id] = f
except ParseError as e:
msg... | Calculate formula compositions for each reaction.
Call :func:`reaction_formula` for each reaction.
Yield (reaction, result) pairs, where result has two formula compositions
or `None`.
Args:
model: :class:`psamm.datasource.native.NativeModel`. | codesearchnet |
def sample_forecast_max_hail(self, dist_model_name, condition_model_name, num_samples, condition_threshold=0.5, query=None):
if (query is not None):
dist_forecasts = self.matched_forecasts['dist'][dist_model_name].query(query)
dist_forecasts = dist_forecasts.reset_index(drop=True)
condition_... | Samples every forecast hail object and returns an empirical distribution of possible maximum hail sizes.
Hail sizes are sampled from each predicted gamma distribution. The total number of samples equals
num_samples * area of the hail object. To get the maximum hail size for each realization, the maximum
value within e... | codesearchnet |
def __init__(self, http_error):
error_details = None
error_response = None
if http_error.fp:
try:
error_response = http_error.fp.read()
error_body = json.loads(error_response)
error_details = ['%s: %s' % (detail['message'], detail['debug_info'])
fo... | Create a ServerRequestException from a given urllib2.HTTPError.
Args:
http_error: The HTTPError that the ServerRequestException will be
based on. | juraj-google-style |
def generate_block_graph(block_graph: blocks.BlockGraph, loader: jinja2.BaseLoader) -> str:
return _generate_visualization(template_file=_BLOCKGRAPH_TEMPLATE_NAME, loader=loader, graph_data=block_serializer.encode_merged_graph(block_graph)) | Generate the visualization webpage.
Args:
block_graph: blocks.BlockGraph. The block graph of the code.
loader: A jinja22 loader
Returns:
str. The rendered visualization page. | github-repos |
def setPadding(self, padding):
self._pad = padding
self._zfill = self.__class__.getPaddingNum(self._pad) | Set new padding characters for the sequence.
i.e. "#" or "@@@" or '%04d', or an empty string to disable range formatting.
Args:
padding (str): sequence padding to set | juraj-google-style |
def squad_v1_exact_match(y_true: List[List[str]], y_predicted: List[str]) -> float:
EM_total = 0
count = 0
for ground_truth, prediction in zip(y_true, y_predicted):
if len(ground_truth[0]) == 0:
continue
count += 1
EMs = [int(normalize_answer(gt) == norm... | Calculates Exact Match score between y_true and y_predicted
EM score uses the best matching y_true answer:
if y_pred equal at least to one answer in y_true then EM = 1, else EM = 0
Skips examples without an answer.
Args:
y_true: list of correct answers (correct answers are represented by list of strings)
y_predicted: l... | juraj-google-style |
def _RemoveAuthorizedKeys(self, user):
pw_entry = self._GetUser(user)
if not pw_entry:
return
home_dir = pw_entry.pw_dir
authorized_keys_file = os.path.join(home_dir, '.ssh', 'authorized_keys')
if os.path.exists(authorized_keys_file):
try:
os.remove(authorized_keys_file)
... | Remove a Linux user account's authorized keys file to prevent login.
Args:
user: string, the Linux user account to remove access. | juraj-google-style |
async def disconnect(self, conn_id):
self._ensure_connection(conn_id, True)
dev = self._get_property(conn_id, 'device')
dev.connected = False
self._teardown_connection(conn_id) | Asynchronously disconnect from a connected device
Args:
conn_id (int): A unique identifier that will refer to this connection
callback (callback): A callback that will be called as
callback(conn_id, adapter_id, success, failure_reason) | juraj-google-style |
def __init__(self, vlan_id=None):
super().__init__(action_type=ActionType.OFPAT_SET_VLAN_VID, length=8)
self.vlan_id = vlan_id | Create an ActionVlanVid with the optional parameters below.
Args:
vlan_id (int): VLAN priority. | juraj-google-style |
def transform_feature(self, transformation_cache, state_manager):
input_tensor = transformation_cache.get(self.key, state_manager)
if self.normalizer_fn is not None:
input_tensor = self.normalizer_fn(input_tensor)
return input_tensor | See `FeatureColumn` base class.
In this case, we apply the `normalizer_fn` to the input tensor.
Args:
transformation_cache: A `FeatureTransformationCache` object to access
features.
state_manager: A `StateManager` to create / access resources such as
lookup tables.
Returns:
Normalized input tensor. | github-repos |
def create_authors(project_dir=os.curdir):
pkg_info_file = os.path.join(project_dir, 'PKG-INFO')
authors_file = os.path.join(project_dir, 'AUTHORS')
if os.path.exists(pkg_info_file):
return
authors = get_authors(project_dir=project_dir)
with open(authors_file, 'wb') as authors_fd:
au... | Creates the authors file, if not in a package.
Returns:
None
Raises:
RuntimeError: If the authors could not be retrieved | codesearchnet |
async def get_records_for_zone(self, dns_zone, params=None):
managed_zone = self.get_managed_zone(dns_zone)
url = f'{self._base_url}/managedZones/{managed_zone}/rrsets'
if not params:
params = {}
if 'fields' not in params:
params['fields'] ... | Get all resource record sets for a managed zone, using the DNS zone.
Args:
dns_zone (str): Desired DNS zone to query.
params (dict): (optional) Additional query parameters for HTTP
requests to the GDNS API.
Returns:
list of dicts representing rrsets. | juraj-google-style |
class TFDebertaXSoftmax(keras.layers.Layer):
def __init__(self, axis=-1, **kwargs):
super().__init__(**kwargs)
self.axis = axis
def call(self, inputs: tf.Tensor, mask: tf.Tensor):
rmask = tf.logical_not(tf.cast(mask, tf.bool))
output = tf.where(rmask, tf.cast(float('-inf'), dty... | Masked Softmax which is optimized for saving memory
Args:
input (`tf.Tensor`): The input tensor that will apply softmax.
mask (`tf.Tensor`): The mask matrix where 0 indicate that element will be ignored in the softmax calculation.
dim (int): The dimension that will apply softmax | github-repos |
def AddValue(self, registry_value):
name = registry_value.name.upper()
if (name in self._values):
raise KeyError('Value: {0:s} already exists.'.format(registry_value.name))
self._values[name] = registry_value | Adds a value.
Args:
registry_value (WinRegistryValue): Windows Registry value.
Raises:
KeyError: if the value already exists. | codesearchnet |
def add_profile_variants(self, profile_variants):
results = self.db.profile_variant.insert_many(profile_variants)
return results | Add several variants to the profile_variant collection in the
database
Args:
profile_variants(list(models.ProfileVariant)) | codesearchnet |
def valueReadPreprocessor(valueString, replaceParamsFile=None):
if (type(valueString) is bool):
log.warning('Only numerical variable types can be handled by the valueReadPreprocessor function.')
return valueString
processedValue = valueString
if ((replaceParamsFile is not None) and (valueStr... | Apply global pre-processing to values during reading throughout the project.
Args:
valueString (str): String representing the value to be preprocessed.
replaceParamsFile (gsshapy.orm.ReplaceParamFile, optional): Instance of the replace param file. Required if
replacement variables are included in the project.
Returns... | codesearchnet |
def index_min(x, idx, y):
return _index_update_helper(tf_np.ndarray._with_index_min, x, idx, y) | Pure equivalent of `x[idx] = minimum(x[idx], y)`.
Returns the value of x that would result from the NumPy-style indexed
assignment `x[idx] = minimum(x[idx], y)`. Because it's a pure function, `x`
itself won't be changed.
Args:
x: an array with the values to be updated.
idx: a Numpy-style index, consisting of `None`, ... | github-repos |
def queuify_logger(logger, queue_handler, queue_listener):
if isinstance(logger, str):
logger = logging.getLogger(logger)
handlers = [handler for handler in logger.handlers if (handler not in queue_listener.handlers)]
if handlers:
queue_listener.handlers = tuple((list(queue_listener.handlers... | Replace logger's handlers with a queue handler while adding existing
handlers to a queue listener.
This is useful when you want to use a default logging config but then
optionally add a logger's handlers to a queue during runtime.
Args:
logger (mixed): Logger instance or string name of logger to queue-ify
handlers.
q... | codesearchnet |
def process_user_info_response(self, response):
mapping = (('username', 'preferred_username'), ('email', 'email'), ('last_name', 'family_name'), ('first_name', 'given_name'))
return {dest: response[source] for (dest, source) in mapping} | Process the user info response data.
By default, this simply maps the edX user info key-values (example below) to Django-friendly names. If your
provider returns different fields, you should sub-class this class and override this method.
.. code-block:: python
{
"username": "jdoe",
"email": "jdoe@example.com",
"firs... | codesearchnet |
def yaml(modules_to_register: Iterable[Any] = None, classes_to_register: Iterable[Any] = None) -> ruamel.yaml.YAML:
yaml = ruamel.yaml.YAML(typ = "rt")
yaml.representer.add_representer(np.ndarray, numpy_to_yaml)
yaml.constructor.add_constructor("!numpy_array", numpy_from_yaml)
... | Create a YAML object for loading a YAML configuration.
Args:
modules_to_register: Modules containing classes to be registered with the YAML object. Default: None.
classes_to_register: Classes to be registered with the YAML object. Default: None.
Returns:
A newly creating YAML object, configured as apporpirate. | juraj-google-style |
def _compute_transitions(self, corpus, order=1):
self.transitions = defaultdict(lambda: defaultdict(int))
for corpus_entry in corpus:
tokens = self.tokenize(corpus_entry)
last_tokens = utils.prefilled_buffer(
self._start_symbol, length=self.order)
... | Computes the transition probabilities of a corpus
Args:
corpus: the given corpus (a corpus_entry needs to be iterable)
order: the maximal Markov chain order | juraj-google-style |
def eval_image(image, height, width, scope=None):
with tf.name_scope(values=[image, height, width], name=scope, default_name='eval_image'):
image = tf.image.central_crop(image, central_fraction=0.875)
image = tf.expand_dims(image, 0)
image = tf.image.resize_bilinear(image, [height, width], a... | Prepare one image for evaluation.
Args:
image: 3-D float Tensor
height: integer
width: integer
scope: Optional scope for name_scope.
Returns:
3-D float Tensor of prepared image. | codesearchnet |
def check_upload_status(self, video_id):
if (not self.authenticated):
raise ApiError(_('Authentication is required'))
entry = self.fetch_video(video_id)
upload_status = Api.yt_service.CheckUploadStatus(entry)
if (upload_status is not None):
video_upload_state = upload_status[0]
d... | Checks the video upload status
Newly uploaded videos may be in the processing state
Authentication is required
Returns:
True if video is available
otherwise a dict containes upload_state and detailed message
i.e. {"upload_state": "processing", "detailed_message": ""} | codesearchnet |
def check_par(chrom, pos):
par = False
for interval in PAR.get(chrom,[]):
if (pos >= interval[0] and pos <= interval[1]):
par = True
return par | Check if a coordinate is in the PAR region
Args:
chrom(str)
pos(int)
Returns:
par(bool) | juraj-google-style |
async def _on_event(self, event_):
conv_id = event_.conversation_id.id
try:
conv = await self._get_or_fetch_conversation(conv_id)
except exceptions.NetworkError:
logger.warning(
'Failed to fetch conversation for event notification: %s',
... | Receive a hangouts_pb2.Event and fan out to Conversations.
Args:
event_: hangouts_pb2.Event instance | juraj-google-style |
def _multiple_field(cls):
klassdict = cls.__dict__
try:
return klassdict['_entitylist_multifield'][0]
except (KeyError, IndexError, TypeError):
from . import fields
multifield_tuple = tuple(fields.find(cls, multiple=True))
assert (len(multifield_tuple) == 1)
multifiel... | Return the "multiple" TypedField associated with this EntityList.
This also lazily sets the ``_entitylist_multiplefield`` value if it
hasn't been set yet. This is set to a tuple containing one item because
if we set the class attribute to the TypedField, we would effectively
add a TypedField descriptor to the class, w... | codesearchnet |
def invert_attention_mask(self, encoder_attention_mask: Tensor) -> Tensor:
if encoder_attention_mask.dim() == 3:
encoder_extended_attention_mask = encoder_attention_mask[:, None, :, :]
if encoder_attention_mask.dim() == 2:
encoder_extended_attention_mask = encoder_attention_mask[:, None, None, :... | Invert an attention mask (e.g., switches 0. and 1.).
Args:
encoder_attention_mask (`torch.Tensor`): An attention mask.
Returns:
`torch.Tensor`: The inverted attention mask. | github-repos |
def _getScalesDiag(self, termx=0):
assert (self.P > 1), 'VarianceDecomposition:: diagonal init_method allowed only for multi trait models'
assert (self.noisPos is not None), 'VarianceDecomposition:: noise term has to be set'
assert (termx < (self.n_randEffs - 1)), 'VarianceDecomposition:: termx>=n_randEffs-... | Internal function for parameter initialization
Uses 2 term single trait model to get covar params for initialization
Args:
termx: non-noise term terms that is used for initialization | codesearchnet |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.