content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def has_dynamic_registration_perm(user_level, obj, ctnr, action):
"""
Permissions for static registrations
"""
return True | a0127cf9ffe45784317a327a3e9dfaec7649263d | 661,286 |
def string_validation(state_input, county_input):
"""
WHAT IT DOES: Processes the State and County variables to ensure that they are strings
PARAMETERS: Two strings representing a state and county in the US
RETURNS: A boolean
"""
has_errors = False
try:
int_variable = int(state_in... | 5f5f6a3f79f8fcb6987758095717ab57e915a9f4 | 661,287 |
def is_above_or_to_left(ref_control, other_ctrl):
"""Return true if the other_ctrl is above or to the left of ref_control"""
text_r = other_ctrl.rectangle()
ctrl_r = ref_control.rectangle()
# skip controls where text win is to the right of ctrl
if text_r.left >= ctrl_r.right:
return False
... | dcc02e8e9424825704682f6b12683bb9de2fe132 | 661,288 |
def relative_humidity(e_a, e_s):
"""
Calculate the relative humidity of air (Allen et al., 1998).
Relative humidity expresses the degree of saturation of the air as a ratio
of the actual (e_a) to the saturation (e_s) vapour pressure at the same
temperature.
Parameters
----------
e_a : ... | a1a37d8273628e2ec51da7c08acf1f37c08b338f | 661,289 |
def is_number(x):
"""Check is a number."""
if isinstance(x, (int, float)):
return True
else:
return False | 6429c9337227dc7515c910a3d1c2c97004e26397 | 661,290 |
def add_data_args(parser):
"""Train/valid/test data arguments."""
group = parser.add_argument_group('data', 'data configurations')
group.add_argument('--model-parallel-size', type=int, default=1,
help='size of the model parallel.')
group.add_argument('--shuffle', action='store_t... | 1140d088daefdc59fa9aada435e229f41f606594 | 661,291 |
import contextlib, cProfile
import sys
def profile(filename):
"""Returns a context manager to perform profiling while the program runs.
This is triggered by setting the PEX_PROFILE_FILENAME env var to the destination file,
at which point this will be invoked automatically at pex startup.
"""
@co... | b964fef81e1846f0cf47bc2af286c353babc08ab | 661,292 |
def get_paths(rlz):
"""
:param rlz:
a logic tree realization (composite or simple)
:returns:
a dict {'source_model_tree_path': string, 'gsim_tree_path': string}
"""
dic = {}
if hasattr(rlz, 'sm_lt_path'): # composite realization
dic['source_model_tree_path'] = '_'.join(r... | 3fef9c612bbb22c818b43284ee72d08e40640a7a | 661,293 |
from textwrap import dedent
import traceback
def format_exception_trace(exception: BaseException) -> str:
"""
Formats the traceback part of an exception as it would appear when printed by Python's exception handler.
Args:
exception: The exception to format
Returns:
A string, usually ... | c5785ee85d914ebdb241c72e034e9268a2304372 | 661,294 |
def format_autopkg_recipes(output):
"""Add lines between Input and Process, and between multiple processes.
This aids readability of yaml recipes"""
# add line before specific processors
for item in ["Input:", "Process:", "- Processor:", "ParentRecipeTrustInfo:"]:
output = output.replace(item, "... | 45be88c0e48b33339a5b808f261a5d8dff47558a | 661,296 |
def sub_group_lines(lines):
""" Splits lines delimited by empty lines, groups split lines into lists.
Args:
lines (list): A list of lines seperated by empty lines.
Returns:
A list of lists of grouped lines.
"""
groups, sub_group = [], []
for line in lines:
if len(line... | 70a946509f89685f3262d709c29ee04370ce18c6 | 661,297 |
def batch_cmd_create_irf(
cwd,
mc_gamma,
mc_proton,
mc_electron,
output_irf_file,
dl3_config
):
"""Create batch command to create IRF file with sbatch."""
return [
"sbatch",
"--parsable",
"--mem=6GB",
"--job-name=irf",
"-D",... | b11b0cc046b9452f3b4b211a1df5788acb19c81e | 661,299 |
def greeting(name: str) -> str:
"""
Build the greeting message
"""
return 'Hello, ' + name + '!' | d6665cf26570dc93208b2f9b98de61ff8cab1a14 | 661,300 |
def get_linear_magnitude_scaling(scale_factor: float):
"""
Get a linear magnitude scaling function, to correct magnitude.
Parameters
----------
scale_factor : float
The scale factor, according to the definition given in STDI-0002.
Returns
-------
callable
"""
def scale... | ef2ded49ce6f0c7e38fcbd9ff8ab7b4352bce56c | 661,301 |
import os
def find_all(fname, path):
"""
Finds all files matching a specified name within the directory specified.
**Parameters**
fname: *string*
The name of the file to be located
path: *string*
The absolute directory path to search.
**Returns**
list of locations... | 31940eddc8bb00caed7a3cee9e104998429637da | 661,302 |
def create_wav_header(sampleRate, bitsPerSample, num_channels, num_samples):
"""Generate WAV file header."""
datasize = num_samples * num_channels * bitsPerSample // 8
o = bytes("RIFF", "ascii") # (4byte) Marks file as RIFF
o += (datasize + 36).to_bytes(
4, "little"
) # (4byte) File size i... | b22e5cced09eb3cdf95ec6d57f4d89c0f935c7d4 | 661,303 |
from functools import reduce
def deepgetattr(obj, attr, default=None, sep="."):
"""Recurse through an attribute chain to get the ultimate value."""
return reduce(lambda o, key: o.get(key, default), attr.split(sep), obj) | 471a6a6407e9e77e8ab6d1eb804fd905e09a721c | 661,304 |
def soma(a, b):
"""Soma dois números"""
return a + b | f8b982b32d114d1e0a8a8061510eb363d61463a5 | 661,305 |
def DeferredQuantumRegister_to_c(self):
"""Syntax conversion for creating a quantum register."""
return f"const int[] {self.name} = {{{', '.join(map(str, self.mapping))}}};" | e8a249dfd6482ff26b6172e5808294d327240889 | 661,306 |
def findCmdLineSwitch(argList, switch, ignoreCase=True):
"""
Argument List에서 command switch를 찾는다.
optViewFields = '/view_fields:'
optDeletedRecords = '/deleted_records'
argv = 'SQLiteParser.py external.db files /view_fields:_data,date_modified,date_added /deleted_records'.split()
v1 = findCmdLi... | 693d160bc21002b3d48775d70d6fa50a570b0fa5 | 661,307 |
import re
def find_idx(ls):
"""
Find index of causality
"""
r = []
element = set(ls)
if 1 in element:
for i in re.finditer('1+', ''.join([str(i) for i in [i if i != 2 else 1 for i in ls]])):
r.append([i for i in range(i.start(), i.end())])
if 3 in element:
for i... | 6cec18be7650c83c5e64f323d961cf62f3705f2e | 661,308 |
from typing import Iterator
from typing import Any
from typing import List
def rm_dups(lst: Iterator[Any]) -> List[Any]:
"""Return a sorted lst of non-duplicated elements from `lst`.
Parameters
----------
lst: sequence of any
Returns
-------
fslst:
Filtered and sorted `lst` with ... | 160da330adfd5d5e9c4c63fa2b72539c92e86efa | 661,309 |
def tio_is_attribute(tree_item):
"""
Returns 'True' if the tree item object is an attribute of the parent
opposed to e.g. a list element.
"""
if tree_item.is_attribute is None:
return ''
else:
return str(tree_item.is_attribute) | 914e150d257cacb8c89c48b94607d773a0736fe5 | 661,310 |
from typing import Callable
def map_values(dictionary: dict, func: Callable):
"""
Parameters
----------
dictionary :
func :
Returns
-------
Examples
-------
>>> users = {'fred': { 'user': 'fred', 'age': 40 }, 'pebbles': { 'user': 'pebbles', 'age': 1 }}
>>> map_values(us... | 6bea49b780a4c10c463a0136346f4da44ff761eb | 661,312 |
def human_seconds(seconds, display='.2f'):
"""
Given `seconds` seconds, return human readable duration.
"""
value = seconds * 1e6
ratios = [1e3, 1e3, 60, 60, 24]
names = ['us', 'ms', 's', 'min', 'hrs', 'days']
last = names.pop(0)
for name, ratio in zip(names, ratios):
if value / ... | 2d7d544989d36595b2a56bb6d6ba7cb1d294cf75 | 661,313 |
def evaluate(conf_matrix, label_filter=None):
"""
Evaluate Precision, Recall and F1 based on a confusion matrix as produced by `create_confusion_matrix`.
Args:
conf_matrix: a confusion matrix in form of a dictionary from `(gold_label,guess_label)` pairs to counts.
label_filter: a set of gold... | 5c3284a1647cfa336ec7170b35f7d702d1538c21 | 661,314 |
def lists_to_dict(list_keys, list_values):
"""two ordered lists to a dict where list_keys are the keys and list_values
are the values
Inputs:
list_keys - a list of n unique elements, where n = 0, 1 or many
list_values - a list of n elements
Returns:
a dict of ... | 15e679be617a5a3e9210ba15d12c605dbffa1686 | 661,315 |
def functionIsCompilable(f):
"""Is a python function 'f' compilable?
Specifically, we try to cordon off the functions we know are not going to compile
so that we can just represent them as python objects.
"""
# we know we can't compile standard numpy and scipy functions
if f.__module__ == "nump... | c6b7dd023aa4f3c00fcf04f33d3e2085d5e5bbaa | 661,317 |
def list_files(root, extension, parts):
"""Construct files from root, parts."""
files = [root + part + extension for part in parts]
return files | 59335ad99a996135ca61468ff6f51f0f553af8f3 | 661,318 |
def has_humanitarian_content (activity):
""" More-thorough review of an activity to check if it seems humanitarian.
Will return true if the activity is flagged humanitarian, any transaction
is flagged humanitarian, a humantarian-scope is present, and/or it
mentions a humanitarian sector.
"""
d... | f9ced3872b1b4c32600525915931fbd546ade751 | 661,319 |
def converge_lists(list_to_converge):
"""
Function to flatten and remove the sublist created during future obj
Args:
list_to_converge (list): arg list of lists, eg: [[1,2],[3,4]]
Returns:
list (list): return converged list eg: [1,2,3,4]
"""
return [item for sublist in list_to_co... | 7ff1db816c1e8b15909b386d829f3237b672bdf8 | 661,320 |
import asyncio
def _get_event_loop() -> asyncio.AbstractEventLoop:
""" This simply wraps the asyncio function so we have typing for autocomplet/linting"""
return asyncio.get_event_loop() | d7b90d74c3ce7445e047af576e4d172e480da597 | 661,321 |
def spaceHolder(response):
"""Return the response without parsing."""
return response | 567741a26d4d2dcb2794d550265bc45fda17e72d | 661,322 |
import subprocess
def get_gcloud_token():
"""Return the gcloud access token as a string.
This functions requires the gcloud executable to be available in the path
variable.
Return (str): The gcloud access token
"""
outs = subprocess.check_output(
["gcloud", "auth", "application-defau... | f476ad570953667ab596c9cf4a75a392f6b54a5b | 661,323 |
def get_schedule_v(df):
"""換気スケジュール
Args:
df(DateFrame): スケジュール
Returns:
ndarray: 換気スケジュール
"""
return df['換気'].values | 4395cf20666cb87da294d8f7743625194354bd90 | 661,324 |
from typing import List
def bert_preprocess(texts: List[str]) -> List[str]:
"""
Apply preprocessing appropriate for a BERT (or BERT-based) model to a set of texts.
Args:
texts: Texts to preprocess.
Returns:
List of preprocessed texts.
"""
# BERT truncates input, so don't pass in ... | 0414ed343cbfc2f662c33f7a7b5b943f01d48823 | 661,325 |
def check_newlines( fname, bytes_to_read=52428800 ):
"""
Determines if there are any non-POSIX newlines in the first
number_of_bytes (by default, 50MB) of the file.
"""
CHUNK_SIZE = 2 ** 20
f = open( fname, 'r' )
for chunk in f.read( CHUNK_SIZE ):
if f.tell() > bytes_to_read:
... | 6e47532f48d600745dfd2ba0b97a28655d4b9968 | 661,326 |
def projection_dict(projection):
"""Get a projection dictionary from a list of attribute names to project.
Args:
projection: List of string names of attributes to project.
Returns:
Dictionary like {'attr1': 1, 'attr': 1, ... }.
"""
if projection:
return dict(zip(projection, [1]... | 67e7755cb522dc9861c81a2f73f2c5fe1e87bffe | 661,327 |
from typing import Dict
import re
def getParameters(msgContent : str) -> Dict[str,str]:
"""
Get parameters parses through a command call and returns all parameters. Inline parameters are simply added
after the command, positional parameters can be added via x=y.
:param msgContent: msgContent for the p... | 4849a282c5837228afb044c1dd9612b36bf8bae6 | 661,329 |
def datetimefilter(value, format='%d/%m/%Y at %H:%M:%S'):
"""Convert a datetime to a different format."""
return value.strftime(format) | 30441124d8138807b3f4ac5b40d960337a1963b2 | 661,330 |
def sortRanking(_pop, _fit):
"""Sorts population and fit values due to fit values
Parameters:
_pop - population to be sorted
_fit - fit values related to population
Returns:
Function returns a tuple of sorted fit values and population
"""
return zip(*sorted(zip(_fit,_pop),reverse=True)) | 7637e3da5449747bd13eaaad6952bb18268f6ac5 | 661,332 |
def filterNone(l):
"""Returns the list l after filtering out None (but 0"s are kept)."""
return [e for e in l if e is not None] | 0e5be1ad0e2127d47cbd9f73e4eda89b8aa35c1b | 661,333 |
def is_good_response(resp):
"""
Returna 'True' si parametro 'resp' tinen como respuesta 200 (peticion exitosa de la solicitud get)
"""
content_type = resp.headers['Content-Type'].lower()
return (resp.status_code == 200
and content_type is not None
and content_type.find('htm... | 1b4e71b82b1eb165d7d74c83e42fcf298ef32e86 | 661,334 |
def create_buffered_data(full_data):
"""
Utility function that does minor cleaning and buffers points for eventual passage into a ViT
"""
clipper_dat_geom = full_data[["geometry", "IrwinID"]].drop_duplicates(
subset=["IrwinID"]
)
clipper_dat_geom["geometry"] = clipper_dat_geom["geometr... | 8ece98100bb10c1f5e66bdd66e74d25ea56fc9b8 | 661,336 |
def remove_empty_quote(output, content_data):
"""
Removes Empty Quotes which can be used as obfuscation to break strings apart.
Args:
output: What is to be returned by the profiler
content_data: "EXA''MPLE"
Returns:
content_data: "EXAMPLE"
modification_flag: Boolean
... | 93e0f0c60b5cc536361a92080a948d58ccb9f003 | 661,337 |
def frequency_set(partition, dim):
"""get the frequency_set of partition on dim
return dict{key: str values, values: count}
"""
frequency = {}
for record in partition.member:
try:
frequency[record[dim]] += 1
except KeyError:
frequency[record[dim]] = 1
retu... | b9101d0d2f62f7f059da1d70a421120269f5da01 | 661,338 |
def hello(name):
"""
Custom function.
"""
return {"text": "Hello, {}".format(name)} | e23fb2f0cd852f11752003b9a6c0808b7b2ac9f9 | 661,339 |
from pathlib import Path
import re
def get_compressed_path(path, is_obs=None, compression='gz'):
"""Get the compressed path corresponding to a RINEX file after compression.
Parameters
----------
path : path or str
Path to the RINEX file being compressed.
is_obs : bool, optional
Wh... | fda088c76792cfa7bd9d19fbfb9edd86159b8306 | 661,340 |
import torch
def kron_einsum_batched_1D(A: torch.Tensor, B: torch.Tensor):
"""
Batched Version of Kronecker Products
:param A: has shape (b, c, a)
:param B: has shape (b, c, k)
:return: (b, c, ak)
"""
res = torch.einsum('ba,bk->bak', A, B).view(A.size(0), A.size(1)*B.size(1) )
# ... | c31ed2363f2c5a240d366fb4315080e06903dca5 | 661,341 |
def build_chunk(data_list, id2label_dict):
"""
Assembly entity
"""
tag_list = [id2label_dict.get(str(id)) for id in data_list]
ner_dict = {}
ner_str = ""
ner_start = 0
for i in range(len(tag_list)):
tag = tag_list[i]
if tag == u"O":
if i != 0:
... | db41e965d5f587705274dc7b5c1da026ce7113cb | 661,342 |
import math
def generate_equator(step=0.5, type='equ'):
"""
step is in degrees
types:
equ = celestial equator
ecl = ecliptic
gal = galactic equator
"""
eps = math.radians(23.4392911)
se = math.sin(eps)
ce = math.cos(eps)
d = 0.
points = []
while d <= 360... | 1f59eeb9f825d549fa5795734fd97eb571b97f46 | 661,344 |
def get_zhang_aspect_ratio(aspect_ratio):
"""Jeffery's equivalent aspect ratio.
Approximation for small aspect ratios from
Zhang et al. 2011
"""
return (0.000035*aspect_ratio**3 - 0.00467*aspect_ratio**2 +
0.764*aspect_ratio + 0.404) | dbd580697a3c88c13febec6cdf3dba5825d46e76 | 661,346 |
def remove_cat_names(X_cats, onehot_dict, onehot_missing_dict=None):
"""removes the leading category names in the onehotencoded columns.
Turning e.g 'Sex_male' into 'male', etc"""
X_cats = X_cats.copy()
for cat, cols in onehot_dict.items():
if len(cols) > 1:
mapping = {c:(c[len(cat)... | ba93ad522c76a9946e430032843d8654ee8025fd | 661,347 |
import string
def removePunctuations(target):
"""
this function takes in a string, and returns it after removing all
leading and trailing punctuations
string.punctuation !"#$%&'()*+,-./:;<=>?@[\]^_`{|}~
logic: to find a starting index and ending index to slice the string
"""
# initialise... | 11e810e10ed39748822c65112e7732ac94d23423 | 661,349 |
def cloudfoundry():
"""
get:
summary: Return a simple string with a status code of 200 to signify
that this web application is working properly. This is used
in systems such as Cloud Foundry.
description: simple response indicates application is running.
... | f6a882b6d07ad4316c77a26dc3f7a068db17aafe | 661,350 |
def bsxfun_eq2(galLabels, probLabels, binaryLabels):
"""get bsxfun_eq2"""
for i, _ in enumerate(galLabels):
for j, ele in enumerate(probLabels):
binaryLabels[i, j] = 1 if galLabels[i, j] == ele else 0
return binaryLabels | 17ef35c5db476cd191f2d45760bd5ef6d17d7ece | 661,351 |
from typing import Dict
def sum_formula_to_html(sumform: Dict[str, str], break_after: int = 99) -> str:
"""
Makes html formatted sum formula from dictionary.
"""
if not sumform:
return ''
l = ['<html><body>']
num = 0
for el in sumform:
if sumform[el] == 0 or sumform[el] == ... | 6cb80323cd00a721d71925bb05e48e9e31fdc3e7 | 661,352 |
import struct
def nunpack(s, default=0):
"""Unpacks 1 to 4 or 8 byte integers (big endian)."""
l = len(s)
if not l:
return default
elif l == 1:
return ord(s)
elif l == 2:
return struct.unpack('>H', s)[0]
elif l == 3:
return struct.unpack('>L', b'\x00' + s)[0]
... | 078ed8d68571d375e38b5ef3708dd17e891b6dad | 661,353 |
import tempfile
import pickle
def unique_serialization(obj):
"""
Checks whether obj is serialized in a fashion that produces a
unique representation. If this returns false, cacher will always conclude
that any function with obj as an argument is fresh
Returns examples of the object in pre-and-pos... | b5013bd0599aa90ea5b79737be849c70ab4e13cb | 661,354 |
import tempfile
import re
def read_xyz(datapath_or_datastring,
is_datafile=True):
"""
Read data in .xyz format, from either a file or a raw string.
:param (string) datapath_or_datastring: Either the path to the XYZ file (can be relative
or absolute... | 5ade25ae41290b465a5e7377ef937c2ebf9639ef | 661,355 |
def get(
coin,
in_coin,
try_conversion=None,
exchange=None,
aggregate=None,
limit=None,
all_data=None,
to_timestamp=None,
extra_params=None,
sign=None,
):
"""
Get open, high, low, close, volumefrom and volumeto from the dayly
hi... | 526aa2b05667d5b5f6b6cf4afe1d798aafc18f50 | 661,356 |
import re
def de_comment_line(line):
"""
Returns a version of the string @line with all
C++ comments removed
"""
line = re.sub(r"/\*.*\*/", "", line) # Remove /* comments
line = re.sub(r"//.*", "", line) # Remove // comments
return line | 2f7883136bc7228cd80ec0f4c8f4c88fd49a3e89 | 661,357 |
def shared_lib_name(group_name: str) -> str:
"""Given a group name, return the actual name of its extension module.
(This just adds a suffix to the final component.)
"""
return '{}__mypyc'.format(group_name) | b4886edd8c7c4ee39215f2ed4d1d9ff7ba568924 | 661,358 |
def get_pos_from_common(words0, tag1, sep="-"):
"""从common模型的输出中重构标注, 即获取未知信息---position
common analysis for sequence-labeling
Args:
words0: String, origin text, eg. "沪是上海"
tag1 : List, common-output of labels, eg. ["S-city", "O", "B-city", "I-city"]
sep : String, split in tag, ... | e172ad0387ab64baf06f8d7fbc801d9ee9693d35 | 661,359 |
def create_plot_settings_dict(emission_name):
"""
Create a dictionary containing the plot settings for the AEM figures
"""
title_dict = {'z_var_ave': 'Average {} emission [mg/s]'.format(emission_name),
'std_var': 'std {} emission per bin [mg/s]'.format(emission_name),
... | da23d741c1e5fb6c6dc89ac6158337628e375424 | 661,360 |
def format_alignment(align1, align2, score, begin, end):
"""format_alignment(align1, align2, score, begin, end) -> string
Format the alignment prettily into a string.
"""
s = []
s.append("%s\n" % align1)
s.append("%s%s\n" % (" "*begin, "|"*(end-begin)))
s.append("%s\n" % align2)
s.appe... | 490fda758e5c8d8dd9f4a7bbdf1f092da474c86d | 661,362 |
def transform_to_bytes(content: str):
"""
Transform a string to bytes
Parameters
----------
- content (str): The string to convert
Raises
------
ValueError: the string is not valid
Returns
-------
- bytes: the converted string in bytes
"""
if isinsta... | cc3084c84444519f04c42a4f721fdd2272852deb | 661,363 |
import uuid
def random_name(length=4, prefix=''):
"""Generate a random string.
Parameters
----------
length : int, optional
prefix : str, optional
"""
return prefix + str(uuid.uuid4().hex[0:length]) | 3289f060faef5412f45cf441cc72bb8c114f7cc4 | 661,364 |
def get_input(question: str) -> int:
"""Get input (int) from user
returns int"""
while True:
try:
value = int(input(question))
if value < 0:
print("Input must be a positive integer, try again: \n")
continue
break
except... | 41f25aae4e4992f490b22e24b9b6b0f3633e0662 | 661,365 |
def get_pausers(df):
"""
Filters the DataFrame for paused (begun but did not finish) replies.
:param df:
:return:
"""
return df[df['dispcode'] == 22] | ed5995a25de17b115633c72101ffa83a151bf3c7 | 661,366 |
def non_binary_search(data, item):
"""Return the position of query if in data."""
for index, val in enumerate(data):
if val == item:
return index
return None | 1bc82832937e1dff695b4f37f75565c17bfc6d9f | 661,367 |
def count_noun(number, noun, plural=None, pad_number=False, pad_noun=False):
"""
EXAMPLES::
sage: from sage.doctest.util import count_noun
sage: count_noun(1, "apple")
'1 apple'
sage: count_noun(1, "apple", pad_noun=True)
'1 apple '
sage: count_noun(1, "apple", p... | 23f40c44d16557b07e7c01deb7537cfdeebc2f1a | 661,368 |
def get_dim_order(x, y, z):
"""
Returns a tuple with the order of dimensions. Tuple can be used with
DIM_ROT.
"""
if x <= y and x <= z:
if y <= z:
return ('x', 'y', 'z')
else:
return ('x', 'z', 'y')
elif y <= x and y <= z:
if x <= z:
... | 1e867a12d130410f2ab5fdc5343bd87d41f3e45e | 661,369 |
from typing import List
from typing import Dict
def content_check(data: List[Dict[str, str]], check: str,
json_file: str, msg: str) -> bool:
"""
Checks whether a dictionary contains a column specific to expected data and returns
a corresponding boolean value. This avoids writing files of... | e4ce5389fae39fb36743d81ca5171534202678ec | 661,370 |
def steps(execution_id, query_params, client):
"""Get execution steps for a certain execution."""
return client.get_execution_steps(execution_id, **query_params) | 4b2a29ec32db80cbe02980d5f2585c48e8284338 | 661,371 |
def gen_labor_force_change(shortened_dv_list):
"""Create variables for the change in labor force for the current and
previous months."""
labor_force_change = round((shortened_dv_list[5] - shortened_dv_list[4]) * 1000)
prev_labor_force_change = round((shortened_dv_list[4] - shortened_dv_list[3]) * 1000)... | f40ff058e81d6f2bfa3f17a6e0165618fab7cebb | 661,372 |
import json
def validate(resp):
"""Check health status response from application.
Args:
resp (string): Response will be converted to JSON and then analyzed.
Returns:
(bool): True if application healthy.
"""
print(resp)
try:
data = json.loads(resp)
except:
... | 87ec568e908c01496f4b3c4fca1b25f518a6a2b3 | 661,373 |
def get_index_size_in_kb(opensearch, index_name):
"""
Gets the size of an index in kilobytes
Args:
opensearch: opensearch client
index_name: name of index to look up
Returns:
size of index in kilobytes
"""
return int(
opensearch.indices.stats(index_name, metric='s... | a5a339d5055e66e007caa82f7a70cb2cf4d84e6a | 661,374 |
def report(dtgen, predicts, metrics, total_time, plus=""):
"""Calculate and organize metrics and predicts informations"""
e_corpus = "\n".join([
f"Total test sentences: {dtgen.size['test']}",
f"{plus}",
f"Total time: {total_time}",
f"Time per item: {total_time /... | a454cdaab1b3c936dd70052005fa76786ebfd62e | 661,375 |
def getbox(face):
"""Convert width and height in face to a point in a rectangle"""
rect = face.face_rectangle
left = rect.left
top = rect.top
right = left + rect.width
bottom = top + rect.height
return top, right, bottom, left | c30b8647785518e9aebb94adf9945ac7ea79faa5 | 661,376 |
def verify_tag_default(tag, hostpart, ffrom) -> bool:
""" return True if callback should be fired (if possible) """
return tag.verification_state == "verified" | cbf16d124f3f46abc36427b777ee732e57fb6a7f | 661,378 |
def exponential(start_at):
"""Return and exponentially increasing value
:param float start_at: Initial delay in seconds
:rtype func:
"""
def func(count):
count -= 1
return start_at * (2**count)
return func | 0245a7a19f354dbafd51ba78467e77a7eae12b6c | 661,379 |
def guess_file_extension(url):
""" Used by the image mirroring service """
url = url.lower()
if '.jpg' in url or '.jpeg' in url:
return '.jpg'
elif '.gif' in url:
return '.gif'
elif '.png' in url:
return '.png'
elif '.svg' in url:
return '.svg'
else:
r... | 8a831c11ab0c723b852b2d4f2695f152a980d4d9 | 661,380 |
def use_node_def_or_num(given_value, default_func):
"""Transform a value of type (None, int, float, Callable) to a node annotation function."""
# Default: use pre-defined function from this module
if given_value is None:
func = default_func
# Transform: value to function that returns the value
... | e3cd540dd8272647c18f6d2d9e65f40bf509e63b | 661,381 |
def find_root(ds):
"""
Helper function to find the root of a netcdf or h5netcdf dataset.
"""
while ds.parent is not None:
ds = ds.parent
return ds | 0deed0eac3164b23a6df67e8fa5ed175b95f2952 | 661,382 |
def get_learnable_params(model):
"""to get the list of learnable params
Arguments:
model {model} -- loaded model
Returns:
list -- learnable params
"""
# list down the names of learnable params
details = []
for name, param in model.named_parameters():
if par... | 4ca14c1094f911732d158fed67b0d2c4f2701a2e | 661,383 |
from typing import List
def make_parallel_commands(
commands: str, repeats: int, parallel: int
) -> List[List[str]]:
""" Build list of lists,
where the inner list contains a group of commands to be executed in a sequence"""
command_list = commands.split("|")
command_list = [comm.strip() for comm... | 813b662f6d31c01e25cf32811fc452f5e7e07b92 | 661,384 |
import codecs
def readfile(filepath):
"""
该函数负责读取文章并生成由文章中每个字符构成的列表
:param filepath: txt文件路径
:return: 返回传入文本文件中文章每个字构成的列表
"""
sentence=[]
for line in codecs.open(filepath, 'r', 'utf8'):
for i in range(len(line)):
sentence.append(line[i])
return sentence
# with o... | 576e754384561012affd8b940d25256d6523fb8a | 661,386 |
import socket
def find_hostname():
"""
Find the current hostname to show the pod in use.
:return str: host name of the underlying vm
"""
return socket.gethostname() | b03a0a18711d47905dd63751232e45bd210d3874 | 661,387 |
import base64
import random
def get_payload(byte_size):
"""Returns a base64 encoded random payload of (roughly) byte_size length
Args:
byte_size: The number of bytes to return after base64 encoding
"""
size_before_b64 = (byte_size / 4) * 3
return base64.b64encode(bytearray(random.getrandb... | 406b492f89690b2b84bf95b3ad46f165526e3a7f | 661,388 |
def prime_sieve(n):
"""
Return a list of all primes smaller than or equal to n.
This algorithm uses a straightforward implementation of the
Sieve of Eratosthenes. For more information, see
https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes
Algorithmic details
-------------------
... | 180dc6a2ff1d3096630a6279ace841e4c5efdd83 | 661,389 |
def _create_into_array_list(phrase):
"""Create load or store into array instructions
For example, with the phrase 'astore':
[
'iastore',
'fastore',
...
'aastore'
]
"""
# noinspection SpellCheckingInspection
return [letter + phrase for letter in 'lfdibcsa'] | 3ae0bfbcd1ef3b6fcb8538ccb02c3a150151458e | 661,390 |
def gas_estimation_error_message(tx_error: Exception) -> str:
"""
Use this method in ``ProviderAPI`` implementations when error handling
transaction errors. This is to have a consistent experience across providers.
"""
return (
f"Gas estimation failed: '{tx_error}'. This transaction will lik... | a8ab35667127dbfe9bca5fe63d720b856490682a | 661,391 |
def removekeys(toc, chapnum):
"""Return new dictionary with all keys that don't start with chapnum"""
newtoc = {}
l = len(chapnum)
for key, value in toc.items():
if key[:l] != chapnum:
newtoc[key] = value
return newtoc | 91d1986e8addf1906a0e7694b229e53148e5d3cf | 661,392 |
import random
def add_noise(chromosome, sigma):
"""
This is a function that will add some noise to the chromosome.
"""
new_x = chromosome[0] + (random.random() - 0.5) * sigma
new_y = chromosome[1] + (random.random() - 0.5) * sigma
return new_x, new_y | c1322719f5eeb7ac15380549a4d3a84a6731d6b0 | 661,393 |
import requests
import json
def find_address_from_GPS(GPS):
"""
使用Geocoding API把经纬度坐标转换为结构化地址。
:param GPS:
:return:
"""
secret_key = 'P8MDgmP4bfytEkj8pyZgV5QT'
if not GPS['GPS_information']:
return '该照片无GPS信息'
lat, lng = GPS['GPS_information']['GPSLatitude'], GPS['GPS_informati... | df760809a46bf24721cdb1c2fd9513d35320c816 | 661,395 |
def readFile(path: str, year: str) -> list:
"""
Returns list of all strings with [year].
"""
with open(path, encoding='latin1') as locations:
locs = []
found_locs = set()
for i, line in enumerate(locations):
if ('('+year+')') in line and line.split('\t')[0] not in fou... | 491a8f9c5639c2b37c2540c42d83a824e7ddcee5 | 661,396 |
import re
def retokenize(s, split_on=r'''([/-])'''):
"""
Apply secondary tokenization rule, e.g.,
split on hyphens or forward slashes.
"""
words, offsets = [], []
#for w, i in zip(s.words, s.offsets):
for w, i in zip(s.words, s.char_offsets):
tokens = [t for t in re.split(split_on... | 27cbe3b353e6c44719667ea56afa612055cbd2f0 | 661,397 |
import pandas
def is_empty_value(val):
""" check if a table value is missing, by value
"""
return pandas.isna(val) | e1663b64e5bf45ac697c7f50081b6e9e79e86d81 | 661,398 |
import builtins
import gzip
def open(filename, mode='r', compress=False, is_text=True, *args, **kwargs):
""" Return a file handle to the given file.
The only difference between this and the standard open command is that this
function transparently opens zip files, if specified. If a gzipped file is
... | 59edbe674ba434326ba9a09b71ae9e0ed770c29a | 661,399 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.