content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def get_answers(request):
"""
Function to gather the form's input values by name: 'choice'
"""
submitted_answers = []
for key in request.POST:
if key.startswith('choice'):
value = request.POST[key]
choice_id = int(value)
submitted_answers.append(choice_id... | f9b3866f7a5af6f7abf51f6a075a4d7388ba7b86 | 675,883 |
def calculate_resize_scale(oringin_image_size, cluster_image_size):
"""
:param oringin_image_size: 图像原本的尺度 (h, w)
:param cluster_image_size: 在所需要训练的尺度下图像的大小 (h, w)
:return: scale 返回需要转换为cluster_image_size需要变换的尺度
"""
o_h, o_w = oringin_image_size
h, w = cluster_image_size
return min(h/o_h... | bbb2bc9abc43b89f1acbf3aa1ac8a1b8d1604c9e | 675,884 |
def precision(c, tweets):
"""Computes precision for class `c` on the specified test data."""
tp = 0
fp = 0
for tweet in tweets:
if c in tweet['predictions']:
if c in tweet['tags']:
tp+=1
else:
fp+=1
if(tp+fp == 0):
return floa... | d5012859f14e114258d05552cc0edac2af998f3f | 675,885 |
def getBondedNeighborLists(atoms, bondProxies):
"""
Helper function to produce a dictionary of lists that contain all bonded
neighbors for each atom in a set of atoms.
:param atoms: Flex array of atoms (could be obtained using model.get_atoms() if there
are no chains with multiple conformations, must ... | cbf2250642cf388c37645fee936306867acf737e | 675,886 |
def format_fasta(title, sequence):
"""
This formats a fasta sequence
Input:
title - String - Title of the sequence
sequence - String - Actual sequence
Output:
String - Fully formatted fasta sequence
"""
fasta_width = 70 # Number of characters in one line
n_lines = 1 + le... | 3c6ac0f1472aa3a8409c9f9c36978eb329491fab | 675,888 |
def list_find(list1, list2):
"""在list1中寻找子串list2,如果找到,返回第一个下标;
如果找不到,返回-1。
"""
n_list2 = len(list2)
for i in range(len(list1)):
if list1[i: i+n_list2] == list2:
return i
return -1 | fa6e6ae340f49e81c957643db42d7ebfe54c2b5a | 675,889 |
def getLocalhostName():
"""What is my name?"""
return str(u'Pocket') | 32189ae1ea280213778a8838ee07ea18e629ecca | 675,890 |
def get_str_bytes_length(value: str) -> int:
"""
- source: https://stackoverflow.com/a/30686735/8445442
"""
return len(value.encode("utf-8")) | b855c9bad2b32b3943d6b59c086e19d40b259a1e | 675,891 |
def site_root_site_traverser(context):
"""Site root ++etc++site traverser extension"""
return context.getSiteManager() | f80a50741244096f0e344766f961d645b0452dc1 | 675,892 |
def authorize_security_group_ingress(ec2_c, sg_id, port):
""" Alows us to open a TCP port. """
try:
ec2_c.authorize_security_group_ingress(
GroupId=sg_id.id,
IpPermissions=[{
'IpProtocol': 'tcp',
'FromPort': int(port),
'ToPort': int... | e172612a1edf1755465a1e085c5480dfb1f4c7a0 | 675,894 |
def add_mutator_group(argparser, name):
"""Add a new argument group for a mutator group"""
return argparser.add_argument_group('{} mutator arguments'.format(name), help_name = name, help_group = 'mutator help', help_text = 'show help for {} mutators') | d26131aaae478060b825c7e0adc56d054dc1e725 | 675,896 |
def vecBetweenBoxes(obj1, obj2):
"""A distance function between two TextBoxes.
Consider the bounding rectangle for obj1 and obj2.
Return vector between 2 boxes boundaries if they don't overlap, otherwise returns vector betweeen boxes centers
+------+..........+ (x1, y1)
| obj1 | ... | e6f794ff14625072f83442b8557ee29eb2981601 | 675,897 |
def ccd_quad_to_rc(ccd: int, quad: int) -> int:
"""Convert ZTF CCD/QUADRANT to readout channel number
:param ccd:
:param quad:
:return:
"""
if ccd not in range(1, 17):
raise ValueError("Bad CCD number")
if quad not in range(1, 5):
raise ValueError("Bad QUADRANT number")
... | 3025f6677e04b20c13790372d89fb2496257d64b | 675,898 |
def delete_cluster(redshift, DWH_CLUSTER_IDENTIFIER):
"""
Request a deletion for Redshift cluster
@type redshift --
@param redshift -- Redshift resource client
@type DWH_CLUSTER_IDENTIFIER -- string
@param DWH_CLUSTER_IDENTIFIER -- value from config file
@return -- None
"""
return ... | 6587ac7107d76b53fef81659d90cef6a49ed6c83 | 675,899 |
def clip(string: str, length: int, suffix = "...") -> str:
"""Clip string to max length
If input `string` has less than `length` characters, then return the original string.
If `length` is less than the number of charecters in `suffix`, then return `string`
truncated to `length`.
Oth... | 52522785fea0d52c706f202d0b521b66401b2651 | 675,900 |
import json
def create_chat_config_file(path: str):
"""Функция "create_config_file" - создает новый конфиг."""
data = {
'chats': [{}]
}
with open(path, 'w', encoding='utf-8') as new_config:
json.dump(data, new_config, indent=4)
return data | 61eb22620cba24ba0983fa182fdf2c01a1053b81 | 675,901 |
def args_trans(args):
"""Parameters transform that must be specified."""
params = {}
#################################################################
params["eta"] = args["eta"] * 0.01 + 0.01
params["nrounds"] = args["nrounds"] * 10 + 80
params['max_depth'] = 2 + args["max_depth"]
params[... | 5f9bc2d2c9447bbfb0dad7a35769ca4d033f8e60 | 675,902 |
def normalize(string):
"""Returns a string without outer quotes or whitespace."""
return string.strip("'\" ") | a8f716f259175ac7ba2e5a5c004cfd95f4410302 | 675,903 |
import ast
def is_ast_equal(node_a: ast.AST, node_b: ast.AST) -> bool:
"""
Compare two ast tree using ast dump
"""
return ast.dump(node_a) == ast.dump(node_b) | 0a1866e72f454af6d4429ea8cd68b3cb087aeab7 | 675,904 |
def decode_text_field(buf):
"""
Convert char[] string in buffer to python str object
:param buf: bytearray with array of chars
:return: string
"""
return buf.decode().strip(b'\x00'.decode()) | d144000057830fa62a6a28caa0f1d61e410e02ba | 675,905 |
def is_prime(number):
"""Check if a number is prime."""
if number < 2:
return False
if number == 2:
return True
if number % 2 == 0:
return False
for _ in range(3, int(number ** 0.5) + 1, 2):
if number % _ == 0:
return False
return True | b37c84314d45abd5a2a4105d2c93d4fdd0b8e722 | 675,906 |
import torch
def subtract_pose(pose_a, pose_b):
"""
Compute pose of pose_b in the egocentric coordinate frame of pose_a.
Inputs:
pose_a - (bs, 3) --- (x, y, theta)
pose_b - (bs, 3) --- (x, y, theta)
Conventions:
The origin is at the center of the map.
X is upward with ... | c6c759297a6cef19349a19abc1dd598cc5ba0a9b | 675,907 |
from pathlib import Path
import os
def convert_to_svg(dvi_file, extension, page=1):
"""Converts a .dvi, .xdv, or .pdf file into an svg using dvisvgm.
Parameters
----------
dvi_file : :class:`str`
File name of the input file to be converted.
extension : :class:`str`
String containi... | 93836243246dd204027856ad418c1c8c116513fe | 675,909 |
from pathlib import Path
def setup(opts):
"""Set up directory for this GenomeHubs instance and handle reset."""
Path(opts["hub-path"]).mkdir(parents=True, exist_ok=True)
return True | ce0c1e6dfb378a313dc4ac8630099ff1e9fcfdd0 | 675,910 |
def accuracy(true_positives, true_negatives, false_positives, false_negatives, description=None):
"""Returns the accuracy, calculated as:
(true_positives+true_negatives)/(true_positives+false_positives+true_negatives+false_negatives)
"""
true_positives = float(true_positives)
true_... | 99a1a8d7a1b59c3f72b711aeb733ea6f32c9c3f2 | 675,911 |
def effective_stiffness(mass_eff, t_eff):
"""
Calculates the effective period based on the mass and period
:param mass_eff: effective mass
:param t_eff: effective period
:return:
"""
return (4 * 3.141 ** 2 * mass_eff) / t_eff ** 2 | 415726bbfe5c305e3fffd0dcd7864ba406cf681f | 675,912 |
import argparse
def get_args():
"""" collects command line arguments """
argparser = argparse.ArgumentParser(description=__doc__)
argparser.add_argument('--config', default=None, type=str, help='configuration file')
argparser.add_argument('--exp_name', default=None, ... | f7f642a12e09b671a1ba1b959ad62efc06b95ccc | 675,913 |
def rate_color(rate: int, units: str = '') -> str:
"""
Get color schema for percentage value.
Color schema looks like red-yellow-green scale for values 0-50-100.
"""
color = '[red]'
if 30 > rate > 20:
color = '[orange_red1]'
if 50 > rate > 30:
color = '[dark_orange]'
if 7... | 0dd1174c9c5d333cad44c5892a8dd32cb6239176 | 675,914 |
def get_gcharts_column_data(data, data_label, data_color, data_annotation):
""" Get data for the column chart """
return_data = ''
j = len(data)-1
i = 0
while i <= j:
return_data = return_data +\
'["'+ str(data_label[i]) +'", '+\
str(data[i]) +', "'+\
str(data_color[i... | bf4fdc278fca29d32917de2c9b651165422d3993 | 675,915 |
import time
def get_duration_timestamp(day=7):
"""
获取当前时间和7天前的时间戳
:param day:
:return:
"""
# 当前时间对应的时间戳
end = int(round(time.time() * 1000))
# 7天前的时间戳
start = end - day * 24 * 60 * 60 * 1000
return start, end | 034bd89e9d70b9804c14073ec109d07a6fa2ebb1 | 675,916 |
import os
def get_log_level():
"""
This function gets the LogLevel from the environment variables table.
"""
return os.environ.get('LOG_LEVEL', 'INFO') | fee1d03e344991a853d790e1fbb9e7d601cd49f7 | 675,917 |
def _match_cookie(flow_to_install, stored_flow_dict):
"""Check if a the cookie and its mask matches between the flows."""
cookie = flow_to_install.get("cookie", 0) & flow_to_install.get("cookie_mask", 0)
cookie_stored = stored_flow_dict.get("cookie", 0) & flow_to_install.get(
"cookie_mask", 0
)
... | 2d52de71f11b4e3d50756999c16290eb5f2eba9b | 675,918 |
def pass_through_filter(cloud, filter_axis='z', axis_limit=(0.6, 1.1)):
"""
Cut off filter
Params:
cloud: pcl.PCLPointCloud2
filter_axis: 'z'|'y'|'x' axis
axis_limit: range
Returns:
filtered cloud: pcl.PCLPointCloud2
"""
# Create a PassThrough filter object.
... | 0dacdb13d0b47ff80e61f2b8f25549472ce98c92 | 675,919 |
def clean_text_up(text: str) -> str:
""" Remove duplicate spaces from str and strip it. """
return ' '.join(text.split()).strip() | 04799b0c22b48b118fdf14efd7b58971eaf35885 | 675,921 |
import argparse
def parse_args():
""" Parses command line arguments.
"""
parser = argparse.ArgumentParser()
parser.add_argument('--n', dest='pkg_name',
action='store', required=True,
help="Name of the package.")
parser.add_argument('--l', dest='pkg_loc', default='',
ac... | b6f3df56457ac2efb4f4407e6372874f9bf0a671 | 675,922 |
import os
def get_files_in_directory(path, absolute, recursive=True):
"""Read a directory and return a list of filenames
Parameters
----------
directory: `path`
directory path
absolute: `bool`
True if absolute file path is desired
recursive: `bool`
... | da8e9d671a364be4e0a03851114186707f241982 | 675,924 |
def pitremove(np, input, output):
""" command: pitremove -z dem.tif -fel demfel.tif, demfile: input elevation grid, felfile: output elevations with pits filled """
pitremove = "mpirun -np {} pitremove -z {} -fel {}".format(
np, input, output)
return pitremove | 3430d76cc545b54257b1c2d21d456d4bb29f955f | 675,925 |
def case_convert(snakecase_string: str) -> str:
"""Converts snake case string to pascal string
Args:
snakecase_string (str): snakecase string
Returns:
str: Pascal string
"""
return snakecase_string.replace("_", " ").title().replace("Cnn", "CNN") | 40b79d4455406c8a3c8bc9324b3b42abf32cf754 | 675,927 |
import asyncio
def get_running_loop():
"""get_running_loop that supports Python 3.6."""
if hasattr(asyncio, "get_running_loop"):
return asyncio.get_running_loop()
else:
return asyncio.get_event_loop() | cc1cd28bb46889180c2e579a5f8116397e876894 | 675,928 |
def current_ratio(current_assets, current_liabilities, inventory = 0):
"""Computes current ratio.
Parameters
----------
current_assets : int or float
Current assets
current_liabilities : int or float
Current liabilities
inventory: int or float
Inventory
Returns
... | 716ef196df285c6dda2b369b5db24a6bc350ad3a | 675,929 |
def format_string(input):
""" Remove whitespaces and xml annotations """
# Remove xml annotation from input_format
input = input.replace('xsd:', '')
# Replace whitespaces with spaces
input = " ".join(input.split())
# Strip the output
return input.strip() | 9e8b3668b122156128d76c26b6d1ce05bbf10338 | 675,930 |
def ci(_tuple):
""" Combine indices """
return "-".join([str(i) for i in _tuple]) | 4f3f66731bea3d9cde0ec085dce0ccbe66438a23 | 675,931 |
def base_point_finder(line1, line2, y=720):
"""
This function calculates the base point of the suggested path by averaging the x coordinates of both detected
lines at the highest y value.
:param line1: Coefficients of equation of first line in standard form as a tuple.
:param line2: Coefficients of ... | c2a7b198f1e76739391efc8fadf00c98c20dcfc0 | 675,932 |
def expand_var(v, env):
""" If v is a variable reference (for example: '$myvar'), replace it using the supplied
env dictionary.
Args:
v: the variable to replace if needed.
env: user supplied dictionary.
Raises:
Exception if v is a variable reference but it is not found in env.
"""
if len(v... | eeeb8ef250cc1fc5f9829f91b3dc0290b6c6fb83 | 675,934 |
from typing import List
def is_primary_stressed(syllable: List[str]) -> bool:
"""
Checks if a syllables is primary stressed or not.
:param syllable: represented as a list of phonemes
:return: True or False
"""
return True if any(phoneme.endswith('1') for phoneme in syllable) else False | 054b85a49a2f4ddc426ce074314be4d319853002 | 675,936 |
def count_bad_pixels_per_block(x, y, bad_bins_x, bad_bins_y):
"""
Calculate number of "bad" pixels per rectangular block of a contact map
"Bad" pixels are inferred from the balancing weight column `weight_name` or
provided directly in the form of an array `bad_bins`.
Setting `weight_name` and `bad... | 33668d6d1efc16a436560171f54647f8e01c2040 | 675,937 |
def merge_regions_and_departments(regions, departments):
"""Merge regions and departments in one DataFrame.
The columns in the final DataFrame should be:
['code_reg', 'name_reg', 'code_dep', 'name_dep']
"""
columns = ['code_reg',
'name_reg',
'code_dep',
... | b1731a89bb97ddb0a5f60a04e815d0d83e13f5e9 | 675,938 |
def confusion_matrix(simple, pred):
"""混淆矩阵
:param simple:实际样本分类列表
:param pred:预测样本分类列表
:return TP,TN,FP,FN
"""
tp, tn, fp, fn = 0, 0, 0, 0
for s, p in zip(simple, pred):
if s == p == 1: # 将正类预测为正类数
tp += 1
elif s == p == 0: # 将负类预测为负类数
tn += 1
... | 7de071b3d5866708e49eb98de2383a55a2edb093 | 675,939 |
import warnings
def precise_reconciliation_efficiency(r, i, h, q, p, d):
"""
Identifies the reconciliation efficiency to be used with extremely high precision under a given set of parameters.
:param r: The code rate.
:param i: The estimated mutual information.
:param h: The estimated entropy.
... | 0d471524ecc169be6ad75ef17ec986145e42b3a5 | 675,940 |
import re
def _not_none_and_len(string: str) -> bool:
"""helper to figure out if not none and string is populated"""
is_str = isinstance(string, str)
has_len = False if re.match(r"\S{5,}", "") is None else True
status = True if has_len and is_str else False
return status | 282ad8e4f0dc66447e47f827f2400694aa761daf | 675,941 |
def ms_attacks(exploit):
""" Receives the input given by the user from create_payload.py """
return {
'1': "dll_hijacking",
'2': "unc_embed",
'3': "exploit/windows/fileformat/ms15_100_mcl_exe",
'4': "exploit/windows/fileformat/ms14_017_rtf",
'5': "exploit/windows/filefor... | 7c57fbd0ee2145ad8b53250f4fdda3c469823467 | 675,942 |
def get_latest_year_term(year_term_list):
"""
Args:
year_term_list -> List[(year: int, term: int)]
Return:
year_term -> (year: int, term: int)
"""
if len(year_term_list) == 0:
raise Exception("get_latest_year_term() error: データが空です")
year_term_list.sort(reverse=True)
... | adae6b5be0ae7e8d15fc31e30e635a240b516a62 | 675,943 |
def scale_to_255(image_array):
"""Default normalizing functor to scale image to [0, 255]"""
a_min = min(image_array.min(), 0)
a_max = image_array.max()
image_array = (image_array - a_min)/ (a_max - a_min) * 255
return image_array | b4bd4b0c98c77ce2b419e399b1e00f181d008621 | 675,944 |
def xnnpack_min_size_copts():
"""Compiler flags for size-optimized builds."""
return ["-Os"] | 6769f56258362924de7a56c691049d83f67ac4ad | 675,945 |
import io
def csv_parseln(
p_line,
delim=',',
quote='\"',
esc='\\'):
"""
Given a sample CSV line, this function will parse the line into
a list of cells representing that CSV row. If the given `p_line`
contains newline characters, only the content present before
the first newline character is parsed.
... | b1aefa153c33788435513e32052b0c9a765e4cf3 | 675,946 |
def get_area_of_rural_land_occupied_by_houses_2013():
"""
Reported area of urban land occupied by houses in 2013 from the USDA ERS Major Land Uses Report
:return:
"""
acres_to_sq_m_conversion = 4046.86
# value originally reported in million acres
area_rural_residence = 106.3
# convert ... | 2343c974ee692db5402184be04dee9e8b1dccfd5 | 675,947 |
import torch
def signed_volume(local_coords):
"""
Compute signed volume given ordered neighbor local coordinates
:param local_coords: (n_tetrahedral_chiral_centers, 4, n_generated_confs, 3)
:return: signed volume of each tetrahedral center (n_tetrahedral_chiral_centers, n_generated_confs)
"""
... | b00b02ee14b87dcc88057a130a3703498c87692b | 675,948 |
def es_document(idx, typ, id, field):
"""Returns a handle on a field in a document living in the ES store.
This does not fetch the document, or even check that it exists.
"""
# Returns a dict instead of a custom object to ensure JSON serialization
# works.
return {'index': idx, 'type': typ, 'id... | 4f41e3c82defa062faa669f9151881a381158825 | 675,949 |
import os
def dir_checker(aurox_dir_path):
"""
Checks to make sure there is a positions.csv file as well as more than
one .tiff file available in the directory. If so it sees this as an
image directory and returns True.
"""
value1 = 0
value2 = 0
for file in os.listdir(aur... | 76f1785f925b918728da5451ca55800d13a45861 | 675,950 |
def rechunk_da(da, sample_chunks):
"""
Args:
da: xarray DataArray
sample_chunks: Chunk size in sample dimensions
Returns:
da: xarray DataArray rechunked
"""
lev_str = [s for s in list(da.coords) if 'lev' in s][0]
return da.chunk({'sample': sample_chunks, lev_str: da.coo... | 5818863205c2d5cf468426fe1678bd8f95fce12b | 675,951 |
from typing import List
def denormalize_identity(texts: List[str], verbose=False) -> List[str]:
"""
Identity function. Returns input unchanged
Args:
texts: input strings
Returns input strings
"""
return texts | 21dca95b74832c4afca2fcaa5e0cd2a750b352fd | 675,952 |
def format_access_token(access_token):
"""Display all the parameters of the Access Token"""
print(access_token)
ret = '<h2>Access Token</h2>'
ret += '<table class="pure-table">'
if access_token.error_code != None:
ret += '<tr><td>Error Code</td><td>' + str(access_token.error_code) + '</td... | eda14715305b8228901259c0f43de6e76454ca8d | 675,954 |
import math
def calculate_fuel_requirement_plus(fuel):
"""Calculates the fuel requirement
based on the given fuel mass. (Part 2)
Parameters:
fuel (int): mass of the fuel
Returns:
int:Additional fuel required
"""
add = math.floor(fuel / 3) - 2
if add > 0:
return add + ca... | 602df3358a1315f683483e2268ce2c7513a3dcde | 675,955 |
def get_data_root(registry):
"""
:type registry: pyramid.registry.Registry
:rtype: Path
"""
return registry.data_root | 7dfdbd7023c92567446702638dcbe2d879204c1f | 675,957 |
def get_secret(client, mount, path):
""" retreiive existing data from mount path and return dictionary """
result = {'data': {}}
try:
if client.secrets.kv.default_kv_version == '1':
result = client.secrets.kv.v1.read_secret(path=path, mount_point=mount)
else:
result =... | 62e3032b6530895d1bd16ecba3d50f07f22ffe33 | 675,958 |
def assumed_metric(y_true, y_pred, metric, assume_unlabeled=0, **kwargs):
"""
This will wrap a metric so that you can pass it in and it will compute it on labeled
and unlabeled instances converting unlabeled to assume_unlabeled
Assumption: label -1 == unlabled, 0 == negative, 1 == positive
"""
... | 96451aa28d87880dc291c32d8ac8f52310755562 | 675,959 |
from typing import List
import os
def get_previously_completed_dates() -> List[str]:
"""Get a list of dates the tool has already imported time entry. Used to avoid duplication of time entry."""
if not os.path.exists('completed_dates.txt'):
return []
with open('completed_dates.txt', 'r') as file:
... | fcb4863a455adaa505f42aa901a6c01b25d9230e | 675,960 |
def _add_multiple_locations(row):
"""A function to add the victim types. To be used with
pandas.DataFrame.apply()."""
if ';' in row['LOCATION_NAME']:
row['MULTIPLE_LOCATION_NAME'] = 'M'
else:
row['MULTIPLE_LOCATION_NAME'] = 'S'
return row | 856894188bc0f0002afd0970b66ba13ec396be03 | 675,962 |
def _HELP_convert_RMSD_nm2angstrom(RMSD_nm):
"""
Helpfunction for plot_HEATMAP_REX_RMSD():
convert RMSD values: RMSD_nm -> RMSD_anstrom
Args:
RMSD_nm (list): rmsd values in nm
Returns:
RMSD (list)
rmsd values in angstrom
"""
RMSD = [x*10 for x in RMSD_nm]
re... | 12c564378f92b571059763c325fe52e82d53b4c1 | 675,964 |
from pathlib import Path
import json
def read_features(corpus_folder):
"""Read the dictionary of each poem in "corpus_folder" and
return the list of python dictionaries
:param corpus_folder: Local folder where the corpus is located
:return: List of python dictionaries with the poems features
"""
... | 2c156317b649ab5c952c47e84e81e4686c63a9e1 | 675,965 |
def test_unlimited(x, expected):
"""Tests that check_args does nothing"""
def unlimited(x):
for i in list(range(10 ** 8)):
_ = 1 + 1
return x
assert unlimited(x) == expected | fffecae1fdecd36ce4ee1d36034058e2c5b1086a | 675,967 |
def static_vars(**kwargs):
"""
Attach static variables to a function.
Usage:
@static_vars(k1=v1, k2=k2, ...)
def myfunc(...):
myfunc.k1...
Parameters:
**kwargs Keyword=value pairs converted to static variables in decorated
function.
Returns:
decorate
"""
def decor... | ee6690d76ca21efd682ef2ade0aa8b8046ec6a51 | 675,968 |
import argparse
import os
def parse_args():
"""Load SageMaker training job (hyper)-parameters from CLI and environment variables"""
parser = argparse.ArgumentParser()
# Training procedure parameters:
parser.add_argument(
"--batch-size",
type=int,
default=64,
metavar="N... | a97e460a8a640045face2bd71eb416e4199ed67a | 675,970 |
import uuid
def random_suffix() -> str:
"""랜덤 ID뒤에 붙일 UUID 기반의 6자리 임의의 ID를 생성합니다."""
return uuid.uuid4().hex[:6] | 74dd00f928c3b35947f7fb9c46fb1c12100056b7 | 675,971 |
def header_types():
"""
Just returns all the headers we need to test
"""
return [
"content-length",
"content-encoding",
"accept-ranges",
"vary",
"connection",
"via",
"cache-control",
"date",
"content-type",
"age",
] | 982fac438b76ef080c0257672ab7d6f7f8d23b93 | 675,972 |
def parse_slack_output(slack_rtm_output):
"""
The Slack Real Time Messaging API is an events firehose.
this parsing function returns None unless a message
starts with ?.
"""
output_list = slack_rtm_output
if output_list and len(output_list) > 0:
for output in output_list... | e6d8596a38d9ee1d9191cc1c019b94287fefb17d | 675,973 |
def flatten(iter_of_iters):
"""
Flatten an iterator of iterators into a single, long iterator, exhausting
each subiterator in turn.
>>> flatten([[1, 2], [3, 4]])
[1, 2, 3, 4]
"""
retval = []
for val in iter_of_iters:
retval.extend(val)
return retval | 0a2132fc2c9e1dc1aef6268412a44de699e05a99 | 675,974 |
def select_per_taxon_stats(cxn, iteration):
"""Get data for the per taxon summary report."""
return cxn.execute(
"""
WITH
properties AS (
SELECT taxon_name, ref_name,
CAST(SUM(LENGTH(seq)) / 3 AS REAL)
/ CAST(LENGTH(ref_seq) AS REAL) AS p... | 322f653d23099c1b3faa10f627a25648a2b2bb1d | 675,975 |
def is_number(s):
"""
Checks if the variable is a number.
:param s: the variable
:return: True if it is, otherwise False
"""
try:
# Don't need to check for int, if it can pass as a float then it's a number
float(s)
return True
except ValueError:
return False | 2d3fa464246833041ac5018afe23f9fbec2989e1 | 675,976 |
def mock_debian(tmpdir):
"""A fake Debian multi-install system"""
tmpdir.ensure("share/gdal/1.11/header.dxf")
tmpdir.ensure("share/gdal/2.0/header.dxf")
tmpdir.ensure("share/gdal/2.1/header.dxf")
tmpdir.ensure("share/gdal/2.2/header.dxf")
tmpdir.ensure("share/gdal/2.3/header.dxf")
tmpdir.ens... | dfb67e3a0a5ca3ad2ff762df91bc65a13ff043f2 | 675,977 |
def get_info(els):
"""Function: get_info
Description: Return a dictionary of a basic Elasticsearch info command.
Arguments:
(input) els -> ElasticSearch instance.
(output) Dictionary of basic Elasticsearch info command.
"""
return els.info() | 0dc173e985ba77a8cfab925e70e28231a18dc357 | 675,978 |
def cronify(string):
"""Prepare normal commands for cron"""
return string.replace('%', '\%') | 3053f18df6f671d49f77cc906c54371a8d8c416d | 675,979 |
import math
def cond_loglik_bpd(model, x, context):
"""Compute the log-likelihood in bits per dim."""
return - model.log_prob(x, context).sum() / (math.log(2) * x.shape.numel()) | 26e1dc0e525b76fc402a5b70ebf02f9547673278 | 675,980 |
import threading
def create_thread(func, args):
"""Creates a thread with specified function and arguments"""
thread = threading.Thread(target=func, args=args)
thread.start()
return thread | 08244612bd467d0d8b8217e07705d9c41670cd4a | 675,981 |
def calculate_stretch_factor(array_length_samples, overlap_ms, sr):
"""Determine stretch factor to add `overlap_ms` to length of signal."""
length_ms = array_length_samples / sr * 1000
return (length_ms + overlap_ms) / length_ms | 66c3b5fadf7998b6ecbd58761242ec4c253fd2f5 | 675,982 |
def half_adder(a, b):
"""
ha_carry_out, ha_sum = a + b
"""
ha_sum = a ^ b
ha_carry_out = a & b
return ha_sum, ha_carry_out | 4a33b2091c4de22da99ccd026666d3a33d7ae247 | 675,983 |
import random
def SamplesWithReplacement(t, n):
"""
有放回抽样
"""
sample = [ random.choice(t) for i in range(n) ]
return sample | 2353cb28454970d3c868018be86b228919252a10 | 675,984 |
def nothing(text: str, expression: str) -> bool: # pylint: disable=unused-argument
"""Always returns False"""
return False | dccfbed553f8178469c2920b09c916c90127e57f | 675,985 |
from win32com.client import Dispatch # Import library only if function is called
def j2000_to_jnow_novas(ra_j2000_hours, dec_j2000_degs):
"""
Given J2000 coordinates (ra in hours, dec in degrees),
return Jnow coordinates as a tuple:
(ra_hours, dec_degs)
Uses the NOVAS library to do the calc... | 9bb42f8ed69e991f855871f1f19554c7464ba2f9 | 675,987 |
def create_security_group(conn, secgrp_name, project_id_in):
""" create a security group from a name """
os_security_group = conn.network.create_security_group(
name = secgrp_name,
description = "S3P secgrp: Allow ICMP + SSH",
project_id = project_id_in
)
retu... | 7b48d90e7cc7c1750e85e0865e920ddd52e3cae7 | 675,988 |
import requests
def read_build_cause(job_url, build_id):
"""Read cause why the e2e job has been started."""
api_query = job_url + "/" + str(build_id) + "/api/json"
response = requests.get(api_query)
actions = response.json()["actions"]
cause = None
for action in actions:
if "_class" i... | 80c3aafc29ae9eed1a7e4165962c4a50281779dd | 675,989 |
import enum
def default_serializer(o):
"""JSON serializer for complex objects."""
if isinstance(o, enum.Enum):
return o.value
return o.__dict__ | 1853a77ea791200284cd268b989facf166adc772 | 675,992 |
import re
def version_tuple_from_str(version, nelem=None):
"""Split a version string using '.' and '-' as separators and return a tuple of integers."""
re_match = re.match(r'([0-9.,_-]+\d+)|(\d+)', version)
if re_match:
version_list = re.split('[.,_-]', re_match.group(0))
if nelem is not N... | a1bd85afc688da129c4bf326e278e6ba5b352c88 | 675,993 |
import re
def to_valid_filename(filename: str) -> str:
"""Given any string, return a valid filename.
For this purpose, filenames are expected to be all lower-cased,
and we err on the side of being more restrictive with allowed characters,
including not allowing space.
Args:
filename (str... | e3fa7a84c4ed8c57042d3c2564c064380e6d2abd | 675,995 |
import subprocess
def annotate_frame(data):
"""
Annotate frames with convert from imagemagick
Parameters
----------
data: Tuple(int, list, float)
frame number, frame_data, time step (ns)
"""
frame, frame_data, timestep = data
in_path, out_path, font, font_size, line_width, ax... | 93887de76a5fd0adf8ea186ac4f83170e1b2277a | 675,996 |
def collapse_sided_value(value):
"""Inverses `expand_sided_value`, returning
the most optimal form of four-sided value.
"""
if not isinstance(value, (tuple, list)):
return value
elif len(value) == 1:
return value[0]
elif len(value) == 2:
if value[0] == value[1]:
return value[0]
else:
... | c725e84a5e282869fc76646b82502e6c6b580da8 | 675,997 |
def shapes(tensors):
"""Get the static shapes of tensors in a list.
Arguments:
tensors: an iterable of `tf.Tensor`.
Returns:
a `list` of `tf.TensorShape`, one for each tensor in `tensors`,
representing their static shape (via `tf.Tensor.get_shape()`).
"""
return [t.get_shape() ... | d5958286782a3ce73621831e5b69d205feeb74d8 | 675,998 |
import functools
def yield_for_change(widget, attribute):
"""Pause a generator to wait for a widget change event.
This is a decorator for a generator function which pauses the generator on yield
until the given widget attribute changes. The new value of the attribute is
sent to the generator and is t... | 85b98db161e94316a286d54cc8df7a5baace7bac | 675,999 |
def get_4d_idx(day):
"""
A small utility function for indexing into a 4D dataset
represented as a 3D dataset.
[month, level, y, x], where level contains 37 levels, and day
contains 28, 29, 30 or 31 days.
"""
start = 1 + 37 * (day - 1)
stop = start + 37
return list(range(start, stop, ... | 7434d734e106ceb32a6ac4c0fc13800ef0245df9 | 676,000 |
def cookielaw(request):
"""Add cookielaw context variable to the context."""
cookie = request.COOKIES.get('cookielaw_accepted')
return {
'cookielaw': {
'notset': cookie is None,
'accepted': cookie == '1',
'rejected': cookie == '0',
}
} | 22f72b6399389b43b1093543e6f65e0c804d7144 | 676,001 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.