code stringlengths 20 4.93k | docstring stringlengths 33 1.27k | source stringclasses 3
values |
|---|---|---|
def __init__(
self,
pooling_type='max',
window=2,
stride=2,
padding='SAME',
named_tensors=None,
scope='pool2d',
summary_labels=()
):
self.pooling_type = pooling_type
if isinstance(window, int):
self.window = (1, win... | 2-dimensional pooling layer.
Args:
pooling_type: Either 'max' or 'average'.
window: Pooling window size, either an integer or pair of integers.
stride: Pooling stride, either an integer or pair of integers.
padding: Pooling padding, one of 'VALID' or 'SAME'. | juraj-google-style |
def _prepare_4d_causal_attention_mask(attention_mask: Optional[torch.Tensor], input_shape: Union[torch.Size, tuple, list], inputs_embeds: torch.Tensor, past_key_values_length: int, sliding_window: Optional[int]=None):
attn_mask_converter = AttentionMaskConverter(is_causal=True, sliding_window=sliding_window)
ke... | Creates a causal 4D mask of shape `(batch_size, 1, query_length, key_value_length)` from a 2D mask of shape
`(batch_size, key_value_length)`
Args:
attention_mask (`torch.Tensor` or `None`):
A 2D attention mask of shape `(batch_size, key_value_length)`
input_shape (`tuple(int)` or `list(int)` or `torch.Size`):
The inpu... | github-repos |
def usufyToPngExport(d, fPath):
newGraph = _generateGraphData(d)
import matplotlib.pyplot as plt
nx.draw(newGraph)
plt.savefig(fPath) | Workaround to export to a png file.
Args:
-----
d: Data to export.
fPath: File path for the output file. | juraj-google-style |
def nonzero(x):
if any_symbolic_tensors((x,)):
return Nonzero().symbolic_call(x)
return backend.numpy.nonzero(x) | Return the indices of the elements that are non-zero.
Args:
x: Input tensor.
Returns:
Indices of elements that are non-zero. | github-repos |
def __build_helper_map(cls):
ret = {}
for name in dir(cls):
obj = getattr(cls, name)
if ishelper(obj):
for cmd in obj.__help_targets__:
if (cmd in ret.keys()):
raise PyShellError("The command '{}' already has helper method '{}', cannot register a s... | Build a mapping from command names to helper names.
One command name maps to at most one helper method.
Multiple command names can map to the same helper method.
Only used by __init__() to initialize self._cmd_map. MUST NOT be used
elsewhere.
Raises:
PyShellError: A command maps to multiple helper methods. | codesearchnet |
def _extract_filename(self, flagfile_str):
if flagfile_str.startswith('--flagfile='):
return os.path.expanduser((flagfile_str[(len('--flagfile=')):]).strip())
elif flagfile_str.startswith('-flagfile='):
return os.path.expanduser((flagfile_str[(len('-flagfile=')):]).strip())
else:
rais... | Returns filename from a flagfile_str of form -[-]flagfile=filename.
The cases of --flagfile foo and -flagfile foo shouldn't be hitting
this function, as they are dealt with in the level above this
function.
Args:
flagfile_str: str, the flagfile string.
Returns:
str, the filename from a flagfile_str of form -[-]flagf... | juraj-google-style |
def find_user(cls, session, mailbox, user):
return cls(
'/mailboxes/%d/users/%s/conversations.json' % (
mailbox.id, user.id,
),
session=session,
) | Return conversations for a specific user in a mailbox.
Args:
session (requests.sessions.Session): Authenticated session.
mailbox (helpscout.models.Mailbox): Mailbox to search.
user (helpscout.models.User): User to search for.
Returns:
RequestPaginator(output_type=helpscout.models.Conversation):
Conversations iterator... | juraj-google-style |
def create_from_options(cls, pipeline_options):
from apache_beam.options.pipeline_options import PipelineOptions
if not isinstance(pipeline_options, PipelineOptions):
raise ValueError('Element of class {}.{} does not subclass PipelineOptions'.format(pipeline_options.__module__, pipeline_options.__class_... | Creates :class:`~apache_beam.transforms.display.DisplayData` from a
:class:`~apache_beam.options.pipeline_options.PipelineOptions` instance.
When creating :class:`~apache_beam.transforms.display.DisplayData`, this
method will convert the value of any item of a non-supported type to its
string representation.
The norma... | github-repos |
def _list_profile_filter(profile_datum, node_name_regex, file_path_regex, op_type_regex, op_time_interval, exec_time_interval, min_lineno=-1, max_lineno=-1):
if node_name_regex and (not node_name_regex.match(profile_datum.node_exec_stats.node_name)):
return False
if file_path_regex:
if not profi... | Filter function for list_profile command.
Args:
profile_datum: A `ProfileDatum` object.
node_name_regex: Regular expression pattern object to filter by name.
file_path_regex: Regular expression pattern object to filter by file path.
op_type_regex: Regular expression pattern object to filter by op type.
op_time_interva... | github-repos |
def _tf_extension_type_with_packed(self, value):
copy = _create_object_from_type_and_dict(type(self), self.__dict__)
copy.__dict__['_tf_extension_type_is_packed'] = value
return copy | Returns a copy of this `TypeSpec` with `packed=value`.
Args:
value: A boolean value.
Returns:
A copy of `self` with `_tf_extension_type_is_packed=value`. | github-repos |
def stats(self, *args):
result = self._fetch_cmd(b'stats', args, False)
for key, value in six.iteritems(result):
converter = STAT_TYPES.get(key, int)
try:
result[key] = converter(value)
except Exception:
pass
return r... | The memcached "stats" command.
The returned keys depend on what the "stats" command returns.
A best effort is made to convert values to appropriate Python
types, defaulting to strings when a conversion cannot be made.
Args:
*arg: extra string arguments to the "stats" command. See the
memcached protocol documentation ... | juraj-google-style |
def flat_values_spec(self):
return self._flat_values_spec | The `TypeSpec` of the flat_values of RaggedTensor.
Returns:
- The TypeSpec of flat_values.
- None when the flat_values is a Tensor. | github-repos |
def init(args):
dir_path = Path().absolute()
if not args.project_name or args.project_name.find("/") >= 0:
print(
"{}You should specify a valid project name{}".format(
utils.colors.FAIL, utils.colors.ENDC
)
)
return
project_path = d... | Initialize a Home Documentation's folder
Args:
args (ArgumentParser): Flags from the CLI | juraj-google-style |
def _init_local_init_op(self, local_init_op=USE_DEFAULT):
if local_init_op is Supervisor.USE_DEFAULT:
local_init_op = self._get_first_op_from_collection(ops.GraphKeys.LOCAL_INIT_OP)
if local_init_op is None:
op_list = [variables.local_variables_initializer(), lookup_ops.tables_initialize... | Initializes local_init_op.
Args:
local_init_op: `Operation` run for every new supervisor instance. If set
to USE_DEFAULT, use the first op from the GraphKeys.LOCAL_INIT_OP
collection. If the collection is empty, create an op that initializes
all local variables and all tables. | github-repos |
def num_samples(self, sr=None):
native_sr = self.sampling_rate
num_samples = units.seconds_to_sample(self.duration, native_sr)
if (sr is not None):
ratio = (float(sr) / native_sr)
num_samples = int(np.ceil((num_samples * ratio)))
return num_samples | Return the number of samples.
Args:
sr (int): Calculate the number of samples with the given
sampling-rate. If None use the native sampling-rate.
Returns:
int: Number of samples | codesearchnet |
def execute(self, triple_map, output, **kwargs):
subjects = []
found_elements = self.source.xpath(
str(triple_map.logicalSource.iterator),
namespaces=self.xml_ns)
for element in found_elements:
subject = self.generate_term(term_map=triple_map.subjectM... | Method executes mapping between source
Args:
-----
triple_map: SimpleNamespace, Triple Map | juraj-google-style |
def MakeSimpleProtoClass(fields, full_name=None, pool=None):
factory = message_factory.MessageFactory(pool=pool)
if (full_name is not None):
try:
proto_cls = _GetMessageFromFactory(factory, full_name)
return proto_cls
except KeyError:
pass
field_items = fi... | Create a Protobuf class whose fields are basic types.
Note: this doesn't validate field names!
Args:
fields: dict of {name: field_type} mappings for each field in the proto. If
this is an OrderedDict the order will be maintained, otherwise the
fields will be sorted by name.
full_name: optional str, the fully-qualifie... | codesearchnet |
def _generate_subtokens(token_counts, alphabet, min_count, num_iterations=4, reserved_tokens=None):
if (reserved_tokens is None):
reserved_tokens = RESERVED_TOKENS
subtoken_list = (reserved_tokens + list(alphabet))
max_subtoken_length = 1
for i in xrange(num_iterations):
tf.logging.info(... | Create a list of subtokens in decreasing order of frequency.
Args:
token_counts: dict mapping str tokens -> int count
alphabet: set of characters
min_count: int minimum number of times a subtoken must appear before it is
added to the vocabulary.
num_iterations: int number of iterations to generate new tokens.
reserved... | codesearchnet |
def pad_to_square(self, images: 'torch.Tensor', background_color: Union[int, Tuple[int, int, int]]=0) -> 'torch.Tensor':
height, width = get_image_size(images, ChannelDimension.FIRST)
if height == width:
return images
num_channels = images.shape[1] if len(images.shape) == 4 else images.shape[0]
... | Pads an image to a square based on the longest edge.
Args:
images (`np.ndarray`):
The images to pad.
background_color (`int` or `Tuple[int, int, int]`, *optional*, defaults to 0):
The color to use for the padding. Can be an integer for single channel or a
tuple of integers representing for multi-channel images. If pas... | github-repos |
def _sd_of_runs(stats, mean, key='runs'):
num_runs = len(stats[key])
first = stats[key][0]
standard_deviation = {}
for stat_key in first:
if isinstance(first[stat_key], numbers.Number):
standard_deviation[stat_key] = math.sqrt(
sum((run[stat_key] - mea... | Obtain the standard deviation of stats.
Args:
stats: dict; A set of stats, structured as above.
mean: dict; Mean for each key in stats.
key: str; Optional key to determine where list of runs is found in stats | juraj-google-style |
def convert_transpose(params, w_name, scope_name, inputs, layers, weights, names):
print('Converting transpose ...')
if (params['perm'][0] != 0):
if (inputs[0] in layers):
print('!!! Cannot permute batch dimension. Result may be wrong !!!')
layers[scope_name] = layers[inputs[0]]
... | Convert transpose layer.
Args:
params: dictionary with layer parameters
w_name: name prefix in state_dict
scope_name: pytorch scope name
inputs: pytorch node inputs
layers: dictionary with keras tensors
weights: pytorch state_dict
names: use short names for keras layers | codesearchnet |
def set_energy(self, spins, target_energy):
spin_energy = self.energy(spins)
self.assertions.add(Equals(spin_energy, limitReal(target_energy))) | Set the energy of Theta with spins fixed to target_energy.
Args:
spins (dict): Spin values for a subset of the variables in Theta.
target_energy (float): The desired energy for Theta with spins fixed.
Notes:
Add equality constraint to assertions. | juraj-google-style |
def create_branch(self, branch_name: str):
LOGGER.info('creating branch: %s', branch_name)
self._validate_branch_name(branch_name)
if branch_name in self.list_branches():
LOGGER.error('branch already exists')
sys.exit(-1)
new_branch = self.repo.create_hea... | Creates a new branch
Args:
branch_name: name of the branch | juraj-google-style |
def _ParseAttribute(self, file_object):
file_offset = file_object.tell()
attribute_map = self._GetDataTypeMap('cups_ipp_attribute')
try:
(attribute, _) = self._ReadStructureFromFileObject(file_object, file_offset, attribute_map)
except (ValueError, errors.ParseError) as exception:
raise ... | Parses a CUPS IPP attribute from a file-like object.
Args:
file_object (dfvfs.FileIO): file-like object.
Returns:
tuple[str, object]: attribute name and value.
Raises:
ParseError: if the attribute cannot be parsed. | codesearchnet |
def _process_exception(e, body, tb):
msg = e.message if hasattr(e, "message") else str(e)
exception_type = str(e.__class__)
exception_name = str(e.__class__.__name__)
properties = pika.BasicProperties(
content_type="application/text",
delivery_mode=2,
headers={
... | Process informations about exception and send them thru AMQP.
Args:
e (obj): Exception instance.
body (str): Text which will be sent over AMQP.
tb (obj): Traceback object with informations, which will be put to the
headers. | juraj-google-style |
def to_insert(table, d):
columns = []
args = []
for (key, val) in d.items():
columns.append('"{}"'.format(key))
args.append(val)
stmt = 'insert into {table} ({columns}) values ({params})'.format(table=table, columns=', '.join(columns), params=', '.join((['?'] * len(columns))))
return... | Generate an insert statement using the given table and dictionary.
Args:
table (str): table name
d (dict): dictionary with column names as keys and values as values.
Returns:
tuple of statement and arguments
>>> to_insert('doc.foobar', {'name': 'Marvin'})
('insert into doc.foobar ("name") values (?)', ['Marvin']) | codesearchnet |
def get_id(date: datetime.datetime) -> str:
date = date.strftime('%Y%m%d')
return 'PB-{}-{}-{:03d}'.format(date, 'sip', randint(0, 100)) | Generate a Processing Block (PB) Instance ID.
Args:
date (datetime.datetime): UTC date of the PB
Returns:
str, Processing Block ID | juraj-google-style |
def _try_parse_datetime(time_str, fmts):
result = None
for fmt in fmts:
try:
result = datetime.strptime(time_str, fmt)
break
except ValueError:
pass
return result | A helper function that attempts to parse the input time_str as a date.
Args:
time_str (str): A string representing the time
fmts (list): A list of date format strings
Returns:
datetime: Returns a datetime object if parsed properly, otherwise None | juraj-google-style |
def raster_erosion(rasterfile):
if is_string(rasterfile):
origin_raster = RasterUtilClass.read_raster(str(rasterfile))
elif isinstance(rasterfile, Raster):
origin_raster = rasterfile.data
elif isinstance(rasterfile, numpy.ndarray):
origin_raster = rasterfile
else:
return ... | Erode the raster image.
Find the min pixel's value in 8-neighborhood. Then change the compute
pixel's value into the min pixel's value.
Args:
rasterfile: input original raster image, type can be filename(string,
like "test1.tif"), rasterfile(class Raster) or numpy.ndarray.
Returns:
erosion_raster: raster image after... | codesearchnet |
def _parse_access_vlan(self, config):
value = re.search(r'switchport access vlan (\d+)', config)
return dict(access_vlan=value.group(1)) | Scans the specified config and parse the access-vlan value
Args:
config (str): The interface configuration block to scan
Returns:
dict: A Python dict object with the value of switchport access
value. The dict returned is intended to be merged into the
resource dict | juraj-google-style |
def assert_consumed(self):
pretty_printer = ObjectGraphProtoPrettyPrinter(self._checkpoint.object_graph_proto)
self.assert_existing_objects_matched()
ignore_node_ids = []
if self._options.experimental_skip_slot_variables:
for node in self._checkpoint.object_graph_proto.nodes:
for sv ... | Asserts that all objects in the checkpoint have been created/matched.
Returns:
`self` for chaining.
Raises:
AssertionError: If there are any Python objects in the dependency graph
which have not been restored from this checkpoint or a later `restore`,
or if there are any checkpointed values which have not been matched... | github-repos |
def get_contrib_features(project_root):
project = Project(project_root)
contrib = project._resolve('.features.contrib')
return _get_contrib_features(contrib) | Get contributed features for a project at project_root
For a project ``foo``, walks modules within the ``foo.features.contrib``
subpackage. A single object that is an instance of ``ballet.Feature`` is
imported if present in each module. The resulting ``Feature`` objects are
collected.
Args:
project_root (str, path-li... | juraj-google-style |
def global_step(sess, global_step_tensor):
if context.executing_eagerly():
return int(global_step_tensor.numpy())
return int(sess.run(global_step_tensor)) | Small helper to get the global step.
```python
# Create a variable to hold the global_step.
global_step_tensor = tf.Variable(10, trainable=False, name='global_step')
# Create a session.
sess = tf.compat.v1.Session()
# Initialize the variable
sess.run(global_step_tensor.initializer)
# Get the variable value.
print('glo... | github-repos |
def sg_summary_audio(tensor, sample_rate=16000, prefix=None, name=None):
r
prefix = '' if prefix is None else prefix + '/'
name = prefix + _pretty_name(tensor) if name is None else prefix + name
if not tf.get_variable_scope().reuse:
tf.summary.audio(name + '-au', tensor, sample_ra... | r"""Register `tensor` to summary report as audio
Args:
tensor: A `Tensor` to log as audio
sample_rate : An int. Sample rate to report. Default is 16000.
prefix: A `string`. A prefix to display in the tensor board web UI.
name: A `string`. A name to display in the tensor board web UI.
Returns:
None | juraj-google-style |
def update(self, session, arrays=None, frame=None):
new_config = self._get_config()
if self._enough_time_has_passed(self.previous_config['FPS']):
self.visualizer.update(new_config)
self.last_update_time = time.time()
final_image = self._update_frame(session, arrays, frame, new_config)
... | Creates a frame and writes it to disk.
Args:
arrays: a list of np arrays. Use the "custom" option in the client.
frame: a 2D np array. This way the plugin can be used for video of any
kind, not just the visualization that comes with the plugin.
frame can also be a function, which only is evaluated when the
"frame" op... | codesearchnet |
def _ReadTablesArray(self, file_object, tables_array_offset):
data_type_map = self._GetDataTypeMap('keychain_tables_array')
tables_array, _ = self._ReadStructureFromFileObject(
file_object, tables_array_offset, data_type_map)
tables = collections.OrderedDict()
for table_offset ... | Reads the tables array.
Args:
file_object (file): file-like object.
tables_array_offset (int): offset of the tables array relative to
the start of the file.
Returns:
dict[int, KeychainDatabaseTable]: tables per identifier.
Raises:
ParseError: if the tables array cannot be read. | juraj-google-style |
def sin(x):
if any_symbolic_tensors((x,)):
return Sin().symbolic_call(x)
return backend.numpy.sin(x) | Trigonometric sine, element-wise.
Arguments:
x: Input tensor.
Returns:
Output tensor of same shape as `x`. | github-repos |
def _setup_test_logger(log_path, prefix=None):
log = logging.getLogger()
kill_test_logger(log)
log.propagate = False
log.setLevel(logging.DEBUG)
terminal_format = log_line_format
if prefix:
terminal_format = '[%s] %s' % (prefix, log_line_format)
c_formatter = logging.Format... | Customizes the root logger for a test run.
The logger object has a stream handler and a file handler. The stream
handler logs INFO level to the terminal, the file handler logs DEBUG
level to files.
Args:
log_path: Location of the log file.
prefix: A prefix for each log line in terminal.
filename: Name of the log file... | juraj-google-style |
def standardize(self, x):
if self.preprocessing_function:
x = self.preprocessing_function(x)
if self.rescale:
x *= self.rescale
if self.samplewise_center:
x -= np.mean(x, keepdims=True)
if self.samplewise_std_normalization:
x /= np.std(x, keepdims=True) + 1e-06
if sel... | Applies the normalization configuration in-place to a batch of
inputs.
`x` is changed in-place since the function is mainly used internally
to standardize images and feed them to your network. If a copy of `x`
would be created instead it would have a significant performance cost.
If you want to apply this method witho... | github-repos |
def set_active(self, username, active_state):
if active_state not in (True, False):
raise ValueError("active_state must be True or False")
user = self.get_user(username)
if user is None:
return None
if user['active'] is active_state:
... | Set the active state of a user
Args:
username: The account username
active_state: True or False
Returns:
True: If successful
None: If no user or failure occurred | juraj-google-style |
async def get_all(self, url, params=None):
if not params:
params = {}
items = []
next_page_token = None
while True:
if next_page_token:
params['pageToken'] = next_page_token
response = await self.get_json(url, params=params)
... | Aggregate data from all pages of an API query.
Args:
url (str): Google API endpoint URL.
params (dict): (optional) URL query parameters.
Returns:
list: Parsed JSON query response results. | juraj-google-style |
def typical_or_extreme_period_name(self, value=None):
if (value is not None):
try:
value = str(value)
except ValueError:
raise ValueError('value {} need to be of type str for field `typical_or_extreme_period_name`'.format(value))
if (',' in value):
raise V... | Corresponds to IDD Field `typical_or_extreme_period_name`
Args:
value (str): value for IDD Field `typical_or_extreme_period_name`
if `value` is None it will not be checked against the
specification and is assumed to be a missing value
Raises:
ValueError: if `value` is not a valid value | codesearchnet |
async def get_tournaments(self, subdomain: str=None, force_update: bool=False) -> list:
if (self.tournaments is None):
force_update = True
self._subdomains_searched.append(('' if (subdomain is None) else subdomain))
elif ((subdomain is None) and ('' not in self._subdomains_searched)):
fo... | gets all user's tournaments
|methcoro|
Args:
subdomain: *optional* subdomain needs to be given explicitely to get tournaments in a subdomain
force_update: *optional* set to True to force the data update from Challonge
Returns:
list[Tournament]: list of all the user tournaments
Raises:
APIException | codesearchnet |
def sample_node_list(self, low, high, generator):
statements = []
for _ in range(np.random.randint(low, high)):
statements.append(generator())
return statements | Generate a list of statements of random length.
Args:
low: Fewest number of statements to generate.
high: Highest number of statements to generate.
generator: Function to call to generate nodes.
Returns:
A list of statements. | github-repos |
def add(self, origin):
digest = self._calc_digest(origin)
if self.exists(digest):
self.logger.debug('Added File: [{0}] ( Already exists. Skipping transfer)'.format(digest))
return digest
absPath = self.get_file_path(digest)
absFolderPath = os.path.dirn... | Add new element to fsdb.
Args:
origin -- could be the path of a file or a readable/seekable object ( fileobject, stream, stringIO...)
Returns:
String rapresenting the digest of the file | juraj-google-style |
def convert_variable_to_constant(self, incoming_edge, tensor_data):
index = incoming_edge.destination.index
for edge in self.outgoing_edges:
if edge.source.index == index:
edge.destination.convertible.convert_variable_to_constant(edge, tensor_data)
function = self.converted_self().functi... | Converts one function argument into a constant.
Args:
incoming_edge: The edge into the argument to be converted.
tensor_data: The constant value. | github-repos |
def enum(cls):
assert (cls.__bases__ == (object,))
d = dict(cls.__dict__)
new_type = type(cls.__name__, (int,), d)
new_type.__module__ = cls.__module__
map_ = {}
for (key, value) in iteritems(d):
if ((key.upper() == key) and isinstance(value, integer_types)):
value_instance =... | A decorator for creating an int enum class.
Makes the values a subclass of the type and implements repr/str.
The new class will be a subclass of int.
Args:
cls (type): The class to convert to an enum
Returns:
type: A new class
::
@enum
class Foo(object):
FOO = 1
BAR = 2 | codesearchnet |
def trigger(self, attr, old, new, hint=None, setter=None):
def invoke():
callbacks = self._callbacks.get(attr)
if callbacks:
for callback in callbacks:
callback(attr, old, new)
if hasattr(self, '_document') and self._document is not No... | Trigger callbacks for ``attr`` on this object.
Args:
attr (str) :
old (object) :
new (object) :
Returns:
None | juraj-google-style |
def AddClient(self, client):
keywords = self.AnalyzeClient(client)
keywords.add(self._NormalizeKeyword(client.client_id))
data_store.REL_DB.AddClientKeywords(client.client_id, keywords) | Adds a client to the index.
Args:
client: A Client object record. | juraj-google-style |
def createDirStruct(paths, verbose=True):
for k, path in paths.items():
p = None
try:
pathlist = path if type(path) is list else [ path ]
for p in pathlist:
os.makedirs(p)
if verbose:
log.info('Creating directory: ' + p... | Loops ait.config._datapaths from AIT_CONFIG and creates a directory.
Replaces year and doy with the respective year and day-of-year.
If neither are given as arguments, current UTC day and year are used.
Args:
paths:
[optional] list of directory paths you would like to create.
doy and year will be replaced by the date... | juraj-google-style |
def get_max_bond_distance(self, el1_sym, el2_sym):
return sqrt(
(self.el_radius[el1_sym] + self.el_radius[el2_sym] + self.tol) ** 2) | Use Jmol algorithm to determine bond length from atomic parameters
Args:
el1_sym: (str) symbol of atom 1
el2_sym: (str) symbol of atom 2
Returns: (float) max bond length | juraj-google-style |
def get_cells_iterator(bq_read_client: BigQueryReadClient, table_metadata: TableMetadata, column: str) -> Generator[Any, None, None]:
if '.' not in column and '[' not in column:
rows = get_readrows_iterator(bq_read_client, table_metadata, [column], data_format=DataFormat.AVRO)
for row in rows:
... | Retrieves an iterator of cell values for a specified column, optimized
for both simple and nested column
access, including handling special value structures with dynamic value types
for nested columns.
Args:
bq_read_client (BigQueryReadClient): The BigQuery Storage API Read client.
table_metadata (TableMetadata): The... | github-repos |
def _prefix_from_prefix_int(self, prefixlen):
if not isinstance(prefixlen, (int, long)):
raise NetmaskValueError('%r is not an integer' % prefixlen)
prefixlen = int(prefixlen)
if not (0 <= prefixlen <= self._max_prefixlen):
raise NetmaskValueError('%d is not a va... | Validate and return a prefix length integer.
Args:
prefixlen: An integer containing the prefix length.
Returns:
The input, possibly converted from long to int.
Raises:
NetmaskValueError: If the input is not an integer, or out of range. | juraj-google-style |
def easeInOutCubic(n):
_checkRange(n)
n = 2 * n
if n < 1:
return 0.5 * n**3
else:
n = n - 2
return 0.5 * (n**3 + 2) | A cubic tween function that accelerates, reaches the midpoint, and then decelerates.
Args:
n (float): The time progress, starting at 0.0 and ending at 1.0.
Returns:
(float) The line progress, starting at 0.0 and ending at 1.0. Suitable for passing to getPointOnLine(). | juraj-google-style |
def validate_primitive_without_value(fhir_primitive: message.Message) -> None:
name = fhir_primitive.DESCRIPTOR.full_name
if len(extensions.get_fhir_extensions(fhir_primitive)) < 2:
raise fhir_errors.InvalidFhirError(f'{name!r} must have either extensions or a value present.')
for field, _ in fhir_p... | Validates a Message which has the PrimitiveWithoutValue extension.
Given that there is a PrimitiveWithoutValue extension present, there must be
at least one other extension. Otherwise, there is truly no value set other
than id and/or extension (non-value fields).
Args:
fhir_primitive: The FHIR primitive Message to va... | github-repos |
def decorate_event_js(js_code):
def add_annotation(method):
setattr(method, '__is_event', True)
setattr(method, '_js_code', js_code)
return method
return add_annotation | setup a method as an event, adding also javascript code to generate
Args:
js_code (str): javascript code to generate the event client-side.
js_code is added to the widget html as
widget.attributes['onclick'] = js_code%{'emitter_identifier':widget.identifier, 'event_name':'onclick'} | codesearchnet |
def get_reconciler(config, metrics, rrset_channel, changes_channel, **kw):
builder = reconciler.GDNSReconcilerBuilder(config, metrics, rrset_channel, changes_channel, **kw)
return builder.build_reconciler() | Get a GDNSReconciler client.
A factory function that validates configuration, creates an auth
and :class:`GDNSClient` instance, and returns a GDNSReconciler
provider.
Args:
config (dict): Google Cloud Pub/Sub-related configuration.
metrics (obj): :interface:`IMetricRelay` implementation.
rrset_channel (asyncio.Queue)... | codesearchnet |
def build_ann(N_input=None, N_hidden=2, N_output=1, hidden_layer_type='Linear', verbosity=1):
N_input = (N_input or 1)
N_output = (N_output or 1)
N_hidden = (N_hidden or tuple())
if isinstance(N_hidden, (int, float, basestring)):
N_hidden = (int(N_hidden),)
hidden_layer_type = (hidden_layer_... | Build a neural net with the indicated input, hidden, and outout dimensions
Arguments:
params (dict or PyBrainParams namedtuple):
default: {'N_hidden': 6}
(this is the only parameter that affects the NN build)
Returns:
FeedForwardNetwork with N_input + N_hidden + N_output nodes in 3 layers | codesearchnet |
def stop(self):
self._logger.info('Cleaning up remaining connection threads.')
for thread in threading.enumerate():
if (thread is not threading.current_thread()):
try:
thread.join(10.0)
except Exception as e:
self._logger.info('Error occurred while... | Stop the server.
Halt server client connections and clean up any existing connection
threads.
Raises:
NetworkingError: Raised if a failure occurs while sutting down
or closing the TLS server socket. | codesearchnet |
def do_batch_status(args):
rest_client = RestClient(args.url, args.user)
batch_ids = args.batch_ids.split(',')
if args.wait and args.wait > 0:
statuses = rest_client.get_statuses(batch_ids, args.wait)
else:
statuses = rest_client.get_statuses(batch_ids)
if args.format == 'yaml... | Runs the batch-status command, printing output to the console
Args:
args: The parsed arguments sent to the command at runtime | juraj-google-style |
def git_checkout(branch_name, create=False):
log.info('Checking out <33>{}'.format(branch_name))
shell.run('git checkout {} {}'.format(('-b' if create else ''), branch_name)) | Checkout or create a given branch
Args:
branch_name (str):
The name of the branch to checkout or create.
create (bool):
If set to **True** it will create the branch instead of checking it
out. | codesearchnet |
def __init__(self, sv, sess):
super(SVSummaryThread, self).__init__(sv.coord, sv.save_summaries_secs)
self._sv = sv
self._sess = sess | Create a SVSummaryThread.
Args:
sv: A `Supervisor`.
sess: A `Session`. | github-repos |
def __call__(self, batch: List[List[str]], mean: bool = None) -> List[Union[list, np.ndarray]]:
batch = [self._encode(sample, mean) for sample in batch]
if self.pad_zero:
batch = zero_pad(batch)
return batch | Embed sentences from batch
Args:
batch: list of tokenized text samples
mean: whether to return mean embedding of tokens per sample
Returns:
embedded batch | juraj-google-style |
def _GetFlagValues(self, flags):
event_types = []
for (event_flag, description) in self._FLAG_VALUES.items():
if (event_flag & flags):
event_types.append(description)
return ', '.join(event_types) | Determines which events are indicated by a set of fsevents flags.
Args:
flags (int): fsevents record flags.
Returns:
str: a comma separated string containing descriptions of the flag values
stored in an fsevents record. | codesearchnet |
def format_rpc(data):
address, rpc_id, args, resp, _status = data
name = rpc_name(rpc_id)
if isinstance(args, (bytes, bytearray)):
arg_str = hexlify(args)
else:
arg_str = repr(args)
if isinstance(resp, (bytes, bytearray)):
resp_str = hexlify(resp)
else:
r... | Format an RPC call and response.
Args:
data (tuple): A tuple containing the address, rpc_id, argument and
response payloads and any error code.
Returns:
str: The formated RPC string. | juraj-google-style |
def from_url(cls, path):
if os.path.isfile(path):
with open(path) as fd:
data = fd.read()
else:
try:
response = urllib.urlopen(path)
if response.code >= 300:
raise RuntimeError('Unable to load repo from ... | Instantiate a :class:`TemplateRepository` instance from the data in a
file or url
Args:
path (str): Path or url to the json file to load
Returns:
TemplateRepository: A new instance | juraj-google-style |
def find_code_in_transformers(object_name: str, base_path: Optional[str]=None, return_indices: bool=False) -> Union[str, Tuple[List[str], int, int]]:
parts = object_name.split('.')
i = 0
if base_path is None:
base_path = TRANSFORMERS_PATH
if base_path == MODEL_TEST_PATH:
base_path = 'tes... | Find and return the source code of an object.
Args:
object_name (`str`):
The name of the object we want the source code of.
base_path (`str`, *optional*):
The path to the base folder where files are checked. If not set, it will be set to `TRANSFORMERS_PATH`.
return_indices(`bool`, *optional*, defaults to `False`):
If ... | github-repos |
def _contains_composite_function_call(self, graphdef: graph_pb2.GraphDef) -> bool:
return any(map(self._is_composite_function, graphdef.library.function)) | Determines if the graph def has composite function call.
Args:
graphdef: A GraphDef object.
Returns:
True if and only if the graph def contains a composite function call. | github-repos |
def _single_shard_restore(file_prefix: tensor_lib.Tensor, shardable_tensors: Sequence[sharding_util.ShardableTensor], options: 'checkpoint_options.CheckpointOptions | None'=None) -> sharding_util.Shard:
options = options or checkpoint_options.CheckpointOptions()
tensor_names = []
tensor_dtypes = []
slic... | Restore the saveable objects from a checkpoint with `file_prefix`.
Args:
file_prefix: A string or scalar string Tensor containing the prefix for
files to read from.
shardable_tensors: A list of ShardableTensors to restore.
options: Optional `CheckpointOptions` object.
Returns:
A restored tensor dict (maps checkpoint_... | github-repos |
def ensure_list_size(list_, size_):
lendiff = (size_ - len(list_))
if (lendiff > 0):
extension = [None for _ in range(lendiff)]
list_.extend(extension) | Allocates more space if needbe.
Ensures len(``list_``) == ``size_``.
Args:
list_ (list): ``list`` to extend
size_ (int): amount to exent by | codesearchnet |
def invert_apply(self, pts: torch.Tensor) -> torch.Tensor:
rot_mats = self.get_rot_mats()
inv_rot_mats = invert_rot_mat(rot_mats)
return rot_vec_mul(inv_rot_mats, pts) | The inverse of the apply() method.
Args:
pts:
A [*, 3] set of points
Returns:
[*, 3] inverse-rotated points | github-repos |
def shape(self):
return self._ragged_shape._to_tensor_shape() | The static shape of this StructuredTensor.
The returned `TensorShape` is guaranteed to have a known rank, but the
individual dimension sizes may be unknown.
Returns:
`tf.TensorShape` | github-repos |
def get(self, catID, includeRelationships=False):
url = ('%(base_url)s/record/%(catID)s' % {'base_url': self.base_url, 'catID': catID})
r = self.gbdx_connection.get(url)
r.raise_for_status()
return r.json() | Retrieves the strip footprint WKT string given a cat ID.
Args:
catID (str): The source catalog ID from the platform catalog.
includeRelationships (bool): whether to include graph links to related objects. Default False.
Returns:
record (dict): A dict object identical to the json representation of the catalog record | codesearchnet |
def _combine_handle_data(handle, initial_value):
assert handle.dtype == dtypes.resource
variable_handle_data = get_eager_safe_handle_data(handle)
if initial_value.dtype != dtypes.variant:
return variable_handle_data
extra_handle_data = get_eager_safe_handle_data(initial_value)
if extra_handl... | Concats HandleData from tensors `handle` and `initial_value`.
Args:
handle: A `Tensor` of dtype `resource`.
initial_value: A `Tensor`.
Returns:
A `CppShapeInferenceResult.HandleData`. If `initial_value` has dtype
`variant`, the `HandleData` contains the concatenation of the shape_and_type
from both `handle` and `ini... | github-repos |
def _GetAnalysisPlugins(self, analysis_plugins_string):
if not analysis_plugins_string:
return []
analysis_plugins_list = [
name.strip() for name in analysis_plugins_string.split(',')]
analysis_plugins = self._analysis_manager.GetPluginObjects(
analysis_plugins_list)
return ... | Retrieves analysis plugins.
Args:
analysis_plugins_string (str): comma separated names of analysis plugins
to enable.
Returns:
list[AnalysisPlugin]: analysis plugins. | juraj-google-style |
def _get_job_metadata(provider, user_id, job_name, script, task_ids,
user_project, unique_job_id):
create_time = dsub_util.replace_timezone(datetime.datetime.now(), tzlocal())
user_id = user_id or dsub_util.get_os_user()
job_metadata = provider.prepare_job_metadata(script.name, job_name, ... | Allow provider to extract job-specific metadata from command-line args.
Args:
provider: job service provider
user_id: user submitting the job
job_name: name for the job
script: the script to run
task_ids: a set of the task-ids for all tasks in the job
user_project: name of the project to be billed for the request
uniq... | juraj-google-style |
def histogram(namespace: Union[Type, str], name: str, bucket_type: 'BucketType', logger: Optional['MetricLogger']=None) -> 'Metrics.DelegatingHistogram':
namespace = UserMetrics.get_namespace(namespace)
return Metrics.DelegatingHistogram(MetricName(namespace, name), bucket_type, logger) | Obtains or creates a Histogram metric.
Args:
namespace: A class or string that gives the namespace to a metric
name: A string that gives a unique name to a metric
bucket_type: A type of bucket used in a histogram. A subclass of
apache_beam.utils.histogram.BucketType
logger: MetricLogger for logging locally aggregated ... | github-repos |
def view_structure(self, only_chains=None, opacity=1.0, recolor=False, gui=False):
if ssbio.utils.is_ipynb():
import nglview as nv
else:
raise EnvironmentError('Unable to display structure - not running in a Jupyter notebook environment')
if (not self.structure_file):
raise ValueErro... | Use NGLviewer to display a structure in a Jupyter notebook
Args:
only_chains (str, list): Chain ID or IDs to display
opacity (float): Opacity of the structure
recolor (bool): If structure should be cleaned and recolored to silver
gui (bool): If the NGLview GUI should show up
Returns:
NGLviewer object | codesearchnet |
def _from_signer_and_info(cls, signer, info, **kwargs):
return cls(
signer,
service_account_email=info['client_email'],
token_uri=info['token_uri'],
project_id=info.get('project_id'), **kwargs) | Creates a Credentials instance from a signer and service account
info.
Args:
signer (google.auth.crypt.Signer): The signer used to sign JWTs.
info (Mapping[str, str]): The service account info.
kwargs: Additional arguments to pass to the constructor.
Returns:
google.auth.jwt.Credentials: The constructed credentials.
... | juraj-google-style |
def get_atlas_per_gene_mutation_df(self, gene_id):
g = self.reference_gempro.genes.get_by_id(gene_id)
(single, fingerprint) = g.protein.sequence_mutation_summary(alignment_type='seqalign')
structure_type_suffix = 'NA'
appender = []
for (k, strains) in single.items():
to_append = {}
o... | Create a single data frame which summarizes a gene and its mutations.
Args:
gene_id (str): Gene ID in the base model
Returns:
DataFrame: Pandas DataFrame of the results | codesearchnet |
def compose_tree_url(tree, issn_url=False):
url = compose_tree_path(tree, issn_url)
if (WEB_PORT == 80):
return ('%s:
return ('%s: | Compose full url for given `tree`, with protocol, server's address and
port.
Args:
tree (obj): :class:`.Tree` instance.
issn_url (bool, default False): Compose URL using ISSN.
Returns:
str: URL of the tree | codesearchnet |
def get_channel(self, chan_name, coll_name, exp_name):
chan = ChannelResource(chan_name, coll_name, exp_name)
return self.get_project(chan) | Helper that gets a fully initialized ChannelResource for an *existing* channel.
Args:
chan_name (str): Name of channel.
coll_name (str): Name of channel's collection.
exp_name (str): Name of channel's experiment.
Returns:
(intern.resource.boss.ChannelResource) | juraj-google-style |
def FindFileByName(self, file_name):
try:
return self._file_descriptors[file_name]
except KeyError:
pass
try:
file_proto = self._internal_db.FindFileByName(file_name)
except KeyError as error:
if self._descriptor_db:
file_proto = self._descriptor_db.FindFileByName(... | Gets a FileDescriptor by file name.
Args:
file_name: The path to the file to get a descriptor for.
Returns:
A FileDescriptor for the named file.
Raises:
KeyError: if the file cannot be found in the pool. | juraj-google-style |
def _create_trial_info(self, expr_dir):
meta = self._build_trial_meta(expr_dir)
self.logger.debug("Create trial for %s" % meta)
trial_record = TrialRecord.from_json(meta)
trial_record.save() | Create information for given trial.
Meta file will be loaded if exists, and the trial information
will be saved in db backend.
Args:
expr_dir (str): Directory path of the experiment. | juraj-google-style |
def bbox_line_intersect(nodes, line_start, line_end):
(left, right, bottom, top) = _helpers.bbox(nodes)
if (_helpers.in_interval(line_start[0], left, right) and _helpers.in_interval(line_start[1], bottom, top)):
return BoxIntersectionType.INTERSECTION
if (_helpers.in_interval(line_end[0], left, righ... | r"""Determine intersection of a bounding box and a line.
We do this by first checking if either the start or end node of the
segment are contained in the bounding box. If they aren't, then
checks if the line segment intersects any of the four sides of the
bounding box.
.. note::
This function is "half-finished". It ... | codesearchnet |
def allocate(self, amount, child=None, update=True):
if (child is not None):
if (child not in self.children):
c = SecurityBase(child)
c.setup(self._universe)
c.update(self.now)
self._add_child(c)
self.children[child].allocate(amount)
else:
... | Allocate capital to Strategy. By default, capital is allocated
recursively down the children, proportionally to the children's
weights. If a child is specified, capital will be allocated
to that specific child.
Allocation also have a side-effect. They will deduct the same amount
from the parent's "account" to offset ... | codesearchnet |
def write(self, output_stream, kmip_version=enums.KMIPVersion.KMIP_1_0):
local_stream = utils.BytearrayStream()
if self._unique_identifier:
self._unique_identifier.write(local_stream, kmip_version=kmip_version)
if self._cryptographic_parameters:
self._cryptographic_parameters.write(local_str... | Write the data encoding the SignatureVerify request payload to a
stream.
Args:
output_stream (stream): A data stream in which to encode object
data, supporting a write method; usually a BytearrayStream
object.
kmip_version (KMIPVersion): An enumeration defining the KMIP
version with which the object will be encoded. O... | codesearchnet |
def util_granulate_time_series(time_series, scale):
n = len(time_series)
b = int(np.fix((n / scale)))
temp = np.reshape(time_series[0:(b * scale)], (b, scale))
cts = np.mean(temp, axis=1)
return cts | Extract coarse-grained time series
Args:
time_series: Time series
scale: Scale factor
Returns:
Vector of coarse-grained time series with given scale factor | codesearchnet |
class RunEnsembleDetector(beam.PTransform[beam.PCollection[NestedKeyedInputT], beam.PCollection[NestedKeyedOutputT]]):
def __init__(self, ensemble_detector: EnsembleAnomalyDetector):
self._ensemble_detector = ensemble_detector
def expand(self, input: beam.PCollection[NestedKeyedInputT]) -> beam.PColle... | Runs an ensemble of anomaly detectors on a PCollection of data.
This PTransform applies an `EnsembleAnomalyDetector` to the input data,
running each sub-detector and aggregating the results.
Args:
ensemble_detector: The `EnsembleAnomalyDetector` to run. | github-repos |
def _page_to_title(page):
start_tag = u"<title>"
end_tag = u"</title>"
start_pos = page.find(start_tag)
end_pos = page.find(end_tag)
assert start_pos != -1
assert end_pos != -1
start_pos += len(start_tag)
return page[start_pos:end_pos] | Extract the title from a page.
Args:
page: a unicode string
Returns:
a unicode string | juraj-google-style |
def get_course_certificate(self, course_id, username):
return self.client.certificates(username).courses(course_id).get() | Retrieve the certificate for the given username for the given course_id.
Args:
* ``course_id`` (str): The string value of the course's unique identifier
* ``username`` (str): The username ID identifying the user for which to retrieve the certificate
Raises:
HttpNotFoundError if no certificate found for the given use... | codesearchnet |
def delete(self, *names: str, pipeline=False):
if pipeline:
self._pipeline.delete(*names)
else:
self._db.delete(*names) | Delete one or more keys specified by names.
Args:
names (str): Names of keys to delete
pipeline (bool): True, start a transaction block. Default false. | juraj-google-style |
def write_to_fp(self, fp):
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
text_parts = self._tokenize(self.text)
log.debug("text_parts: %i", len(text_parts))
assert text_parts, 'No text to send to TTS API'
for idx, part in enumera... | Do the TTS API request and write bytes to a file-like object.
Args:
fp (file object): Any file-like object to write the ``mp3`` to.
Raises:
:class:`gTTSError`: When there's an error with the API request.
TypeError: When ``fp`` is not a file-like object that takes bytes. | juraj-google-style |
def parse_default_property_value(property_name, property_type_id, default_value_string):
if ((property_type_id == PROPERTY_TYPE_EMBEDDED_SET_ID) and (default_value_string == '{}')):
return set()
elif ((property_type_id == PROPERTY_TYPE_EMBEDDED_LIST_ID) and (default_value_string == '[]')):
retur... | Parse the default value string into its proper form given the property type ID.
Args:
property_name: string, the name of the property whose default value is being parsed.
Used primarily to construct meaningful error messages, should the default
value prove invalid.
property_type_id: int, one of the property type ID co... | codesearchnet |
def image_preprocessing(image_buffer, bbox, train, thread_id=0):
if (bbox is None):
raise ValueError('Please supply a bounding box.')
image = decode_jpeg(image_buffer)
height = FLAGS.image_size
width = FLAGS.image_size
if train:
image = distort_image(image, height, width, bbox, threa... | Decode and preprocess one image for evaluation or training.
Args:
image_buffer: JPEG encoded string Tensor
bbox: 3-D float Tensor of bounding boxes arranged [1, num_boxes, coords]
where each coordinate is [0, 1) and the coordinates are arranged as
[ymin, xmin, ymax, xmax].
train: boolean
thread_id: integer indicating ... | codesearchnet |
def camel_to_title(name):
split = re.findall('[A-Z]?[a-z0-9]+|[A-Z]+(?=[A-Z]|$)', name)
ret = ' '.join(split)
ret = (ret[0].upper() + ret[1:])
return ret | Takes a camelCaseFieldName and returns an Title Case Field Name
Args:
name (str): E.g. camelCaseFieldName
Returns:
str: Title Case converted name. E.g. Camel Case Field Name | codesearchnet |
def sorted(field_name, ascending=True, fields=None, count=5):
if field_name is None:
raise Exception('Sort field must be specified')
direction = '' if ascending else ' DESC'
projection = Sampling._create_projection(fields)
return lambda sql: 'SELECT %s FROM (%s) ORDER BY %s%s LIMIT %d' % (pro... | Provides a sampling strategy that picks from an ordered set of rows.
Args:
field_name: the name of the field to sort the rows by.
ascending: whether to sort in ascending direction or not.
fields: an optional list of field names to retrieve.
count: optional number of rows to limit the sampled results to.
Returns:
A sam... | juraj-google-style |
def process_cgmlst_results(df):
assert isinstance(df, pd.DataFrame)
markers = []
alleles = []
for x in df['qseqid']:
(marker, allele) = x.split('|')
markers.append(marker)
alleles.append(int(allele))
df.loc[(:, 'marker')] = markers
df.loc[(:, 'allele')] = alleles
df.l... | Append informative fields to cgMLST330 BLAST results DataFrame
The `qseqid` column must contain cgMLST330 query IDs with `{marker name}|{allele number}` format.
The `qseqid` parsed allele numbers and marker names are appended as new fields.
`is_perfect` column contains boolean values for whether an allele result is 1... | codesearchnet |
def metar_to_speech(metar: str) -> str:
LOGGER.info('getting speech text from METAR: %s', metar)
(metar_data, metar_units) = emiz.avwx.metar.parse_in(metar)
speech = emiz.avwx.speech.metar(metar_data, metar_units)
speech = str(speech).replace('Altimeter', 'Q N H')
LOGGER.debug('resulting speech: %s'... | Creates a speakable text from a METAR
Args:
metar: METAR string to use
Returns: speakable METAR for TTS | codesearchnet |
def title_of_design_condition(self, value=None):
if value is not None:
try:
value = str(value)
except ValueError:
raise ValueError(
'value {} need to be of type str '
'for field `title_of_design_condition`'.... | Corresponds to IDD Field `title_of_design_condition`
Args:
value (str): value for IDD Field `title_of_design_condition`
if `value` is None it will not be checked against the
specification and is assumed to be a missing value
Raises:
ValueError: if `value` is not a valid value | juraj-google-style |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.