code stringlengths 20 4.93k | docstring stringlengths 33 1.27k | source stringclasses 3
values |
|---|---|---|
def convert(self, point):
x, y = point
(x1, y1) = x - self.x_offset, y - self.y_offset
logger.debug("converted {} {} ==> {} {}".format(x, y, x1, y1))
return x1, y1 | Convert a point from one coordinate system to another.
Args:
point: tuple(int x, int y)
The point in the original coordinate system.
Returns:
converted_point: tuple(int x, int y)
The point in the new coordinate system.
Example: convert coordinate from original image into a pixel location
within a cutout image.
@rty... | juraj-google-style |
def _event_size(event_shape, name=None):
with tf.compat.v1.name_scope(name, 'event_size', [event_shape]):
event_shape = tf.convert_to_tensor(
value=event_shape, dtype=tf.int32, name='event_shape')
event_shape_const = tf.get_static_value(event_shape)
if event_shape_const is not None:
retu... | Computes the number of elements in a tensor with shape `event_shape`.
Args:
event_shape: A tensor shape.
name: The name to use for the tensor op to compute the number of elements
(if such an op needs to be created).
Returns:
event_size: The number of elements in `tensor_shape`. Returns a numpy int
when the number of... | juraj-google-style |
def from_row_lengths(cls, row_lengths, validate=True, dtype=None, dtype_hint=None):
if not isinstance(validate, bool):
raise TypeError('validate must have type bool')
with ops.name_scope(None, 'RowPartitionFromRowLengths', [row_lengths]):
row_lengths = cls._convert_row_partition(row_lengths, 'ro... | Creates a `RowPartition` with rows partitioned by `row_lengths`.
This `RowPartition` divides a sequence `values` into rows by indicating
the length of each row:
```python
partitioned_rows = [[values.pop(0) for _ in range(length)]
for length in row_lengths]
```
Args:
row_lengths: A 1-D integer tensor with shape `[nro... | github-repos |
def freeze_graph(session, outputs):
return convert_to_constants.convert_variables_to_constants(session, session.graph.as_graph_def(), [x.op.name for x in outputs]) | Freeze the current graph.
Args:
session: Tensorflow sessions containing the graph
outputs: List of output tensors
Returns:
The frozen graph_def. | github-repos |
def resolves_for(self, session):
if self.url:
self.actual_path = session.current_url
else:
result = urlparse(session.current_url)
if self.only_path:
self.actual_path = result.path
else:
request_uri = result.path
if result.query:
... | Returns whether this query resolves for the given session.
Args:
session (Session): The session for which this query should be executed.
Returns:
bool: Whether this query resolves. | codesearchnet |
def replace(self, **kwargs):
clone = copy(self)
clone.transforms = list(clone.transforms)
for (key, value) in kwargs.items():
if (not hasattr(clone, key)):
raise TypeError(u'replace() got an unexpected keyword argument {!r}'.format(key))
setattr(clone, key, value)
return clon... | Return a copy of this `Query`, but with attributes specified
as keyword arguments replaced by the keyword values.
Keyword Args:
Attributes/values to replace in the copy.
Returns:
A copy of the query that has its attributes updated with the specified values.
Raises:
TypeError: The `Query` does not have the specified ... | codesearchnet |
def GetFileObject(self, data_stream_name=''):
if data_stream_name:
return None
return resolver.Resolver.OpenFileObject(
self.path_spec, resolver_context=self._resolver_context) | Retrieves the file-like object.
Args:
data_stream_name (Optional[str]): name of the data stream, where an empty
string represents the default data stream.
Returns:
FileIO: a file-like object or None if not available. | juraj-google-style |
def get_user_info(self):
resp = self.requester.get(urljoin(self.base_url, '/api/mobile/v0.5/my_user_info'))
resp.raise_for_status()
return Info(resp.json()) | Returns a UserInfo object for the logged in user.
Returns:
UserInfo: object representing the student current grades | codesearchnet |
def add_config(self, slot, config_id, config_type, value):
if (slot not in self.config_database):
self.config_database[slot] = {}
self.config_database[slot][config_id] = (config_type, value) | Add a config variable assignment to this sensor graph.
Args:
slot (SlotIdentifier): The slot identifier that this config
variable is assigned to.
config_id (int): The 16-bit id of this config_id
config_type (str): The type of the config variable, currently
supported are fixed width integer types, strings and binary
bl... | codesearchnet |
class _EmbeddingHandler(ModelHandler):
def __init__(self, embeddings_manager: EmbeddingsManager):
self.embedding_config = embeddings_manager
self._underlying = self.embedding_config.get_model_handler()
self.columns = self.embedding_config.get_columns_to_apply()
def load_model(self):
... | A ModelHandler intended to be work on list[dict[str, Any]] inputs.
The inputs to the model handler are expected to be a list of dicts.
For example, if the original mode is used with RunInference to take a
PCollection[E] to a PCollection[P], this ModelHandler would take a
PCollection[dict[str, E]] to a PCollection[dic... | github-repos |
def get_global_namespace(decls):
found = [
decl for decl in scopedef.make_flatten(decls) if decl.name == '::' and
isinstance(decl, namespace_t)]
if len(found) == 1:
return found[0]
raise RuntimeError("Unable to find global namespace.") | Get the global namespace (::) from a declaration tree.
Args:
decls (list[declaration_t]): a list of declarations
Returns:
namespace_t: the global namespace_t object (::) | juraj-google-style |
def parse_options(cls, options):
d = {}
for filename_check, dictionary in cls.filename_checks.items():
filename_data = getattr(options, filename_check)
if len(filename_data) != 0:
parsed_params = {}
for single_line in filename... | Required by flake8
parse the options, called after add_options
Args:
options (dict): options to be parsed | juraj-google-style |
def to_value_list(original_strings, corenlp_values=None):
assert isinstance(original_strings, (list, tuple, set))
if (corenlp_values is not None):
assert isinstance(corenlp_values, (list, tuple, set))
assert (len(original_strings) == len(corenlp_values))
return list(set((to_value(x, y) f... | Convert a list of strings to a list of Values
Args:
original_strings (list[basestring])
corenlp_values (list[basestring or None])
Returns:
list[Value] | codesearchnet |
def list_files_by_mtime(dirpath):
files = [f for f in os.listdir(dirpath) if is_real_file(dirpath, f)]
return sorted(files, key=lambda f: get_mtime(dirpath, f)) | Return a list of files in the directory, sorted in increasing "mtime".
Return a list of files in the given directory, sorted from older to newer file
according to their modification times. Only return actual files, skipping
directories, symbolic links, pipes, etc.
Args:
dirpath: directory pathname
Returns:
A list o... | github-repos |
def __init__(self, value: Any, compute_derived: bool=False, where: Optional[Callable[[base.HyperPrimitive], bool]]=None):
super().__init__()
self._value = value
self._root_path = utils.KeyPath()
self._compute_derived = compute_derived
self._where = where
self._parse_generators() | Constructor.
Args:
value: Value (maybe) annotated with generators to use as template.
compute_derived: Whether to compute derived value at this level.
We only want to compute derived value at root level since reference path
may go out of scope of a non-root ObjectTemplate.
where: Function to filter hyper primitives. I... | github-repos |
def autorotate(image, orientation=None):
orientation_value = orientation if orientation else \
image._getexif().get(EXIF_KEYS.get('Orientation'))
if orientation_value is None:
raise ImDirectException("No orientation available in Exif "
"tag or given explicitl... | Rotate and return an image according to its Exif information.
ROTATION_NEEDED = {
1: 0,
2: 0 (Mirrored),
3: 180,
4: 180 (Mirrored),
5: -90 (Mirrored),
6: -90,
7: 90 (Mirrored),
8: 90,
}
Args:
image (PIL.Image.Image): PIL image to rotate
orientation (): Optional orientation value in [1, 8]
Returns:
A :py:class:`~PIL.... | juraj-google-style |
def _tensor_product(self, other, reverse=False):
if not isinstance(other, Chi):
other = Chi(other)
if reverse:
input_dims = self.input_dims() + other.input_dims()
output_dims = self.output_dims() + other.output_dims()
data = np.kron(other.data, se... | Return the tensor product channel.
Args:
other (QuantumChannel): a quantum channel.
reverse (bool): If False return self ⊗ other, if True return
if True return (other ⊗ self) [Default: False
Returns:
Chi: the tensor product channel as a Chi object.
Raises:
QiskitError: if other is not a QuantumChannel subclass. | juraj-google-style |
def _ConvertInputMapValues(name, input_map):
if not all((isinstance(v, tensor.Tensor) for v in input_map.values())):
if name == '':
raise ValueError('tf.import_graph_def() requires a non-empty `name` if `input_map` contains non-Tensor values. Try calling tf.convert_to_tensor() on `input_map` val... | Ensures all input map values are tensors.
This should be called from inside the import name scope.
Args:
name: the `name` argument passed to import_graph_def
input_map: the `input_map` argument passed to import_graph_def.
Returns:
An possibly-updated version of `input_map`.
Raises:
ValueError: if input map values c... | github-repos |
def acquire_multi(self, n=1):
browsers = []
with self._lock:
if (len(self._in_use) >= self.size):
raise NoBrowsersAvailable
while ((len(self._in_use) < self.size) and (len(browsers) < n)):
browser = self._fresh_browser()
browsers.append(browser)
se... | Returns a list of up to `n` browsers.
Raises:
NoBrowsersAvailable if none available | codesearchnet |
def execute_work_items(work_items, config):
return celery.group((worker_task.s(work_item, config) for work_item in work_items)) | Execute a suite of tests for a given set of work items.
Args:
work_items: An iterable of `work_db.WorkItem`s.
config: The configuration to use for the test execution.
Returns: An iterable of WorkItems. | codesearchnet |
def is_user_profile_valid(user_profile):
if not user_profile:
return False
if not type(user_profile) is dict:
return False
if UserProfile.USER_ID_KEY not in user_profile:
return False
if UserProfile.EXPERIMENT_BUCKET_MAP_KEY not in user_profile:
return False
experiment_bucket_map = use... | Determine if provided user profile is valid or not.
Args:
user_profile: User's profile which needs to be validated.
Returns:
Boolean depending upon whether profile is valid or not. | juraj-google-style |
def __init__(self, max_size=-1, client_timeout=-1, autoclose=False,
**client_kwargs):
self.max_size = max_size
self.client_timeout = client_timeout
self.client_kwargs = client_kwargs
self.__ioloop = client_kwargs.get('ioloop',
... | Constructor.
Args:
max_size (int): max size of the pool (-1 means "no limit").
client_timeout (int): timeout in seconds of a connection released
to the pool (-1 means "no timeout").
autoclose (boolean): automatically disconnect released connections
with lifetime > client_timeout (test made every
client_timeout/10 seco... | juraj-google-style |
def ccy_pair(local, base='USD') -> CurrencyPair:
ccy_param = param.load_info(cat='ccy')
if (f'{local}{base}' in ccy_param):
info = ccy_param[f'{local}{base}']
elif (f'{base}{local}' in ccy_param):
info = ccy_param[f'{base}{local}']
info['factor'] = (1.0 / info.get('factor', 1.0))
... | Currency pair info
Args:
local: local currency
base: base currency
Returns:
CurrencyPair
Examples:
>>> ccy_pair(local='HKD', base='USD')
CurrencyPair(ticker='HKD Curncy', factor=1.0, power=1)
>>> ccy_pair(local='GBp')
CurrencyPair(ticker='GBP Curncy', factor=100, power=-1)
>>> ccy_pair(local='USD', base='GBp')
Curre... | codesearchnet |
def recipe_dcm(config, auth_read, account, body, delete):
dcm(config, {'auth': auth_read, 'report': {'account': account, 'body': body}, 'delete': delete}) | Create a CM report from a JSON definition.
Args:
auth_read (authentication) - Credentials used for reading data.
account (string) - NA
body (json) - NA
delete (boolean) - NA | github-repos |
def __init__(self, loss_tensor, fail_on_nan_loss=True):
self._loss_tensor = loss_tensor
self._fail_on_nan_loss = fail_on_nan_loss | Initializes a `NanTensorHook`.
Args:
loss_tensor: `Tensor`, the loss tensor.
fail_on_nan_loss: `bool`, whether to raise exception when loss is NaN. | github-repos |
def _global_report_benchmark(name, iters=None, cpu_time=None, wall_time=None, throughput=None, extras=None, metrics=None):
logging.info('Benchmark [%s] iters: %d, wall_time: %g, cpu_time: %g,throughput: %g, extras: %s, metrics: %s', name, iters if iters is not None else -1, wall_time if wall_time is not None else -... | Method for recording a benchmark directly.
Args:
name: The BenchmarkEntry name.
iters: (optional) How many iterations were run
cpu_time: (optional) Total cpu time in seconds
wall_time: (optional) Total wall time in seconds
throughput: (optional) Throughput (in MB/s)
extras: (optional) Dict mapping string keys to addit... | github-repos |
def output(self, filename):
if not filename.endswith('.dot'):
filename += '.dot'
if filename == ".dot":
filename = "all_contracts.dot"
with open(filename, 'w', encoding='utf8') as f:
self.info(f'Call Graph: {filename}')
f.write('\n'.join... | Output the graph in filename
Args:
filename(string) | juraj-google-style |
def _inquire(self, **kwargs):
if (rname_rfc6680 is None):
raise NotImplementedError('Your GSSAPI implementation does not support RFC 6680 (the GSSAPI naming extensions)')
if (not kwargs):
default_val = True
else:
default_val = False
attrs = kwargs.get('attrs', default_val)
me... | Inspect this name for information.
This method inspects the name for information.
If no keyword arguments are passed, all available information
is returned. Otherwise, only the keyword arguments that
are passed and set to `True` are returned.
Args:
mech_name (bool): get whether this is a mechanism name,
and, if so,... | codesearchnet |
def get_memory_region(x, query_block_shape, memory_flange, q_indices):
x_query_padded = pad_to_multiple_2d(x, query_block_shape)
x_center = gather_blocks_2d(x_query_padded, q_indices)
paddings = [[0, 0], [0, 0], [memory_flange[0], 0],
[memory_flange[1], memory_flange[1]], [0, 0]]
x_mem... | Get the memory regions that surround a 2d query.
The memory regions will be the left and top right.
Args:
x: A tensor with shape [batch, heads, height, width, depth]
query_block_shape: a 2-d tuple of integers
memory_flange: a 2-d tuple of integers
q_indices: a tensor of indices for each of the center blocks.
[num_blo... | juraj-google-style |
def make_group_index(self, groupby_cols, bool_arr):
factor_list, values_list = self.factorize_groupby_cols(groupby_cols)
if len(factor_list) == 0:
tmp_rootdir = self.create_tmp_rootdir()
carray_factor = bcolz.zeros(len(self), dtype='in... | Create unique groups for groupby loop
Args:
factor_list:
values_list:
groupby_cols:
bool_arr:
Returns:
carray: (carray_factor)
int: (nr_groups) the number of resulting groups
int: (skip_key) | juraj-google-style |
def learn(self, grad_arr):
deconvolution_layer_list = self.__deconvolution_layer_list[::-1]
for i in range(len(deconvolution_layer_list)):
try:
grad_arr = deconvolution_layer_list[i].back_propagate(grad_arr)
except:
self.__logger.debug("Er... | Update this Discriminator by ascending its stochastic gradient.
Args:
grad_arr: `np.ndarray` of gradients.
Returns:
`np.ndarray` of delta or gradients. | juraj-google-style |
def decode_datetime(encoded_datetime):
time_zone_match = _TIME_ZONE_RE.search(encoded_datetime)
if time_zone_match:
time_string = encoded_datetime[:time_zone_match.start(1)].upper()
else:
time_string = encoded_datetime.upper()
if '.' in time_string:
format_st... | Decode a DateTimeField parameter from a string to a python datetime.
Args:
encoded_datetime: A string in RFC 3339 format.
Returns:
A datetime object with the date and time specified in encoded_datetime.
Raises:
ValueError: If the string is not in a recognized format. | juraj-google-style |
def _ReadSelectedVolumes(self, volume_system, prefix='v'):
volume_identifiers_string = self._input_reader.Read()
volume_identifiers_string = volume_identifiers_string.strip()
if not volume_identifiers_string:
return []
selected_volumes = self._ParseVolumeIdentifiersString(
volume_id... | Reads the selected volumes provided by the user.
Args:
volume_system (APFSVolumeSystem): volume system.
prefix (Optional[str]): volume identifier prefix.
Returns:
list[str]: selected volume identifiers including prefix.
Raises:
KeyboardInterrupt: if the user requested to abort.
ValueError: if the volume identifiers ... | juraj-google-style |
def read_xyz(cls, buf, start_index=0, get_bonds=True, nrows=None, engine=None):
frame = pd.read_table(buf, skiprows=2, comment='
remove_digits = partial(re.sub, '[0-9]+', '')
frame['atom'] = frame['atom'].apply(remove_digits)
molecule = cls(frame)
molecule.index = range(start_index, (start_index + l... | Read a file of coordinate information.
Reads xyz-files.
Args:
inputfile (str):
start_index (int):
get_bonds (bool):
nrows (int): Number of rows of file to read.
Note that the first two rows are implicitly excluded.
engine (str): Wrapper for argument of :func:`pandas.read_csv`.
Returns:
Cartesian: | codesearchnet |
def create_version(self, version_label):
version_response = self.repo.api.http_request('POST', ('%s/fcr:versions' % self.uri), data=None, headers={'Slug': version_label})
if (version_response.status_code == 201):
logger.debug(('version created: %s' % version_response.headers['Location']))
self._... | method to create a new version of the resource as it currently stands
- Note: this will create a version based on the current live instance of the resource,
not the local version, which might require self.update() to update.
Args:
version_label (str): label to be used for version
Returns:
(ResourceVersion): instance... | codesearchnet |
def _create_extractors(col_params):
result = []
for col_param in col_params:
result.append(_create_extractor(col_param))
return result | Creates extractors to extract properties corresponding to 'col_params'.
Args:
col_params: List of ListSessionGroupsRequest.ColParam protobufs.
Returns:
A list of extractor functions. The ith element in the
returned list extracts the column corresponding to the ith element of
_request.col_params | juraj-google-style |
def with_target_audience(self, target_audience):
return self.__class__(
self._signer,
service_account_email=self._service_account_email,
token_uri=self._token_uri,
target_audience=target_audience,
additional_claims=self._additional_claims.copy... | Create a copy of these credentials with the specified target
audience.
Args:
target_audience (str): The intended audience for these credentials,
used when requesting the ID Token.
Returns:
google.auth.service_account.IDTokenCredentials: A new credentials
instance. | juraj-google-style |
def members(name, members_list, **kwargs):
members_list = [salt.utils.win_functions.get_sam_name(m) for m in members_list.split(",")]
if not isinstance(members_list, list):
log.debug('member_list is not a list')
return False
try:
obj_group = _get_group_object(name)
except p... | Ensure a group contains only the members in the list
Args:
name (str):
The name of the group to modify
members_list (str):
A single user or a comma separated list of users. The group will
contain only the users specified in this list.
Returns:
bool: ``True`` if successful, otherwise ``False``
CLI Example:
.. code... | juraj-google-style |
def send_email_message(self, recipient, subject, html_message, text_message, sender_email, sender_name):
if (not current_app.testing):
from flask_sendmail import Message
message = Message(subject, recipients=[recipient], html=html_message, body=text_message)
self.mail.send(message) | Send email message via Flask-Sendmail.
Args:
recipient: Email address or tuple of (Name, Email-address).
subject: Subject line.
html_message: The message body in HTML.
text_message: The message body in plain text. | codesearchnet |
def parsetime(text):
mins, maxs = text.split('-', 1)
minv = s_time.parse(mins)
maxv = s_time.parse(maxs, base=minv)
return minv, maxv | Parse an interval time string and return a (min,max) tuple.
Args:
text (str): A time interval string
Returns:
((int,int)): A epoch millis epoch time string | juraj-google-style |
def reply(self, reply_comment):
payload = '{ "Comment": "' + reply_comment + '"}'
endpoint = 'https:
self._make_api_call('post', endpoint, data=payload) | Reply to the Message.
Notes:
HTML can be inserted in the string and will be interpreted properly by Outlook.
Args:
reply_comment: String message to send with email. | juraj-google-style |
def bottleneck_block(cnn, depth, depth_bottleneck, stride, pre_activation):
if pre_activation:
bottleneck_block_v2(cnn, depth, depth_bottleneck, stride)
else:
bottleneck_block_v1(cnn, depth, depth_bottleneck, stride) | Bottleneck block with identity short-cut.
Args:
cnn: the network to append bottleneck blocks.
depth: the number of output filters for this bottleneck block.
depth_bottleneck: the number of bottleneck filters for this block.
stride: Stride used in the first layer of the bottleneck block.
pre_activation: use pre_activat... | juraj-google-style |
def solveAsync(self, callback):
def async_call():
self._lock.acquire()
try:
self._impl.solve()
except Exception:
self._lock.release()
raise
else:
self._lock.release()
callback... | Solve the current model asynchronously.
Args:
callback: Callback to be executed when the solver is done. | juraj-google-style |
def dropout(inputs, keep_prob=0.5, is_training=True, scope=None):
if (is_training and (keep_prob > 0)):
with tf.name_scope(scope, 'Dropout', [inputs]):
return tf.nn.dropout(inputs, keep_prob)
else:
return inputs | Returns a dropout layer applied to the input.
Args:
inputs: the tensor to pass to the Dropout layer.
keep_prob: the probability of keeping each input unit.
is_training: whether or not the model is in training mode. If so, dropout is
applied and values scaled. Otherwise, inputs is returned.
scope: Optional scope for na... | codesearchnet |
def _parse_dataset(file_path, tmp_dir, train):
input_path = file_path
file_name = 'train' if train else 'dev'
gen_output_path = os.path.join(tmp_dir, file_name + '.txt')
example_output_path = os.path.join(tmp_dir, _EXAMPLES_FILE)
print('input path: ' + input_path)
print('gen_output_path: ' + gen_output_... | Convert the dataset in to a simpler format.
This function creates two files. One for being processed to produce a vocab
and another to generate the data.
Args:
file_path: string, path to the file to parse.
tmp_dir: string, path to the directory to output the files.
train: bool, indicating if we are parsing the traini... | juraj-google-style |
def load_profile_variants(adapter, variant_file):
vcf_info = check_vcf(variant_file)
nr_variants = vcf_info['nr_variants']
variant_type = vcf_info['variant_type']
if variant_type != 'snv':
LOG.critical('Variants used for profiling must be SNVs only')
raise VcfError
vcf = get... | Loads variants used for profiling
Args:
adapter (loqusdb.plugins.Adapter): initialized plugin
variant_file(str): Path to variant file | juraj-google-style |
def by_issn(issn):
old_url = aleph.ALEPH_URL
aleph.ALEPH_URL = NTK_ALEPH_URL
records = aleph.getISSNsXML(issn, base='STK02')
aleph.ALEPH_URL = old_url
for record in records:
marc = MARCXMLRecord(record)
additional_info = {'222': marc.get('222', None), 'PER': marc.get('PER', None), '7... | Query aleph for records with given `issn`. The lookup is directed to the
NTK's Aleph.
Args:
issn (str): ISSN of the periodical.
Returns:
obj: :class:`Model` instances for each record. | codesearchnet |
def _init_profile_batch(self, profile_batch):
profile_batch_error_message = f'profile_batch must be a non-negative integer or 2-tuple of positive integers. A pair of positive integers signifies a range of batches to profile. Found: {profile_batch}'
if isinstance(profile_batch, str):
profile_batch = str(... | Validate profile_batch value and set the range of batches to profile.
Sets values of _start_batch and _stop_batch attributes,
specifying the start and stop batch to profile.
Setting `profile_batch=0` disables profiling.
Args:
profile_batch: The range of batches to profile. Should be a
non-negative integer or a comma ... | github-repos |
def get_volume():
if (system.get_name() == 'windows'):
pass
elif (system.get_name() == 'mac'):
volume = system.get_cmd_out(['osascript', '-e', 'set ovol to output volume of (get volume settings); return the quoted form of ovol'])
return (int(volume) * 10)
else:
volume = syste... | Get the volume.
Get the current volume.
Returns:
int: The current volume (percentage, between 0 and 100). | codesearchnet |
def codemirror_field_css_bundle(field):
manifesto = CodemirrorAssetTagRender()
manifesto.register_from_fields(field)
try:
bundle_name = manifesto.css_bundle_names()[0]
except IndexError:
msg = "Given field with configuration name '{}' does not have a Javascript bundle name"
raise... | Filter to get CodeMirror CSS bundle name needed for a single field.
Example:
::
{% load djangocodemirror_tags %}
{{ form.myfield|codemirror_field_css_bundle }}
Arguments:
field (djangocodemirror.fields.CodeMirrorField): A form field.
Raises:
CodeMirrorFieldBundleError: Raised if Codemirror configuration from
field ... | codesearchnet |
def constant_value(pred):
if isinstance(pred, int):
if pred == 1:
pred = True
elif pred == 0:
pred = False
if isinstance(pred, variables.Variable):
return None
return smart_module.smart_constant_value(pred) | Return the bool value for `pred`, or None if `pred` had a dynamic value.
Args:
pred: A scalar, either a Python bool or a TensorFlow boolean variable
or tensor, or the Python integer 1 or 0.
Returns:
True or False if `pred` has a constant boolean value, None otherwise.
Raises:
TypeError: If `pred` is not a Variable, ... | github-repos |
def _path_components(self, path):
if ((not path) or (path == self._path_separator(path))):
return []
(drive, path) = self.splitdrive(path)
path_components = path.split(self._path_separator(path))
assert (drive or path_components)
if (not path_components[0]):
if ((len(path_components)... | Breaks the path into a list of component names.
Does not include the root directory as a component, as all paths
are considered relative to the root directory for the FakeFilesystem.
Callers should basically follow this pattern:
.. code:: python
file_path = self.absnormpath(file_path)
path_components = self._path_co... | codesearchnet |
def thread_safe_client(client, lock=None):
if (lock is None):
lock = threading.Lock()
return _ThreadSafeProxy(client, lock) | Create a thread-safe proxy which locks every method call
for the given client.
Args:
client: the client object to be guarded.
lock: the lock object that will be used to lock client's methods.
If None, a new lock will be used.
Returns:
A thread-safe proxy for the given client. | codesearchnet |
def deserialize_ndarray_npy(d):
with io.BytesIO() as f:
f.write(json.loads(d['npy']).encode('latin-1'))
f.seek(0)
return np.load(f) | Deserializes a JSONified :obj:`numpy.ndarray` that was created using numpy's
:obj:`save` function.
Args:
d (:obj:`dict`): A dictionary representation of an :obj:`ndarray` object, created
using :obj:`numpy.save`.
Returns:
An :obj:`ndarray` object. | juraj-google-style |
def open_stream(self, destination, timeout_ms=None):
timeout = timeouts.PolledTimeout.from_millis(timeout_ms)
stream_transport = self._make_stream_transport()
self.transport.write_message(adb_message.AdbMessage(command='OPEN', arg0=stream_transport.local_id, arg1=0, data=(destination + '\x00')), timeout)
... | Opens a new stream to a destination service on the device.
Not the same as the posix 'open' or any other Open methods, this
corresponds to the OPEN message described in the ADB protocol
documentation mentioned above. It creates a stream (uniquely identified
by remote/local ids) that connects to a particular service e... | codesearchnet |
def get_subject_without_validation(jwt_bu64):
try:
jwt_dict = get_jwt_dict(jwt_bu64)
except JwtException as e:
return log_jwt_bu64_info(logging.error, str(e), jwt_bu64)
try:
return jwt_dict['sub']
except LookupError:
log_jwt_dict_info(logging.error, 'Missing "sub" key', j... | Extract subject from the JWT without validating the JWT.
- The extracted subject cannot be trusted for authn or authz.
Args:
jwt_bu64: bytes
JWT, encoded using a a URL safe flavor of Base64.
Returns:
str: The subject contained in the JWT. | codesearchnet |
def _get_validation_labels(val_path):
labels_path = tfds.core.get_tfds_path(_VALIDATION_LABELS_FNAME)
with tf.io.gfile.GFile(labels_path) as labels_f:
labels = labels_f.read().strip().split('\n')
with tf.io.gfile.GFile(val_path, 'rb') as tar_f_obj:
tar = tarfile.open(mode='r:', fileobj=tar_... | Returns labels for validation.
Args:
val_path: path to TAR file containing validation images. It is used to
retrieve the name of pictures and associate them to labels.
Returns:
dict, mapping from image name (str) to label (str). | juraj-google-style |
def diff_charsToLines(self, diffs, lineArray):
for i in range(len(diffs)):
text = []
for char in diffs[i][1]:
text.append(lineArray[ord(char)])
diffs[i] = (diffs[i][0], ''.join(text)) | Rehydrate the text in a diff from a string of line hashes to real lines
of text.
Args:
diffs: Array of diff tuples.
lineArray: Array of unique strings. | codesearchnet |
def forward(self, x):
head_outputs = [None] * self.t
if isinstance(self.input_layer, list):
input_outputs = [mod(x) for mod, x in zip(self.input_layer, x)]
x = torch.stack(input_outputs, dim=1)
for t in self.task_map[0]:
... | Returns a list of outputs for tasks 0,...t-1
Args:
x: a [batch_size, ...] batch from X | juraj-google-style |
def send_message(
self, request: str, response_expected: bool, **kwargs: Any
) -> Response:
payload = str(request) + self.delimiter
self.socket.send(payload.encode(self.encoding))
response = bytes()
decoded = None
while True:
r... | Transport the message to the server and return the response.
Args:
request: The JSON-RPC request string.
response_expected: Whether the request expects a response.
Returns:
A Response object. | juraj-google-style |
def userhome(username=None):
if username is None:
if 'HOME' in os.environ:
userhome_dpath = os.environ['HOME']
else:
if sys.platform.startswith('win32'):
if 'USERPROFILE' in os.environ:
userhome_dpath = os.e... | Returns the user's home directory.
If `username` is None, this is the directory for the current user.
Args:
username (str): name of a user on the system
Returns:
PathLike: userhome_dpath: path to the home directory
Example:
>>> import getpass
>>> username = getpass.getuser()
>>> assert userhome() == expanduser('~')
... | juraj-google-style |
def quantization_mode(self):
return self._quantization_mode | The quantization mode of this policy.
Returns:
The quantization mode of this policy, as a string. If this policy is
not quantized, it will return `None`. | github-repos |
def index_update(x, idx, y):
return _index_update_helper(tf_np.ndarray._with_index_update, x, idx, y) | Pure equivalent of `x[idx] = y`.
Returns the value of x that would result from the NumPy-style indexed
assignment `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`, integers, slice objects,
ellipses,... | github-repos |
def _cmd_quote(cmd):
r
pattern = re.compile('^(\\"|\').*|.*(\\"|\')$')
while pattern.match(cmd) is not None:
cmd = cmd.strip('"').strip('\'')
cmd = '"{0}"'.format(cmd)
return cmd | r'''
Helper function to properly format the path to the binary for the service
Must be wrapped in double quotes to account for paths that have spaces. For
example:
``"C:\Program Files\Path\to\bin.exe"``
Args:
cmd (str): Full path to the binary
Returns:
str: Properly quoted path to the binary | juraj-google-style |
def parse_pair_args(labels, argclass):
label_data = set()
for arg in labels:
(name, value) = split_pair(arg, '=', nullable_idx=1)
label_data.add(argclass(name, value))
return label_data | Parse flags of key=value pairs and return a list of argclass.
For pair variables, we need to:
* split the input into name=value pairs (value optional)
* Create the EnvParam object
Args:
labels: list of 'key' or 'key=value' strings.
argclass: Container class for args, must instantiate with argclass(k, v).
Returns:
li... | codesearchnet |
def GetCommand(self, include_separators=True):
args = []
if self.name:
args.append(self.name)
for element in self.elements:
if element.HasError():
continue
if element.args:
args.extend(element.args)
if element.HasSeparator() and include_separators:
... | Returns the command representing the trace up to this point.
Args:
include_separators: Whether or not to include separators in the command.
Returns:
A string representing a Fire CLI command that would produce this trace. | github-repos |
def update_endpoint(self, endpoint_name, endpoint_config_name):
if not _deployment_entity_exists(lambda: self.sagemaker_client.describe_endpoint(EndpointName=endpoint_name)):
raise ValueError('Endpoint with name "{}" does not exist; please use an existing endpoint name'
... | Update an Amazon SageMaker ``Endpoint`` according to the endpoint configuration specified in the request
Raise an error if endpoint with endpoint_name does not exist.
Args:
endpoint_name (str): Name of the Amazon SageMaker ``Endpoint`` to update.
endpoint_config_name (str): Name of the Amazon SageMaker endpoint confi... | juraj-google-style |
def _extract_relative_dates(self, text: str) -> List[Extraction]:
if not text or not self._etk:
return list()
base = self._settings[RELATIVE_BASE] if self._settings[RELATIVE_BASE] else datetime.datetime.now()
if not self._settings[RETURN_AS_TIMEZONE_AWARE]:
base ... | Extract relative dates using spaCy rules
Args:
text: str - the text to extract the relative date strings from
Returns: List of Extraction(s) | juraj-google-style |
def flatten_dict_items(dictionary):
return _pywrap_nest.FlattenDictItems(dictionary) | Returns a dictionary with flattened keys and values.
This function flattens the keys and values of a dictionary, which can be
arbitrarily nested structures, and returns the flattened version of such
structures:
```python
example_dictionary = {(4, 5, (6, 8)): ("a", "b", ("c", "d"))}
result = {4: "a", 5: "b", 6: "c", 8... | github-repos |
def convert_tanh(params, w_name, scope_name, inputs, layers, weights, names):
print('Converting tanh ...')
if names == 'short':
tf_name = 'TANH' + random_string(4)
elif names == 'keep':
tf_name = w_name
else:
tf_name = w_name + str(random.random())
tanh = keras.layers.... | Convert tanh layer.
Args:
params: dictionary with layer parameters
w_name: name prefix in state_dict
scope_name: pytorch scope name
inputs: pytorch node inputs
layers: dictionary with keras tensors
weights: pytorch state_dict
names: use short names for keras layers | juraj-google-style |
def get_package(self, name) -> 'EffectPackage':
name, cls_name = parse_package_string(name)
try:
return self.package_map[name]
except KeyError:
raise EffectError("No package '{}' registered".format(name)) | Get a package by python path. Can also contain path to an effect.
Args:
name (str): Path to effect package or effect
Returns:
The requested EffectPackage
Raises:
EffectError when no package is found | juraj-google-style |
def _events_from_file(filepath):
records = list(tf.compat.v1.python_io.tf_record_iterator(filepath))
result = []
for r in records:
event = tf.compat.v1.Event()
event.ParseFromString(r)
result.append(event)
return result | Returns all events in a single event file.
Args:
filepath: Path to the event file.
Returns:
A list of all tf.compat.v1.Event protos in the event file. | github-repos |
def _parse_peer_link(self, config):
match = re.search(r'peer-link (\S+)', config)
value = match.group(1) if match else None
return dict(peer_link=value) | Scans the config block and parses the peer-link value
Args:
config (str): The config block to scan
Returns:
dict: A dict object that is intended to be merged into the
resource dict | juraj-google-style |
def get_path(self, url):
cache_path = self._url_to_path(url)
if os.path.exists(cache_path):
return cache_path
return None | Returns the path of a cached resource.
Args:
url: The url of the resource
Returns:
The path to the cached resource or None if not in the cache | juraj-google-style |
def evaluate(conditions, leaf_evaluator):
if isinstance(conditions, list):
if (conditions[0] in list(EVALUATORS_BY_OPERATOR_TYPE.keys())):
return EVALUATORS_BY_OPERATOR_TYPE[conditions[0]](conditions[1:], leaf_evaluator)
else:
return EVALUATORS_BY_OPERATOR_TYPE[ConditionOpera... | Top level method to evaluate conditions.
Args:
conditions: Nested array of and/or conditions, or a single leaf condition value of any type.
Example: ['and', '0', ['or', '1', '2']]
leaf_evaluator: Function which will be called to evaluate leaf condition values.
Returns:
Boolean: Result of evaluating the conditions usi... | codesearchnet |
def forward(self, s: torch.Tensor, z: Optional[torch.Tensor], r: Rigid, mask: torch.Tensor, _offload_inference: bool=False, _z_reference_list: Optional[Sequence[torch.Tensor]]=None) -> torch.Tensor:
z = [z]
q = self.linear_q(s)
kv = self.linear_kv(s)
q = q.view(q.shape[:-1] + (self.num_heads, -1))
k... | Args:
s:
[*, N_res, C_s] single representation
z:
[*, N_res, N_res, C_z] pair representation
r:
[*, N_res] transformation object
mask:
[*, N_res] mask
Returns:
[*, N_res, C_s] single representation update | github-repos |
def Open(self, file_object):
self._file_object = file_object
self._regf_file.open_file_object(self._file_object)
return True | Opens the Windows Registry file using a file-like object.
Args:
file_object (file): file-like object.
Returns:
bool: True if successful or False if not. | juraj-google-style |
def _retrieve_offsets(self, timestamps, timeout_ms=float('inf')):
if (not timestamps):
return {}
start_time = time.time()
remaining_ms = timeout_ms
while (remaining_ms > 0):
future = self._send_offset_requests(timestamps)
self._client.poll(future=future, timeout_ms=remaining_ms)
... | Fetch offset for each partition passed in ``timestamps`` map.
Blocks until offsets are obtained, a non-retriable exception is raised
or ``timeout_ms`` passed.
Arguments:
timestamps: {TopicPartition: int} dict with timestamps to fetch
offsets by. -1 for the latest available, -2 for the earliest
available. Otherwise ti... | codesearchnet |
def internal_convert_n_to_tensor_or_composite(values, dtype=None, name=None, as_ref=False) -> list[Union[EagerTensor, SymbolicTensor, composite_tensor.CompositeTensor, type(None)]]:
if not isinstance(values, collections_abc.Sequence):
raise TypeError('values must be a sequence.')
ret = []
for i, val... | Converts `values` to a list of `Tensor` or `CompositeTensor` objects.
Any `CompositeTensor` objects in `values` are returned unmodified.
Args:
values: A list of `None`, `CompositeTensor`, or objects that can be consumed
by `convert_to_tensor()`.
dtype: (Optional.) The required `DType` of the returned `Tensor`s or
`Co... | github-repos |
def get_new_requests(self):
content_type = self.__queue_item.response.headers.get('content-type')
scrapers = self.__get_all_scrapers()
new_requests = []
for scraper in scrapers:
instance = scraper(self.__options, self.__queue_item)
if self.__content_type_matches(content_type, instance.co... | Retrieve all the new request that were found in this request.
Returns:
list(:class:`nyawc.http.Request`): A list of request objects. | codesearchnet |
def get_examples(self, compact=False):
examples = copy.deepcopy(self._examples)
if (not compact):
return examples
def make_compact(d):
if (not isinstance(d, dict)):
return
for key in d:
if isinstance(d[key], dict):
inner_d = d[key]
... | Returns an OrderedDict mapping labels to Example objects.
Args:
compact (bool): If True, union members of void type are converted
to their compact representation: no ".tag" key or containing
dict, just the tag as a string. | codesearchnet |
def get_chain(self, name, table="filter"):
return [r for r in self.rules if r["table"] == table and r["chain"] == name] | Get the list of rules for a particular chain. Chain order is kept intact.
Args:
name (str): chain name, e.g. ``
table (str): table name, defaults to ``filter``
Returns:
list: rules | juraj-google-style |
def __init__(self, channel):
self.ListNotificationChannelDescriptors = channel.unary_unary(
"/google.monitoring.v3.NotificationChannelService/ListNotificationChannelDescriptors",
request_serializer=google_dot_cloud_dot_monitoring__v3_dot_proto_dot_notification__service__pb2.List... | Constructor.
Args:
channel: A grpc.Channel. | juraj-google-style |
def write_to_file(self, filename='material_index.dat', plot=True):
path = os.path.dirname(sys.modules[__name__].__file__) + '/'
dir_plot = 'material_index/'
if not os.path.exists(dir_plot):
os.makedirs(dir_plot)
for axis, name in zip(self.axes, self.axes_str):
... | Write the refractive index profile to file.
Args:
filename (str): The nominal filename the refractive
index data should be saved to.
plot (bool): `True` if plots should be generates,
otherwise `False`. Default is `True`. | juraj-google-style |
def _database_string(self):
if (self._database_string_internal is None):
db_str = firestore_client.FirestoreClient.database_root_path(self.project, self._database)
self._database_string_internal = db_str
return self._database_string_internal | The database string corresponding to this client's project.
This value is lazy-loaded and cached.
Will be of the form
``projects/{project_id}/databases/{database_id}``
but ``database_id == '(default)'`` for the time being.
Returns:
str: The fully-qualified database string for the current
project. (The default data... | codesearchnet |
def smear(self, sigma):
diff = [self.x[i + 1] - self.x[i] for i in range(len(self.x) - 1)]
avg_x_per_step = np.sum(diff) / len(diff)
if len(self.ydim) == 1:
self.y = gaussian_filter1d(self.y, sigma / avg_x_per_step)
else:
self.y = np.array([
... | Apply Gaussian smearing to spectrum y value.
Args:
sigma: Std dev for Gaussian smear function | juraj-google-style |
def parse(cls, buf: memoryview, params: Params) \
-> Tuple[Parseable, memoryview]:
for data_type in params.expected:
try:
return data_type.parse(buf, params)
except NotParseable:
pass
raise UnexpectedType(buf) | Parses the given buffer by attempting to parse the list of
:attr:`~Params.expected` types until one of them succeeds,
then returns the parsed object.
Args:
buf: The bytes containing the data to be parsed.
params: The parameters used by some parseable types. | juraj-google-style |
def _get_segments(self, start, request_size):
if not request_size:
return []
end = start + request_size
futures = []
while request_size > self._max_request_size:
futures.append(self._get_segment(start, self._max_request_size))
request_size -= self._max_request_size
start +... | Get segments of the file from Google Storage as a list.
A large request is broken into segments to avoid hitting urlfetch
response size limit. Each segment is returned from a separate urlfetch.
Args:
start: start offset to request. Inclusive. Have to be within the
range of the file.
request_size: number of bytes to r... | juraj-google-style |
def lock(vcs, lock_object, wait=True):
if wait:
timeout = (- 1)
else:
timeout = 0
lock_path = _get_lock_path(vcs, lock_object)
lock = filelock.FileLock(lock_path)
with lock.acquire(timeout=timeout):
(yield) | A context manager that grabs the lock and releases it when done.
This blocks until the lock can be acquired.
Args:
vcs (easyci.vcs.base.Vcs)
lock_object (Lock)
wait (boolean) - whether to wait for the lock or error out
Raises:
Timeout | codesearchnet |
def get_shape(value: Union[types.FloatTensor, types.IntTensor]) -> types.IntTensor:
result = value.shape
return tf.shape(value) if None in result.as_list() else result | Returns the `shape` of a given `Tensor`.
Args:
value: Scalar `Tensor of integers or real values.
Returns:
`Tensor` of integers with rank 1. | github-repos |
def is_registered(self, prefix):
return self._resolve_prefix(prefix) is not None | Test if a command prefix or its alias is has a registered handler.
Args:
prefix: A prefix or its alias, as a str.
Returns:
True iff a handler is registered for prefix. | github-repos |
def parse(self, text, key=None):
try:
data = json.loads(text)
except ValueError as e:
raise ValueError(('%s: Value: [%s]' % (e, text)))
if (data and key):
if (key not in data):
raise ValueError(('Invalid response (key %s not found): %s' % (key, data)))
data = data... | Parses a response.
Args:
text (str): Text to parse
Kwargs:
key (str): Key to look for, if any
Returns:
Parsed value
Raises:
ValueError | codesearchnet |
def plot_heldout_prediction(input_vals, probs, fname, n=10, title=''):
fig = figure.Figure(figsize=(9, (3 * n)))
canvas = backend_agg.FigureCanvasAgg(fig)
for i in range(n):
ax = fig.add_subplot(n, 3, ((3 * i) + 1))
ax.imshow(input_vals[(i, :)].reshape(IMAGE_SHAPE[:(- 1)]), interpolation='No... | Save a PNG plot visualizing posterior uncertainty on heldout data.
Args:
input_vals: A `float`-like Numpy `array` of shape
`[num_heldout] + IMAGE_SHAPE`, containing heldout input images.
probs: A `float`-like Numpy array of shape `[num_monte_carlo,
num_heldout, num_classes]` containing Monte Carlo samples of
class pro... | codesearchnet |
def from_text_vision_configs(cls, text_config: BlipTextConfig, vision_config: BlipVisionConfig, **kwargs):
return cls(text_config=text_config.to_dict(), vision_config=vision_config.to_dict(), **kwargs) | Instantiate a [`BlipConfig`] (or a derived class) from blip text model configuration and blip vision model
configuration.
Returns:
[`BlipConfig`]: An instance of a configuration object | github-repos |
def printMe(self, selfKey, selfValue):
text = '<key>{keyName}</key>\n'.format(keyName=selfKey)
if len(selfValue) == 0:
return ''
else:
valueText = ''
for element in selfValue:
if singleOrPair(element) == 'Single':
... | Parse the single and its value and return the parsed str.
Args:
selfTag (str): The tag. Normally just ``self.tag``
selfValue (list): a list of value elements(single, subclasses, str, int). Normally just ``self.value``
Returns:
str: A parsed text | juraj-google-style |
def SetCampaignTargetingCriteria(client, campaign):
campaign_criterion_service = client.GetService('CampaignCriterionService')
criteria = [
{
'xsi_type': 'Location',
'id': 21137
},
{
'xsi_type': 'Location',
'id': 2484
},
{
... | Sets targeting criteria for the given campaign.
Args:
client: An AdWordsClient instance.
campaign: A suds object representing the campaign we wish to attach
targeting criteria. | juraj-google-style |
def upgrade_name(self, user_):
if user_.name_type > self.name_type:
self.full_name = user_.full_name
self.first_name = user_.first_name
self.name_type = user_.name_type
logger.debug('Added %s name to User "%s": %s',
self.name_type... | Upgrade name type of this user.
Google Voice participants often first appear with no name at all, and
then get upgraded unpredictably to numbers ("+12125551212") or names.
Args:
user_ (~hangups.user.User): User to upgrade with. | juraj-google-style |
def has_node_with_value(self, value):
for node in self.node_list:
if node.value == value:
return True
else:
return False | Whether any node in ``self.node_list`` has the value ``value``.
Args:
value (Any): The value to find in ``self.node_list``
Returns: bool
Example:
>>> from blur.markov.node import Node
>>> node_1 = Node('One')
>>> graph = Graph([node_1])
>>> graph.has_node_with_value('One')
True
>>> graph.has_node_with_value('Foo')
F... | juraj-google-style |
def get_distribution_dict(metric_type, submit_timestamp, dist, metric_id):
return DistributionMetric(dist, submit_timestamp, metric_id, metric_type).as_dict() | Function creates :class:`DistributionMetric`
Args:
metric_type(str): type of value from distribution metric which will
be saved (ex. max, min, mean, sum)
submit_timestamp: timestamp when metric is saved
dist(object) distribution object from pipeline result
metric_id(uuid): id of the current test run
Returns:
dictiona... | github-repos |
def profile_view(request, user_id=None):
if request.user.is_eighthoffice and "full" not in request.GET and user_id is not None:
return redirect("eighth_profile", user_id=user_id)
if user_id is not None:
try:
profile_user = User.objects.get(id=user_id)
if profile_us... | Displays a view of a user's profile.
Args:
user_id
The ID of the user whose profile is being viewed. If not
specified, show the user's own profile. | juraj-google-style |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.