content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def model_repr(models, key):
"""Get a model representation."""
m = [(char, proba)
for char, proba in models[key].items() if proba > 0.0001]
m = sorted(m, key=lambda n: n[1], reverse=True)
s = ""
for char, prob in m:
s += u"{}={:4.2f}% ".format(char, prob * 100)
return s | 5,300,000 |
def read_file(filename):
"""
Read a whole file into memory.
Automatically detect gzipped files based on suffix.
Args:
filename (str): Name of file to read.
Returns:
str: Content of file as a string. Will return None if file cannot be read.
"""
try:
with open_file_h... | 5,300,001 |
def findNewFiles():
"""
Find all of the files that have been downloaded, and then determine all of
those that have not been decrypted. Return a list of those that need to be
decrypted now.
"""
allFiles = glob.glob('*.gpg')
oldFiles = glob.glob('*.gz')
retFiles = []
for f in allFiles... | 5,300,002 |
def search_twitter(api, max_results=None, progress=False, **query):
"""Perform a twitter search.
See http://docs.tweepy.org/en/latest/api.html#API.search
Parameters
----------
api : tweepy.API
max_results : int, optional
The maximum number of tweets to return.
Default is None (... | 5,300,003 |
def load_global_params(path: str, report=True):
"""Load and return global paramss
Args:
path (str): path to param file
report (bool, optional): Add params to EuroPy report. Defaults to True.
Returns:
Dict[str:Any]: global params
"""
params = {}
with open(path, 'r') as ... | 5,300,004 |
def test_kubernetes_metrics_get_cpu_cores_missing(kubernetes_metrics_obj: KubernetesMetrics):
"""
This test verifies that KubernetesMetrics.get_cpu_cores() returns None for undefined metrics.
:param kubernetes_metrics_obj: The pre-loaded KubernetesMetrics fixture object for testing.
"""
assert kube... | 5,300,005 |
def parse_joa_html(inner_html):
"""
Retourne les cotes disponibles sur une page html joa
"""
match_odds_hash = {}
match = None
date_time = None
soup = BeautifulSoup(inner_html, features="lxml")
id_match = None
for line in soup.findAll():
if "class" in line.attrs and "bet-even... | 5,300,006 |
def create_or_update_pipeline(origin_pipeline, api_url):
"""Create or update Storage Location and return it."""
pipeline = Pipeline.query.filter_by(origin_pipeline=origin_pipeline).first()
request_url, request_url_without_api_key = get_storage_service_api_url(
api_url, origin_pipeline
)
resp... | 5,300,007 |
def wechat_pay_call_back(request):
"""
"""
try:
from datetime import datetime, timedelta
time_format = '%Y%m%d%H%M%S'
date_now = datetime.now()
after_2_hour = date_now + timedelta(hours=2)
logger.debug("wechat_pay_call_back")
pay_a = WeChatPayModeA(appid=pay... | 5,300,008 |
def _validate_additional_args(param_dict):
"""
:param param_dict: parameters to enter into the backing store
:type param_dict: dictionary
:returns: a string that tidies up the additional arguments
:rtype: string
"""
if 'additional_arguments' not in param_dict:
return "{}"
param... | 5,300,009 |
def delete_empty_courts(dry_run='true'):
"""
Delete empty courts, and reslug any other courts that are affected by the newly-available slug.
NOTE: this may not be a good idea to run if users depend on stable court slugs.
"""
from django.db import transaction
import re
courts_to_delet... | 5,300,010 |
def get_request_in_pull_url(data):
"""Отправление get запроса ко всем url из выбранного пулла"""
for index, row in data.iterrows():
url = row['url']
label = row['label']
try:
response = requests.get(url, timeout=config.TIMEOUT)
except Exception as ex:
ts =... | 5,300,011 |
def fib_dp(n):
"""
Series - 1, 1, 2, 3, 5, 8, 13
`n` starts from 0.
:param n:
:return:
"""
fib_arr = empty_1d_array(n)
if n < 2:
return 1
if fib_arr[n-1] is None:
fib_arr[n-1] = fib_rec(n-1)
if fib_arr[n-2] is None:
fib_arr[n-2] = fib_rec(n-2)
return ... | 5,300,012 |
def compute_distance_adjacent_finger(finger_name, adjacent_finger, hand_fingers_points):
"""
Cálcula a distância entre a ponta do dedo analisado e a ponta do dedo adjacente. Divide
por fator de correção (distância de referência).
:param finger_name: dedo analisado
:param adjacent_finger: dedo adjace... | 5,300,013 |
def superpixel_plotpixel(connect_mat_1,
unique_pix,
pure_pix,
ax1=None,
plot_aspect=None,
text=False,
plot_colormap='jet',
type='pure'):
"""
""... | 5,300,014 |
def get_linters(files_to_lint, file_cache):
"""Creates GeneralPurposeLinter object and returns it.
Args:
files_to_lint: list(str). A list of filepaths to lint.
file_cache: object(FileCache). Provides thread-safe access to cached
file content.
Returns:
tuple(GeneralPurpo... | 5,300,015 |
def extract_common_countries(FILES, eu28_countries):
"""This function extract countries common to all
data sets.
Arguments of fucntion are FILES -> list of triples
where elements are data set filename, column/row/header
depending where the countries' names reside in the
da... | 5,300,016 |
def catch_toil_exceptions(orig_func):
"""Catch uncaught exceptions and turn them into http errors"""
@functools.wraps(orig_func)
def catch_exceptions_wrapper(self, *args, **kwargs):
try:
return orig_func(self, *args, **kwargs)
except RuntimeError as e:
return {"msg":... | 5,300,017 |
def generateTmatrixFullRandom(N,badf=0.2):
# print("p_act01 < p01/(p01+p10)")
"""
Generates a Nx2x2x2 T matrix indexed as: T[patient_number][action][current_state][next_state]
action=0 denotes passive action, a=1 is active action
State 0 denotes NA and state 1 denotes A
"""
... | 5,300,018 |
def data_transform(tables_dict):
"""
数据迁移
:return:
"""
# 按照主键排序搜索,
select_sql = "select * from %s where %s > '%s' order by %s limit %d"
# 分页条数
size = 3000
select_data = ["table_name", "key_column", "last_key", "key_column", size]
for logic_table_name in tables_dict:
ol... | 5,300,019 |
def ResolveVersion(api_name, default_override=None):
"""Resolves the version for an API based on the APIs map and API overrides.
Args:
api_name: str, The API name (or the command surface name, if different).
default_override: str, The override for the default version.
Raises:
apis_internal.UnknownAP... | 5,300,020 |
def decrypt_master(master_pwd,master_dict):
"""Decrypt a master key with a master password"""
secondary = hashlib.pbkdf2_hmac('sha256',master_pwd.encode(),master_dict['salt'],2**14,16)
cipher = AES.new(secondary,AES.MODE_EAX,nonce=master_dict['nonce'])
master = cipher.decrypt_and_verify(master_dict['cip... | 5,300,021 |
def runSingleFile(inputFile, outputDir, parser, databaseVersion, listOfExpRes,
timeout, development, parameterFile):
"""
Call testPoint on inputFile, write crash report in case of problems
:parameter inputFile: path to input file
:parameter outputDir: path to directory where output ... | 5,300,022 |
def new_pipeline(tickers, start_date, end_date):
"""The pipeline implemented with Dask"""
def compute():
# The pipeline construction will store 'get_signals', so we need to
# delay it until we enter the 'intercept_function_arguments' context
signals = get_full_pipeline(tickers, start_da... | 5,300,023 |
def handleNonAscii(text):
"""
If default locale supports UTF-8 reencode the string otherwise
remove the offending characters.
"""
if preferred_encoding == 'ASCII':
return ''.join([i if ord(i) < 128 else ' ' for i in text])
else:
return text.encode(preferred_encoding) | 5,300,024 |
def folding(eventfile,Porb,nbins):
"""
Folding the events by some orbital period
"""
times = fits.open(eventfile)[1].data['TIME'] #getting array of times
gtis_data = fits.open(eventfile)[2].data #getting GTIs
T = sum([ gtis_data[i]['STOP']-gtis_data[i]['START'] for i in range(len(gtis_data)) ]) ... | 5,300,025 |
def is_global(wire):
"""Return true if a wire is part of the global clock network"""
return bool(global_spine_tap_re.match(wire) or
global_cmux_out_re.match(wire) or
global_cmux_in_re.match(wire) or
clock_pin_re.match(wire) or
pll_out_re.match(wire... | 5,300,026 |
def sendfile(out, in_, offset, count): # real signature unknown; restored from __doc__
"""
sendfile(out, in, offset, count) -> byteswritten
sendfile(out, in, offset, count[, headers][, trailers], flags=0)
-> byteswritten
Copy count bytes from file descriptor in to file descriptor out.
... | 5,300,027 |
def create_lookup_tables(
vocabulary_path, num_oov_buckets=1, as_asset=True, unk_token=None
):
"""Creates TensorFlow lookup tables from a vocabulary file.
Args:
vocabulary_path: Path to the vocabulary file.
num_oov_buckets: Number of out-of-vocabulary buckets.
as_asset: If ``True``, the v... | 5,300,028 |
def get_bprop_less_equal(self):
"""Grad definition for `LessEqual` operation."""
def bprop(x, y, out, dout):
return zeros_like(x), zeros_like(y)
return bprop | 5,300,029 |
def queuer(args):
"""
Handles queuing of subjects and checking of statuses in `qsub`.
Grabs initial queue state from `start_queue`. Checks state of
queue via `qstat` every 30 seconds and replaces subjects as
necessary. Prints and logs subject status every 15 minutes.
When all subjects are compl... | 5,300,030 |
def group_by( l, key ):
"""
agrupa por alguna llave
Arguments
=========
l: list, tuple, finite iter
key: callable or str
funcion que separara los elementos
si es un string se asume que los elementos son dicionarios
y el valor de key se usara para obtener el valor
Re... | 5,300,031 |
def plot_heartbeat(patient, lead, beat_index):
"""
Plots a single heartbeat
:param patient: patient index
:param lead: lead number (0-3)
:param beat_index: index of the heartbeat into the array of heartbeats
:return:
"""
plt.figure(dpi=500)
data = np.load(f"Working_Data/Fixed_Dim_HBs_Idx{patient}.npy")
heartb... | 5,300,032 |
def get_lr_rotate(current_step, lr_max, max_step):
"""
Warmup training strategy.
Args:
current_step (int): current step
lr_max (float): original learning rate
max_step (int): total steps
Returns:
list of learning rate at each step
"""
lr_each_step = []
deca... | 5,300,033 |
def walk(_path: str) -> tuple:
"""
:param _path:
:return: tuple(_path, tuple('dirs',), tuple('files',))
"""
dirs = []
files = []
path = Path(_path)
for i in path.iterdir():
if i.is_file():
files.append(str(i))
if i.is_dir():
dirs.append(str(i))
... | 5,300,034 |
def zxxgamma(v, t, gamma, H0):
"""
Takes in:
v = values at z=0;
t = list of redshifts to integrate over;
gamma = interaction term.
Returns a function f = [dt/dz, d(a)/dz,
d(e'_m)/dz, d(e'_de)/dz,
d... | 5,300,035 |
def _meshgrid2d(x, y):
"""
Special-cased implementation of np.meshgrid.
For just two arguments, (x, y). Found to be about 3x faster on some simple
test arguments.
Parameters
----------
x : TYPE
DESCRIPTION.
y : TYPE
DESCRIPTION.
Returns
-------
r1 : TYPE
... | 5,300,036 |
def reaction_details(scores_output, final, to_wiki, out_harm):
"""
Add information of reactions and associated biobricks and sequences
Reads the intermediate file metabolic_detailed_output.csv as
pandas.DataFrame and per each reaction identifiers reads the
corresponding EC number and KEGG IDs from... | 5,300,037 |
def py(code, input):
"""python <commands> -- Execute Python inside of a sandbox"""
query = input.group(2)
try:
answer = web.exec_py(query)
if answer:
answer = answer.replace('\n', ' ').replace('\t', ' ').replace('\r', '')
return code.reply(answer)
return code.... | 5,300,038 |
def get_participial_constructions(tokens):
"""Identify, color and count participial constructions"""
# get part pres and praets
part_pres = [t for t in tokens if t.full_pos == 'ADJD' and t.mo.part == '<PPRES' and t.function in ['root','pn']]
part_praet = [t for t in tokens if t.full_pos == 'VVPP' ... | 5,300,039 |
def bin_stats(predictions: tf.Tensor, labels: tf.Tensor, prefix: Optional[str]=None,
suffix: Optional[str]=None) -> Tuple[tf.Tensor, tf.Tensor, tf.Tensor]:
"""
Calculate f1, precision and recall from binary classification expected and predicted values.
:param predictions: 2-d tensor (batch, p... | 5,300,040 |
def add_lang(key, phrase):
"""Add a language to the list."""
global base
if key in base:
print('Language {} already available'.format(key))
return
base[key] = phrase | 5,300,041 |
def idx2token(idx, reverse_vocab):
"""
index换取词
:param idx: index
:param reverse_vocab: 反查表 @see chatbot.build_vocab
:return: 词
"""
return reverse_vocab[idx] | 5,300,042 |
def update_episodes():
"""
GoogleDocs: Parses episode data.
"""
import_sheet('1')
parse_sheet('1', 'episodes') | 5,300,043 |
def bbc_news(to_say: str) -> str:
"""
This function provides the needed information for the news briefing.
:param to_say: str - to_say
:return: str - to say
"""
api_key2 = data["api_key2"]
url = "https://newsapi.org/v1/articles?source=bbc-news&sortBy=top&apiKey="
final_url = url + api_k... | 5,300,044 |
def write_json(filepath,data):
"""Given a valid filepath writes data to a JSON file.
Parameters:
filepath (str): the path to the file.
data (dict): the data to be encoded as JSON and written to the file.
Returns:
None
"""
with open(filepath, 'w') as file1:
json.dum... | 5,300,045 |
def mkdir(*unused_args, **unused_kwargs):
"""Method os.mkdir() is forbidden"""
raise RuntimeError('Usage of os.mkdir() is forbidden. '
'Use certbot.compat.filesystem.mkdir() instead.') | 5,300,046 |
def _get_lines(file_path: Path, encoding: str) -> Iterator[str]:
"""
Yields lines from `file_path` with current `encoding`.
"""
with open(file=file_path, encoding=encoding) as lines:
for line in lines:
yield line | 5,300,047 |
def commandPanelOverride(*args, **kwargs):
"""
Returns an command panel override wrapper for the supplied function.
:rtype: method
"""
# Check number of arguments
#
numArgs = len(args)
if numArgs == 0:
return partial(commandPanelOverride, **kwargs)
elif numArgs == 1:
... | 5,300,048 |
def _run_suite_concurrently(tasks, context, max_thread_count=10):
"""concorrence type to run cases.
:param tasks: dict for tasks, key is task name, value is the path for
task module, task should have __main__ entry.
:param max_thread_count: max thread count to run tasks.
"""
if ... | 5,300,049 |
def create_empty_anki_collection() -> typing.Iterator[Collection]:
"""ContextManager used to create an empty Anki Collection.
This collection is used for importing and exporting decks. For some reason
creating a collection also changes the current working directory. Therefore
it is necessary to call `c... | 5,300,050 |
def _process_video(filename, coder):
"""
Process a single video file using FFmpeg
Args
filename: path to the video file
coder: instance of ImageCoder to provide TensorFlow image coding utils.
Returns:
video_buffer: numpy array with the video frames
mask_buffer: activity m... | 5,300,051 |
def combine_multiple_callers(samples):
"""Collapse together variant calls from multiple approaches into single data item with `variants`.
"""
by_bam = collections.OrderedDict()
for data in (x[0] for x in samples):
work_bam = tz.get_in(("combine", "work_bam", "out"), data, data.get("align_bam"))
... | 5,300,052 |
def add_category():
"""Add a new category."""
if 'username' not in login_session:
flash("Please log in to continue.")
return redirect(url_for('login'))
elif request.method == 'POST':
if request.form['new-category-name'] == '':
flash('The field cannot be empty.')
... | 5,300,053 |
def temporarily_enabled():
""" Temporarily enable the cache
>>> from minicache import cache
>>> with cache.temporarily_disabled():
... with cache.temporarily_enabled():
... cache.update('temp', 'disable')
...
>>> cache.has('temp')
True
"""
old_setting = options.enabl... | 5,300,054 |
def predict(model_dir, Ytruth_file ,multi_flag=False):
"""
Predict the output from given spectra
"""
print("Retrieving flag object for parameters")
if (model_dir.startswith("models")):
model_dir = model_dir[7:]
print("after removing prefix models/, now model_dir is:", model_di... | 5,300,055 |
def formatString(format: str, data: typing.Dict, structure=None, language=None):
"""Central entryPoint
if string contains $( we use old formatstrings
else we use evalStrings (core 3.0 draft)
displayStrings actually only used in relations and records. This handler can be used with display param
""... | 5,300,056 |
def _analyzable_entities(ns: str, ws: str, workflow_name: str, etype: str, enames: List[str],
days_back: int or None, count: int or None) -> List[str]:
"""
Given a homogeneous (in terms of etype) list of entities, return a sub-list of them who are analyzable now.
One can also speci... | 5,300,057 |
def call(func: Types.Function) -> Types.Function:
"""
Call the function during module exection if microtest is running
or doing configuration.
"""
if core.running or core.config_in_process:
core.call_with_resources(func)
return func | 5,300,058 |
def localize_utc(value):
"""
Localise a UTC datetime
"""
if isinstance(value, datetime):
return value.replace(tzinfo=tzutc()).astimezone(tzlocal())
else:
return value | 5,300,059 |
def generate_init_tfs(pairs, n_slcs, n_tiles):
"""Find the transformation of each tile to tile[0,0]."""
tf0 = SimilarityTransform()
init_tfs = np.empty([n_slcs, n_tiles, 3])
for pair in pairs:
p, _, _, model, _ = pair
if (p[0][1] == 0) & (p[0][0] == p[1][0]): # referenced to tile 0 with... | 5,300,060 |
def matches(event, name):
"""
Returns True if the given event represents the same key as the one given in
`name`.
"""
if is_number(name):
return event.scan_code == name
normalized = _normalize_name(name)
matched_name = (
normalized == event.name
or 'left ' + normaliz... | 5,300,061 |
def process_csv(csv_file: str, store_name: str, store_list: list) -> int: # pragma: no cover
"""
Input the specified CSV file and process the narratives defined in it.
The format of the CSV MUST be:
Source,Title,Person,Type,Given,Given2,Surname,Maiden,Maiden2,Gender,Start,End,Remove,Header,Footer
... | 5,300,062 |
def vectorize_unknown(content_to_analyze):
""" """
try:
start = time.time()
print("Tfidf Vectorizing data to be analyzed...")
unknown = pd.DataFrame({"content": [content_to_analyze]})
unknown_vectors = vectorizer.transform(unknown.content)
unknown_words_df = pd.DataFrame... | 5,300,063 |
def message_from_lax(data):
"""
format a message from a Lax response data
"""
return data.get("message") if data.get("message") else "(empty message)" | 5,300,064 |
def get_username():
"""get the current users user name"""
return pwd.getpwuid(os.geteuid()).pw_name | 5,300,065 |
def b58decode(encoded):
"""Decodes a base58 string to its integer value"""
value = 0
multiplier = 1
for c in encoded[::-1]:
value += b58chars.index(c) * multiplier
multiplier *= b58base
return value | 5,300,066 |
def calc_geyser_rewards(badger, periodStartBlock, endBlock, cycle):
"""
Calculate rewards for each geyser, and sum them
userRewards = (userShareSeconds / totalShareSeconds) / tokensReleased
(For each token, for the time period)
"""
rewardsByGeyser = {}
# For each Geyser, get a list of user ... | 5,300,067 |
def createWindow(mainWidget, theme=None, title='CandySweet', ico_path=''):
"""
快速创建彩色窗 (带TitleBar)
:param mainWidget:
:param theme:
:param title:
:param ico_path:
:return:
"""
coolWindow = WindowWithTitleBar.WindowWithTitleBar(mainWidget)
coolWindow.setWindowTitle(title... | 5,300,068 |
async def send_welcome(message: types.Message):
"""
This handler will be called when user sends `/start` or `/help` command
"""
await message.reply("Hi!\nI'm ec20 Bot!\nPowered by aiogram.") | 5,300,069 |
def center_image_in_frame3d(image, centroid, size):
"""Centers a point in an image.
Parameters
----------
image : 3d np.ndarray
Image.
centroid : 2-tuple of int/float
Point to center. Coordinates should be (rr, cc).
size : 2-tuple of int
Size of returned-im... | 5,300,070 |
def part1(_input):
"""
part 1
"""
dif1 = 0
dif3 = 0
for idx, num in enumerate(_input):
try:
nxt = abs(_input[idx+1] - num)
if nxt == 1:
dif1 += 1
if nxt == 3:
dif3 += 1
except IndexError:
break
#... | 5,300,071 |
def captured_wave_energy_to_shape(energy_cap, wave_shape_uri):
"""Adds each captured wave energy value from the dictionary
energy_cap to a field of the shapefile wave_shape. The values are
set corresponding to the same I,J values which is the key of the
dictionary and used as the unique iden... | 5,300,072 |
def get_n_bits_combinations(num_bits: int) -> list:
"""
Function returning list containing all combinations of n bits.
Given num_bits binary bits, each bit has value 0 or 1,
there are in total 2**n_bits combinations.
:param num_bits: int, number of combinations to evaluate
:return: a list of le... | 5,300,073 |
def test_delete_task(sample_data, test_client):
"""
GIVEN some test data
WHEN delete task is called
THEN task should be deleted from the test data
"""
r = test_client.get('get_tasks?project_id=2')
r_body = r.json
assert len(r_body['tasks']) == 4
r2 = test_client.post('delete_task', json = {'project_id': 2, 'ta... | 5,300,074 |
def determine_file_source(targetpath, rd):
"""Assuming we know a file came from a specific recipe, figure out exactly where it came from"""
import oe.recipeutils
# See if it's in do_install for the recipe
workdir = rd.getVar('WORKDIR')
src_uri = rd.getVar('SRC_URI')
srcfile = ''
modpatches ... | 5,300,075 |
def mastQuery(request):
"""Perform a MAST query.
Parameters
----------
request (dictionary): The Mashup request json object
Returns head,content where head is the response HTTP headers, and content is the returned data"""
server='mast.stsci.edu'
# Grab Pyt... | 5,300,076 |
def counting_sort(nums):
"""
counting sort algorithm's complexity is:
time = O(n + k)
space = O(n + k)
where k = max(nums)
Apply this algorithm when O(k) <= O(n), and when all numbers in nums are >= 0
"""
# get frequency list
num_max = max(nums)
freqs = [0] * (num_max + 1)
fo... | 5,300,077 |
def sendDataHeader(sock, data, window, number):
"""Sends data to a given socket."""
try:
sock.send((data).encode(ENCODING))
print("Client sent: " + str((data).encode(ENCODING)))
response = ''
while True:
buff = sock.recv(4096)
buff = (str(buf... | 5,300,078 |
def action_convert(config, root, explore, remove_original):
"""Convert non MP3 files to MP3 using FFmpeg.
Parameters
----------
config : musar.config.Config
The configuration contains options and more importantly the list of
file extensions that should be converted to MP3 when encounter... | 5,300,079 |
def make_dict(data_for_dict):
""" takes all text from nubbe list and makes a dictionary.
data_for_dict: nubbe list created with parse_file()
"""
column_name_list = data_for_dict[0]
db_list = data_for_dict[1:]
column_list1 = []
column_list2 = []
column_list3 = []
column... | 5,300,080 |
def accuracy_wilson(y_true, y_pred):
"""Return a Wilson confidence interval for the accuracy metric.
Parameters
----------
y_true : array-like of shape (n_samples,)
Ground truth labels
y_pred : array-like of shape (n_samples,)
Predicted labels
Returns
-------
np.nda... | 5,300,081 |
def subdLayoutUV(*args, **kwargs):
"""
Move UVs in the texture plane to avoid overlaps.
Flags:
- caching : cch (bool) [create,query,edit]
Modifies the node caching mode. See the node documentation for more information. Note:For advanced users only.
-... | 5,300,082 |
async def clear_server_settings(event):
"""
for now, simple deletes server profile, which for security reasons will be refreshed
if server re-adds whistlebot.
currently reports pertaining to server are archived, may change to a mass delete.
"""
server = bot_db.db.servers.find_one({'server_id':... | 5,300,083 |
def extract_object_boxes_for_scenes(name, scene_info, sids, padding, swap_yz,
box_delta_t):
"""Extracts object boxes given scene IDs.
Args:
name: The object name.
scene_info: The scene information.
sids: [R, 1] tf.int32. Scene IDs.
padding: float32. The amount of... | 5,300,084 |
def api_get_and_validate_credentials() -> (str, str):
""" Sanitize access and secret keys from request """
access_key = request.values.get("access_key", None)
secret_key = request.values.get("secret_key", None)
# reject empty strings and value-not-present cases
if not access_key or not secret_key:
... | 5,300,085 |
def resource_exists(filename: str) -> bool:
"""
Check if a package resource exists.
Parameters
----------
filename : str
The filename.
Returns
-------
bool
True if the file exists otherwise False.
"""
return pkg_resources.resource_exists(get_package_name(), fil... | 5,300,086 |
def getSerieData(serie, proxies=None, url="http://www.epguides.com/"):
"""Get all data for given series from epguides.com
@param series a dict of {<name on epguides>:<long name>, ...}
"""
# line example
# 1. 1- 1 535J 30 Sep 01 <a href="http://www.tvtome.com/Alias/season1.html#ep... | 5,300,087 |
def guess_type(val, empty_as_null: bool) -> ColumnType:
"""Guess type of a value"""
if val is None:
return ColumnType.NULL
assert isinstance(val, (int, float, str)), "Invalid column data"
if fastnumbers.isfloat(val):
return ColumnType.NUMBER
else:
if len(val.strip()) == 0 an... | 5,300,088 |
def test_compartmentModel_fftconvolution_with_exponential_zero(preparedmodel):
""" Convolution with an exponential with time constant zero.
the default implementation will crash here
"""
int_vector=preparedmodel.intvector()
conv_w_zero=preparedmodel.convolution_w_exp(0.0, fftconvolution=True)
... | 5,300,089 |
def test_open_affine_and_transform(path_rgb_byte_tif):
"""Passsing both 'affine' and 'transform' to rasterio.open() should issue
some helpful warnings.
By settings the 'affine' kwarg to a wacky value we ensure that the
'transform' kwarg is used while ignoring the 'affine' kwarg.
"""
with pytest... | 5,300,090 |
def get_centers(bins):
"""Return the center of the provided bins.
Example:
>>> get_centers(bins=np.array([0.0, 1.0, 2.0]))
array([0.5, 1.5])
"""
bins = bins.astype(float)
return (bins[:-1] + bins[1:]) / 2 | 5,300,091 |
def test_dont_bind_data():
"""
Configuration contains no argument mapping for `my_param`. ergo will assume that `my_param` is supposed be a key
in `data`, and will raise TypeError if it doesn't find it there.
"""
component = AMQPComponent(handler_with_mapped_params, args={"my_context": "context"})
... | 5,300,092 |
def parse_all_validations_on_disk(path,
groups=None,
categories=None,
products=None):
"""Return a list of validations metadata which can be sorted by Groups, by
Categories or by Products.
:param path: The ... | 5,300,093 |
def create_alexnet_model_2d(input_image_size,
number_of_classification_labels=1000,
number_of_dense_units=4096,
dropout_rate=0.0,
mode='classification'):
"""
2-D implementation of the AlexNet deep lea... | 5,300,094 |
def pretty_event_latex(event: EventType, nonexisting: str = r'\varnothing') -> str:
"""
Takes an event type an prettifies it.
:param event: event type to prettify
:param nonexisting: string to represent non-existing nodes
:return: prettified event type as string \makebox[\elen][c]{{{}}}
"""
... | 5,300,095 |
def hex_16bit(value):
"""Converts 16bit value into bytearray.
args:
16bit value
returns:
bytearray of size 2
"""
if value > 0xffff or value < 0:
raise Exception('Sar file 16bit value %s out of range' % value)
return value.to_bytes(2, 'little') | 5,300,096 |
def comp_subclusters_params_min_dist(codes_k, mu_sub_1, mu_sub_2):
"""
Comp assignments to subclusters by min dist to subclusters centers
codes_k (torch.tensor): the datapoints assigned to the k-th cluster
mu_sub_1, mu_sub_2 (torch.tensor, torch.tensor): the centroids of the first and second subclusters... | 5,300,097 |
def test_create_boardgroup() -> None:
"""Test that we can create a board group of testing boards."""
board_group = BoardGroup[MockBoard, NoBoardMockBackend](NoBoardMockBackend)
assert type(board_group) == BoardGroup | 5,300,098 |
def test_sun_pos(jd, r_true, tol):
"""
test solar position vector in ECEF coordinates
"""
r = _solar.sun_pos(jd)
r_expected = np.asarray(r_true)
rel = norm(r - r_expected) / norm(r_expected)
assert rel < tol | 5,300,099 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.