content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def extract_tags(signature_def, graph):
"""."""
output = dict()
for key in signature_def:
output[key] = dict()
output[key]['inputs'] = extract_tensors(signature_def[key].inputs, graph)
output[key]['outputs'] = extract_tensors(signature_def[key].outputs, graph)
return output | 5,285,900 |
def test_patrons_cannot_search_other_loans(client, json_headers, users,
testdata):
"""Test that patrons cannot search for loans of other patrons."""
res = _search_loans(client, json_headers, user=users['patron1'],
state='PENDING', # test extra ... | 5,285,901 |
def otsu(gray_image):
"""
h:图像的宽度
w:图像的高度
(h*w 得到图像的像素数量)
threshold_t :灰度阈值(我们要求的值,大于这个值的像素我们将它的灰度设置为255,小于的设置为0)
n0:小于阈值的像素数量,前景
n1:大于等于阈值的像素数量,背景
n0 + n1 == h * w
w0:前景像素数量占总像素数量的比例
w0 = n0 / (h * w)
w1:背景像素数量占总像素数量的比例
w1 = n1... | 5,285,902 |
def batch_list_all(api, requests: list, next_function: Callable, log_text: str):
"""Similar to list_all but using batch API."""
pending_requests = requests
page = 1
while pending_requests:
next_requests = pending_requests
pending_requests = []
if page == 1:
logging.info(log_text)
else:
... | 5,285,903 |
def test_ste_sign_backward_multiloss():
"""
Test STESign backward computes gradient correctly.
x = [x1, x2, ..., xn]
l = sum(sign(x))
dl/dxi = 1 iff |xi| <= 1
"""
x = torch.tensor([42, -42, 0, -1, 1, -0.2, 0.2], requires_grad=True)
xb = binarize(x)
loss = xb.sum()
loss.backward... | 5,285,904 |
def initialize(config_path='config.ini'):
"""
Initializes the user settings and folders.
Parameters
----------
config_path : str
the path of the config.ini file relative to this file
"""
config_path = os.path.abspath(
os.path.join(
... | 5,285,905 |
def initParser():
"""initialize parser arguments"""
global parser
parser = argparse.ArgumentParser()
parser.add_argument("-d", help="SQL injection dork", type=str)
parser.add_argument("-e", help="search engine [Google only for now]", type=str)
parser.add_argument("-p", help="number of websites ... | 5,285,906 |
def get_modules(path):
"""
Get a dictionary containing metadata about all the Python modules found in
the referenced path.
:param str path: The directory in which to find modules.
:return: A dictionary containing metadata about the found modules.
"""
result = {}
if not path:
ret... | 5,285,907 |
def load_report(report):
"""Splits the report from a string into a list of list of "bits" """
return [list(c for c in code) for code in report.split("\n") if len(code)] | 5,285,908 |
def test_divisor_count1():
"""
Testing for a small integer
"""
assert divisor_count(10) == 4 | 5,285,909 |
def standardized_euclidean_distance_0(x_list, data_list):
"""
:param
x_list:
[(x0, y0), (x1, y1), (x2, y2), ..., (xn-2, yn-2), (xn-1, yn-1)]
data_list:
[x_list_0 (same data structure as x_list), x_list_1, x_list_2, ..., x_list_n-2, x_list_n-1]
:return:
sed_lis... | 5,285,910 |
def downgrade():
"""Downgrade database."""
# ### commands auto generated by Alembic - please adjust! ###
op.drop_table('enrollment')
# ### end Alembic commands ### | 5,285,911 |
def update():
"""
Init
"""
global APIKEY
global TIMEOUT
global font
global TEMP_FILE
global screen
global lcd
global icons
global cur_location
global fio
global cur_time
lcd.clear()
"""
Main Code
"""
try:
with timeout.timeout(seco... | 5,285,912 |
def get_airport_details(airport_name: str = Query(..., min_length=1,
description="Name of the airport you are trying to " +
"find, can be its full name or just a phrase",
example="Heathrow")):
"""
Find all the airp... | 5,285,913 |
def attr_visitor_name(attr_name: str) -> str:
"""
Returns the visitor_method name for `attr_name`, e.g.::
>>> attr_visitor_name('class')
'attr_class'
"""
# assert re.match(r'\w+$', node_name)
return 'attr_' + attr_name | 5,285,914 |
def permutation_test_cv(X, y, n_permutations=1000,
C=None, Cs=np.logspace(-7, 1, 9),
seed=0, n_jobs=1, verbose=1):
"""Cross-validated permutation test shuffling the target
Parameters
-----------
X : ndarray, shape (n_samples, n_features)
Data.
... | 5,285,915 |
def compile_akg_kernel_parallel(json_infos, process, waitime):
"""
compile kernel use multi processes
Parameters:
json_infos: list. list contain kernel info(task id and json str)
process: int. processes num
waittime: int. max time the function blocked
Returns:
True for ... | 5,285,916 |
def mk_string(strings: List[str], separator: str) -> str:
"""
Creates a string from a list of strings, with a separator in between elements.
:param strings: the list of strings.
:param separator: the separator.
:return: the string of elements separated by the separator.
"""
result = ''
s... | 5,285,917 |
def relay_group_wa(message):
""" Send a message received in a bound group to the correspondending contact through Whatsapp.
Args:
message: Received Telegram message.
"""
cid = message.chat.id
uid = message.from_user.id
if uid != SETTINGS['owner']:
tgbot.reply_to(message, 'you a... | 5,285,918 |
def radtherm_set_float(what, value, trace):
"""Set the value of a piece of floating point data from the thermostat"""
try:
if what != "t_heat":
wg_error_print("radtherm_set_float", " Invalid 'what' argument " + what)
return RADTHERM_FLOAT_ERROR
pman = PoolManager()
... | 5,285,919 |
def func_delete_venv(args):
"""
Delete a virtual environment.
This will remove both containers and images that match the
name "dockenv-<envname>"
:param args: cli arguments
"""
dockenv_name = f"dockenv-{args.envname}"
# Check env exists:
if not local_image_exists(dockenv_name):
... | 5,285,920 |
def subsets(x, L):
"""Return all subsets of length 1, 2, ..., min(l, len(x)) from x"""
return chain.from_iterable([x[s:s+l+1] for s in range(len(x)-l)] for l in range(min(len(x),L))) | 5,285,921 |
async def test_event_gps_exit_unknown_zone(hass, context):
"""Test the event for unknown zone."""
# Just treat as location update
message = build_message({"desc": "unknown"}, REGION_GPS_LEAVE_MESSAGE)
await send_message(hass, EVENT_TOPIC, message)
assert_location_latitude(hass, REGION_GPS_LEAVE_MESS... | 5,285,922 |
def pic_in_db(hash_val):
"""
Args:
hash_val(bytes obj): Hash value of uploaded pic
Returns:
Boolean true if pic in db, o.w. false
"""
if imagePost.query.filter_by(hash_val=hash_val).count() > 1:
return True
return False | 5,285,923 |
def get_dev_risk(weight, error):
"""
:param weight: shape [N, 1], the importance weight for N source samples in the validation set
:param error: shape [N, 1], the error value for each source sample in the validation set
(typically 0 for correct classification and 1 for wrong classification)
"""
... | 5,285,924 |
def _parse_args(template_dir, all_services, sets, pick, dst_project, env_files):
"""Parses args common to 'process' and 'deploy'."""
if not template_dir:
path = appdirs_path / "templates"
template_dir = path if path.exists() else pathlib.Path(pathlib.os.getcwd()) / "templates"
template_dir ... | 5,285,925 |
def unflatten_list(flat_dict, separator='_'):
"""
Unflattens a dictionary, first assuming no lists exist and then tries to
identify lists and replaces them
This is probably not very efficient and has not been tested extensively
Feel free to add test cases or rewrite the logic
Issues that stand o... | 5,285,926 |
def notes(filters=None):
"""Retrieve all Note objects.
Args:
filters (list, optional): A list of additional filters to apply to
the query.
"""
filter_list = FilterSet(filters)
filter_list.add(Filter('type', '=', 'note'))
return query(filter_list) | 5,285,927 |
def test_get_variants(gemini_path):
"""Test to get some variants from the gemini adapter"""
adapter = GeminiPlugin(db=gemini_path)
variants = []
for variant in adapter.variants('643594', count=5):
variants.append(variant)
assert len(variants) == 5 | 5,285,928 |
def Normalize(df):
"""
This function takes a pandas dataframe and normalize it
Arguments
----------
- df: pandas dataframe
Return
----------
- df: pandas dataframe
The initial dataframe normalized
"""
df = (df - df.min())/(df.max() - df.min())
return df | 5,285,929 |
def export_paired_end_reads_fastq(parser):
""" For paired-end sequence reads, write paired-end reads for pre-selected
reads into a separate FASTQ file
"""
outdir = parser.sample.work_directory
read_ids = {}
for read_id in sorted(parser.reads.keys()):
read_ids[read_id] = read_id
fastq... | 5,285,930 |
def remove_shelf_set(name):
"""
Removes given ShelfSet
:param name: str
"""
if not shelf_set_exists(shelf_set_name=name):
return
shelf_set = get_shelf_set(shelf_set_name=name)
if shelf_set:
shelf_set.destroy() | 5,285,931 |
def emp_img_exists(filepath):
""" # For use if hosting static content in a remote location
try:
urllib.request.urlopen(STATIC_URL+filepath)
return filepath
except:
index = filepath.rfind('/')
new_filepath = filepath[:index] + '/default.jpg'
return new_filepath
"... | 5,285,932 |
def _filter_featured_downloads(lst):
"""Filter out the list keeping only Featured files."""
ret = []
for item in lst:
if 'Featured' in item['labels']:
ret.append(item)
return ret | 5,285,933 |
def shifted_conv2d(input,
out_channels,
kernel_size,
spatial_shift,
strides=(1, 1),
channels_last=True,
conv_fn=conv2d,
name=None,
scope=None,
**kwar... | 5,285,934 |
def alphabet_index(text: str) -> str:
"""Replaces each letter with its appropriate position in the alphabet."""
return " ".join([str(ord(x.lower())-96)
for x in text
if ord(x.lower())-96 >= 1 and ord(x.lower())-96 < 27]) | 5,285,935 |
def set_authorize_resource(authorized, res_id, name, res_type, organization, project):
"""
param authorized: Boolean value set to authorize or unauthorize resource
param id: Id of the resource to authorize
param name: Name of the resource to authorize
param type: Type of the resource to authorize
... | 5,285,936 |
def test_ringbuffer_append_increases_length():
"""pushing to a RingBuffer increases its length by 1"""
rblength = 16
rb = RingBuffer(rblength)
# fill buffer with random number of elements, but at most length-1
n = random.randint(1,rblength-1)
for i in range(n):
rb.append(n)
rb.appen... | 5,285,937 |
def AddJetID(proc, jetName="", jetSrc="", jetTableName="", jetSequenceName=""):
"""
Setup modules to calculate PF jet ID
"""
isPUPPIJet = True if "Puppi" in jetName else False
looseJetId = "looseJetId{}".format(jetName)
setattr(proc, looseJetId, proc.looseJetId.clone(
src = jetSrc,
filterPa... | 5,285,938 |
def gradz_gaussian_sparse_kernel(out, z, a_indices, a_counts, no_count_indicator):
"""
:param z: D x K x My x Mx x 2
:param z_hat: D x K x My x Mx x 2
:param a_indices: D x K x counts
:param a_counts: D x K x counts
:param beta: float
:param frame_dimensions: (2,... | 5,285,939 |
def hds_builder(
project_id,
table_id,
dataset_id,
landing_zone_dataset,
landing_zone_table_name_override,
column_mapping,
column_casting,
new_column_udfs,
surrogate_keys,
ingestion_type,
hds_table_config,
partition_expiration,
location,
dag,
cluster_fields=No... | 5,285,940 |
def raiseValueError(message, source, convertPath=True):
"""
Raises value error with message.
Args:
message (str): error message
source (str): file name/path where error happened
"""
if convertPath:
source = getModuleNameAndSuffix(source)
line = inspect.cu... | 5,285,941 |
def init(username, password):
"""Initialize the saltshaker_plus."""
initialize(username, password) | 5,285,942 |
def _should_use_gp(search_space: SearchSpace, num_trials: Optional[int] = None) -> bool:
"""We should use only Sobol and not GPEI if:
1. there are less continuous parameters in the search space than the sum of
options for the choice parameters,
2. the number of total iterations in the optimization is kn... | 5,285,943 |
def validate_region_one_ldap_config(region_config):
"""Validate ldap on region one by a ldap search"""
ldapserver_uri = region_config.get('SHARED_SERVICES', 'LDAP_SERVICE_URL')
cmd = ["ldapsearch", "-xH", ldapserver_uri,
"-b", "dc=cgcs,dc=local", "(objectclass=*)"]
try:
with open(os.... | 5,285,944 |
def k_means_extraction(arr, height, width, palette_size):
"""
Extracts a color palette using KMeans.
:param arr: pixel array (height, width, 3)
:param height: height
:param width: width
:param palette_size: number of colors
:return: a palette of colors sorted by frequency
"""
arr = n... | 5,285,945 |
def test_xyz2inlmp_if():
"""Test the write of an xyz frame to lammps input data file."""
fi = TEST_DATA_PATH / "test_ref.xyz"
fo = TEST_DATA_PATH / "exma_in.test"
exma.io.xyz2inlmp(
fi,
fo,
{
"box": np.array([4.5, 1.0, 6.0], dtype=np.float32),
"type": {"H"... | 5,285,946 |
def poll_lol_api():
"""
This function polls for 2 different events
- Game ending
- Game starting
"""
_poll_game_end()
_poll_game_start() | 5,285,947 |
def check(rule, target, creds, *args, **kwargs):
"""A shortcut for policy.Enforcer.enforce()
Checks authorization of a rule against the target and credentials
and returns True or False.
"""
enforcer = get_enforcer()
return enforcer.enforce(rule, target, creds, *args, **kwargs) | 5,285,948 |
def organize_content_by_type(archive_content):
"""Organize JSON content by resourceType.
"""
content_by_type = { }
for item in archive_content:
if PACKAGE_REGEX.match(item['name']):
# parse JSON to get resourceType
parsed_json = json.loads(item['data'])
if 'r... | 5,285,949 |
def mark_white_cell_at_boundary(mask, meta):
"""Rule 1.3:
For each black runj, j = 1,...,k
(1) If the lengths of all black run i covering cell rj.s with i != j
are all one, cell rj.s - 1 will be left empty
(2) If the lengths of all black run i covering rj.e with i != j
are all one, cell... | 5,285,950 |
def logout():
"""
Logout current user from session
"""
# remove user from session
session.pop("user_id", None)
flash("Logged Out", "success")
return redirect(url_for("index")) | 5,285,951 |
def mozilla(cve_or_mfsa, output):
"""Extract CVEs assigned by Mozilla using the CVE or MFSA number"""
cves_all = json.loads(requests.get(API_ENDPOINT).content)
cves_selected = []
for selector in cve_or_mfsa:
cves = [
cve
for cve in cves_all
if cve["CVE_data_m... | 5,285,952 |
def find_ammr_path(folder=None):
"""Return the root AMMR path if possible .
The function will walk up a directory tree looking
for a ammr_verion.any file to parse.
"""
folder = folder or os.getcwd()
version_files = ("AMMR.version.any", "AMMR.version.xml")
for basedir, _, files in walk_up(fo... | 5,285,953 |
def print_snd(expr):
"""
Arguments:
- `expr`:
"""
return color.cyan + "snd" + color.reset + "({0!s})".format(expr.expr) | 5,285,954 |
def metadef_namespace_get_by_id(context, namespace_id):
"""Get a namespace object"""
try:
namespace = next(namespace for namespace in DATA['metadef_namespaces']
if namespace['id'] == namespace_id)
except StopIteration:
msg = (_("Metadata definition namespace not foun... | 5,285,955 |
def detect_edge(image_array, sigma=1.0,
low_threshold=None, high_threshold=None):
"""
Detect the edges in an image using the Canny filter
Parameters
----------
image_array
Returns
-------
array with edges identified
Side Effects
------------
None
"""
... | 5,285,956 |
def remove_duplicate(id_list, class_target_id, return_type, check):
"""
Check duplication in class member and return a new user id list that is not duplicate in class.
This function mainly use in add_member_to_class function.
:param id_list: A user id list as a string.
:type id_list: str
:para... | 5,285,957 |
def wait_selector(
gen: PQGen[RV], fileno: int, timeout: Optional[float] = None
) -> RV:
"""
Wait for a generator using the best strategy available.
:param gen: a generator performing database operations and yielding
`Ready` values when it would block.
:param fileno: the file descriptor to ... | 5,285,958 |
def test_slash_dn(executor):
"""List all schemas."""
results = executor('\dn')
title = None
rows = [('public', 'postgres'),
('schema1', 'postgres'),
('schema2', 'postgres')]
headers = ['Name', 'Owner']
status = 'SELECT 3'
expected = [title, rows, headers, status]
... | 5,285,959 |
def field_has_type(needle: BaseType, field: BaseType) -> bool: # pylint: disable=too-many-return-statements, too-many-branches
"""
Return True if field haystack contains a field of type needle.
:param needle: A schematics field class to search for.
:param haystack: An instance of a schematics field wi... | 5,285,960 |
def test_successful() -> None:
"""Create the user.""" | 5,285,961 |
def get_max_batch_size(model, tile_size, device, classes):
"""get max possible batch_size based on GPU memory
This function calculates the maximum possible batch
size based on the available GPU memory.
Args:
model (pytorch model): model to train
tile_size (int): size of the input image... | 5,285,962 |
def abspath(path):
"""convert relative path to absolute path"""
try:
path=pathexists(path)
curpath = os.getcwd()
changedir(path)
path = os.getcwd() + '/'
changedir(curpath)
except:
raise SaltIOError('Could not determine absolute path to '+path)
return pat... | 5,285,963 |
def authorize(func):
"""
User needs to be logged in
"""
@wraps(func)
def wrapper(*args, **kwargs):
if app.current_user is not None:
return func(*args, **kwargs)
app.flash('Login to view this page')
redirect('/login?back=' + request.path)
return wrapper | 5,285,964 |
def abort_job(id):
"""Abort a job by API Job ID.
Args:
id (str): Job ID to be aborted
Returns: None
"""
# Attempt is unused in aborting because only one attempt can be running at
# a time.
proj_id, job_id, task_id, _ = job_ids.api_to_dsub(id, _provider_type())
provider = provid... | 5,285,965 |
def handle_no_range(node):
"""Returns stl_node with range set to [0,0] if not previously set"""
if node.range_start==None or node.range_end==None:
node.range_start = 0
node.range_end = 0
return node | 5,285,966 |
def PageRankResponseStartValuesVector(builder, numElems):
"""This method is deprecated. Please switch to Start."""
return StartValuesVector(builder, numElems) | 5,285,967 |
def normdiff(p, q) -> float:
"""
Alias to the 2-norm of a difference between two vectors
Parameters
----------
p : iterable
q : iterable
Returns
-------
float
Norm discrepancy.
"""
return np.linalg.norm(p - q) | 5,285,968 |
def test_random_waveform_dataset_whitening(
random_hanford_background,
random_livingston_background,
sample_rate,
data_length,
device,
):
"""
Test the `.whiten` method to make sure that it
produces results roughly consistent with gwpy's
whitening functionality using the bac... | 5,285,969 |
def cp_img_to(src, dst, rank, prefix):
"""
- src: image path or tuple (for vidreid)
- dst: target directory
- rank: int, denoting ranked position, starting from 1
- prefix: string
"""
if isinstance(src, tuple) or isinstance(src, list):
dst = osp.join(dst, prefix + '_top' + str(rank).zf... | 5,285,970 |
def social_connect_profile(backend, user, response, *args, **kwargs) -> None:
"""
This is used by python social auth to connect and/or pre-create all user
profiles (AssopyUser, AttendeeProfile, etc.
"""
AssopyUser.objects.get_or_create(user=user)
get_or_create_attendee_profile_for_new_user(user... | 5,285,971 |
def build_frequency_case(mt):
"""
Bin frequencies. Output refers to bin floor
:param MatrixTable mt: Input MatrixTable with .freq annotation
:return: Binned frequencies
:rtype: FloatExpression
"""
return (hl.case()
.when(mt.freq[0].AF >= 0.2, 0.2)
.when(mt.freq[0].AF... | 5,285,972 |
def transform_architecture(model, pretrained_model_file=None):
"""Transform architecture."""
if not hasattr(model, "_arch_params") or not model._arch_params or \
PipeStepConfig.pipe_step.get("type") == "TrainPipeStep":
return model
model._apply_names()
logging.info("Start to transfor... | 5,285,973 |
def merge_kwargs(kwargs, defaults):
"""Helper function to merge ``kwargs`` into ``defaults``.
Args:
kwargs: Keyword arguments.
defaults: Default keyword arguments.
Returns:
Merged keyword arguments (``kwargs`` overrides ``defaults``).
"""
if defaults is not None:
kw... | 5,285,974 |
def f84a():
"""Return a unit-distance embedding of the F84A graph - not degenerate
despite its looks. The graph is notable in having the simple PSL(2,8)
as its automorphism group."""
t0 = findroot(lambda *t: f84a_vertices(*t)[1], (-0.46, -1.44, 0.25, 0.75))
return all_unit_distances(f84a_vertices(*t... | 5,285,975 |
def text2speech(text):
"""Different voices used for text to speech"""
if os_info == 'Darwin':
os.system('say ' + text)
elif os_info == 'Linux':
os.system('espeak -v en ' + text) # must install python espeak module for ubuntu
else:
import win32com.client
speech = win32c... | 5,285,976 |
def plot_metrics(couplings, cost_func, cost_func_name, epsilons, log = False, points=False, scale=1.0, label_font_size=18, tick_font_size=12):
"""
Plots cost_func evaluated as a function of epsilon
"""
zero_offset = epsilons[0]/2
all_ys = []
if "lineageOT" in couplings.keys():
ys = np.ar... | 5,285,977 |
def translateUpdate(q, base=None, initNs=None):
"""
Returns a list of SPARQL Update Algebra expressions
"""
res = []
prologue = None
if not q.request:
return res
for p, u in zip(q.prologue, q.request):
prologue = translatePrologue(p, base, initNs, prologue)
# absolu... | 5,285,978 |
def format_decimal(value):
"""Format value to 2 decimal places"""
formatter = "{0:.2f}"
return float(formatter.format(value)) | 5,285,979 |
def substitute(s, mapping):
"""Substitute values from *mapping* into *s*.
*mapping* can be a :class:`dict` or any type that supports the
``get()`` method of the mapping protocol. Replacement values are
copied into the result without further interpretation. Raises
:exc:`~.SubstitutionSyntaxError` if... | 5,285,980 |
def test_aggregate_empty(test_df, variable, append, caplog):
"""Check for performing an "empty" aggregation"""
caplog.set_level(logging.INFO, logger="pyam.aggregation")
if append:
# with `append=True`, the instance is unchanged
obs = test_df.copy()
obs.aggregate(variable, append=Tru... | 5,285,981 |
def rename_pretrained(name: str):
""" Matches the name of a variable saved in the pre-trained MobileNet
networks with the name of the corresponding variable in this network.
https://github.com/tensorflow/models/blob/master/research/slim/nets/mobilenet_v1.md
Parameters
----------
name: the orig... | 5,285,982 |
def do_ldap_search(conn, query):
""" Search Yale LDAP for a particular netid. On the command
line this would be something like the following:
ldapsearch \
-H ldaps://ad.its.yale.edu:3269 \
-D cn=s_klj39,OU=Non-Netids,OU=Users-OU,dc=yu,dc=yale,dc=edu \
-w $LDAP_PAS... | 5,285,983 |
def BrokerFeaturesAddEventHistory(builder, eventHistory):
"""This method is deprecated. Please switch to AddEventHistory."""
return AddEventHistory(builder, eventHistory) | 5,285,984 |
def run_viz(port=None, line=None) -> None:
"""
Line magic function to start kedro viz. It calls a kedro viz in a process and display it in
the Jupyter notebook environment.
Args:
port: TCP port that viz will listen to. Defaults to 4141.
line: line required by line magic interface.
... | 5,285,985 |
def gcode_gen_2( out_name, x, y, z, printer_offset, speed ):
"""
gcode_gen_2
Newest version of the gcode generator function
Features:
10/12/2018 - Converted printer offsets as an input to the function
"""
# Data-specific Variables and Edits ======================================= #
arr... | 5,285,986 |
def _forwarder(func):
"""Returns a function that applies func to all given images."""
def fwd(*images):
_apply_images(func, images)
fwd.__doc__ = "Forward to Canvas." + func.__doc__
return fwd | 5,285,987 |
def main():
"""Instantiates a FileWatcher based on environment variables, or command
line args."""
# Required inputs
bucket, accessKey, privateKey, pzApiKey, gatewayHost = None, None, None, None, None
# Check env vars
bucket = os.environ.get('s3.bucket.name')
accessKey = os.environ.get('s3.... | 5,285,988 |
def clip_norm(g, c, n):
"""Clip the gradient `g` if the L2 norm `n` exceeds `c`.
# Arguments
g: Tensor, the gradient tensor
c: float >= 0. Gradients will be clipped
when their L2 norm exceeds this value.
n: Tensor, actual norm of `g`.
# Returns
Tensor, the gradi... | 5,285,989 |
def update_action(body):
"""
Updates an action
:param body: Updated action instance
:type body: list | bytes
:rtype: None
"""
if connexion.request.is_json:
body = [Action.from_dict(d) for d in connexion.request.get_json()]
return 'do some magic!' | 5,285,990 |
def anagram(word1, word2):
"""Determines if two words are anagram of each other
NOTE: This solutoin does not work for all test cases.
"""
# if the strings are not equal length they can't be anagram
if len(word1) != len(word2):
return False
s1 = 0
s2 = 0
# add up the ascii valu... | 5,285,991 |
def build_table_def(table_name, keys, additional_attributes=None, global_secondary_indices=None):
"""
Creates a minimal dynamodb definition suitable for use with localstack.
Args:
table_name: The full name of the test table
keys: The key definitions to use - a list of 4-tuples (<name>, <key... | 5,285,992 |
async def delete_config(key: str, type: str, response: Response, id: str = ""):
"""Delete a config from the database
Attributes:
key (str): key to be deleted
type (str): global/package/node
id (str): package or node id as per type
response (Response): Starlette response object
... | 5,285,993 |
def resume(tags, pattern, all):
"""
This command resumes a map (reverses the pause command).
The running components of a resumed map will resume execution on their
claimed resources.
"""
tags = _get_tags(all, pattern, tags)
for tag in tags:
with make_spinner(f"Resuming map {tag} ...... | 5,285,994 |
def test_http_h1_mini_stress_test_with_client_side_queueing(http_test_server_fixture):
"""
Run a max rps test with the h1 pool against our test server, using a small client-side
queue."""
counters = mini_stress_test(http_test_server_fixture, [
http_test_server_fixture.getTestServerRootUri(), "--rps", "999... | 5,285,995 |
def scan_grib(url, common_vars, storage_options, inline_threashold=100, skip=0, filter={}):
"""
Generate references for a GRIB2 file
Parameters
----------
url: str
File location
common_vars: list[str]
Names of variables that are common to multiple measurable (i.e., coordinates)... | 5,285,996 |
def reauth():
"""
Reauthenticates a user
"""
if not login_fresh():
form = ReauthForm(request.form)
if form.validate_on_submit():
confirm_login()
flash(("Reauthenticated"), "success")
return redirect(request.args.get("next") or
... | 5,285,997 |
def execution_has_failures(playbook_results):
"""Return value 2 means failure in ansible-playbook"""
if type(playbook_results) != list:
playbook_results = [playbook_results]
return 2 in playbook_results | 5,285,998 |
def overlay(xss):
"""
Interleave two playlists by overlaying unique elements.
Elements from YS are only picked if they are unique.
Non-unique YS elements are ignored, and an element
from XS is picked instead. Thus, the unique elements of YS
are "overlaid" onto XS. The general case is a left fold... | 5,285,999 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.