code stringlengths 20 4.93k | docstring stringlengths 33 1.27k | source stringclasses 3
values |
|---|---|---|
def text(self, value):
self._text = value
self.timestamps.edited = datetime.datetime.utcnow()
self.touch(True) | Set the text value.
Args:
value (str): Text value. | juraj-google-style |
def is_outlier(df, item_id, segment_id, price):
if (segment_id, item_id) not in df.index:
return False
mean = df.loc[(segment_id, item_id)]['mean']
std = df.loc[(segment_id, item_id)]['std']
return gaussian_outlier.is_outlier(
x=price, mean=mean, standard_deviation=std
) | Verify if a item is an outlier compared to the
other occurrences of the same item, based on his price.
Args:
item_id: idPlanilhaItens
segment_id: idSegmento
price: VlUnitarioAprovado | juraj-google-style |
def reindex(self, kdims=[], force=False):
if not isinstance(kdims, list):
kdims = [kdims]
kdims = [self.get_dimension(kd, strict=True) for kd in kdims]
dropped = [kd for kd in self.kdims if kd not in kdims]
if dropped:
raise ValueError("DynamicMap does no... | Reorders key dimensions on DynamicMap
Create a new object with a reordered set of key dimensions.
Dropping dimensions is not allowed on a DynamicMap.
Args:
kdims: List of dimensions to reindex the mapping with
force: Not applicable to a DynamicMap
Returns:
Reindexed DynamicMap | juraj-google-style |
def _run_eager_benchmark(self, iterable, iters, warmup):
deltas = []
if not context.executing_eagerly():
raise RuntimeError('Eager mode benchmarking is not supported in graph mode.')
for _ in range(iters):
if warmup:
iterator = iter(iterable)
next(iterator)
it... | Benchmark the iterable in eager mode.
Runs the iterable `iters` times. In each iteration, the benchmark measures
the time it takes to go execute the iterable.
Args:
iterable: The tf op or tf.data Dataset to benchmark.
iters: Number of times to repeat the timing.
warmup: If true, warms up the session caches by running... | github-repos |
def key_validation_check(tweet_keys_list, superset_keys, minset_keys):
tweet_keys = set(tweet_keys_list)
minset_overlap = tweet_keys & minset_keys
if minset_overlap != minset_keys:
raise UnexpectedFormatError("keys ({}) missing from Tweet (Public API data is not supported)"
... | Validates the keys present in a Tweet.
Args:
tweet_keys_list (list): the keys present in a tweet
superset_keys (set): the set of all possible keys for a tweet
minset_keys (set): the set of minimal keys expected in a tweet.
Returns:
0 if no errors
Raises:
UnexpectedFormatError on any mismatch of keys. | juraj-google-style |
def __init__(self, thresholds: List[float], labels: List[int], allow_low_quality_matches: bool=False):
thresholds = thresholds[:]
if thresholds[0] < 0:
raise ValueError('Thresholds should be positive')
thresholds.insert(0, -float('inf'))
thresholds.append(float('inf'))
if not all((low <= hig... | Args:
thresholds (`list[float]`):
A list of thresholds used to stratify predictions into levels.
labels (`list[int`):
A list of values to label predictions belonging at each level. A label can be one of {-1, 0, 1}
signifying {ignore, negative class, positive class}, respectively.
allow_low_quality_matches (`bool`, *opt... | github-repos |
def signature_type(self):
if (not self.mardata.signatures):
return None
for sig in self.mardata.signatures.sigs:
if (sig.algorithm_id == 1):
return 'sha1'
elif (sig.algorithm_id == 2):
return 'sha384'
else:
return 'unknown' | Return the signature type used in this MAR.
Returns:
One of None, 'unknown', 'sha1', or 'sha384' | codesearchnet |
def resize(self, image: np.ndarray, size: Dict[str, int], size_divisor: int=0, resample: PILImageResampling=PILImageResampling.BILINEAR, data_format=None, input_data_format: Optional[Union[str, ChannelDimension]]=None, **kwargs) -> np.ndarray:
max_size = kwargs.pop('max_size', None)
size = get_size_dict(size, m... | Resize the image to the given size. Size can be min_size (scalar) or `(height, width)` tuple. If size is an
int, smaller edge of the image will be matched to this number.
Args:
image (`np.ndarray`):
Image to resize.
size (`Dict[str, int]`):
The size of the output image.
size_divisor (`int`, *optional*, defaults to 0):... | github-repos |
def GetAPFSVolumeByPathSpec(self, path_spec):
volume_index = apfs_helper.APFSContainerPathSpecGetVolumeIndex(path_spec)
if volume_index is None:
return None
return self._fsapfs_container.get_volume(volume_index) | Retrieves an APFS volume for a path specification.
Args:
path_spec (PathSpec): path specification.
Returns:
pyfsapfs.volume: an APFS volume or None if not available. | juraj-google-style |
def transform(self, new_frame):
steps = self.__class__.steps(new_frame)
orbit = self.orbit
for (_from, _to) in steps:
from_obj = _from(self.date, orbit)
direct = ('_to_%s' % _to)
if hasattr(from_obj, direct):
(rotation, offset) = getattr(from_obj, direct)()
else:
... | Change the frame of the orbit
Args:
new_frame (str)
Return:
numpy.ndarray | codesearchnet |
def get_summed_cohp_by_label_list(self, label_list, divisor=1):
first_cohpobject = self.get_cohp_by_label(label_list[0])
summed_cohp = first_cohpobject.cohp.copy()
summed_icohp = first_cohpobject.icohp.copy()
for label in label_list[1:]:
cohp_here = self.get... | Returns a COHP object that includes a summed COHP divided by divisor
Args:
label_list: list of labels for the COHP that should be included in the summed cohp
divisor: float/int, the summed cohp will be divided by this divisor
Returns:
Returns a COHP object including a summed COHP | juraj-google-style |
def _VerifyValues(self, tensor_in_sizes, filter_in_sizes, stride, padding, expected):
total_size_1 = 1
total_size_2 = 1
for s in tensor_in_sizes:
total_size_1 *= s
for s in filter_in_sizes:
total_size_2 *= s
x1 = np.array([f for f in range(1, total_size_1 + 1)])
x1 = x1.astype(np... | Verifies the output values of the convolution function.
Args:
tensor_in_sizes: Input tensor dimensions in
[batch, input_rows, input_cols, input_depth].
filter_in_sizes: Filter tensor dimensions in
[kernel_rows, kernel_cols, input_depth, output_depth].
stride: Stride.
padding: Padding type.
expected: An array containin... | github-repos |
def __eq__(self, other: Any) -> bool:
if self is other:
return True
if isinstance(other, MissingValue):
return self._value_spec == other.value_spec
return MISSING_VALUE == other | Operator ==.
NOTE: `MissingValue(value_spec) and `utils.MissingValue` are
considered equal, but `MissingValue(value_spec1)` and
`MissingValue(value_spec2)` are considered different. That being said,
the 'eq' operation is not transitive.
However in practice this is not a problem, since user always compare
against `sch... | github-repos |
def get_classes(tensors):
return nest.pack_sequence_as(tensors, [sparse_tensor.SparseTensor if isinstance(tensor, sparse_tensor.SparseTensor) else tensor_lib.Tensor for tensor in nest.flatten(tensors)]) | Gets classes for a structure of tensors.
Args:
tensors: the tensor structure to get classes for.
Returns:
a structure matching the nested structure of `tensors`, containing
`tf.sparse.SparseTensor` at positions where `tensors` contains a sparse
tensor and `tf.Tensor` otherwise. | github-repos |
def StatFS(self, path=None):
if (platform.system() == 'Windows'):
raise RuntimeError('os.statvfs not available on Windows')
local_path = client_utils.CanonicalPathToLocalPath((path or self.path))
return os.statvfs(local_path) | Call os.statvfs for a given list of rdf_paths.
OS X and Linux only.
Note that a statvfs call for a network filesystem (e.g. NFS) that is
unavailable, e.g. due to no network, will result in the call blocking.
Args:
path: a Unicode string containing the path or None. If path is None the
value in self.path is used.
Re... | codesearchnet |
def __init__(self, input_dim: int, hidden_dim: int, output_dim: int, num_layers: int=3):
super().__init__()
in_dims = [input_dim] + [hidden_dim] * (num_layers - 1)
out_dims = [hidden_dim] * (num_layers - 1) + [output_dim]
layers = []
for i, (in_dim, out_dim) in enumerate(zip(in_dims, out_dims)):
... | A classic Multi Layer Perceptron (MLP).
Args:
input_dim (`int`):
The input dimensions.
hidden_dim (`int`):
The hidden dimensions.
output_dim (`int`):
The output dimensions.
num_layers (int, *optional*, defaults to 3):
The number of layers. | github-repos |
def read(self, input_stream, kmip_version=enums.KMIPVersion.KMIP_1_0):
super(SignatureVerifyRequestPayload, self).read(input_stream, kmip_version=kmip_version)
local_stream = utils.BytearrayStream(input_stream.read(self.length))
if self.is_tag_next(enums.Tags.UNIQUE_IDENTIFIER, local_stream):
self._... | Read the data encoding the SignatureVerify request payload and decode
it into its constituent parts.
Args:
input_stream (stream): A data stream containing encoded object
data, supporting a read method; usually a BytearrayStream
object.
kmip_version (KMIPVersion): An enumeration defining the KMIP
version with which the... | codesearchnet |
def read(self, size=None):
if not self._is_open:
raise IOError('Not opened.')
return self._fsapfs_file_entry.read(size=size) | Reads a byte string from the file-like object at the current offset.
The function will read a byte string of the specified size or
all of the remaining data if no size was specified.
Args:
size (Optional[int]): number of bytes to read, where None is all
remaining data.
Returns:
bytes: data read.
Raises:
IOError: if... | juraj-google-style |
def loads(s, single=False):
corpus = etree.fromstring(s)
if single:
ds = _deserialize_mrs(next(corpus))
else:
ds = (_deserialize_mrs(mrs_elem) for mrs_elem in corpus)
return ds | Deserialize MRX string representations
Args:
s (str): a MRX string
single (bool): if `True`, only return the first Xmrs object
Returns:
a generator of Xmrs objects (unless *single* is `True`) | codesearchnet |
def _safe_mean(losses, num_present):
total_loss = math_ops.reduce_sum(losses)
return math_ops.div_no_nan(total_loss, num_present, name='value') | Computes a safe mean of the losses.
Args:
losses: `Tensor` whose elements contain individual loss measurements.
num_present: The number of measurable elements in `losses`.
Returns:
A scalar representing the mean of `losses`. If `num_present` is zero,
then zero is returned. | github-repos |
def _connect_nodes(self, first, second):
if isinstance(first, Node):
first.next.add(second)
second.prev.add(first)
self.forward_edges.add((first, second))
else:
for node in first:
self._connect_nodes(node, second) | Connects nodes to signify that control flows from first to second.
Args:
first: Union[Set[Node, ...], Node]
second: Node | github-repos |
def as_dict(self, voigt=False):
input_array = (self.voigt if voigt else self)
d = {'@module': self.__class__.__module__, '@class': self.__class__.__name__, 'input_array': input_array.tolist()}
if voigt:
d.update({'voigt': voigt})
return d | Serializes the tensor object
Args:
voigt (bool): flag for whether to store entries in
voigt-notation. Defaults to false, as information
may be lost in conversion.
Returns (Dict):
serialized format tensor object | codesearchnet |
def _parse_trunk_groups(self, config):
values = re.findall(r'switchport trunk group ([^\s]+)', config, re.M)
return dict(trunk_groups=values) | Scans the specified config and parses the trunk group values
Args:
config (str): The interface configuraiton blcok
Returns:
A dict object with the trunk group values that can be merged
into the resource dict | juraj-google-style |
def publish_traceback(debug_server_urls, graph, feed_dict, fetches, old_graph_version):
from tensorflow.python.debug.lib import source_remote
if graph.version > old_graph_version:
run_key = common.get_run_key(feed_dict, fetches)
source_remote.send_graph_tracebacks(debug_server_urls, run_key, tra... | Publish traceback and source code if graph version is new.
`graph.version` is compared with `old_graph_version`. If the former is higher
(i.e., newer), the graph traceback and the associated source code is sent to
the debug server at the specified gRPC URLs.
Args:
debug_server_urls: A single gRPC debug server URL as ... | github-repos |
def parse_xml_to_obj(self, xml_file, check_version=True, check_root=True, encoding=None):
root = get_etree_root(xml_file, encoding=encoding)
if check_root:
self._check_root_tag(root)
if check_version:
self._check_version(root)
entity_class = self.get_entity_class(root.tag)
entity_obj... | Creates a STIX binding object from the supplied xml file.
Args:
xml_file: A filename/path or a file-like object representing a STIX
instance document
check_version: Inspect the version before parsing.
check_root: Inspect the root element before parsing.
encoding: The character encoding of the input `xml_file`.
Raises... | codesearchnet |
def __init__(self, element_type, dimensions, layout=None):
self.message = xla_data_pb2.ShapeProto()
self.message.element_type = element_type
if element_type == xla_data_pb2.TUPLE:
if not all((isinstance(subshape, Shape) for subshape in dimensions)):
raise ValueError('XLA tuple requires s... | Creates a new XLA Shape.
Args:
element_type: element type from xla_data_pb2.
dimensions: sequence of dimensions sizes (integers), or sequence
of Shapes in the case of a tuple, i.e. when element_type is
TUPLE.
layout: optional minor_to_major sequence for layout. If not given, the
default major-to-minor layout is used.
... | github-repos |
def parse_GSE(filepath):
gpls = {}
gsms = {}
series_counter = 0
database = None
metadata = {}
gse_name = None
with utils.smart_open(filepath) as soft:
groupper = groupby(soft, lambda x: x.startswith("^"))
for is_new_entry, group in groupper:
if is_new_entry:
... | Parse GSE SOFT file.
Args:
filepath (:obj:`str`): Path to GSE SOFT file.
Returns:
:obj:`GEOparse.GSE`: A GSE object. | juraj-google-style |
def __init__(self, *args, **kwargs):
super(self.__class__, self).__init__(*args, **kwargs)
if not self.name.strip():
raise ValueError(".name property must be set!")
if type(self.sub_trees) not in [list, tuple]:
raise ValueError(".sub_trees property must... | Constructor.
Args:
name (str): Name of the periodical.
sub_trees (list): List of other trees.
sub_publications (list): List of sub-publication UUID's.
aleph_id (str): ID used in aleph.
issn (str): ISSN given to the periodical.
is_public (bool): Is the tree public?
Raises:
ValueError: In case that `name` is not set, o... | juraj-google-style |
def __init__(self, contents, out=None, prompt=None):
self._contents = contents
self._out = out or sys.stdout
self._search_pattern = None
self._search_direction = None
self.prev_pos, self.prev_nxt = self.PREV_POS_NXT_REPRINT
self._attr = console_attr.GetConsoleAttr()
self._width, self._height... | Constructor.
Args:
contents: The entire contents of the text lines to page.
out: The output stream, log.out (effectively) if None.
prompt: The page break prompt, a default prompt is used if None.. | github-repos |
def get_cache_index_key(resource):
if isinstance(resource, APIResource):
attr, attr_value = list(resource.get_cache_index_keys().items())[0]
key = (type(resource), attr, attr_value)
else:
key = tuple(resource)
if len(key) != 3:
raise TypeError('Cache key must be tuple o... | Return a usable cache lookup key for an already initialized resource
Args:
resource (APIResource|tuple): APIResource instance or 3-length tuple key returned from this function
Raises:
TypeError: If resource is not an APIResource instance or acceptable 3-length tuple cache key | juraj-google-style |
def roots_in_unit_interval(coeffs):
r
all_roots = polynomial.polyroots(coeffs)
all_roots = all_roots[
(_UNIT_INTERVAL_WIGGLE_START < all_roots.real)
& (all_roots.real < _UNIT_INTERVAL_WIGGLE_END)
]
real_inds = np.abs(all_roots.imag) < _IMAGINARY_WIGGLE
return all_r... | r"""Compute roots of a polynomial in the unit interval.
Args:
coeffs (numpy.ndarray): A 1D array (size ``d + 1``) of coefficients in
monomial / power basis.
Returns:
numpy.ndarray: ``N``-array of real values in :math:`\left[0, 1\right]`. | juraj-google-style |
def chrome_tracing_dump(self, filename=None):
profile_table = self.profile_table()
all_events = []
for (component_id_hex, component_events) in profile_table.items():
component_type = component_events[0]['component_type']
if (component_type not in ['worker', 'driver']):
continue
... | Return a list of profiling events that can viewed as a timeline.
To view this information as a timeline, simply dump it as a json file
by passing in "filename" or using using json.dump, and then load go to
chrome://tracing in the Chrome web browser and load the dumped file.
Make sure to enable "Flow events" in the "Vi... | codesearchnet |
def require(builder_name):
reg = ComponentRegistry()
for (_name, autobuild_func) in reg.load_extensions('iotile.autobuild', name_filter=builder_name):
return autobuild_func
raise BuildError('Cannot find required autobuilder, make sure the distribution providing it is installed', name=builder_name) | Find an advertised autobuilder and return it
This function searches through all installed distributions to find
if any advertise an entry point with group 'iotile.autobuild' and
name equal to builder_name. The first one that is found is returned.
This function raises a BuildError if it cannot find the required
autob... | codesearchnet |
def acl_required(permission, context):
def decorator(func):
@wraps(func)
async def wrapper(*args):
request = args[(- 1)]
if callable(context):
context = context()
if (await get_permitted(request, permission, context)):
return (awa... | Returns a decorator that checks if a user has the requested permission
from the passed acl context.
This function constructs a decorator that can be used to check a aiohttp's
view for authorization before calling it. It uses the get_permission()
function to check the request against the passed permission and context. ... | codesearchnet |
def gbest_idx(swarm):
best = 0
cmp = comparator(swarm[best].best_fitness)
for (idx, particle) in enumerate(swarm):
if cmp(particle.best_fitness, swarm[best].best_fitness):
best = idx
return best | gbest Neighbourhood topology function.
Args:
swarm: list: The list of particles.
Returns:
int: The index of the gbest particle. | codesearchnet |
def get_posts(self, num=None, tag=None, private=False):
posts = self.posts
if (not private):
posts = [post for post in posts if post.public]
if tag:
posts = [post for post in posts if (tag in post.tags)]
if num:
return posts[:num]
return posts | Get all the posts added to the blog.
Args:
num (int): Optional. If provided, only return N posts (sorted by date,
most recent first).
tag (Tag): Optional. If provided, only return posts that have a
specific tag.
private (bool): By default (if False), private posts are not included.
If set to True, private posts will a... | codesearchnet |
def _ReadConstantDataTypeDefinition(self, definitions_registry, definition_values, definition_name, is_member=False):
if is_member:
error_message = 'data type not supported as member'
raise errors.DefinitionReaderError(definition_name, error_message)
value = definition_values.get('value', None)
... | Reads a constant data type definition.
Args:
definitions_registry (DataTypeDefinitionsRegistry): data type definitions
registry.
definition_values (dict[str, object]): definition values.
definition_name (str): name of the definition.
is_member (Optional[bool]): True if the data type definition is a member
data type de... | codesearchnet |
def add_hgnc_id(self, genes):
genes_by_alias = self.genes_by_alias()
for gene in genes:
id_info = genes_by_alias.get(gene['hgnc_symbol'])
if (not id_info):
LOG.warning('Gene %s does not exist in scout', gene['hgnc_symbol'])
continue
gene['hgnc_id'] = id_info['true... | Add the correct hgnc id to a set of genes with hgnc symbols
Args:
genes(list(dict)): A set of genes with hgnc symbols only | codesearchnet |
def _make_mail(self, complete=True):
mail = {}
keys = get_mail_keys(self.message, complete)
for i in keys:
log.debug('Getting header or part {!r}'.format(i))
value = getattr(self, i)
if value:
mail[i] = value
mail['has_defects'] = self.has_defects
if self.has_defe... | This method assigns the right values to all tokens of email.
Returns a parsed object
Keyword Arguments:
complete {bool} -- If True returns all mails parts
(default: {True})
Returns:
dict -- Parsed email object | codesearchnet |
def _check_approval_wrapper(self, grr_object, grr_function, *args, **kwargs):
approval_sent = False
while True:
try:
return grr_function(*args, **kwargs)
except grr_errors.AccessForbiddenError as exception:
print('No valid approval found: {0!s}'.format(exception))
... | Wraps a call to GRR functions checking for approval.
Args:
grr_object: the GRR object to create the eventual approval on.
grr_function: The GRR function requiring approval.
*args: Positional arguments that are to be passed to `grr_function`.
**kwargs: Keyword arguments that are to be passed to `grr_function`.
Returns... | codesearchnet |
def smart_init_mapping(candidate_mapping, instance1, instance2):
random.seed()
matched_dict = {}
result = []
no_word_match = []
for i, candidates in enumerate(candidate_mapping):
if not candidates:
result.append(-1)
continue
val... | Initialize mapping based on the concept mapping (smart initialization)
Arguments:
candidate_mapping: candidate node match list
instance1: instance triples of AMR 1
instance2: instance triples of AMR 2
Returns:
initialized node mapping between two AMRs | juraj-google-style |
def find_block_end(lines: List[str], start_index: int, indent: int) -> int:
indent = ' ' * indent
line_index = start_index + 1
while line_index < len(lines) and _should_continue(lines[line_index], indent):
line_index += 1
while len(lines[line_index - 1]) <= 1:
line_index -= 1
return ... | Find the end of the class/func block starting at `start_index` in a source code (defined by `lines`).
Args:
lines (`List[str]`):
The source code, represented by a list of lines.
start_index (`int`):
The starting index of the target class/func block.
indent (`int`):
The indent of the class/func body.
Returns:
`int`: T... | github-repos |
def lookup_id(self, group):
filter = ["(cn={})".format(group), "(objectclass=posixGroup)"]
results = self.client.search(filter, ['gidNumber'])
if len(results) < 1:
raise ldap_tools.exceptions.NoGroupsFound(
'No Groups Returned by LDAP')
elif len(resu... | Lookup GID for the given group.
Args:
group: Name of group whose ID needs to be looked up
Returns:
A bytestring representation of the group ID (gid)
for the group specified
Raises:
ldap_tools.exceptions.NoGroupsFound:
No Groups were returned by LDAP
ldap_tools.exceptions.TooManyResults:
More than one group was retu... | juraj-google-style |
def from_file(cls, filename, constant_lattice=True, **kwargs):
fname = os.path.basename(filename)
if fnmatch(fname, '*XDATCAR*'):
structures = Xdatcar(filename).structures
elif fnmatch(fname, 'vasprun*.xml*'):
structures = Vasprun(filename).structures
else:
raise ValueError('Unsu... | Convenience constructor to obtain trajectory from XDATCAR or vasprun.xml file
Args:
filename (str): The filename to read from.
constant_lattice (bool): Whether the lattice changes during the simulation, such as in an NPT MD
simulation. True results in
Returns:
(Trajectory) | codesearchnet |
def kld(d1, d2):
d1, d2 = flatten(d1), flatten(d2)
return entropy(d1, d2, 2.0) | Return the Kullback-Leibler Divergence (KLD) between two distributions.
Args:
d1 (np.ndarray): The first distribution.
d2 (np.ndarray): The second distribution.
Returns:
float: The KLD of ``d1`` from ``d2``. | juraj-google-style |
def _get_elements(mol, label):
elements = [int(mol.GetAtom(i).GetAtomicNum()) for i in label]
return elements | The the elements of the atoms in the specified order
Args:
mol: The molecule. OpenBabel OBMol object.
label: The atom indices. List of integers.
Returns:
Elements. List of integers. | codesearchnet |
def _IsType(clean_lines, nesting_state, expr):
last_word = Match('^.*(\\b\\S+)$', expr)
if last_word:
token = last_word.group(1)
else:
token = expr
if _TYPES.match(token):
return True
typename_pattern = (('\\b(?:typename|class|struct)\\s+' + re.escape(token)) + '\\b')
blo... | Check if expression looks like a type name, returns true if so.
Args:
clean_lines: A CleansedLines instance containing the file.
nesting_state: A NestingState instance which maintains information about
the current stack of nested blocks being parsed.
expr: The expression to check.
Returns:
True, if token looks like a ... | codesearchnet |
def from_json(cls, json, image_config=None):
cls.image_config = image_config
return cls(**{attr: json.get((attr if (key is None) else key)) for (attr, key) in cls.JSON_MAPPING.items()}) | Create a model instance
Arguments:
json (:py:class:`dict`): The parsed JSON data.
image_config (:py:class:`dict`): The API image configuration
data.
Returns:
:py:class:`BaseModel`: The model instance. | codesearchnet |
def to_jdbc_url(self) -> str:
url = f'jdbc:postgresql:
properties = {'socketFactory': 'com.google.cloud.alloydb.SocketFactory', 'alloydbInstanceName': self.instance_name, 'alloydbIpType': self.ip_type}
if self.enable_iam_auth:
properties['alloydbEnableIAMAuth'] = 'true'
if self.target_principal:... | Convert options to a properly formatted JDBC URL.
Returns:
JDBC URL string configured with all options. | github-repos |
def delete_direct(self, addresses):
with self._lock:
for address in addresses:
self._validate_write(address)
if (address in self._state):
self._state[address].set_deleted()
else:
fut = _ContextFuture(address=address)
self._s... | Called in the context manager's delete method to either
mark an entry for deletion , or create a new future and immediately
set it for deletion in the future.
Args:
address_list (list of str): The unique full addresses.
Raises:
AuthorizationException | codesearchnet |
def vgg13(pretrained=False, **kwargs):
if pretrained:
kwargs['init_weights'] = False
model = VGG(make_layers(cfg['B']), **kwargs)
if pretrained:
model.load_state_dict(model_zoo.load_url(model_urls['vgg13']))
return model | VGG 13-layer model (configuration "B")
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet | juraj-google-style |
def max_sequence_length(self, dataset_split):
return {
problem.DatasetSplit.TRAIN: 64,
problem.DatasetSplit.EVAL: 128,
problem.DatasetSplit.TEST: 128
}[dataset_split] | Determine the maximum sequence length given a dataset_split.
Args:
dataset_split: A problem.DatasetSplit.
Returns:
The maximum length that a sequence can be for this dataset_split. | juraj-google-style |
def summary_dict(self):
d = {}
d['Requested'] = len(self.requested)
d['Executed'] = len(self.executed)
d['Passed'] = len(self.passed)
d['Failed'] = len(self.failed)
d['Skipped'] = len(self.skipped)
d['Error'] = len(self.error)
return d | Gets a dictionary that summarizes the stats of this test result.
The summary provides the counts of how many tests fall into each
category, like 'Passed', 'Failed' etc.
Returns:
A dictionary with the stats of this test result. | github-repos |
def from_compatible_tensor_list(element_spec, tensor_list):
return _from_tensor_list_helper(lambda spec, value: spec._from_compatible_tensor_list(value), element_spec, tensor_list) | Returns an element constructed from the given spec and tensor list.
Args:
element_spec: A nested structure of `tf.TypeSpec` objects representing to
element type specification.
tensor_list: A list of tensors to use for constructing the value.
Returns:
An element constructed from the given spec and tensor list.
Raises... | github-repos |
def sign(self, message):
message = _helpers._to_bytes(message, encoding='utf-8')
return rsa.pkcs1.sign(message, self._key, 'SHA-256') | Signs a message.
Args:
message: bytes, Message to be signed.
Returns:
string, The signature of the message for the given key. | juraj-google-style |
def url(self, url, owner=None, **kwargs):
return URL(self.tcex, url, owner=owner, **kwargs) | Create the URL TI object.
Args:
owner:
url:
**kwargs:
Return: | juraj-google-style |
def get_out_of_order(list_of_numbers):
result = []
for i in range(len(list_of_numbers)):
if (i == 0):
continue
if (list_of_numbers[i] < list_of_numbers[(i - 1)]):
result.append((list_of_numbers[(i - 1)], list_of_numbers[i]))
return result | Returns elements that break the monotonically non-decreasing trend.
This is used to find instances of global step values that are "out-of-order",
which may trigger TensorBoard event discarding logic.
Args:
list_of_numbers: A list of numbers.
Returns:
A list of tuples in which each tuple are two elements are adjacent... | codesearchnet |
def update_info(self, custom=None):
self.figure.suptitle(self.info_string() if custom is None else custom) | Updates the figure's suptitle.
Calls self.info_string() unless custom is provided.
Args:
custom: Overwrite it with this string, unless None. | juraj-google-style |
def extract_formats(config_handle):
configurations = dict(config_handle)
formats = dict(configurations.get('formats', {}))
return formats | Get application formats.
See :class:`gogoutils.Formats` for available options.
Args:
config_handle (configparser.ConfigParser): Instance of configurations.
Returns:
dict: Formats in ``{$format_type: $format_pattern}``. | juraj-google-style |
def get_all_ad_units(inventory_service):
statement = (ad_manager.StatementBuilder(version='v201811')
.OrderBy('id', ascending=True))
keep_iterating = True
total_results = 0
found_ad_units = []
while keep_iterating:
page = inventory_service.getAdUnitsByStatement(statement.ToStateme... | Download all ad units.
Args:
inventory_service: An instance of the InventoryService.
Returns:
A list containing all ad units. | juraj-google-style |
def string_handle(self, name=None):
if name is None:
return self._string_handle
else:
return gen_dataset_ops.iterator_to_string_handle(self._iterator_resource, name=name) | Returns a string-valued `tf.Tensor` that represents this iterator.
Args:
name: (Optional.) A name for the created operation.
Returns:
A scalar `tf.Tensor` of type `tf.string`. | github-repos |
def set(cls, values):
cls.mrc_out_el.text = values.get('mrc', '')
cls.oai_out_el.text = values.get('oai', '')
cls.dc_out_el.text = values.get('dc', '')
cls.filename = values.get('fn', 'fn')
cls.values = values | Set the elements from the data obtained from REST API.
Args:
values (dict): Dict with ``mrc``, ``oai``, ``dc`` and ``fn`` keys. | codesearchnet |
def getTextBlocks(page, images=False):
CheckParent(page)
dl = page.getDisplayList()
flags = TEXT_PRESERVE_LIGATURES | TEXT_PRESERVE_WHITESPACE
if images:
flags |= TEXT_PRESERVE_IMAGES
tp = dl.getTextPage(flags)
l = tp._extractTextBlocks_AsList()
del tp
del dl
return l | Return the text blocks on a page.
Notes:
Lines in a block are concatenated with line breaks.
Args:
images: (bool) also return meta data of any images.
Image data are never returned with this method.
Returns:
A list of the blocks. Each item contains the containing rectangle coordinates,
text lines, block type and runni... | juraj-google-style |
def reset(self, indices, observations):
assert isinstance(indices, np.ndarray)
assert len(indices.shape) == 1
assert isinstance(observations, np.ndarray)
assert indices.shape[0] == observations.shape[0]
for index, observation in zip(indices, observations):
trajectory = se... | Resets trajectories at given indices and populates observations.
Reset can either be called right at the beginning, when there are no
time-steps, or to reset a currently active trajectory.
If resetting a currently active trajectory then we save it in
self._completed_trajectories.
Args:
indices: 1-D np.ndarray statin... | juraj-google-style |
def authenticate(self, code: str) -> 'Preston':
headers = self._get_authorization_headers()
data = {
'grant_type': 'authorization_code',
'code': code
}
r = self.session.post(self.TOKEN_URL, headers=headers, data=data)
if not r.status_code == 200:
... | Authenticates using the code from the EVE SSO.
A new Preston object is returned; this object is not modified.
The intended usage is:
auth = preston.authenticate('some_code_here')
Args:
code: SSO code
Returns:
new Preston, authenticated | juraj-google-style |
def assign(self, institute, case, user, link):
LOG.info('Creating event for assigning {0} to {1}'.format(user['name'].encode('utf-8'), case['display_name']))
self.create_event(institute=institute, case=case, user=user, link=link, category='case', verb='assign', subject=case['display_name'])
LOG.info('Updati... | Assign a user to a case.
This function will create an Event to log that a person has been assigned
to a case. Also the user will be added to case "assignees".
Arguments:
institute (dict): A institute
case (dict): A case
user (dict): A User object
link (str): The url to be used in the event
Returns:
updated_case(dict... | codesearchnet |
def groups_replies(self, *, channel: str, thread_ts: str, **kwargs) -> SlackResponse:
self._validate_xoxp_token()
kwargs.update({'channel': channel, 'thread_ts': thread_ts})
return self.api_call('groups.replies', http_verb='GET', params=kwargs) | Retrieve a thread of messages posted to a private channel
Args:
channel (str): The channel id. e.g. 'C1234567890'
thread_ts (str): The timestamp of an existing message with 0 or more replies.
e.g. '1234567890.123456' | codesearchnet |
def __init__(self, default: typing.Optional[bool]=MISSING_VALUE, is_noneable: bool=False, frozen: bool=False):
super().__init__(bool, default, is_noneable=is_noneable, frozen=frozen) | Constructor.
Args:
default: Default value for the value spec.
is_noneable: If True, None is acceptable.
frozen: If True, values other than the default value is not accceptable. | github-repos |
def ListChildPathInfos(self, client_id, path_type, components,
timestamp=None):
return self.ListDescendentPathInfos(
client_id, path_type, components, max_depth=1, timestamp=timestamp) | Lists path info records that correspond to children of given path.
Args:
client_id: An identifier string for a client.
path_type: A type of a path to retrieve path information for.
components: A tuple of path components of a path to retrieve child path
information for.
timestamp: If set, lists only descendants that ex... | juraj-google-style |
def users_setPhoto(self, *, image: Union[(str, IOBase)], **kwargs) -> SlackResponse:
self._validate_xoxp_token()
return self.api_call('users.setPhoto', files={'image': image}, data=kwargs) | Set the user profile photo
Args:
image (str): Supply the path of the image you'd like to upload.
e.g. 'myimage.png' | codesearchnet |
def __init__(self, name, segments):
self.name = name
self.meta = []
self.segments = sorted(segments, key=lambda s: s.points[0].time) | Constructor
When constructing a track it's not guaranteed that the segments
have their properties computed. Call preprocess method over this
class, or over each segment to guarantee it.
Args:
name (:obj:`str`)
segments(:obj:`list` of :obj:`Segment`) | juraj-google-style |
def sparse_categorical_crossentropy(target, output, from_logits=False, axis=-1):
target = tensor_conversion.convert_to_tensor_v2_with_dispatch(target)
output = tensor_conversion.convert_to_tensor_v2_with_dispatch(output)
if hasattr(output, '_keras_logits'):
output = output._keras_logits
if f... | Categorical crossentropy with integer targets.
Args:
target: An integer tensor.
output: A tensor resulting from a softmax
(unless `from_logits` is True, in which
case `output` is expected to be the logits).
from_logits: Boolean, whether `output` is the
result of a softmax, or is a tensor of logits.
axis: Int specifyin... | github-repos |
def parse_results(lines):
idx = 0
batch, onednn, model = (None, None, None)
state = State.FIND_CONFIG_OR_MODEL
while idx < len(lines):
if state is State.FIND_CONFIG_OR_MODEL:
config = re.match("\\+ echo 'BATCH=(?P<batch>[\\d]+), ONEDNN=(?P<onednn>[\\d]+)", lines[idx])
if ... | Parses benchmark results from run_onednn_benchmarks.sh.
Stores results in a global dict.
Args:
lines: Array of strings corresponding to each line of the output from
run_onednn_benchmarks.sh
Raises:
RuntimeError: If the program reaches an unknown state. | github-repos |
class _IdentityBlock(tf.keras.Model):
def __init__(self, kernel_size, filters, stage, block, data_format):
super(_IdentityBlock, self).__init__(name='')
filters1, filters2, filters3 = filters
conv_name_base = 'res' + str(stage) + block + '_branch'
bn_name_base = 'bn' + str(stage) + ... | _IdentityBlock is the block that has no conv layer at shortcut.
Args:
kernel_size: the kernel size of middle conv layer at main path
filters: list of integers, the filters of 3 conv layer at main path
stage: integer, current stage label, used for generating layer names
block: 'a','b'..., current block label, used for ... | github-repos |
def mode(self, **kwargs):
axis = kwargs.get('axis', 0)
def mode_builder(df, **kwargs):
result = df.mode(**kwargs)
if ((not axis) and (len(df) != len(result))):
append_values = pandas.DataFrame(columns=result.columns, index=range(len(result), len(df)))
result = pandas.con... | Returns a new QueryCompiler with modes calculated for each label along given axis.
Returns:
A new QueryCompiler with modes calculated. | codesearchnet |
def pack_tag(field_number, wire_type):
if not 0 <= wire_type <= _WIRETYPE_MAX:
raise errors.EncodeError('Unknown wire type: %d' % wire_type)
return (field_number << TAG_TYPE_BITS) | wire_type | Returns an unsigned 32-bit integer that encodes the field number and
wire type information in standard protocol message wire format.
Args:
field_number: Expected to be an integer in the range [1, 1 << 29)
wire_type: One of the WIRETYPE_* constants. | juraj-google-style |
def Process(self, parser_mediator, cookie_name, cookie_data, url, **kwargs):
if ((cookie_name is None) or (cookie_data is None)):
raise ValueError('Cookie name or data are not set.')
if (cookie_name != self.COOKIE_NAME):
raise errors.WrongPlugin('Not the correct cookie plugin for: {0:s} [{1:s}]'... | Determine if this is the right plugin for this cookie.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
cookie_name (str): the name of the cookie value.
cookie_data (bytes): the cookie data, as a byte sequence.
url (str): the full URL or pat... | codesearchnet |
def remove_instance(self, instance):
query = { "instance_id" : instance.instance_id, "binding_id" : { "$exists" : False } }
try:
result = self.broker.delete_one(query)
except:
raise ErrStorageMongoConnection("Remove Instance")
... | Remove an instance
Remove an object from the MongoDB storage for caching
Args:
instance (AtlasServiceInstance.Instance): instance
Raises:
ErrStorageMongoConnection: Error during MongoDB communication.
ErrStorageRemoveInstance: Failed to remove the instance. | juraj-google-style |
def __init__(self, filesystem, os_path_module=None):
self.filesystem = filesystem
self.sep = filesystem.path_separator
self.altsep = filesystem.alternative_path_separator
self.linesep = filesystem.line_separator()
self._os_module = os
if os_path_module is None:
... | Also exposes self.path (to fake os.path).
Args:
filesystem: FakeFilesystem used to provide file system information
os_path_module: (deprecated) Optional FakePathModule instance | juraj-google-style |
def connect_to_websocket(self):
self.logger.info('Making websocket connection')
try:
if hasattr(self, '_ws'):
self._ws.close()
except:
self.logger.debug('Couldn\'t terminate previous websocket connection')
self._ws = websocket.WebSocketApp... | Call this method to make the connection to the Discord websocket
This method is not blocking, so you'll probably want to call it after
initializating your Pycord object, and then move on with your code. When
you want to block on just maintaining the websocket connection, then call
``keep_running``, and it'll block unt... | juraj-google-style |
def run_inference(self, batch: Sequence[Sequence[OpenAIChatMessage]], model: _VLLMModelServer, inference_args: Optional[dict[str, Any]]=None) -> Iterable[PredictionResult]:
return asyncio.run(self._async_run_inference(batch, model, inference_args)) | Runs inferences on a batch of text strings.
Args:
batch: A sequence of examples as OpenAI messages.
model: A _VLLMModelServer for connecting to the spun up server.
inference_args: Any additional arguments for an inference.
Returns:
An Iterable of type PredictionResult. | github-repos |
def update_ports(self, ports, id_or_uri):
ports = merge_default_values(ports, {'type': 'port'})
uri = self._client.build_uri(id_or_uri) + "/update-ports"
return self._client.update(uri=uri, resource=ports) | Updates the switch ports. Only the ports under the management of OneView and those that are unlinked are
supported for update.
Note:
This method is available for API version 300 or later.
Args:
ports: List of Switch Ports.
id_or_uri: Can be either the switch id or the switch uri.
Returns:
dict: Switch | juraj-google-style |
def major_complex(network, state):
log.info('Calculating major complex...')
result = complexes(network, state)
if result:
result = max(result)
else:
empty_subsystem = Subsystem(network, state, ())
result = _null_sia(empty_subsystem)
log.info("Finished calculating major... | Return the major complex of the network.
Args:
network (Network): The |Network| of interest.
state (tuple[int]): The state of the network (a binary tuple).
Returns:
SystemIrreducibilityAnalysis: The |SIA| for the |Subsystem| with
maximal |big_phi|. | juraj-google-style |
def create_binary(self, key, value):
data = None
if key is not None and value is not None:
try:
data = self.db.create(
key.strip(), json.dumps(base64.b64encode(bytes(value)).decode('utf-8'))
... | Create method of CRUD operation for binary data.
Args:
key (string): The variable to write to the DB.
value (any): The data to write to the DB.
Returns:
(string): Result of DB write. | juraj-google-style |
def parse_ped(ped_stream, family_type='ped'):
pedigree = FamilyParser(ped_stream, family_type=family_type)
if (len(pedigree.families) != 1):
raise PedigreeError('Only one case per ped file is allowed')
family_id = list(pedigree.families.keys())[0]
family = pedigree.families[family_id]
sample... | Parse out minimal family information from a PED file.
Args:
ped_stream(iterable(str))
family_type(str): Format of the pedigree information
Returns:
family_id(str), samples(list[dict]) | codesearchnet |
def with_start_after(self, after_namespace):
namespace_start = _ord_to_namespace(_namespace_to_ord(after_namespace) + 1)
return NamespaceRange(namespace_start, self.namespace_end, _app=self.app) | Returns a copy of this NamespaceName with a new namespace_start.
Args:
after_namespace: A namespace string.
Returns:
A NamespaceRange object whose namespace_start is the lexographically next
namespace after the given namespace string.
Raises:
ValueError: if the NamespaceRange includes only a single namespace. | juraj-google-style |
def __init__(self, cells, state_is_tuple=True):
logging.warning('`tf.nn.rnn_cell.MultiRNNCell` is deprecated. This class is equivalent as `tf.keras.layers.StackedRNNCells`, and will be replaced by that in Tensorflow 2.0.')
super(MultiRNNCell, self).__init__()
if not cells:
raise ValueError('Must spe... | Create a RNN cell composed sequentially of a number of RNNCells.
Args:
cells: list of RNNCells that will be composed in this order.
state_is_tuple: If True, accepted and returned states are n-tuples, where
`n = len(cells)`. If False, the states are all concatenated along the
column axis. This latter behavior will so... | github-repos |
def find_log_dir_and_names(program_name=None, log_dir=None):
if (not program_name):
program_name = os.path.splitext(os.path.basename(sys.argv[0]))[0]
program_name = ('py_%s' % program_name)
actual_log_dir = find_log_dir(log_dir=log_dir)
try:
username = getpass.getuser()
except Ke... | Computes the directory and filename prefix for log file.
Args:
program_name: str|None, the filename part of the path to the program that
is running without its extension. e.g: if your program is called
'usr/bin/foobar.py' this method should probably be called with
program_name='foobar' However, this is just a convent... | codesearchnet |
def __init__(self, size, dropout=None, lstmcell_args={}, named_tensors=None, scope='internal_lstm', summary_labels=()):
self.size = size
self.dropout = dropout
self.lstmcell_args = lstmcell_args
super(InternalLstm, self).__init__(named_tensors=named_tensors, scope=scope, summary... | LSTM layer.
Args:
size: LSTM size.
dropout: Dropout rate. | juraj-google-style |
def from_api_repr(cls, api_repr):
mode = api_repr.get("mode", "NULLABLE")
description = api_repr.get("description")
fields = api_repr.get("fields", ())
return cls(
field_type=api_repr["type"].upper(),
fields=[cls.from_api_repr(f) for f in fields]... | Return a ``SchemaField`` object deserialized from a dictionary.
Args:
api_repr (Mapping[str, str]): The serialized representation
of the SchemaField, such as what is output by
:meth:`to_api_repr`.
Returns:
google.cloud.biquery.schema.SchemaField:
The ``SchemaField`` object. | juraj-google-style |
def _on_cancelok(self, cancel_frame):
_log.info("Consumer canceled; returning all unprocessed messages to the queue")
self._channel.basic_nack(delivery_tag=0, multiple=True, requeue=True) | Called when the server acknowledges a cancel request.
Args:
cancel_frame (pika.spec.Basic.CancelOk): The cancelok frame from
the server. | juraj-google-style |
def __init__(self, dataset_fn, coordinator):
def disallow_variable_creation(next_creator, **kwargs):
raise ValueError('Creating variables in `dataset_fn` is not allowed.')
if isinstance(dataset_fn, def_function.Function):
with variable_scope.variable_creator_scope(disallow_variable_creation):
... | Makes an iterable from datasets created by the given function.
Args:
dataset_fn: A function that returns a `Dataset`.
coordinator: a `ClusterCoordinator` object, used to create dataset
resources. | github-repos |
def rewards_to_go(rewards, mask, gamma=0.99):
r
B, T = rewards.shape
masked_rewards = rewards * mask
r2gs = [masked_rewards[:, -1]]
for t in reversed(range(T - 1)):
r2gs.append(masked_rewards[:, t] + (gamma * r2gs[-1]))
assert T == len(r2gs)... | r"""Computes rewards to go.
Reward to go is defined as follows, the discounted reward that we have to
yet collect, going forward from this point, i.e.:
r2g_t = \sum_{l=0}^{\infty} (\gamma^{l} * reward_{t+l})
Args:
rewards: np.ndarray of shape (B, T) of rewards.
mask: np.ndarray of shape (B, T) of mask for the reward... | juraj-google-style |
def add_rec_new(self, k, val):
self.rec_new(val)
self[k] = val
return val | Recursively add a new value and its children to me, and assign a
variable to it.
Args:
k (str): The name of the variable to assign.
val (LispVal): The value to be added and assigned.
Returns:
LispVal: The added value. | codesearchnet |
def run(self, resources):
if (not resources['connection']._port.startswith('jlink')):
raise ArgumentError('FlashBoardStep is currently only possible through jlink', invalid_port=args['port'])
hwman = resources['connection']
debug = hwman.hwman.debug(self._debug_string)
debug.flash(self._file) | Runs the flash step
Args:
resources (dict): A dictionary containing the required resources that
we needed access to in order to perform this step. | codesearchnet |
def get_text_features(self, input_ids: Optional[torch.Tensor]=None, attention_mask: Optional[torch.Tensor]=None, position_ids: Optional[torch.Tensor]=None, output_attentions: Optional[bool]=None, output_hidden_states: Optional[bool]=None, return_dict: Optional[bool]=None) -> torch.FloatTensor:
output_attentions = o... | Returns:
text_features (`torch.FloatTensor` of shape `(batch_size, output_dim`): The text embeddings obtained by
applying the projection layer to the pooled output of [`CLIPSegTextModel`].
Examples:
```python
>>> from transformers import AutoTokenizer, CLIPSegModel
>>> tokenizer = AutoTokenizer.from_pretrained("CIDA... | github-repos |
def _all_gather(self, input_tensor: core.TensorLike, options: Optional[collective_util.Options]) -> core.Tensor:
instance_key = self._next_instance_key()
options = self._options.merge(options)
ordering_token = self._get_ordering_token()
with ops.device(self._device):
return collective_ops.all_ga... | All-gather a dense tensor.
Args:
input_tensor: a dense tensor. It must have the same shape on all replicas.
options: an optional tf.distribute.experimental.CommunicationOptions. If
provided, it overrides the default options.
Returns:
The reduced tensor. | github-repos |
def screenshot(path=None):
if (not _rootinitialized):
raise TDLError('Initialize first with tdl.init')
if isinstance(path, str):
_lib.TCOD_sys_save_screenshot(_encodeString(path))
elif (path is None):
filelist = _os.listdir('.')
n = 1
filename = ('screenshot%.3i.png' ... | Capture the screen and save it as a png file.
If path is None then the image will be placed in the current
folder with the names:
``screenshot001.png, screenshot002.png, ...``
Args:
path (Optional[Text]): The file path to save the screenshot. | codesearchnet |
def is_periodic_image(self, other, tolerance=1e-8, check_lattice=True):
if check_lattice and self.lattice != other.lattice:
return False
if self.species != other.species:
return False
frac_diff = pbc_diff(self.frac_coords, other.frac_coords)
return np.al... | Returns True if sites are periodic images of each other.
Args:
other (PeriodicSite): Other site
tolerance (float): Tolerance to compare fractional coordinates
check_lattice (bool): Whether to check if the two sites have the
same lattice.
Returns:
bool: True if sites are periodic images of each other. | juraj-google-style |
def from_dir(dirpath: Path, feat_type: str) -> None:
logger.info("Extracting features from directory {}".format(dirpath))
dirname = str(dirpath)
def all_wavs_processed() -> bool:
for fn in os.listdir(dirname):
prefix, ext = os.path.splitext(fn)
if ext == ".w... | Performs feature extraction from the WAV files in a directory.
Args:
dirpath: A `Path` to the directory where the WAV files reside.
feat_type: The type of features that are being used. | juraj-google-style |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.