content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
from re import T
def sms_outbound_gateway():
""" SMS Outbound Gateway selection for the messaging framework """
# CRUD Strings
s3.crud_strings["msg_sms_outbound_gateway"] = Storage(
label_create = T("Create SMS Outbound Gateway"),
title_display = T("SMS Outbound Gateway Details"),
... | bb0796dabbfe14b6a7e2a1d25960beae3d065717 | 3,644,600 |
def _insert_volume(_migration, volume_number, volume_obj):
"""Find or create the corresponding volume, and insert the attribute."""
volumes = _migration["volumes"]
volume_obj = deepcopy(volume_obj)
volume_obj["volume"] = volume_number
volumes.append(volume_obj)
return volume_obj | 3a89024aa5b2bc9fc2bb16094a1a95ca6fd43f63 | 3,644,601 |
def create_vnet(credentials, subscription_id, **kwargs):
"""
Create a Batch account
:param credentials: msrestazure.azure_active_directory.AdalAuthentication
:param subscription_id: str
:param **resource_group: str
:param **virtual_network_name: str
:param **subnet_na... | 3a0a670c89f4a2c427a205039bf12b3af42e6b0a | 3,644,602 |
def to_inorder_iterative(root: dict, allow_none_value: bool = False) -> list:
"""
Convert a binary tree node to depth-first in-order list (iteratively).
"""
node = root
node_list = []
stack = []
while node or len(stack) > 0:
if node:
stack.append(node) # push a node into... | 90cf850f5e0fa91432bd2b9cde642e13fc0d8723 | 3,644,603 |
import logging
import time
def init_log(logfile=None, file_size=5, debug=False):
"""
Initializes logging to file and console.
:param logfile: the name of the file
:param file_size: the max size of the file in megabytes, before wrapping occurs
:param debug: Boolean to enable verbose logging
:r... | 3c87e7dc14368e9432b45d348f6f79e43f2974d8 | 3,644,604 |
def symmetric_mean_absolute_percentage_error(a, b):
"""
Calculates symmetric Mean Absolute Percentage Error (sMAPE).
Args:
a (): ctual values.
b (): Predicted values.
Returns: sMAPE float %.
"""
a = np.reshape(a, (-1,))
b = np.reshape(b, (-1,))
return 100.0 * np.mean(... | 90557e6f2a702aeea27b2a881b6ef3e35c0b7f46 | 3,644,605 |
def exec_quiet(handle, *args, **kwargs):
"""
Like exe.execute but doesnt print the exception.
"""
try:
val = handle(*args, **kwargs)
except Exception:
pass
else:
return val | d0e922672c8a2d302bc2bfcb30bec91d32988945 | 3,644,606 |
def make_modified_function_def(original_type, name, original, target):
"""Make the modified function definition.
:return: the definition for the modified function
"""
arguments = format_method_arguments(name, original)
argument_names = set(target.parameters)
unavailable_arguments = [p for p in ... | 35263518c9edf9a710f66c6432ef9fb1a85df3fa | 3,644,607 |
import pathlib
import multiprocessing
from functools import reduce
def fetch_tiles(server, tile_def_generator, output=pathlib.Path('.'), force=False):
"""
fetch and store tiles
@param server
server definition object
@param tile_def_generator
generator of ti... | 6e42da71bff389b36485dc34222fa4a1b5d5abf3 | 3,644,608 |
def _UTMLetterDesignator(lat):
"""
This routine determines the correct UTM letter designator for the
given latitude returns 'Z' if latitude is outside the UTM limits of
84N to 80S.
Written by Chuck Gantz- [email protected]
"""
if 84 >= lat >= 72: return 'X'
elif 72 > lat >= 64: ... | 3c5b9a54a9824d6755937aeaece8fa53483045fc | 3,644,609 |
import re
def is_ignored(file: str) -> bool:
"""
Check if the given file is ignored
:param file: the file
:return: if the file is ignored or not
"""
for ignored in config.get('input').get('ignored'):
ignored_regex = re.compile(ignored)
if re.match(ignored_regex, file):
... | 22b038b17435b2a2a9c79d24136de8f6322d8093 | 3,644,610 |
from typing import Iterable
def get_powerups_wf(original_wf):
"""
get user powerups setting.
"""
idx_list = get_fws_and_tasks(original_wf)
for idx_fw, idx_t in idx_list:
f0 = original_wf.fws[idx_fw].tasks[idx_t]
if not isinstance(f0, Iterable) or isinstance(f0, str) : continue
... | 85f0a6b7cc6cde1a177ff45365607140a89324e6 | 3,644,611 |
def enumerate_phone_column_index_from_row(row):
"""Enumerates the phone column from a given row. Uses Regexs
Parameters
----------
row : list
list of cell values from row
Returns
-------
int
phone column index enumerated from row
"""
# initial phone_column_index va... | bbc5f1abceb51d5a7385d235c7dae9ed07ffcc1f | 3,644,612 |
def fetch_words(url):
"""
Fetch a list of words from URL
Args:
url: The URL of a UTF-8 text doxument
Returns:
A list of strings containing the words from
the document.
"""
story = urlopen(url)
story_words = []
for line in story:
line_words = line.decode(... | 939bc5409b4ae824a3671e555d9ebdf8454c6358 | 3,644,613 |
def pipe(func):
"""command pipe"""
@wraps(func)
def wrapper(*args, **kwargs):
if PIPE_LOCK.locked():
LOGGER.debug("process locked")
return None
window = sublime.active_window()
view = window.active_view()
status_key = "pythontools"
with PIPE... | 31aaed3c5214453b1bca7b1db6c552e8b99792ea | 3,644,614 |
from typing import Dict
def dot_keys_to_nested(data: Dict) -> Dict:
"""old['aaaa.bbbb'] -> d['aaaa']['bbbb']
Args:
data (Dict): [description]
Returns:
Dict: [description]
"""
rules = defaultdict(lambda: dict())
for key, val in data.items():
if '.' in key:
... | 06bbf2b154c1cfb840d556c082bcb0b9282c44be | 3,644,615 |
def vec2adjmat(source, target, weight=None, symmetric=True):
"""Convert source and target into adjacency matrix.
Parameters
----------
source : list
The source node.
target : list
The target node.
weight : list of int
The Weights between the source-target values
symm... | fa5e8370557b8e1f37cbe2957ec16c614c4ad70d | 3,644,616 |
def is_valid(number):
"""Check if the number provided is a valid PAN. This checks the
length and formatting."""
try:
return bool(validate(number))
except ValidationError:
return False | 2a2c99c29072e402cc046fa1eef8eefd2c4ee0af | 3,644,617 |
def remove_spaces(string: str):
"""Removes all whitespaces from the given string"""
if string is None:
return ""
return "".join(l for l in str(string) if l not in WHITESPACES) | 5dc928124c0a080f8e283450dc9754b4b301f047 | 3,644,618 |
def decode_event_to_internal(abi, log_event):
""" Enforce the binary for internal usage. """
# Note: All addresses inside the event_data must be decoded.
decoded_event = decode_event(abi, log_event)
if not decoded_event:
raise UnknownEventType()
# copy the attribute dict because that data... | 1005507ea129be88462b75685d5b8a993fd6f0cd | 3,644,619 |
def run_ode_solver(system, slope_func, **options):
"""Computes a numerical solution to a differential equation.
`system` must contain `init` with initial conditions,
`t_0` with the start time, and `t_end` with the end time.
It can contain any other parameters required by the slope function.
`opti... | ae2994aeaca5590d61921a25877807a1611841cd | 3,644,620 |
def case_configuration(group_id, det_obj, edges):
"""
Get all the needed information of the detectors for the chosen edges, as well as only those trajectories that map
onto one of the edges.
Parameters
----------
group_id
det_obj
edges
Returns
-------
"""
ds = det_obj.d... | 8e6910943e705fa952992ef5e2551140e578e8ef | 3,644,621 |
def _remarks(item: str) -> str:
"""Returns the remarks. Reserved for later parsing"""
return item | d515837e52ee88edeb5bdb5e8f2d37ed28789362 | 3,644,622 |
def unauthorized():
# TODO: security
"""Redirect unauthorised users to Login page."""
flash('Please log in to access this page.', 'danger')
return redirect(url_for('auth.login', next=request.path)) | 130bbfaf141fe68142e74afbe3bf95cd6aad556e | 3,644,623 |
from datetime import datetime
def _date_to_datetime(value):
"""Convert a date to a datetime for datastore storage.
Args:
value: A datetime.date object.
Returns:
A datetime object with time set to 0:00.
"""
assert isinstance(value, datetime.date)
return datetime.datetime(value.year, value.month, ... | 872efa93fd256f38c2c82f979d0942114c6254b9 | 3,644,624 |
import os
def DirType(d):
""" given a string path to a directory, D, verify it can be used.
"""
d = os.path.abspath(d)
if not os.path.exists(d):
raise ArgumentTypeError('DirType:%s does not exist' % d)
if not os.path.isdir(d):
raise ArgumentTypeError('DirType:%s is not a directory' % d)
if os.acce... | 08865b9bc0fb928f38fff4159f10d8e2123953f2 | 3,644,625 |
def get_posted_float(key):
"""
Retrieve a named float value from a POSTed form
:param key: Value key
:return: Value or None if not specified
"""
value = request.form[key]
return float(value) if value else None | 1d88d4b0fc09f8e0d323bb8cc0aba83ac5fa9d9f | 3,644,626 |
def te_ds(mass, norm_vel, x_ratios, source_distance, te_einstein, gamma, sigma_total, \
xval, val):
"""Returns the probability of a sampled value T_E by weighting from the
T_E probability distribution of the data """
if min(xval) < te_einstein <= max(xval):
omegac = gamma*norm_vel*np.sqrt(x_rati... | 4322a1266610f047e2efef023d8f0cccf80e697a | 3,644,627 |
def roulette(fitness_values, return_size, elite=0):
"""
Perform a roulette wheel selection
Return return_size item indices
"""
sorted_indices = np.argsort(fitness_values)
c_sorted = np.sort(fitness_values).cumsum()
c_sorted /= np.max(c_sorted)
sampled = [sorted_indices[np.sum(np.random... | 6ac06a28a6ce22ef8828597985332913aa0987e2 | 3,644,628 |
import os
def working_dir(val, **kwargs): # pylint: disable=unused-argument
"""
Must be an absolute path
"""
try:
is_abs = os.path.isabs(val)
except AttributeError:
is_abs = False
if not is_abs:
raise SaltInvocationError("'{0}' is not an absolute path".format(val))
... | f31df7e7a7950936c8247c11766208ba188042b6 | 3,644,629 |
import logging
import os
import glob
def apply_latency_predictor_cli(args):
"""apply latency predictor to predict model latency according to the command line interface arguments
"""
if not args.predictor:
logging.keyinfo('You must specify a predictor. Use "nn-meter --list-predictors" to see all su... | 82c0fabdbe553b6321677a4fbffe426c4f296ac8 | 3,644,630 |
def create_sample_tree():
"""
1
/ \
2 3
/ \
4 5
"""
root = TreeNode(1)
root.left = TreeNode(2)
root.right = TreeNode(3)
root.right.left = TreeNode(4)
root.right.right = TreeNode(5)
return root | 7e5c252cf66df3fed236e0891185b545e0c9c861 | 3,644,631 |
import copy
def sp_normalize(adj_def, device='cpu'):
"""
:param adj: scipy.sparse.coo_matrix
:param device: default as cpu
:return: normalized_adj:
"""
adj_ = sp.coo_matrix(adj_def)
adj_ = adj_ + sp.coo_matrix(sp.eye(adj_def.shape[0]), dtype=np.float32)
rowsum = np.array(adj_.sum(axis=... | a4ef96d439c27047def02234c3308e45dc934067 | 3,644,632 |
def isTileEvent(x:int, y:int):
"""
checks if a given tile is an event or not quicker than generateTileAt
x: the x value of the target tile
y: the y value of the target tile
"""
perlRand = getPerlin(x, y, s=2.501)
if Math.floor(perlRand * 3400) == 421 and deriveTile(x, y)=='H':
return True
elif Math.floor(pe... | 34efeef5e05830faef886f69fb95287817ced1c6 | 3,644,633 |
def to_onehot_sym(ind, dim):
"""Return a matrix with one hot encoding of each element in ind."""
assert ind.ndim == 1
return theano.tensor.extra_ops.to_one_hot(ind, dim) | db4871b3108aef0cbf2b2a63497dd30c22e2805e | 3,644,634 |
def generate_potential_grasp(object_cloud):
"""
The object_cloud needs to be in table coordinates.
"""
# https://www.cs.princeton.edu/~funk/tog02.pdf picking points in triangle
nrmls = object_cloud.normals.copy()
# if object_cloud.points[:,2].max()<0.11:
# nrmls[nrmls[:,2]>0] *= -1
#... | 169552dfea38c9f4a15a67f23ca40cda2e824769 | 3,644,635 |
import torch
import time
def ACP_O(model, Xtrain, Ytrain, Xtest, labels = [0,1], out_file = None, seed = 42, damp = 10**-3, batches = 1):
"""Runs ACP (ordinary) CP-IF to make a prediction for all points in Xtest
"""
N = len(Xtrain)
# Train model on D.
model_D = model
model_D = model_D.to... | 6205e62c153fac5fe58529882d232bba4a83ce8a | 3,644,636 |
import math
def func (x):
"""
sinc (x)
"""
if x == 0:
return 1.0
return math.sin (x) / x | c91242e360547107f7767e442f40f4bf3f2b53e8 | 3,644,637 |
def grad_norm(model=None, parameters=None):
"""Compute parameter gradient norm."""
assert parameters is not None or model is not None
total_norm = 0
if parameters is None:
parameters = []
if model is not None:
parameters.extend(model.parameters())
parameters = [p for p in parameters if p.grad is no... | ff471715a72f0d2afbafa60d19eb802a748a2419 | 3,644,638 |
import copy
def db_entry_trim_empty_fields(entry):
""" Remove empty fields from an internal-format entry dict """
entry_trim = copy.deepcopy(entry) # Make a copy to modify as needed
for field in [ 'url', 'title', 'extended' ]:
if field in entry:
if (entry[field] is None) or \
... | d5b31c823f4e8091872f64445ab603bcbf6a2bef | 3,644,639 |
def loadconfig(PATH):
"""Load Latte's repo configuration from
the PATH. A dictionary of the config data is returned, otherwise None."""
try:
f = open(PATH, "r")
except FileNotFoundError:
return None
else:
confobj = SWConfig(f.read())
if confobj is None:
re... | cd912b1e9d7fddbecf72165b42d1eb8b47687838 | 3,644,640 |
import logging
def _call_token_server(method, request):
"""Sends an RPC to tokenserver.minter.TokenMinter service.
Args:
method: name of the method to call.
request: dict with request fields.
Returns:
Dict with response fields.
Raises:
auth.AuthorizationError on HTTP 403 reply.
Internal... | a81a6b0f8a42517bb2b7e6fafc762f2620c18dbb | 3,644,641 |
import requests
def get_keywords(text):
"""Get keywords that relate to this article (from NLP service)
Args:
text (sting): text to extract keywords from
Returns:
[list]: list of extracted keywords
"""
extracted_keywords = []
request = {'text': text}
nlp_output = requests.po... | 56caaa6af416c425eb54ef9e85460cd5921e9d74 | 3,644,642 |
def weather_config() -> str:
"""The function config_handle() is called
and the contents that are returned are
stored in the variable 'config file'.
This is then appropriately parsed so the
weather api key is accessed. This is then
returned at the end of the function."""
#Accessing... | 6eb35a876eb73160d39417a213195b39e68ea568 | 3,644,643 |
import warnings
def interpret_bit_flags(bit_flags, flip_bits=None, flag_name_map=None):
"""
Converts input bit flags to a single integer value (bit mask) or `None`.
When input is a list of flags (either a Python list of integer flags or a
string of comma-, ``'|'``-, or ``'+'``-separated list of flags... | ea657c9f4abfe8503d7ea120ea7c5ff039f82634 | 3,644,644 |
import torch
def reparam(mu, std, do_sample=True, cuda=True):
"""Reparametrization for Normal distribution.
"""
if do_sample:
eps = torch.FloatTensor(std.size()).normal_()
if cuda:
eps = eps.cuda()
eps = Variable(eps)
return mu + eps * std
else:
retu... | dc959b0f1f3972ae612d44d90694480270b42a3e | 3,644,645 |
import random
def simu_grid_graph(width, height, rand_weight=False):
"""Generate a grid graph.
To generate a grid graph. Each node has 4-neighbors. Please see more
details in https://en.wikipedia.org/wiki/Lattice_graph. For example,
we can generate 5x3(width x height) grid graph
0---1-... | 139be873014c96f05b3fb391ea1352fab68b8357 | 3,644,646 |
import os
def solrctl():
"""
solrctl path
"""
for dirname in os.environ.get('PATH', '').split(os.path.pathsep):
path = os.path.join(dirname, 'solrctl')
if os.path.exists(path):
return path
return None | dd34e187d2ae27514c2290bda69cfd1f538c76ea | 3,644,647 |
def calculate_sensitivity_to_weighting(jac, weights, moments_cov, params_cov):
"""calculate the sensitivity to weighting.
The sensitivity measure is calculated for each parameter wrt each moment.
It answers the following question: How would the precision change if the weight of
the kth moment is i... | ed41e5e369446144e10bb7b7edfc59d2c3f8621e | 3,644,648 |
def subword(w):
"""
Function used in the Key Expansion routine that takes a four-byte input word
and applies an S-box to each of the four bytes to produce an output word.
"""
w = w.reshape(4, 8)
return SBOX[w[0]] + SBOX[w[1]] + SBOX[w[2]] + SBOX[w[3]] | 36dfd4c82484fda342629c94fc66454723e371f6 | 3,644,649 |
import multiprocessing
from typing import Counter
def deaScranDESeq2(counts, conds, comparisons, alpha, scran_clusters=False):
"""Makes a call to DESeq2 with SCRAN to
perform D.E.A. in the given
counts matrix with the given conditions and comparisons.
Returns a list of DESeq2 results for each comparis... | de6c6a1640819c72ef72275f3205cf24d7a8ce0a | 3,644,650 |
def cylindrical_to_cartesian(a: ArrayLike) -> NDArray:
"""
Transform given cylindrical coordinates array :math:`\\rho\\phi z`
(radial distance, azimuth and height) to cartesian coordinates array
:math:`xyz`.
Parameters
----------
a
Cylindrical coordinates array :math:`\\rho\\phi z` ... | 27b8d95c2c09b8b78069a4ad0c4cf351de93db13 | 3,644,651 |
def eigenarray_to_array( array ):
"""Convert Eigen::ArrayXd to numpy array"""
return N.frombuffer( array.data(), dtype='d', count=array.size() ) | 7caa9ab71ca86b6a8afa45879d0f29c8122973fe | 3,644,652 |
from typing import List
def _ncon_to_adjmat(labels: List[List[int]]):
""" Generate an adjacency matrix from the network connections. """
# process inputs
N = len(labels)
ranks = [len(labels[i]) for i in range(N)]
flat_labels = np.hstack([labels[i] for i in range(N)])
tensor_counter = np.hstack(
[i ... | 8e7171321f547084bdaff4cefa1bd9e00b453cc9 | 3,644,653 |
import requests
import json
import sys
def search(name="", address="", description=""):
"""
Returns a list of Plan Objects
"""
plans = []
name = name.replace(' ','+')
address = address.replace(' ','+')
description = description.replace(' ','+')
Address_Search_URL = f"http://webgeo.ki... | 9360ebc1a26340f16c86d2a81333d6ed8cd9d75e | 3,644,654 |
def _is_install_requirement(requirement):
""" return True iff setup should install requirement
:param requirement: (str) line of requirements.txt file
:return: (bool)
"""
return not (requirement.startswith('-e') or 'git+' in requirement) | 339f6a8a573f33157a46193216e90d62475d2dea | 3,644,655 |
def confusion_matrices_runs_thresholds(
y, scores, thresholds, n_obs=None, fill=0.0, obs_axis=0
):
"""Compute confusion matrices over runs and thresholds.
`conf_mats_runs_thresh` is an alias for this function.
Parameters
----------
y : np.ndarray[bool, int32, int64, float32, float64]
t... | 7a7b640a724a2ffba266403ac72940da5a28f57b | 3,644,656 |
def new_project(request):
"""
Function that enables one to upload projects
"""
profile = Profile.objects.all()
for profile in profile:
if request.method == 'POST':
form = ProjectForm(request.POST, request.FILES)
if form.is_valid():
pro = form.save(comm... | da4adb286e6b972b9ac37019cd4ff0ed4c82dd3f | 3,644,657 |
def move_to_next_pixel(fdr, row, col):
""" Given fdr (flow direction array), row (current row index), col (current col index).
return the next downstream neighbor as row, col pair
See How Flow Direction works
http://desktop.arcgis.com/en/arcmap/latest/tools/spatial-analyst-toolbox/how-flow-direction-w... | d134bb35ed4962945c86c0ac2c6af1aff5acd06b | 3,644,658 |
import re
import string
def clean_text(post):
"""
Function to filter basic greetings and clean the input text.
:param post: raw post
:return: clean_post or None if the string is empty after cleaning
"""
post = str(post)
""" filtering basic greetings """
for template in TEMPLATES:
... | 1896cc991e0c061bad16e0a2ae9768c06f2b0029 | 3,644,659 |
def turnIsLegal(speed, unitVelocity, velocity2):
"""
Assumes all velocities have equal magnitude and only need their relative angle checked.
:param velocity1:
:param velocity2:
:return:
"""
cosAngle = np.dot(unitVelocity, velocity2) / speed
return cosAngle > MAX_TURN_ANGLE_COS | e598630d47ca77ed953199852a08ce376cdc0e0f | 3,644,660 |
def convert_selection_vars_to_common_effects(G: ADMG) -> nx.DiGraph:
"""Convert all undirected edges to unobserved common effects.
Parameters
----------
G : ADMG
A causal graph with undirected edges.
Returns
-------
G_copy : ADMG
A causal graph that is a fully specified DAG... | 00f4530e1262bac92b31b8855efdd453de035c57 | 3,644,661 |
def plot_confusion_matrix(estimator, X, y_true, *, labels=None,
sample_weight=None, normalize=None,
display_labels=None, include_values=True,
xticks_rotation='horizontal',
values_format=None,
... | bcfd587d28c75f3b56580631d1dc8e1aa60a0f35 | 3,644,662 |
def mean_binary_proto_to_np_array(caffe, mean_binproto):
"""
:param caffe: caffe instances from import_caffe() method
:param mean_binproto: full path to the mode's image-mean .binaryproto created from train.lmdb.
:return:
"""
# I don't have my image mean in .npy file but in binaryproto. I'm con... | e79488051f26c9e3781c1fbeeb9f42683e8e2df0 | 3,644,663 |
def delete_channel(u, p, cid):
"""
Delete an existing service hook.
"""
c = Channel.query.filter_by(
id=cid,
project_id=p.id
).first()
if not c:
# Project or channel doesn't exist (404 Not Found)
return abort(404)
if c.project.owner.id != g.user.id or c.proj... | 31f6b7640bb222a6b7c7ae62af24e6da170fbaeb | 3,644,664 |
def joint_img_freq_loss(output_domain, loss, loss_lambda):
"""Specifies a function which computes the appropriate loss function.
Loss function here is computed on both Fourier and image space data.
Args:
output_domain(str): Network output domain ('FREQ' or 'IMAGE')
loss(str): Loss type ('L... | 9f9a95314c109d6d331c494c77cae8a3578e659d | 3,644,665 |
import requests
import json
def verify_auth_token(untrusted_message):
"""
Verifies a Auth Token. Returns a
django.contrib.auth.models.User instance if successful or False.
"""
# decrypt the message
untrusted = URLSafeTimedSerializer(settings.SSO_SECRET).loads(
untrusted_message, max_ag... | f470d96fea2561e5d754f5e39dad5cf816bb4e69 | 3,644,666 |
def get_requirements():
"""
Obtenir la liste de toutes les dépences
:return: la liste de toutes les dépences
"""
requirements = []
with open(REQUIREMENTS_TXT, encoding="utf-8") as frequirements:
for requirement_line in frequirements.readlines():
requirement_line = requirement... | 68d73653818b9ede5f7be00cc79842d9ca4fa59a | 3,644,667 |
import math as m
from math import sin, cos, atan, asin, floor
def equ2gal(ra, dec):
"""Converts Equatorial J2000d coordinates to the Galactic frame.
Note: it is better to use AstroPy's SkyCoord API for this.
Parameters
----------
ra, dec : float, float [degrees]
Input J2000 coordinates (... | ebed665e798a00b649367bc389747f046659d9af | 3,644,668 |
import unittest
from pyoptsparse import OPT
def require_pyoptsparse(optimizer=None):
"""
Decorate test to raise a skiptest if a required pyoptsparse optimizer cannot be imported.
Parameters
----------
optimizer : String
Pyoptsparse optimizer string. Default is None, which just checks for ... | 2df011c38f9a44047a5a259be983ba23bf9ebe92 | 3,644,669 |
from typing import Union
def addition(a:Union[int, float], b:Union[int, float]) -> Union[int, float]:
"""
A simple addition function. Add `a` to `b`.
"""
calc = a + b
return calc | b9adaf3bea178e23bd4c02bdda3f286b6ca8f3ab | 3,644,670 |
def print_version():
"""
Print the module version information
:return: returns 1 for for exit code purposes
:rtype: int
"""
print("""
%s version %s - released %s"
""" % (__docname__, __version__, __release__))
return 1 | 28f5ce2a922fe66de5dce2ed2bfab6241835c759 | 3,644,671 |
def splitpath(path):
""" Split a path """
drive, path = '', _os.path.normpath(path)
try:
splitunc = _os.path.splitunc
except AttributeError:
pass
else:
drive, path = splitunc(path)
if not drive:
drive, path = _os.path.splitdrive(path)
elems = []
try:
... | 830c7aa2e825bb57d819bc014afe7cb0ba31aaf5 | 3,644,672 |
def vmf1_zenith_wet_delay(dset):
"""Calculates zenith wet delay based on gridded zenith wet delays from VMF1
Uses gridded zenith wet delays from VMF1, which are rescaled from the gridded height to actual station height by
using Equation(5) described in Kouba :cite:`kouba2007`.
Args:
dset (Data... | defa135bac27c1540caceee4ca12f6741c5e6475 | 3,644,673 |
from functools import reduce
import random
import hashlib
def get_hash(dictionary):
"""Takes a dictionary as input and provides a unique hash value based on the
values in the dictionary. All the values in the dictionary after
converstion to string are concatenated and then the HEX hash is generated
:param dic... | 2e69c397611510151996d152c4fc0b5573d62fdc | 3,644,674 |
def convert_to_tensor(value, dtype=None, device = None):
"""
Converts the given value to a Tensor.
Parameters
----------
value : object
An object whose type has a registered Tensor conversion function.
dtype : optional
Optional element type for the returned tensor. If missing, t... | fbae4561f3a38b8f72146f584ce07faf5096cdc1 | 3,644,675 |
def aggregate_extrema(features, Th, percentage = True) :
"""
Summary:
Function that tries to remove false minima aggregating closeby extrema
Arguments:
features - pandas series containing the extrema to be aggregated.
The series is of the form: Max, Min, Max, Max, M... | 6eeed204de4c39f8b66353595cbc04800bb1b176 | 3,644,676 |
from pathlib import Path
def load_embedded_frame_data(session_path, camera: str, raw=False):
"""
:param session_path:
:param camera: The specific camera to load, one of ('left', 'right', 'body')
:param raw: If True the raw data are returned without preprocessing (thresholding, etc.)
:return: The f... | 865d5151680b901fb0941cf487bd01836748f2c4 | 3,644,677 |
def reconstruct(edata, mwm=80.4, cme=1000):
"""
Reconstructs the momentum of the neutrino and anti-neutrino, given the
momentum of the muons and bottom quarks.
INPUT:
edata: A list containing the x, y, and z momentum in GeV of the charged leptons
and bottom quarks, i... | 31ecb3f8982f8026a4d0052778b53f1e76912252 | 3,644,678 |
import contextlib
import sqlite3
def run_sql_command(query: str, database_file_path:str, unique_items=False) -> list:
"""
Returns the output of an SQL query performed on a specified SQLite database
Parameters:
query (str): An SQL query
database_file_path (str): absolute path o... | 705584db31fd270d4127e7d1b371a24a8a9dd22e | 3,644,679 |
def zeta_nbi_nvi_ode(t, y, nb, C, nv, nb0, nbi_ss, f, g, c0, alpha, B, pv, e, R, eta, mu, nbi_norm = True):
"""
Solving the regular P0 equation using the ODE solver (changing s > 0)
t : time to solve at, in minutes
y : y[0] = nvi, y[1] = nbi, y[2] = zeta(t)
"""
F = f*g*c0
r = R*g*... | 5c30846bbb1bbf4c9a698dcec3627edece63e4bc | 3,644,680 |
from astroquery.irsa import Irsa
def get_irsa_catalog(ra=165.86, dec=34.829694, radius=3, catalog='allwise_p3as_psd', wise=False, twomass=False):
"""Query for objects in the `AllWISE <http://wise2.ipac.caltech.edu/docs/release/allwise/>`_ source catalog
Parameters
----------
ra, dec : float
... | 13308f9ae6ffd61c70588eb7ee7980cc1cd71578 | 3,644,681 |
def _create_supporting_representation(model,
support_root = None,
support_uuid = None,
root = None,
title = None,
content_type = '... | bd2ad356e185af0c68d8505c4e07bdc87c049c14 | 3,644,682 |
import platform
def os_kernel():
"""
Get the operating system's kernel version
"""
ker = "Unknown"
if LINUX:
ker = platform.release()
elif WIN32 or MACOS:
ker = platform.version()
return ker | 1f528ae3710485726736fd9596efbc84b8bc76fd | 3,644,683 |
def call(args, env=None, cwd=None, outputHandler=None, outputEncoding=None, timeout=None, displayName=None, options=None):
"""
Call a process with the specified args, logging stderr and stdout to the specified
output handler which will throw an exception if the exit code or output
of the process indicates an erro... | e3140a7206ba63c6a19aedf5fd8eaa35cf11ffbc | 3,644,684 |
def prettyFloat(value, roundValue=False):
"""Return prettified string for a float value.
TODO
----
add flag for round to
add test
"""
## test-cases:
# if change things her, look that they are still good (mod-dc-2d)
if roundValue and abs(round(value)-value) < 1e-4 and abs(val... | 00b75da77570749978607ae517013dd6cb4186b4 | 3,644,685 |
def make_nested_pairs_from_seq(args):
"""
Given a list of arguments, creates a list in Scheme representation
(nested Pairs).
"""
cdr = Nil()
for arg in reversed(args):
cdr = Pair(arg, cdr)
return cdr | 74aeeb54b648ccf231b6619800d1727fc7504cd4 | 3,644,686 |
import ast
def get_aug_assign_symbols(code):
"""Given an AST or code string return the symbols that are augmented
assign.
Parameters
----------
code: A code string or the result of an ast.parse.
"""
if isinstance(code, str):
tree = ast.parse(code)
else:
tree = code
... | d7ee8834b5d1aa0ac93369815206c95919907ae1 | 3,644,687 |
from typing import Dict
from typing import Any
def stack_dict(state: Dict[Any, tf.Tensor]) -> tf.Tensor:
"""Stack a dict of tensors along its last axis."""
return tf.stack(sorted_values(state), axis=-1) | d50b774b708715934f2c9998d7a477839c73593a | 3,644,688 |
def compact_float(n, max_decimals=None):
"""Reduce a float to a more compact value.
Args:
n: Floating point number.
max_decimals: Maximum decimals to keep; defaults to None.
Returns:
An integer if `n` is essentially an integer, or a string
representation of `n` red... | 827e49e05aaca31d497f84c2a8c8dd52cfad73d9 | 3,644,689 |
def resample_2d(X, resolution):
"""Resample input data for efficient plotting.
Parameters:
-----------
X : array_like
Input data for clustering.
resolution : int
Number of "pixels" for 2d histogram downscaling.
Default 'auto' downscales to 200x200 for >5000
samples, ... | 88cf98f82e0bf538df6e8a00b49f07eab75da1fe | 3,644,690 |
def is_mocked(metric_resource: MetricResource) -> bool:
"""
Is this metrics a mocked metric or a real metric?
"""
return metric_resource.spec.mock is not None | d76f6a0a04026245605176799346092d4a8eb994 | 3,644,691 |
def negative_embedding_subtraction(
embedding: np.ndarray,
negative_embeddings: np.ndarray,
faiss_index: faiss.IndexFlatIP,
num_iter: int = 3,
k: int = 10,
beta: float = 0.35,
) -> np.ndarray:
"""
Post-process function to obtain more discriminative image descriptor.
Parameters
-... | da20719f1b0b46fcfa4b7b11deb81aa2731abc5f | 3,644,692 |
def op_conv_map(operator):
"""Convert operator or return same operator"""
return OPERATOR_CONVERSION.get(operator, operator) | 91f6fea341b473e4965495af23cf957fef39234a | 3,644,693 |
def getGMapKey():
"""Return value for <gmapKey/> configuration parameter."""
return sciflo.utils.ScifloConfigParser().getParameter('gmapKey') | 0d4e36e39672b698b07d4be4d2cb0b6eff8a26c9 | 3,644,694 |
def get_stored_credentials():
"""
Gets the credentials, username and password, that have been stored in
~/.shrew/config.ini and the secure keychain respectively without bothering
to prompt the user if either credential cannot be found.
:returns: username and password
:rtype:... | 9d8e1379dde5ee43a64d7d4a4b94244890e6c4ab | 3,644,695 |
def _ro_hmac(msg, h=None):
"""Implements random oracle H as HMAC-SHA256 with the all-zero key.
Input is message string and output is a 32-byte sequence containing the HMAC
value.
Args:
msg: Input message string.
h: An optional instance of HMAC to use. If None a new zeroed-out instance
will be u... | 97aa326be593096a6441546a5d449b052ccc603a | 3,644,696 |
def get_unique_slug(model_instance, sluggable_field_name, slug_field_name):
"""
Takes a model instance, sluggable field name (such as 'title') of that
model as string, slug field name (such as 'slug') of the model as string;
returns a unique slug as string.
"""
slug = slugify(getattr(model_insta... | bbf1aa6108670f45b8a5b1a112f9b42a07344763 | 3,644,697 |
def get_precomputed_features(source_dataset, experts):
"""Get precomputed features from a set of experts and a dataset.
Arguments:
source_dataset: the source dataset as an instance of Base Dataset.
experts: a list of experts to use precomputed features from
Returns: A list of dicts, where ... | d89a932490f3c3ef4aca31301586ce628a720233 | 3,644,698 |
def _local_distribution():
"""
获取地区分布
"""
data = {}
all_city = Position.objects.filter(status=1).values_list("district__province__name", flat=True)
value_count = pd.value_counts(list(all_city)).to_frame()
df_value_counts = pd.DataFrame(value_count).reset_index()
df_value_counts.columns =... | 2f81365c66680c1b04805869e45118601ed769df | 3,644,699 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.