code stringlengths 20 4.93k | docstring stringlengths 33 1.27k | source stringclasses 3
values |
|---|---|---|
def add_deploy(state, deploy_func, *args, **kwargs):
frameinfo = get_caller_frameinfo()
kwargs['frameinfo'] = frameinfo
for host in state.inventory:
deploy_func(state, host, *args, **kwargs) | Prepare & add an deploy to pyinfra.state by executing it on all hosts.
Args:
state (``pyinfra.api.State`` obj): the deploy state to add the operation
deploy_func (function): the operation function from one of the modules,
ie ``server.user``
args/kwargs: passed to the operation function | codesearchnet |
def to_geotiff(arr, path='./output.tif', proj=None, spec=None, bands=None, **kwargs):
assert has_rasterio, "To create geotiff images please install rasterio"
try:
img_md = arr.rda.metadata["image"]
x_size = img_md["tileXSize"]
y_size = img_md["tileYSize"]
except (Attr... | Write out a geotiff file of the image
Args:
path (str): path to write the geotiff file to, default is ./output.tif
proj (str): EPSG string of projection to reproject to
spec (str): if set to 'rgb', write out color-balanced 8-bit RGB tif
bands (list): list of bands to export. If spec='rgb' will default to RGB bands
Re... | juraj-google-style |
def AddTask(self, target, args=(), name='Unnamed task', blocking=True, inline=True):
if (not self.started):
raise ThreadPoolNotStartedError(self.name)
if (self.max_threads == 0):
target(*args)
return
if inline:
blocking = False
with self.lock:
while True:
... | Adds a task to be processed later.
Args:
target: A callable which should be processed by one of the workers.
args: A tuple of arguments to target.
name: The name of this task. Used to identify tasks in the log.
blocking: If True we block until the task is finished, otherwise we raise
queue.Full
inline: If set, process... | codesearchnet |
def elmo_loss2ppl(losses: List[np.ndarray]) -> float:
avg_loss = np.mean(losses)
return float(np.exp(avg_loss)) | Calculates perplexity by loss
Args:
losses: list of numpy arrays of model losses
Returns:
perplexity : float | codesearchnet |
def partial_declaration_path(decl):
if not decl:
return []
if not decl.cache.partial_declaration_path:
result = [decl.partial_name]
parent = decl.parent
while parent:
if parent.cache.partial_declaration_path:
result.reverse()
... | Returns a list of parent declarations names without template arguments that
have default value.
Args:
decl (declaration_t): declaration for which the partial declaration
path should be calculated.
Returns:
list[(str | basestring)]: list of names, where first item is the top
parent name and last item the inputted
decl... | juraj-google-style |
def __init__(self, bundle_context_manager: execution.BundleContextManager, progress_frequency: Optional[float]=None, cache_token_generator=FnApiRunner.get_cache_token_generator(), split_managers=()) -> None:
self.bundle_context_manager: execution.BundleContextManager = bundle_context_manager
self._progress_freq... | Set up a bundle manager.
Args:
progress_frequency | github-repos |
def _HasId(self, schedule, entity_id):
try:
self._GetById(schedule, entity_id)
has = True
except KeyError:
has = False
return has | Check if the schedule has an entity with the given id.
Args:
schedule: The transitfeed.Schedule instance to look in.
entity_id: The id of the entity.
Returns:
True if the schedule has an entity with the id or False if not. | juraj-google-style |
def analyze_directory(self, directory: Path, identifier: Union[str, None]=None, ignore_files: Union[list[str], None]=None, n_identifier: Union[str, list[str], None]=None, only_modules: bool=True):
files = [file for file in os.listdir(directory) if os.path.isfile(os.path.join(directory, file))]
if identifier is ... | Runs through the specific directory, looking for the files identified with `identifier`. Executes
the doctests in those files
Args:
directory (`Path`): Directory containing the files
identifier (`str`): Will parse files containing this
ignore_files (`List[str]`): List of files to skip
n_identifier (`str` or `List[str]... | github-repos |
def verify_profile_name(msg, cfg):
if msg.profile not in cfg.data:
raise UnknownProfileError(msg.profile) | Verifies the profile name exists in the config.json file.
Args:
:msg: (Message class) an instance of a message class.
:cfg: (jsonconfig.Config) config instance. | juraj-google-style |
def launch(self, image, command, **kwargs):
if isinstance(command, PythonCall):
return PythonJob(self, image, command, **kwargs)
else:
return Job(self, image, command, **kwargs) | Create a job on this engine
Args:
image (str): name of the docker image to launch
command (str): shell command to run | codesearchnet |
def diagonal_gaussian_posterior_builder(getter, name, shape=None, *args, **kwargs):
parameter_shapes = tfp.distributions.Normal.param_static_shapes(shape)
loc_var = getter((name + '/posterior_loc'), *args, shape=parameter_shapes['loc'], **kwargs)
scale_var = getter((name + '/posterior_scale'), *args, shape=... | A pre-canned builder for diagonal gaussian posterior distributions.
Given a true `getter` function and arguments forwarded from `tf.get_variable`,
return a distribution object for a diagonal posterior over a variable of the
requisite shape.
Args:
getter: The `getter` passed to a `custom_getter`. Please see the
docume... | codesearchnet |
def replace_keywords(self, sentence):
if (not sentence):
return sentence
new_sentence = []
orig_sentence = sentence
if (not self.case_sensitive):
sentence = sentence.lower()
current_word = ''
current_dict = self.keyword_trie_dict
current_white_space = ''
sequence_end_pos ... | Searches in the string for all keywords present in corpus.
Keywords present are replaced by the clean name and a new string is returned.
Args:
sentence (str): Line of text where we will replace keywords
Returns:
new_sentence (str): Line of text with replaced keywords
Examples:
>>> from flashtext import KeywordProces... | codesearchnet |
def flowread(flow_or_path, quantize=False, concat_axis=0, *args, **kwargs):
if isinstance(flow_or_path, np.ndarray):
if ((flow_or_path.ndim != 3) or (flow_or_path.shape[(- 1)] != 2)):
raise ValueError('Invalid flow with shape {}'.format(flow_or_path.shape))
return flow_or_path
elif (... | Read an optical flow map.
Args:
flow_or_path (ndarray or str): A flow map or filepath.
quantize (bool): whether to read quantized pair, if set to True,
remaining args will be passed to :func:`dequantize_flow`.
concat_axis (int): The axis that dx and dy are concatenated,
can be either 0 or 1. Ignored if quantize is Fal... | codesearchnet |
def qhull_cmd(cmd, options, points):
prep_str = [str(len(points[0])), str(len(points))]
prep_str.extend([' '.join(map(repr, row)) for row in points])
output = getattr(hull, cmd)(options, '\n'.join(prep_str))
return list(map(str.strip, output.strip().split('\n'))) | Generalized helper method to perform a qhull based command.
Args:
cmd:
Command to perform. Supported commands are qconvex,
qdelaunay and qvoronoi.
options:
Options to be provided for qhull command. See specific methods for
info on supported options. Up to two options separated by spaces
are supported.
points:
Sequence... | codesearchnet |
def from_file_msg(cls, fp):
log.debug("Parsing email from file Outlook")
f, _ = msgconvert(fp)
return cls.from_file(f, True) | Init a new object from a Outlook message file,
mime type: application/vnd.ms-outlook
Args:
fp (string): file path of raw Outlook email
Returns:
Instance of MailParser | juraj-google-style |
def from_dense(tensor, name=None):
with ops.name_scope(name, 'dense_to_sparse'):
tensor = ops.convert_to_tensor(tensor)
indices = array_ops.where_v2(math_ops.not_equal(tensor, array_ops.zeros_like(tensor)))
values = array_ops.gather_nd(tensor, indices)
shape = array_ops.shape(tensor,... | Converts a dense tensor into a sparse tensor.
Only elements not equal to zero will be present in the result. The resulting
`SparseTensor` has the same dtype and shape as the input.
>>> sp = tf.sparse.from_dense([0, 0, 3, 0, 1])
>>> sp.shape.as_list()
[5]
>>> sp.values.numpy()
array([3, 1], dtype=int32)
>>> sp.indices... | github-repos |
def download_apcor(self, uri):
local_file = os.path.basename(uri)
if os.access(local_file, os.F_OK):
fobj = open(local_file)
else:
fobj = storage.vofile(uri, view='data')
fobj.seek(0)
str = fobj.read()
fobj.close()
apcor_str =... | Downloads apcor data.
Args:
uri: The URI of the apcor data file.
Returns:
apcor: ossos.downloads.core.ApcorData | juraj-google-style |
def load(self, txt_fst_filename):
with open(txt_fst_filename, 'r') as txt_fst:
for line in txt_fst:
line = line.strip()
splitted_line = line.split()
if len(splitted_line) == 1:
self[int(splitted_line[0])].final = True
... | Save the transducer in the text file format of OpenFST.
The format is specified as follows:
arc format: src dest ilabel olabel [weight]
final state format: state [weight]
lines may occur in any order except initial state must be first line
Args:
txt_fst_filename (string): The name of the file
Returns:
None | juraj-google-style |
def intersects(self, other):
try:
return (self.min_x <= other.max_x and
self.max_x >= other.min_x and
self.min_y <= other.max_y and
self.max_y >= other.min_y)
except AttributeError:
return self.intersects(Envelo... | Returns true if this envelope intersects another.
Arguments:
other -- Envelope or tuple of (minX, minY, maxX, maxY) | juraj-google-style |
def __delitem__(self, anchor_id):
try:
self._anchor_path(anchor_id).unlink()
except OSError:
raise KeyError('No anchor with id {}'.format(anchor_id)) | Remove an anchor from storage.
Args:
anchor_id: The ID of the anchor to remove.
Raises:
KeyError: There is no anchor with that ID. | juraj-google-style |
def get_vm(access_token, subscription_id, resource_group, vm_name):
endpoint = ''.join([get_rm_endpoint(), '/subscriptions/', subscription_id, '/resourceGroups/', resource_group, '/providers/Microsoft.Compute/virtualMachines/', vm_name, '?api-version=', COMP_API])
return do_get(endpoint, access_token) | Get virtual machine details.
Args:
access_token (str): A valid Azure authentication token.
subscription_id (str): Azure subscription id.
resource_group (str): Azure resource group name.
vm_name (str): Name of the virtual machine.
Returns:
HTTP response. JSON body of VM properties. | codesearchnet |
async def update_notifications(self, on_match_open: bool=None, on_tournament_end: bool=None):
params = {}
if (on_match_open is not None):
params['notify_users_when_matches_open'] = on_match_open
if (on_tournament_end is not None):
params['notify_users_when_the_tournament_ends'] = on_tourname... | update participants notifications for this tournament
|methcoro|
Args:
on_match_open: Email registered Challonge participants when matches open up for them
on_tournament_end: Email registered Challonge participants the results when this tournament ends
Raises:
APIException | codesearchnet |
def _compile_output_step(outputs):
if (not outputs):
raise GraphQLCompilationError(u'No fields were selected for output! Please mark at least one field with the @output directive.')
output_fields = {}
for (output_name, output_context) in six.iteritems(outputs):
location = output_context['loc... | Construct the final ConstructResult basic block that defines the output format of the query.
Args:
outputs: dict, output name (string) -> output data dict, specifying the location
from where to get the data, and whether the data is optional (and therefore
may be missing); missing optional data is replaced with 'null'
... | codesearchnet |
def add_task(self, tile_address, coroutine):
self._loop.call_soon_threadsafe(self._add_task, tile_address, coroutine) | Add a task into the event loop.
This is the main entry point for registering background tasks that are
associated with a tile. The tasks are added to the EmulationLoop and
the tile they are a part of is recorded. When the tile is reset, all
of its background tasks are canceled as part of the reset process.
If you ha... | codesearchnet |
def check_function_argument_count(func, input_arity, infeed_queue):
def format_error(complaint, quantity):
return '%s %d argument%s' % (complaint, quantity, '' if quantity == 1 else 's')
num_args_supplied = input_arity
if infeed_queue is not None:
num_args_supplied += infeed_queue.number_of... | Validate the number of input arguments to an XLA function.
Args:
func: the Python function that will be called to generate the body of an XLA
computation graph.
input_arity: the number of explicit arguments supplied by the caller.
infeed_queue: if not None, the infeed queue that will supply
additional arguments to the... | github-repos |
def split_line(what, indent='', cols=79):
if len(indent) > cols:
raise ValueError("The indent can't be longer than cols.")
if cols < 2:
raise ValueError(
"The cols can't be smaller than 2 (a char plus a possible '-')"
)
what = indent + what.lstrip()
if len(wha... | Split a line on the closest space, or break the last word with '-'.
Args:
what(str): text to spli one line of.
indent(str): will prepend this indent to the split line, taking it into
account in the column count.
cols(int): maximum length of the split line.
Returns:
tuple(str, str): rest of the text and split line in ... | juraj-google-style |
def purity(state):
rho = np.array(state)
if rho.ndim == 1:
return 1.0
return np.real(np.trace(rho.dot(rho))) | Calculate the purity of a quantum state.
Args:
state (ndarray): a quantum state
Returns:
float: purity. | juraj-google-style |
def _UpdateUsers(self, update_users):
for (user, ssh_keys) in update_users.items():
if ((not user) or (user in self.invalid_users)):
continue
configured_keys = self.user_ssh_keys.get(user, [])
if (set(ssh_keys) != set(configured_keys)):
if (not self.utils.UpdateUser(u... | Provision and update Linux user accounts based on account metadata.
Args:
update_users: dict, authorized users mapped to their public SSH keys. | codesearchnet |
def fit_to_structure(self, structure, symprec=0.1):
sga = SpacegroupAnalyzer(structure, symprec)
symm_ops = sga.get_symmetry_operations(cartesian=True)
return sum([self.transform(symm_op)
for symm_op in symm_ops]) / len(symm_ops) | Returns a tensor that is invariant with respect to symmetry
operations corresponding to a structure
Args:
structure (Structure): structure from which to generate
symmetry operations
symprec (float): symmetry tolerance for the Spacegroup Analyzer
used to generate the symmetry operations | juraj-google-style |
def __init__(self, group, provider, checker, code, messages):
self.group = group
self.provider = provider
self.checker = checker
self.code = code
self.messages = messages | Initialization method.
Args:
group (AnalysisGroup): parent group.
provider (Provider): parent Provider.
checker (Checker): parent Checker.
code (int): constant from Checker class.
messages (str): messages string. | juraj-google-style |
def get_file_list(wildcard):
files = glob.glob(os.path.expanduser(wildcard))
return files | Search for files to be concatenated. Currently very basic, but could
expand to be more sophisticated.
Args:
wildcard (regular expression string)
Returns:
files (list of full file paths) | codesearchnet |
def read(keypath, configfile=None):
if configfile in _configs:
appconfig = _configs[configfile]
else:
appconfig = AppConfig(configfile=configfile)
_configs[configfile] = appconfig
return appconfig.read(keypath) | Reads a value from the configuration file.
Args:
keypath: str
Specifies the key for which the value is desired. It can be a
hierarchical path. Example: "section1.subsection.key1"
configfile: str
Path to the config file to read. Defaults to None, in which case
the application's default config file is used.
Returns:... | juraj-google-style |
def _get_client_by_id(self, client_id):
client = self.grr_api.Client(client_id)
print('Checking for client approval')
self._check_approval_wrapper(client, client.ListFlows)
print('{0:s}: Client approval is valid'.format(client_id))
return client.Get() | Get GRR client dictionary and make sure valid approvals exist.
Args:
client_id: GRR client ID.
Returns:
GRR API Client object | juraj-google-style |
def util_pattern_space(time_series, lag, dim):
n = len(time_series)
if ((lag * dim) > n):
raise Exception('Result matrix exceeded size limit, try to change lag or dim.')
elif (lag < 1):
raise Exception('Lag should be greater or equal to 1.')
pattern_space = np.empty(((n - (lag * (dim - 1... | Create a set of sequences with given lag and dimension
Args:
time_series: Vector or string of the sample data
lag: Lag between beginning of sequences
dim: Dimension (number of patterns)
Returns:
2D array of vectors | codesearchnet |
def get_resource(self, feature_column, name):
del feature_column, name
raise NotImplementedError('StateManager.get_resource') | Returns an already created resource.
Resources can be things such as tables, variables, trackables, etc.
Args:
feature_column: A `FeatureColumn` object this variable corresponds to.
name: Name of the resource. | github-repos |
def create_bulk(self, resource, timeout=-1):
uri = self.URI + '/bulk'
default_values = self._get_default_values(self.BULK_DEFAULT_VALUES)
updated_data = self._helper.update_resource_fields(resource, default_values)
self._helper.create(updated_data, uri=uri, timeout=timeout)
... | Creates bulk Ethernet networks.
Args:
resource (dict): Specifications to create in bulk.
timeout:
Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation
in OneView; it just stops waiting for its completion.
Returns:
list: List of created Ethernet Networks. | juraj-google-style |
def make(cls, name: str, ctx: 'context.Context', module: str, pyval_name: str | None=None) -> 'PyTDFunction':
pyval = ctx.loader.lookup_pytd(module, pyval_name or name)
if isinstance(pyval, pytd.Alias) and isinstance(pyval.type, pytd.Function):
pyval = pyval.type
pyval = pyval.Replace(name=f'{module... | Create a PyTDFunction.
Args:
name: The function name.
ctx: The abstract context.
module: The module that the function is in.
pyval_name: Optionally, the name of the pytd.Function object to look up,
if it is different from the function name.
Returns:
A new PyTDFunction. | github-repos |
def _OpenFile(self, path):
if (not self._registry_file_reader):
return None
return self._registry_file_reader.Open(path, ascii_codepage=self._ascii_codepage) | Opens a Windows Registry file.
Args:
path (str): path of the Windows Registry file.
Returns:
WinRegistryFile: Windows Registry file or None if not available. | codesearchnet |
def annotate(self, sent):
preds = []
words = []
for (word, fv) in self.sent2examples(sent):
probs = self.predictor(fv)
tags = probs.argsort()
tag = self.ID_TAG[tags[(- 1)]]
words.append(word)
preds.append(tag)
annotations = zip(words, preds)
return annotations | Annotate a squence of words with entity tags.
Args:
sent: sequence of strings/words. | codesearchnet |
def flush(cls, *args):
return _remove_keys([], [((cls._make_key(args) if args else cls.PREFIX) + '*')]) | Removes all keys of this namespace
Without args, clears all keys starting with cls.PREFIX
if called with args, clears keys starting with given cls.PREFIX + args
Args:
*args: Arbitrary number of arguments.
Returns:
List of removed keys. | codesearchnet |
def save_data_files(vr, bs, prefix=None, directory=None):
filename = '{}_band.dat'.format(prefix) if prefix else 'band.dat'
directory = directory if directory else '.'
filename = os.path.join(directory, filename)
if bs.is_metal():
zero = vr.efermi
else:
zero = bs.get_vbm()['ene... | Write the band structure data files to disk.
Args:
vs (`Vasprun`): Pymatgen `Vasprun` object.
bs (`BandStructureSymmLine`): Calculated band structure.
prefix (`str`, optional): Prefix for data file.
directory (`str`, optional): Directory in which to save the data.
Returns:
The filename of the written data file. | juraj-google-style |
def get_variants(self, chromosome=None, start=None, end=None):
query = {}
if chromosome:
query['chrom'] = chromosome
if start:
query['start'] = {'$lte': end}
query['end'] = {'$gte': start}
LOG.info("Find all variants {}".format(query))
... | Return all variants in the database
If no region is specified all variants will be returned.
Args:
chromosome(str)
start(int)
end(int)
Returns:
variants(Iterable(Variant)) | juraj-google-style |
def is_empty(self):
for family in self.iter_package_families():
for pkg in self.iter_packages(family):
return False
return True | Determine if the repository contains any packages.
Returns:
True if there are no packages, False if there are at least one. | codesearchnet |
def start(self, **kwargs):
if not self.is_running():
self.websock_url = self.chrome.start(**kwargs)
self.websock = websocket.WebSocketApp(self.websock_url)
self.websock_thread = WebsockReceiverThread(
self.websock, name='WebsockThread:%s' % self.c... | Starts chrome if it's not running.
Args:
**kwargs: arguments for self.chrome.start(...) | juraj-google-style |
def persons_significant_control(self, num, statements=False, **kwargs):
baseuri = (self._BASE_URI + 'company/{}/persons-with-significant-control'.format(num))
if (statements is True):
baseuri += '-statements'
res = self.session.get(baseuri, params=kwargs)
self.handle_http_error(res)
return r... | Search for a list of persons with significant control.
Searches for persons of significant control based on company number for
a specified company. Specify statements=True to only search for
officers with statements.
Args:
num (str, int): Company number to search on.
statements (Optional[bool]): Search only for perso... | codesearchnet |
def GetRawDevice(path):
path = CanonicalPathToLocalPath(path)
try:
path = win32file.GetLongPathName(path)
except pywintypes.error:
pass
try:
mount_point = win32file.GetVolumePathName(path)
except pywintypes.error as details:
logging.info('path not found. %s', details)... | Resolves the raw device that contains the path.
Args:
path: A path to examine.
Returns:
A pathspec to read the raw device as well as the modified path to read
within the raw device. This is usually the path without the mount point.
Raises:
IOError: if the path does not exist or some unexpected behaviour occurs. | codesearchnet |
async def set_headline(self, name, level, message):
if (name not in self.services):
raise ArgumentError('Unknown service name', short_name=name)
self.services[name]['state'].set_headline(level, message)
headline = self.services[name]['state'].headline.to_dict()
(await self._notify_update(name, '... | Set the sticky headline for a service.
Args:
name (string): The short name of the service to query
level (int): The level of the message (info, warning, error)
message (string): The message contents | codesearchnet |
def compute_shader(self, source) -> 'ComputeShader':
res = ComputeShader.__new__(ComputeShader)
res.mglo, ls1, ls2, ls3, ls4, res._glo = self.mglo.compute_shader(source)
members = {}
for item in ls1:
obj = Uniform.__new__(Uniform)
obj.mglo, obj._locati... | A :py:class:`ComputeShader` is a Shader Stage that is used entirely for computing arbitrary information.
While it can do rendering, it is generally used for tasks not directly related to drawing.
Args:
source (str): The source of the compute shader.
Returns:
:py:class:`ComputeShader` object | juraj-google-style |
def _RunAction(self, rule, client_id):
actions_count = 0
try:
if self._CheckIfHuntTaskWasAssigned(client_id, rule.hunt_id):
logging.info(
"Foreman: ignoring hunt %s on client %s: was started "
"here before", client_id, rule.hunt_id)
else:
logging.info("F... | Run all the actions specified in the rule.
Args:
rule: Rule which actions are to be executed.
client_id: Id of a client where rule's actions are to be executed.
Returns:
Number of actions started. | juraj-google-style |
def dependency_of_fetches(fetches, op):
try:
from tensorflow.python.client.session import _FetchHandler as FetchHandler
handler = FetchHandler(op.graph, fetches, {})
targets = tuple(handler.fetches() + handler.targets())
except ImportError:
if isinstance(fetches, li... | Check that op is in the subgraph induced by the dependencies of fetches.
fetches may have more general structure.
Args:
fetches: An argument to `sess.run`. Nested structure will affect performance.
op (tf.Operation or tf.Tensor):
Returns:
bool: True if any of `fetches` depend on `op`. | juraj-google-style |
def label_matrix_to_one_hot(L, k=None):
n, m = L.shape
if k is None:
k = L.max()
L_onehot = torch.zeros(n, m, k + 1)
for i, row in enumerate(L):
for j, k in enumerate(row):
if k > 0:
L_onehot[i, j, k - 1] = 1
return L_onehot | Converts a 2D [n,m] label matrix into an [n,m,k] one hot 3D tensor
Note that in the returned 3D matrix, abstain votes continue to be
represented by 0s, not 1s.
Args:
L: a [n,m] label matrix with categorical labels (0 = abstain)
k: the number of classes that could appear in L
if None, k is inferred as the max element ... | juraj-google-style |
def _create_node(self, index: int, name: str, external_id: Optional[str] = None) -> SpotifyArtistNode:
if external_id is None:
graph: SpotifyArtistGraph = self._graph
items: List[NameExternalIDPair] = graph.client.search_artists_by_name(name)
for item in items:
... | Returns a new `SpotifyArtistNode` instance with the given index and name.
Arguments:
index (int): The index of the node to create.
name (str): The name of the node to create.
external_id (Optional[str]): The external ID of the node. | juraj-google-style |
def GetZipInfoByPathSpec(self, path_spec):
location = getattr(path_spec, 'location', None)
if location is None:
raise errors.PathSpecError('Path specification missing location.')
if not location.startswith(self.LOCATION_ROOT):
raise errors.PathSpecError('Invalid location in path specificat... | Retrieves the ZIP info for a path specification.
Args:
path_spec (PathSpec): a path specification.
Returns:
zipfile.ZipInfo: a ZIP info object or None if not available.
Raises:
PathSpecError: if the path specification is incorrect. | juraj-google-style |
def crscode_to_string(codetype, code, format):
link = 'http:
result = urllib2.urlopen(link).read()
if not isinstance(result, str):
result = result.decode()
return result | Lookup crscode on spatialreference.org and return in specified format.
Arguments:
- *codetype*: "epsg", "esri", or "sr-org".
- *code*: The code.
- *format*: The crs format of the returned string. One of "ogcwkt", "esriwkt", or "proj4", but also several others...
Returns:
- Crs string in the specified format. | juraj-google-style |
def micros_to_timestamp(micros, timestamp):
seconds = long((micros / _MICROS_PER_SECOND))
micro_remainder = (micros % _MICROS_PER_SECOND)
timestamp.seconds = seconds
timestamp.nanos = (micro_remainder * _NANOS_PER_MICRO) | Convert microseconds from utc epoch to google.protobuf.timestamp.
Args:
micros: a long, number of microseconds since utc epoch.
timestamp: a google.protobuf.timestamp.Timestamp to populate. | codesearchnet |
def activate_backup_image(reset=False):
dn = "sys/rack-unit-1/mgmt/fw-boot-def/bootunit-combined"
r = "no"
if reset is True:
r = "yes"
inconfig = .format(r)
ret = __proxy__['cimc.set_config_modify'](dn, inconfig, False)
return ret | Activates the firmware backup image.
CLI Example:
Args:
reset(bool): Reset the CIMC device on activate.
.. code-block:: bash
salt '*' cimc.activate_backup_image
salt '*' cimc.activate_backup_image reset=True | juraj-google-style |
def update(self, grads):
grads = nest.flatten(grads)
if distribute_lib.has_strategy() and distribute_lib.in_cross_replica_context():
distribution = distribute_lib.get_strategy()
is_finite_per_replica = distribution.extended.call_for_each_replica(_is_all_finite, args=(grads,))
is_finite =... | Updates the value of the loss scale.
Args:
grads: A nested structure of unscaled gradients, each which is an
all-reduced gradient of the loss with respect to a weight.
Returns:
update_op: In eager mode, None. In graph mode, an op to update the loss
scale.
should_apply_gradients: Either a bool or a scalar boolean tens... | github-repos |
def decode(self, ids):
_, tmp_file_path = tempfile.mkstemp()
wavfile.write(tmp_file_path, self._sample_rate, np.asarray(ids))
return tmp_file_path | Transform a sequence of float32 into a waveform.
Args:
ids: list of integers to be converted.
Returns:
Path to the temporary file where the waveform was saved.
Raises:
ValueError: if the ids are not of the appropriate size. | juraj-google-style |
def removeTags(dom):
try:
string_type = basestring
except NameError:
string_type = str
element_stack = None
if (type(dom) in [list, tuple]):
element_stack = dom
elif isinstance(dom, HTMLElement):
element_stack = (dom.childs if dom.isTag() else [dom])
elif isinstan... | Remove all tags from `dom` and obtain plaintext representation.
Args:
dom (str, obj, array): str, HTMLElement instance or array of elements.
Returns:
str: Plain string without tags. | codesearchnet |
def find(self, title):
if title not in self._titles:
raise KeyError(title)
return self._titles[title][0] | Return the first worksheet with the given title.
Args:
title(str): title/name of the worksheet to return
Returns:
WorkSheet: contained worksheet object
Raises:
KeyError: if the spreadsheet has no no worksheet with the given ``title`` | juraj-google-style |
def get_processid(config):
pidfile = config.get('daemon', 'pidfile', fallback=None)
if pidfile is None:
raise ValueError("Configuration doesn't have pidfile option!")
try:
with open(pidfile, 'r') as _file:
pid = _file.read().rstrip()
try:
pid = i... | Return process id of anycast-healthchecker.
Arguments:
config (obj): A configparser object with the configuration of
anycast-healthchecker.
Returns:
The process id found in the pid file
Raises:
ValueError in the following cases
- pidfile option is missing from the configuration
- pid is either -1 or 1
- stale pidfil... | juraj-google-style |
def _read_file(file_name):
with open(file_name) as config_file:
data = json.load(config_file)
return data | Read the file content and load it as JSON.
Arguments:
file_name (:py:class:`str`): The filename.
Returns:
:py:class:`dict`: The loaded JSON data.
Raises:
:py:class:`FileNotFoundError`: If the file is not found. | juraj-google-style |
def _get_first_approximation(self):
equalities = set(chain((implication.extract_equalities() for _, _, implication in self._iter_implications()))).union(self.ground_truth.extract_equalities())
var_assignments = {}
value_assignments = {}
for var in self.variables:
var_assignments[var] = {var}
... | Get all (variable, value) combinations to consider.
This gets the (variable, value) combinations that the solver needs to
consider based on the equalities that appear in the implications. E.g.,
with the following implication:
t1 = v1 => t1 = t2 | t3 = v2
the combinations to consider are
(t1, v1) because t1 = v1 appear... | github-repos |
def __getattr__(self, attr):
if not self._protocol:
raise usb_exceptions.HandleClosedError()
val = getattr(self._protocol, attr)
if callable(val):
def _retry_wrapper(*args, **kwargs):
result = _retry_usb_function(self._num_retries, val, *args, **kwargs)
_LOG.debu... | Fallthrough to underlying FastbootProtocol handler.
Args:
attr: Attribute to get.
Returns:
Either the attribute from the device or a retrying function-wrapper
if attr is a method on the device. | juraj-google-style |
def _get_tensors_for_gradient(x):
if not isinstance(x, composite_tensor.CompositeTensor):
return x
if not isinstance(x, CompositeTensorGradientProtocol):
raise ValueError(f'Type {type(x).__name__} is not supported as a gradient source or gradient target.')
composite_gradient = x.__composite_... | Returns the Tensors in `x` that should be differentiated.
Args:
x: A `Tensor` or `CompositeTensor`.
Returns:
A `Tensor` or a nested structure of `Tensor`. | github-repos |
def add_output(self, name, value):
self.template.add_output(Output(name, Value=value)) | Simple helper for adding outputs.
Args:
name (str): The name of the output to create.
value (str): The value to put in the output. | juraj-google-style |
def _parse_hparams(hparams):
prefixes = ["agent_", "optimizer_", "runner_", "replay_buffer_"]
ret = []
for prefix in prefixes:
ret_dict = {}
for key in hparams.values():
if prefix in key:
par_name = key[len(prefix):]
ret_dict[par_name] = hparams.get(key)
ret.append(ret_dict)
... | Split hparams, based on key prefixes.
Args:
hparams: hyperparameters
Returns:
Tuple of hparams for respectably: agent, optimizer, runner, replay_buffer. | juraj-google-style |
def release(self, subnets):
if (isinstance(subnets, str) or isinstance(subnets, IPNetwork)):
subnets = [subnets]
subnets_iter = ((str(subnet) if isinstance(subnet, IPNetwork) else subnet) for subnet in subnets)
try:
with self._create_lock():
for subnet in subnets_iter:
... | Free the lease of the given subnets
Args:
subnets (list of str or netaddr.IPAddress): dotted ipv4 subnet in
CIDR notation (for example ```192.168.200.0/24```) or IPAddress
object.
Raises:
LagoSubnetLeaseException: If subnet is a str and can't be parsed
LagoSubnetLeaseLockException:
If the lock to self.path can't be a... | codesearchnet |
def read_from_tfrecord(file_pattern: str, coder: Optional[coders.BytesCoder]=coders.BytesCoder(), compression_type: str='AUTO', validate: Optional[bool]=True):
return ReadFromTFRecord(file_pattern=file_pattern, compression_type=getattr(CompressionTypes, compression_type), validate=validate) | beam.Map(lambda s: bea... | Reads data from TFRecord.
Args:
file_pattern (str): A file glob pattern to read TFRecords from.
coder (coders.BytesCoder): Coder used to decode each record.
compression_type (CompressionTypes): Used to handle compressed input files.
Default value is CompressionTypes.AUTO, in which case the file_path's
extension will b... | github-repos |
def parse_genetic_models(models_info, case_id):
genetic_models = []
if models_info:
for family_info in models_info.split(','):
splitted_info = family_info.split(':')
if (splitted_info[0] == case_id):
genetic_models = splitted_info[1].split('|')
return genetic_... | Parse the genetic models entry of a vcf
Args:
models_info(str): The raw vcf information
case_id(str)
Returns:
genetic_models(list) | codesearchnet |
def get_average_voltage(self, min_voltage=None, max_voltage=None):
pairs_in_range = self._select_in_voltage_range(min_voltage,
max_voltage)
if len(pairs_in_range) == 0:
return 0
total_cap_in_range = sum([p.mAh for p in p... | Average voltage for path satisfying between a min and max voltage.
Args:
min_voltage (float): The minimum allowable voltage for a given
step.
max_voltage (float): The maximum allowable voltage allowable for a
given step.
Returns:
Average voltage in V across the insertion path (a subset of the
path can be chosen by th... | juraj-google-style |
def authorization_code_pkce(self, client_id, code_verifier, code, redirect_uri, grant_type='authorization_code'):
return self.post('https: | Authorization code pkce grant
This is the OAuth 2.0 grant that mobile apps utilize in order to access an API.
Use this endpoint to exchange an Authorization Code for a Token.
Args:
grant_type (str): Denotes the flow you're using. For authorization code pkce
use authorization_code
client_id (str): your application's ... | codesearchnet |
def get_policies_from_aws(client, scope='Local'):
done = False
marker = None
policies = []
while (not done):
if marker:
response = client.list_policies(Marker=marker, Scope=scope)
else:
response = client.list_policies(Scope=scope)
policies += response['Pol... | Returns a list of all the policies currently applied to an AWS Account. Returns a list containing all the
policies for the specified scope
Args:
client (:obj:`boto3.session.Session`): A boto3 Session object
scope (`str`): The policy scope to use. Default: Local
Returns:
:obj:`list` of `dict` | codesearchnet |
def events_from_file(filepath):
records = list(tf_record.tf_record_iterator(filepath))
result = []
for r in records:
event = event_pb2.Event()
event.ParseFromString(r)
result.append(event)
return result | Returns all events in a single event file.
Args:
filepath: Path to the event file.
Returns:
A list of all tf.compat.v1.Event protos in the event file. | github-repos |
def _TopKGrad(op: ops.Operation, grad, _):
in_shape = array_ops.shape(op.inputs[0])
ind_shape = array_ops.shape(op.outputs[1])
ind_lastdim = array_ops.gather(math_ops.cast(ind_shape, dtypes.int64), array_ops.size(ind_shape) - 1)
ind_2d = array_ops.reshape(op.outputs[1], array_ops_stack.stack([-1, ind_la... | Return the gradients for TopK.
Args:
op: The TopKOp for which we need to generate gradients.
grad: Tensor. The gradients passed to the TopKOp.
Returns:
A list of two tensors, the first being the gradient w.r.t to the input and
TopK, and the second being the gradient w.r.t. to the indices (all zero). | github-repos |
def fmt_addr_raw(addr, reverse=True):
addr = addr.replace(':', '')
raw_addr = [int(addr[i:i+2], 16) for i in range(0, len(addr), 2)]
if reverse:
raw_addr.reverse()
if sys.version_info[0] == 2:
return str(bytearray(raw_addr))
return bytearray(raw_addr) | Given a string containing a xx:xx:xx:xx:xx:xx address, return as a byte sequence.
Args:
addr (str): Bluetooth address in xx:xx:xx:xx:xx:xx format.
reverse (bool): True if the byte ordering should be reversed in the output.
Returns:
A bytearray containing the converted address. | juraj-google-style |
def read_dftbp(filename):
infile = open(filename, 'r')
lines = infile.readlines()
for ss in lines:
if ss.strip().startswith('
lines.remove(ss)
natoms = int(lines[0].split()[0])
symbols = lines[1].split()
if (lines[0].split()[1].lower() == 'f'):
is_scale... | Reads DFTB+ structure files in gen format.
Args:
filename: name of the gen-file to be read
Returns:
atoms: an object of the phonopy.Atoms class, representing the structure
found in filename | juraj-google-style |
def migrate_database(adapter):
all_variants = adapter.get_variants()
nr_variants = all_variants.count()
nr_updated = 0
with progressbar(all_variants, label="Updating variants", length=nr_variants) as bar:
for variant in bar:
if 'chrom' in variant:
... | Migrate an old loqusdb instance to 1.0
Args:
adapter
Returns:
nr_updated(int): Number of variants that where updated | juraj-google-style |
def str_internal(self, is_recursive=False):
printable_name = self.__class__.__name__
if hasattr(self, 'step_name'):
printable_name += ' %s' % self.name_context.logging_name()
if is_recursive:
return '<%s>' % printable_name
if self.spec is None:
printable_fields = []
e... | Internal helper for __str__ that supports recursion.
When recursing on receivers, keep the output short.
Args:
is_recursive: whether to omit some details, particularly receivers.
Returns:
Compact string representing this object. | github-repos |
def create_handler(Model, name=None, **kwds):
async def action_handler(service, action_type, payload, props, notify=True, **kwds):
if (action_type == get_crud_action('create', (name or Model))):
try:
message_props = {}
if ('correlation_id' in props):
... | This factory returns an action handler that creates a new instance of
the specified model when a create action is recieved, assuming the
action follows nautilus convetions.
Args:
Model (nautilus.BaseModel): The model to create when the action
received.
Returns:
function(action_type, payload): The action handler for t... | codesearchnet |
async def iter(self, url: Union[(str, methods)], data: Optional[MutableMapping]=None, headers: Optional[MutableMapping]=None, *, limit: int=200, iterkey: Optional[str]=None, itermode: Optional[str]=None, minimum_time: Optional[int]=None, as_json: Optional[bool]=None) -> AsyncIterator[dict]:
itervalue = None
if ... | Iterate over a slack API method supporting pagination
When using :class:`slack.methods` the request is made `as_json` if available
Args:
url: :class:`slack.methods` or url string
data: JSON encodable MutableMapping
headers:
limit: Maximum number of results to return per call.
iterkey: Key in response data to iterate ... | codesearchnet |
def get_object_metadata(self, request):
file_ = self.get_file(request.bucket, request.object)
return file_.get_metadata() | Retrieves an object's metadata.
Args:
request: (GetRequest) input message
Returns:
(Item) The response message. | github-repos |
def should_stop_early(self) -> bool:
if not self._trial.measurements:
return False
return self._should_stop_early_fn(self._trial) | Tells whether current trial should be stopped early.
In `pg.sample`, an optional `EarlyStoppingPolicy` can be provided, which is
useful for terminating trials which are progressive evaluated. Progressive
evaluation on examples can be achieved by calling `feedback.add_measurement`
multiple times at different steps. In-... | github-repos |
def _load_partition_graphs(self, client_partition_graphs, validate):
self._debug_graphs = {}
self._node_devices = {}
partition_graphs_and_device_names = []
for device_name in self._device_names:
partition_graph = None
if device_name in self._dump_graph_file_paths:
partition_g... | Load and process partition graphs.
Load the graphs; parse the input and control input structure; obtain the
device and op type of each node; remove the Copy and debug ops inserted
by the debugger. The gathered information can be used to validate the
tensor dumps.
Args:
client_partition_graphs: A repeated field of Gra... | github-repos |
def quantize(self, input_grid):
pixels = {}
for i in range(self.max_bin+1):
pixels[i] = []
data = (np.array(input_grid, dtype=int) - self.min_thresh) / self.data_increment
data[data < 0] = -1
data[data > self.max_bin] = self.max_bin
good_points = np.... | Quantize a grid into discrete steps based on input parameters.
Args:
input_grid: 2-d array of values
Returns:
Dictionary of value pointing to pixel locations, and quantized 2-d array of data | juraj-google-style |
def _VerifyValues(self, tensor_in_sizes, filter_in_sizes, stride, padding, expected, data_format, dtype, use_gpu, op_name):
if use_gpu and (not test.is_gpu_available(cuda_only=True)):
self.skipTest('GPU not available')
results = []
result = self._SetupValuesForDevice(tensor_in_sizes, filter_in_sizes... | Verifies the output values of the convolution function.
Args:
tensor_in_sizes: Input tensor dimensions [batch, input_x, input_y,
input_z, input_depth].
filter_in_sizes: Filter tensor dimensions [kernel_x, kernel_y, kernel_z,
input_depth, output_depth].
stride: [x_stride, y_stride, z_stride]
padding: Padding type.
expe... | github-repos |
def alias_inplace_update(x, i, v):
return _inplace_helper(x, i, v, gen_array_ops.inplace_update) | Applies an inplace update on input x at index i with value v. Aliases x.
If i is None, x and v must be the same shape. Computes
x = v;
If i is a scalar, x has a rank 1 higher than v's. Computes
x[i, :] = v;
Otherwise, x and v must have the same rank. Computes
x[i, :] = v;
Args:
x: A Tensor.
i: None, a scalar or a vec... | github-repos |
def parse_location(location):
def split_dms(text, hemisphere):
'Split degrees, minutes and seconds string.\n\n Args:\n text (str): Text to split\n\n Returns::\n float: Decimal degrees\n '
out = []
sect = []
for i in text:
if i.i... | Parse latitude and longitude from string location.
Args:
location (str): String to parse
Returns:
tuple of float: Latitude and longitude of location | codesearchnet |
def _validate_testbed_name(name):
if not name:
raise MoblyConfigError("Test bed names can't be empty.")
name = str(name)
for char in name:
if char not in utils.valid_filename_chars:
raise MoblyConfigError('Char "%s" is not allowed in test bed names.' % char) | Validates the name of a test bed.
Since test bed names are used as part of the test run id, it needs to meet
certain requirements.
Args:
name: The test bed's name specified in config file.
Raises:
MoblyConfigError: The name does not meet any criteria. | github-repos |
def write(self, session, directory, name, replaceParamFile=None, **kwargs):
name_split = name.split('.')
name = name_split[0]
extension = ''
if (len(name_split) >= 2):
extension = name_split[(- 1)]
try:
name = self._namePreprocessor(name)
except:
'DO NOTHING'
if (exte... | Write from database back to file.
Args:
session (:mod:`sqlalchemy.orm.session.Session`): SQLAlchemy session object bound to PostGIS enabled database.
directory (str): Directory where the file will be written.
name (str): The name of the file that will be created (including the file extension is optional).
replaceParam... | codesearchnet |
def rotate(self, image, angle, resample=None, expand=0, center=None, translate=None, fillcolor=None):
resample = resample if resample is not None else PIL.Image.NEAREST
self._ensure_format_supported(image)
if not isinstance(image, PIL.Image.Image):
image = self.to_pil_image(image)
return image.r... | Returns a rotated copy of `image`. This method returns a copy of `image`, rotated the given number of degrees
counter clockwise around its centre.
Args:
image (`PIL.Image.Image` or `np.ndarray` or `torch.Tensor`):
The image to rotate. If `np.ndarray` or `torch.Tensor`, will be converted to `PIL.Image.Image` before
rot... | github-repos |
def true_num_genes(model, custom_spont_id=None):
true_num = 0
for gene in model.genes:
if not is_spontaneous(gene, custom_id=custom_spont_id):
true_num += 1
return true_num | Return the number of genes in a model ignoring spontaneously labeled genes.
Args:
model (Model):
custom_spont_id (str): Optional custom spontaneous ID if it does not match the regular expression ``[Ss](_|)0001``
Returns:
int: Number of genes excluding spontaneous genes | juraj-google-style |
def create_analyzer_ui(debug_dump, tensor_filters=None, ui_type='readline', on_ui_exit=None, config=None):
if config is None:
config = cli_config.CLIConfig()
analyzer = DebugAnalyzer(debug_dump, config=config)
if tensor_filters:
for tensor_filter_name in tensor_filters:
analyzer.... | Create an instance of ReadlineUI based on a DebugDumpDir object.
Args:
debug_dump: (debug_data.DebugDumpDir) The debug dump to use.
tensor_filters: (dict) A dict mapping tensor filter name (str) to tensor
filter (Callable).
ui_type: (str) requested UI type, only "readline" is supported.
on_ui_exit: (`Callable`) the ca... | github-repos |
def gremove(pattern):
for item in glob.glob(pattern):
if not remove(item):
return False
return True | Remove all file found by glob.glob(pattern).
Args:
pattern (str): Pattern of files to remove
Returns:
bool: True if the operation is successful, False otherwise. | juraj-google-style |
def monitoring_helper(service_addr, duration_ms, monitoring_level, num_queries):
if monitoring_level <= 0 or monitoring_level > 2:
sys.exit('Please choose a monitoring level between 1 and 2.')
for query in range(0, num_queries):
res = profiler_client.monitor(service_addr, duration_ms, monitoring... | Helper function to print monitoring results.
Helper function to print monitoring results for num_queries times.
Args:
service_addr: Address of the TPU profiler service.
duration_ms: Duration of one monitoring sample in milliseconds.
monitoring_level: An integer between 1 and 2. Level 2 is more verbose than
level 1 an... | github-repos |
def attach_template(self, _template, _key, **unbound_var_values):
if (_key in unbound_var_values):
raise ValueError(('%s specified twice.' % _key))
unbound_var_values[_key] = self
return _template.as_layer().construct(**unbound_var_values) | Attaches the template to this such that _key=this layer.
Note: names were chosen to avoid conflicts with any likely unbound_var keys.
Args:
_template: The template to construct.
_key: The key that this layer should replace.
**unbound_var_values: The values for the unbound_vars.
Returns:
A new layer with operation app... | codesearchnet |
def needs_keras_history(tensors, ignore_call_context=False):
input_tensors = nest.flatten(tensors)
if call_context().in_call and (not ignore_call_context):
return False
if all((getattr(tensor, '_keras_history', None) is not None for tensor in input_tensors)):
return False
return uses_ker... | Check if any Tensors need to be wrapped in TensorFlowOpLayers.
This will never return True inside a sublayer, because sublayers
do not need to create Keras History. Otherwise, this returns True
if one or more of `tensors` originates from a `keras.Input` and
does not have `_keras_history` set.
Args:
tensors: An arbitr... | github-repos |
def recipe_sdf_to_bigquery(config, auth_write, partner_id, file_types, filter_type, filter_ids, dataset, version, table_suffix, time_partitioned_table, create_single_day_table):
dataset(config, {'auth': auth_write, 'dataset': dataset})
sdf(config, {'auth': 'user', 'version': version, 'partner_id': partner_id, '... | Download SDF reports into a BigQuery table.
Args:
auth_write (authentication) - Credentials used for writing data.
partner_id (integer) - The sdf file types.
file_types (string_list) - The sdf file types.
filter_type (choice) - The filter type for the filter ids.
filter_ids (integer_list) - Comma separated list of fil... | github-repos |
def reflection(normal, origin=(0, 0, 0)):
n = (np.array(normal, dtype=float) / np.linalg.norm(normal))
(u, v, w) = n
translation = np.eye(4)
translation[(0:3, 3)] = (- np.array(origin))
xx = (1 - (2 * (u ** 2)))
yy = (1 - (2 * (v ** 2)))
zz = (1 - (2 * (w ** 2)))
xy = (((- 2) * u) * v)
... | Returns reflection symmetry operation.
Args:
normal (3x1 array): Vector of the normal to the plane of
reflection.
origin (3x1 array): A point in which the mirror plane passes
through.
Returns:
SymmOp for the reflection about the plane | codesearchnet |
def area_frac_vs_chempot_plot(self, ref_delu, chempot_range, delu_dict=None, delu_default=0, increments=10, no_clean=False, no_doped=False):
delu_dict = (delu_dict if delu_dict else {})
chempot_range = sorted(chempot_range)
all_chempots = np.linspace(min(chempot_range), max(chempot_range), increments)
h... | 1D plot. Plots the change in the area contribution
of each facet as a function of chemical potential.
Args:
ref_delu (sympy Symbol): The free variable chempot with the format:
Symbol("delu_el") where el is the name of the element.
chempot_range (list): Min/max range of chemical potential to plot along
delu_dict (Dict)... | codesearchnet |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.