content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def similarity(item, user, sim_dict):
"""
similarity between an item and a user (a set of items)
"""
if user not in sim_dict or item not in sim_dict[user]:
return 0
else:
return sim_dict[user][item] | e63eec781f7ed9fa72d21d1119daf9ce89d39b1b | 4,400 |
import requests
def get_totalt_result(req_url):
"""[summary]
This gets all the results in INT from the specified query
Args:
req_url ([STR]): [The request query that decides the data]
"""
r = requests.get(req_url, headers=headers)
json = r.json()
return json['result']['totalHits'] | 8c6ff54fbb285fc765afd8bb5e5ba3195ec624d0 | 4,401 |
def lorentz(x, FWHM, x0=0):
"""
Returns Lorentzian lineshape.
"""
return FWHM/2/np.pi*((x-x0)**2+(FWHM/2)**2)**-1 | 92c21b7b99b600b2dc622d2ea09b0bd3e39f8047 | 4,402 |
def count_collision(strMap: list[str], right: int, down: int) -> int:
"""Read the map and count how many tree would be encountered if someone start from the top left corner"""
mapWidth = len(strMap[0]) # All lines are assumed to have same width
xCoord, yCoord = right % mapWidth, down
count = 0
whi... | b233224a407493757ba7976ede22499b21afe068 | 4,403 |
def svn_config_find_group(*args):
"""svn_config_find_group(svn_config_t cfg, char key, char master_section, apr_pool_t pool) -> char"""
return _core.svn_config_find_group(*args) | 3974798a82f2dfb77957e8de1c4814725d82c3a9 | 4,404 |
def _database_exists():
"""Checks for existence of database"""
_require_environment()
database = _get_database_name()
with settings(hide('warnings'), warn_only=True):
result = run(MYSQL_PREFIX % "\"SHOW DATABASES LIKE '%(NAME)s';\"" % database)
if database['NAME'] in result:
... | 94cbffb4d7e62d6c9fcae7d0966c6d595ddf7907 | 4,405 |
def EncoderDecoder(d_model, d_ff, n_heads, dropout, layer_idx, mode,
ff_activation):
"""Transformer encoder-decoder layer.
The input is a triple (decoder_input, mask, encoder) where the mask is
created from the original source to prevent attending to the padding part
of the encoder.
Args:... | 8dd8032d2b0b270f49f21adedb22474565827801 | 4,406 |
from operator import concat
def group_normalize(strokes):
""" normilize a multistroke drawing """
long_stroke = concat(strokes)
x_min = min(long_stroke.x)
x_max = max(long_stroke.x)
y_min = min(long_stroke.y)
y_max = max(long_stroke.y)
x_range = float(x_max-x_min)
y_range = float(y_ma... | ec7a44573b2334b69d3d878bd381a0ced1fdd304 | 4,407 |
def _get_sa_bracket(myimt, saset):
"""
For a given SA IMT, look through the input SAs and return a tuple of
a) a pair of IMT strings representing the periods bracketing the given
period; or c) the single IMT representing the first or last period in
the input list if the given period is off the end o... | 2588fb1a45a008ec81770f69b5f6ee815f1f2511 | 4,408 |
def fb83(A, B, eta=1., nu=None):
"""
Generates the FB8 distribution using the orthogonal vectors A and B
where A = gamma1*kappa and B = gamma2*beta (gamma3 is inferred)
A may have not have length zero but may be arbitrarily close to zero
B may have length zero however. If so, then an arbitrary value... | 1162c99eb3964512d935db8e5ce19bfc6eb5b391 | 4,409 |
def replicate(pta, ptac, p0, coefficients=False):
"""Create a replicated residuals conditioned on the data.
Here pta is standard marginalized-likelihood PTA, and
ptac is a hierarchical-likelihood version of pta with
coefficients=True for all GPs. This function:
- calls utils.get_coefficients(pta, p... | addab624fb2314a004a7454ca3a3199539baabf9 | 4,410 |
def load_danube() -> pd.DataFrame:
"""
The danube dataset contains ranks of base flow observations from the Global River Discharge
project of the Oak Ridge National Laboratory Distributed Active Archive Center (ORNL DAAC),
a NASA data center. The measurements are monthly average flow rate for two statio... | f1ae04e37e69acf1fa805953f58c96633136be09 | 4,411 |
def get_index(grid_mids, values):
"""get the index of a value in an array
Args:
grid_mids: array of grid centers
value: array of values
Returns:
indices
"""
diff = np.diff(grid_mids)
diff = np.concatenate((diff, diff[-1:]))
edges = np.concatenate((grid_mids-d... | b8277e84ddaae5c951ad032f3a738d1f9c02feac | 4,412 |
def validate_incoming_edges(graphs, param=None):
"""
In case a node of a certain type has more then a threshold of incoming
edges determine a possible stitches as a bad stitch.
"""
param = param or {}
res = {}
i = 0
for candidate in graphs:
res[i] = 'ok'
for node, values ... | 7872ad52c942d986725d7dc1e089ad91850b5c71 | 4,413 |
def face_area(bounding_box, correction):
"""
Increase face area, to square format, face detectors are very close
clipping useless when you want to get whole head
Arguments: bounding box original, correction value
Returns: 4-element list - bounding box for expanded area (ints)
"""
x_1, y_1, ... | b4c47b01989acb706e9c959cd29902b6045a7fad | 4,414 |
def ut_to_dt(ut):
"""Converts a universal time in days to a dynamical time in days."""
# As at July 2020, TAI is 37 sec ahead of UTC, TDT is 32.184 seconds ahead of TAI.
return ut + 69.184/SEC_IN_DAY | 1f9af7758c53d32494013280b401393e5723d358 | 4,415 |
from pathlib import Path
def _read_group_h5(filename: Path, groupname: str) -> ndarray:
"""Return group content.
Args:
filename: path of hdf5 file.
groupname: name of group to read.
Returns:
content of group.
"""
try:
with h5py.File(filename, 'r') as h5f:
... | 3febc0c0322ca9d9a7f30b4d9cf94ce32f5d3109 | 4,416 |
def _clip_bbox(min_y, min_x, max_y, max_x):
"""Clip bounding box coordinates between 0 and 1.
Args:
min_y: Normalized bbox coordinate of type float between 0 and 1.
min_x: Normalized bbox coordinate of type float between 0 and 1.
max_y: Normalized bbox coordinate of type float between 0 and 1.
max_... | bb5b2ed23626e26004ae87bdd7fc03b2d177f38f | 4,417 |
def hot(df, hot_maps, drop_cold=True, ret_hots_only=False, verbose=False):
"""
df: pd.DataFrame
hot_maps: list(dict)
hot_map: dict
key: str column in df
value: one_hot vector for unique row value
---
returns dataframe
"""
if verbose:
print(f"hot_df c... | b0912ae22aa3ee34acde76e89c5f926c9d309492 | 4,418 |
def menu(function_text):
"""
Decorator for plain-text handler
:param function_text: function which set as handle in bot class
:return:
"""
def wrapper(self, bot, update):
self.text_menu(bot, update)
function_text(self, bot, update)
return wrapper | dc68a46aaf402cd5ce3bd832a0f2a661b5cbc71b | 4,419 |
def create_delete_classes(system_id_or_identifier, **kwargs):
"""Create classes for a classification system.
:param system_id_or_identifier: The id or identifier of a classification system
"""
if request.method == "DELETE":
data.delete_classes(system_id_or_identifier)
return {'message'... | 4f48ebb7fe80854d255f47fb795e83b54f9f60b3 | 4,420 |
def ajax_upload_key():
"""Ajax upload a functionary key. Key files are stored to the db in their
dictionary representation. """
functionary_key = request.files.get("functionary_key", None)
functionary_name = request.form.get("functionary_name", None)
if not functionary_name:
flash("Something went wrong: ... | cd5cca4ff1a3283224362ccacab8c20c450eeaf6 | 4,421 |
def add_latents_to_dataset_using_tensors(args, sess, tensors, data):
""" Get latent representations from model.
Args:
args: Arguments from parser in train_grocerystore.py.
sess: Tensorflow session.
tensors: Tensors used for extracting latent representations.
data: Data used... | 550c7c878b43737b5fcabbb007062774f404b0b3 | 4,422 |
def normal_distribution_parameter_estimation(data):
"""
Notice: Unbiased Estimation Adopted. Line 115.
:param data: a list, each element is a real number, the value of some attribute
eg: [0.46, 0.376, 0.264, 0.318, 0.215, 0.237, 0.149, 0.211]
:return miu: the estimation of miu of the normal distri... | ce8ca8010f98fdd2067285fea4779507fe7e958b | 4,423 |
def reverse_complement(seq):
"""
ARGS:
seq : sequence with _only_ A, T, C or G (case sensitive)
RETURN:
rcSeq : reverse complement of sequenced passed to it.
DESCRIPTION:
DEBUG:
Compared several sequences. Is working.
FUTURE:
"""
rcSeq = "" # Re... | a6dee7ccb862e21534fd1736e345438f9df18fac | 4,424 |
def compose(chosung, joongsung, jongsung=u''):
"""This function returns a Hangul letter by composing the specified chosung, joongsung, and jongsung.
@param chosung
@param joongsung
@param jongsung the terminal Hangul letter. This is optional if you do not need a jongsung."""
if jongsung is None... | 047d0cf68a558d795a5bf71b0ebe686a41208af7 | 4,425 |
from typing import Dict
from typing import List
def generate_markdown_metadata(metadata_obj: Dict[str, str]) -> List[str]:
"""generate_markdown_metadata
Add some basic metadata to the top of the file
in HTML tags.
"""
metadata: List[str] = ["<!---"]
passed_metadata: List[str] = [
f"... | 02ef3952c265276f4e666f060be6cb1d4a150cca | 4,426 |
def fftshift(x:np.ndarray):
"""平移FFT频谱
FFT默认频谱不是关于零频率对称的,使用fftshift可以对调左右频谱。
:Parameters:
- x: 频谱序列
:Returns: 平移后的频谱
"""
N = x.size
return np.append(x[N//2:], x[:N//2]) | beaf2dcd0d5c9ff0b9bd83d326b3d3a9f6471968 | 4,427 |
from typing import List
from typing import Tuple
def get_20newsgroups_data(
train_test,
categories=None,
max_text_len: int = None,
min_num_tokens=0,
random_state=42,
) -> List[Tuple[str, str]]:
"""
'alt.atheism',
'comp.graphics',
'comp.os.ms-windows.misc',
'comp.sys.ibm.pc.... | 6053f967ac1fb782cab28fe401e384940703e384 | 4,428 |
def crossdomain(allowed_origins=None, methods=None, headers=None,
max_age=21600, attach_to_all=True,
automatic_options=True, credentials=False):
"""
http://flask.pocoo.org/snippets/56/
"""
if methods is not None:
methods = ', '.join(sorted(x.upper() for x in metho... | 9d352718406f62eaeb184a081b4223b67f6200f3 | 4,429 |
from typing import Callable
def make_vector_gradient(bcs: Boundaries) -> Callable:
""" make a discretized vector gradient operator for a cylindrical grid
|Description_cylindrical|
Args:
bcs (:class:`~pde.grids.boundaries.axes.Boundaries`):
|Arg_boundary_conditions|
R... | 61d4f1a29d4a81e57ad37a6b963e201e5deabc06 | 4,430 |
def exec_in_terminal(command):
"""Run a command in the terminal and get the
output stripping the last newline.
Args:
command: a string or list of strings
"""
return check_output(command).strip().decode("utf8") | 1186649cebbd20559f7de0ba8aa743d70f35c924 | 4,431 |
def replace_string(original, start, end, replacement):
"""Replaces the specified range of |original| with |replacement|"""
return original[0:start] + replacement + original[end:] | c71badb26287d340170cecdbae8d913f4bdc14c6 | 4,432 |
def edit_mod():
""" Admin endpoint used for sub transfers. """
if not current_user.is_admin():
abort(403)
form = EditModForm()
try:
sub = Sub.get(fn.Lower(Sub.name) == form.sub.data.lower())
except Sub.DoesNotExist:
return jsonify(status='error', error=[_("Sub does not exist... | debab16603e2cfe412eb0f819753fb7571a9c803 | 4,433 |
def get_current_info(symbol_list, columns='*'):
"""Retrieves the latest data (15 minute delay) for the
provided symbols."""
columns = ','.join(columns)
symbols = __format_symbol_list(symbol_list)
yql = ('select %s from %s where symbol in (%s)'
% (columns, FINANCE_TABLES['quotes'], symbo... | a13df0f44b31ac091a5283958cdb1aa675fe9bdc | 4,434 |
def dictionarify_recpat_data(recpat_data):
"""
Covert a list of flat dictionaries (single-record dicts) into a dictionary.
If the given data structure is already a dictionary, it is left unchanged.
"""
return {track_id[0]: patterns[0] for track_id, patterns in \
[zip(*item.items()) for ... | d1cdab68ab7445aebe1bbcce2f220c73d6db308f | 4,435 |
def _get_qualified_name(workflow_name, job_name):
"""Construct a qualified name from workflow name and job name."""
return workflow_name + _NAME_DELIMITER + job_name | 29881480a9db33f18ff4b01abcdd1aaf39781f36 | 4,436 |
def normalize_each_time_frame(input_array):
"""
Normalize each time frame
- Input: 3D numpy array
- Output: 3D numpy array
"""
for i in range(input_array.shape[0]):
max_value = np.amax(input_array[i, :, :])
if max_value != 0:
input_array[i, :, :] = input_arr... | bee7f41f17e4e24a654426f65c6a73c518abafca | 4,437 |
def pre_process_data(full_data):
"""
pre process data- dump invalid values
"""
clean_data = full_data[(full_data["Temp"] > -10)]
return clean_data | 6172d4a77f5805c60ae9e4f146da2bd8283beef0 | 4,438 |
def invalid_grant(_):
"""Handles the Invalid Grant error when doing Oauth
"""
del current_app.blueprints['google'].token
flash(("InvalidGrant Error"), category="danger")
return redirect(url_for('index')) | 95b8b20d3d96b46387c6dd23ede9b54c6b056da1 | 4,439 |
import difflib
def diff_text(a, b):
"""
Performs a diffing algorithm on two pieces of text. Returns
a string of HTML containing the content of both texts with
<span> tags inserted indicating where the differences are.
"""
def tokenise(text):
"""
Tokenises a string by spliting i... | e15348e942ac3e6936872ec61f123a9241f49eba | 4,440 |
from common.aes import encrypt
from common.datatypes import PasswordResetToken
from config import AUTH_TOKEN, RESET_PASSWORD_EXPIRE_SECONDS
from time import time
from urllib.parse import quote_plus
from utils import send_mail
import traceback
from operator import or_
def require_reset_password():
"""
请求重设密码
... | aa1c14755485fe3ac5fc294e43fa1d4e610e0a83 | 4,441 |
def coerce_affine(affine, *, ndim, name=None):
"""Coerce a user input into an affine transform object.
If the input is already an affine transform object, that same object is returned
with a name change if the given name is not None. If the input is None, an identity
affine transform object of the give... | 66900e32b83100004d2ea62a742fc0afe8a26cbb | 4,442 |
def provider_filtered_machines(request, provider_uuid,
identity_uuid, request_user=None):
"""
Return all filtered machines. Uses the most common,
default filtering method.
"""
identity = Identity.objects.filter(uuid=identity_uuid)
if not identity:
raise Obj... | f6251e9b72649f37489c5a9d97d7b3835d400cbe | 4,443 |
def known_peaks():
"""Return a list of Peak instances with data (identified)."""
peak1 = Peak(
name="Test1Known",
r_time=5.00,
mz=867.1391,
charge="+",
inchi_key="IRPOHFRNKHKIQA-UHFFFAOYSA-N",
)
peak2 = Peak(
name="Test2Known",
r_time=8.00,
... | 3f7d5eb5b16d61f09c0c10f32e9d8d40324e2d5d | 4,444 |
def explode_sheet_music(sheet_music):
"""
Splits unformatted sheet music into formated lines of LINE_LEN_LIM
and such and returns a list of such lines
"""
split_music = sheet_music.split(',')
split_music = list(map(lambda note: note+',', split_music))
split_list = []
counter = 0
line... | f89ae58a0deb315c61419bd381cd0bf84f079c3e | 4,445 |
def norm_coefficient(m, n):
"""
Calculate the normalization coefficient for the (m, n) Zernike mode.
Parameters
----------
m : int
m-th azimuthal Zernike index
n : int
n-th radial Zernike index
Returns
-------
norm_coeff : float
Noll normalization coefficien... | 1632ffac5e771e4ab16b3f7918d9543ffd67171e | 4,446 |
def get_waveglow(ckpt_url):
"""
Init WaveGlow vocoder model with weights.
Used to generate realistic audio from mel-spectrogram.
"""
wn_config = {
'n_layers': hp.wg_n_layers,
'n_channels': hp.wg_n_channels,
'kernel_size': hp.wg_kernel_size
}
audio_config = {
... | a5b494299fae98be2bb5f764ed7a53fc42d36eff | 4,447 |
def user_exists(keystone, user):
"""" Return True if user already exists"""
return user in [x.name for x in keystone.users.list()] | 17d99e12c0fc128607a815f0b4ab9897c5d45578 | 4,448 |
from typing import List
from typing import Dict
import itertools
def gen_cartesian_product(*args: List[Dict]) -> List[Dict]:
""" generate cartesian product for lists
生成笛卡尔积,估计是参数化用的
Args:
args (list of list): lists to be generated with cartesian product
Returns:
list: cartesian p... | cbe85f440f399b523aa70bc10733ea175dc93f7a | 4,449 |
def get_234_df(x):
"""
This function get the dataframe for model2.1,2.2,2.3
input: x, the col we want
output: the dataframe only for x
"""
styles = pd.read_csv("styles.csv", error_bad_lines=False)
styles = styles.drop(["productDisplayName"],axis = 1)
styles = styles.drop(["year"],axis = 1)
sty... | c9d456ae058492e5e242bbde2288885158681f98 | 4,450 |
def appropriate_bond_orders(params, smrts_mol, smrts):
"""Checks if a SMARTS substring specification has appropriate bond orders
given the user-specified mode.
:param params: A dictionary of the user parameters and filters.
:type params: dict
:param smrts_mol: RDKit mol object of the SMARTS string.... | 045abda277716812694cc1093256742e1d67a016 | 4,451 |
def train(model, train_path, val_path, steps_per_epoch, batch_size,
records_path):
"""
Train the Keras graph model
Parameters:
model (keras Model): The Model defined in build_model
train_path (str): Path to training data
val_path (str): Path to validation data
steps... | 24a8080a8b4738f7eb32846729b006ca2237a576 | 4,452 |
def Mcnu_to_m1m2(Mc, nu):
"""Convert chirp mass, symmetric mass ratio pair to m1, m2"""
q = nu_to_q(nu)
M = Mcq_to_M(Mc, q)
return Mq_to_m1m2(M, q) | 8b4eb6e49549607bda0ea9a17baec8c4d0b38cb6 | 4,453 |
import functools
def _AccumulateActions(args):
"""Given program arguments, determines what actions we want to run.
Returns [(ResultsReportCtor, str)], where ResultsReportCtor can construct a
ResultsReport, and the str is the file extension for the given report.
"""
results = []
# The order of these is ar... | 73925fe55e6986e1222a5e88f804caaa9793044a | 4,454 |
def build_predictions_dictionary(data, class_label_map):
"""Builds a predictions dictionary from predictions data in CSV file.
Args:
data: Pandas DataFrame with the predictions data for a single image.
class_label_map: Class labelmap from string label name to an integer.
Returns:
Dictionary with key... | 738e1c9c4568bc689ecda9765c3412d36f2d73ec | 4,455 |
def create_file_link(link_id, file_id, parent_share_id, parent_datastore_id):
"""
DB wrapper to create a link between a file and a datastore or a share
Takes care of "degenerated" tree structures (e.g a child has two parents)
In addition checks if the link already exists, as this is a crucial part of ... | 0c4abe1d5aa4bce8bd489f8bec1ae900a9194631 | 4,456 |
def deptree(lines):
"""Build a tree of what step depends on what other step(s).
Test input becomes
{'A': set(['C']), 'C': set([]), 'B': set(['A']),
'E': set(['B', 'D', 'F']), 'D': set(['A']),
'F': set(['C'])}
A depends on C
B depends on A
C depends on nothing (starting point)
D ... | 9a435a0e78dd3a68c97df4bcd2e03583841de216 | 4,457 |
from datetime import datetime
def get_datetime(time_str, model="0"):
"""
时间格式化 '20200120.110227'转为'2020-01-20 11:02:27'
返回一个datetime格式
"""
if model == "0":
time_str = get_time(time_str)
time = datetime.datetime.strptime(time_str, "%Y-%m-%d %H:%M:%S")
return time | 568c46efab9366f64fc0e286cf9876cd48e7a9bb | 4,458 |
def gather_parent_cnvs(vcf, fa, mo):
"""
Create BEDTools corresponding to parent CNVs for converage-based inheritance
"""
cnv_format = '{0}\t{1}\t{2}\t{3}\t{4}\n'
fa_cnvs = ''
mo_cnvs = ''
for record in vcf:
# Do not include variants from sex chromosomes
if record.chrom i... | 2d685586a917bbd94f87758221b4d06c2d6ad7c1 | 4,459 |
import json
def create_images():
""" Create new images
Internal Parameters:
image (FileStorage): Image
Returns:
success (boolean)
image (list)
"""
# vars
image_file = request.files.get('image')
validate_image_data({"image": image_file})
i... | 682bb2f6044265fbd6c29c4ff6581d6bc2469edb | 4,460 |
from typing import Union
from pathlib import Path
from typing import Optional
def docx2python(
docx_filename: Union[str, Path],
image_folder: Optional[str] = None,
html: bool = False,
paragraph_styles: bool = False,
extract_image: bool = None,
) -> DocxContent:
"""
Unzip a docx file and ex... | 557ba8502b62ffc771a7d3b6f88a8b769dd55d68 | 4,461 |
def parcel_analysis(con_imgs, parcel_img,
msk_img=None, vcon_imgs=None,
design_matrix=None, cvect=None,
fwhm=8, smooth_method='default',
res_path=None):
"""
Helper function for Bayesian parcel-based analysis.
Given a sequence o... | 8abface7ad72f5ca2679dc9a8ea6cedd93f681a5 | 4,462 |
def memoize(fn):
"""Simple memoization decorator for functions and methods,
assumes that all arguments to the function can be hashed and
compared.
"""
memoized_values = {}
@wraps(fn)
def wrapped_fn(*args, **kwargs):
key = (args, tuple(sorted(kwargs.items())))
try:
... | 2a48fad065e04a7eed9b9865adc0640f2a7cff9f | 4,463 |
from pydantic import BaseModel # noqa: E0611
import torch
def validate(
args: Namespace,
model: BaseModel
) -> pd.DataFrame:
"""Perform the validation.
Parameters
----------
args : Namespace
Arguments to configure the model and the validation.
model : BaseModel
The model ... | 456ec24e1639970db285e260028e9ba3bd4d2e31 | 4,464 |
def stats(last_day=None, timeframe=None, dates_sources=None):
"""See :class:`bgpranking.api.get_stats`"""
query = {'method': 'stats'}
query.update({'last_day': last_day, 'timeframe': timeframe,
'dates_sources': dates_sources})
return __prepare_request(query) | 5da42848926372fa5fe90338529ab47396203fd8 | 4,465 |
def restore_purchases() -> None:
"""restore_purchases() -> None
(internal)
"""
return None | 7f047cdfe892bd724c2203d846762c3b3786d7c2 | 4,466 |
import time
def sim_mat(fc7_feats):
"""
Given a matrix of features, generate the similarity matrix S and sparsify it.
:param fc7_feats: the fc7 features
:return: matrix_S - the sparsified matrix S
"""
print("Something")
t = time.time()
pdist_ = spatial.distance.pdist(fc7_feats)
pri... | 6b896a4912f4a9a8fc765674ad47e17aea73bfa0 | 4,467 |
def text_split(in_text, insert_points, char_set):
""" Returns: Input Text Split into Text and Nonce Strings. """
nonce_key = []
encrypted_nonce = ""
in_list = list(in_text)
for pos in range(3967):
if insert_points[pos] >= len(in_list) - 1: point = len(in_list) - 2
else: point = inser... | 15f496513e63236b0df7e2d8a8949a8b2e632af4 | 4,468 |
import decimal
def f_approximation(g_matrix, coeficients_array):
"""
Retorna um vetor para o valor aproximado de f, dados os coeficientes ak.
"""
decimal.getcontext().prec = PRECSION
decimal.getcontext().rounding = ROUNDING_MODE
num_of_xs = len(g_matrix[0])
num_of_coeficients = len(g_mat... | f5f8ce78b07e877c521a6374548e21273c61dcee | 4,469 |
def _module_exists(module_name):
"""
Checks if a module exists.
:param str module_name: module to check existance of
:returns: **True** if module exists and **False** otherwise
"""
try:
__import__(module_name)
return True
except ImportError:
return False | 8f3ed2e97ee6dbb41d6e84e9e5595ec8b6f9b339 | 4,470 |
def users(request):
"""Show a list of users and their puzzles."""
context = {'user_list': []}
for user in User.objects.all().order_by('username'):
objs = Puzzle.objects.filter(user=user, pub_date__lte=timezone.now()).order_by('-number')
if objs:
puzzle_list = []
for p... | abf953394af6baff08bedf252796eb0d89cba3f4 | 4,471 |
from xidplus.stan_fit import get_stancode
def MIPS_SPIRE_gen(phot_priors,sed_prior_model,chains=4,seed=5363,iter=1000,max_treedepth=10,adapt_delta=0.8):
"""
Fit the three SPIRE bands
:param priors: list of xidplus.prior class objects. Order (MIPS,PACS100,PACS160,SPIRE250,SPIRE350,SPIRE500)
:param se... | be3d168e6a7a5a8159e83371059cfcbd1f0c187e | 4,472 |
def check_cstr(solver, indiv):
"""Check the number of constraints violations of the individual
Parameters
----------
solver : Solver
Global optimization problem solver
indiv : individual
Individual of the population
Returns
-------
... | 2aa52d2badfb45d8e289f8314700648ddc621252 | 4,473 |
def _FixFsSelectionBit(key, expected):
"""Write a repair script to fix a bad fsSelection bit.
Args:
key: The name of an fsSelection flag, eg 'ITALIC' or 'BOLD'.
expected: Expected value, true/false, of the flag.
Returns:
A python script to fix the problem.
"""
if not _ShouldFix('fsSelection'):
... | 6dda9ccbb565857c4187afc4dada6dd84653b427 | 4,474 |
def dilation_dist(path_dilation, n_dilate=None):
"""
Compute surface of distances with dilation
:param path_dilation: binary array with zeros everywhere except for paths
:param dilate: How often to do dilation --> defines radious of corridor
:returns: 2dim array of same shape as path_dilation, with ... | 0d35ec5a0a14b026f0df228ae752f104502b82ba | 4,475 |
def plot_rgb_phases(absolute, phase):
"""
Calculates a visualization of an inverse Fourier transform, where the absolute value is plotted as brightness
and the phase is plotted as color.
:param absolute: 2D numpy array containing the absolute value
:param phase: 2D numpy array containing phase info... | d2f12df2af25925ae9607ef102f4b0fc1cb01373 | 4,476 |
import uuid
from sys import float_info
def layer_view_attachment_warning():
"""Unlimited attachments are warnings"""
content = {
'id': str(uuid.uuid4()),
'_type': 'CatXL',
'attachment': {
'currency': 'USD',
'value': float_info.max,
}
}
return con... | 9a5340a1c726ee39029f8475aed15a99c17aff6d | 4,477 |
import logging
import os
import sqlite3
def create_resfinder_sqlite3_db(dbfile, mappings):
"""
Create and fill an sqlite3 DB with ResFinder mappings.
Expects mappings to be a list of tuples:
(header, symbol, family, class, extra)
"""
logging.info("Creating sqlite3 db: %s ...", dbfile)
... | 39fbdffc3088c5265b8bf388c5aa2d7530f8ca87 | 4,478 |
def normal_shock_pressure_ratio(M, gamma):
"""Gives the normal shock static pressure ratio as a function of upstream Mach number."""
return 1.0+2.0*gamma/(gamma+1.0)*(M**2.0-1.0) | 30d0a339b17bab2b662fecd5b19073ec6478a1ec | 4,479 |
from typing import Tuple
import numpy
def _lorentz_berthelot(
epsilon_1: float, epsilon_2: float, sigma_1: float, sigma_2: float
) -> Tuple[float, float]:
"""Apply Lorentz-Berthelot mixing rules to a pair of LJ parameters."""
return numpy.sqrt(epsilon_1 * epsilon_2), 0.5 * (sigma_1 + sigma_2) | b27c282cec9f880442be4e83f4965c0ad79dfb1e | 4,480 |
def verify_password_str(password, password_db_str):
"""Verify password matches database string."""
split_password_db = password_db_str.split('$')
algorithm = split_password_db[0]
salt = split_password_db[1]
return password_db_str == generate_password_str(algorithm, salt, password) | 467dcbfa1dbf1af0d7cd343f00149fc8322053e5 | 4,481 |
def get_ical_file_name(zip_file):
"""Gets the name of the ical file within the zip file."""
ical_file_names = zip_file.namelist()
if len(ical_file_names) != 1:
raise Exception(
"ZIP archive had %i files; expected 1."
% len(ical_file_names)
)
return ical_file_names... | 7013840891844358f0b4a16c7cefd31a602d9eae | 4,482 |
def unquoted_str(draw):
"""Generate strings compatible with our definition of an unquoted string."""
start = draw(st.text(alphabet=(ascii_letters + "_"), min_size=1))
body = draw(st.text(alphabet=(ascii_letters + digits + "_")))
return start + body | 7927e828a82786f45749e25e25376f48479c0662 | 4,483 |
from typing import List
from typing import Optional
from typing import Any
from typing import Callable
def _reduce_attribute(states: List[State],
key: str,
default: Optional[Any] = None,
reduce: Callable[..., Any] = _mean) -> Any:
"""Find the first... | bfc4ca6826e05b04ae9e1af6d3c167935bceda6f | 4,484 |
def sync_garmin(fit_file):
"""Sync generated fit file to Garmin Connect"""
garmin = GarminConnect()
session = garmin.login(ARGS.garmin_username, ARGS.garmin_password)
return garmin.upload_file(fit_file.getvalue(), session) | 8e604a0461f503d83b5a304081020d54acd7577c | 4,485 |
from typing import Callable
from typing import List
def get_paths(graph: Graph, filter: Callable) -> List:
""" Collect all the paths consist of valid vertices.
Return one path every time because the vertex index may be modified.
"""
result = []
if filter == None:
return result
vis... | f7e1679bae48781010257b4fe8e980964dee80ce | 4,486 |
def create_app(app_name=PKG_NAME):
"""Initialize the core application."""
app = Flask(app_name)
CORS(app)
with app.app_context():
# Register Restx Api
api.init_app(app)
return app | 1773b0a84253aa6a1bca5c6f6aec6cd6d59b74fa | 4,487 |
from typing import Dict
from typing import Callable
import sympy
import warnings
def smtlib_to_sympy_constraint(
smtlib_input: str,
interpreted_constants: Dict[str, Callable] = default_interpreted_constants,
interpreted_unary_functions: Dict[str,
Callable] = default_i... | d04782272cd13fcb7eafdb4b8f9cb7b1fd857dcc | 4,488 |
async def revert(app, change_id: str) -> dict:
"""
Revert a history change given by the passed ``change_id``.
:param app: the application object
:param change_id: a unique id for the change
:return: the updated OTU
"""
db = app["db"]
change = await db.history.find_one({"_id": change_i... | ad5484639f0a70913b17799534fa52b8531b3356 | 4,489 |
def days_away(date):
"""Takes in the string form of a date and returns the number of days until date."""
mod_date = string_to_date(date)
return abs((current_date() - mod_date).days) | f76b10d9e72d8db9e42d7aba7481e63cf1382502 | 4,490 |
def node_constraints_transmission(model):
"""
Constrains e_cap symmetrically for transmission nodes.
"""
m = model.m
# Constraint rules
def c_trans_rule(m, y, x):
y_remote, x_remote = transmission.get_remotes(y, x)
if y_remote in m.y_trans:
return m.e_cap[y, x] == m... | 0fc51f39b63324c73503b349cfd38da4c9816c50 | 4,491 |
def plot_mtf(faxis, MTF, labels=None):
"""Plot the MTF. Return the figure reference."""
fig_lineplot = plt.figure()
plt.rc('axes', prop_cycle=PLOT_STYLES)
for i in range(0, MTF.shape[0]):
plt.plot(faxis, MTF[i, :])
plt.xlabel('spatial frequency [cycles/length]')
plt.ylabel('Radial MTF'... | dac09628a72666a4f4e3e8aae4263cb9f2688fa2 | 4,492 |
import enum
def forward_ref_structure_hook(context, converter, data, forward_ref):
"""Applied to ForwardRef model and enum annotations
- Map reserved words in json keys to approriate (safe) names in model.
- handle ForwardRef types until github.com/Tinche/cattrs/pull/42/ is fixed
Note: this is the... | acbbf365c7a80c7a9f5230bcd038c2c286ae58c5 | 4,493 |
def cross(x: VariableLike, y: VariableLike) -> VariableLike:
"""Element-wise cross product.
Parameters
----------
x:
Left hand side operand.
y:
Right hand side operand.
Raises
------
scipp.DTypeError
If the dtype of the input is not vector3.
Returns
---... | 372156ba869e3dabb2421e1ea947fdc710c316eb | 4,494 |
def delete(service, name, parent_id=None,
appProperties=defaults.GDRIVE_USE_APPPROPERTIES):
""" Delete a file/folder on Google Drive
Parameters
----------
service : googleapiclient.discovery.Resource
Google API resource for GDrive v3
name : str
Name of file/folder
par... | e2653005d8d0e53df80119869586542b08405c55 | 4,495 |
def _is_LoginForm_in_this_frame(driver, frame):
""" 判断指定的 frame 中是否有 登录表单 """
driver.switch_to.frame(frame) # 切换进这个 frame
if _is_LoginForm_in_this_page(driver):
return True
else:
driver.switch_to.parent_frame() # 如果没有找到就切换回去
return False | 16a4b3af1d5cf9abe2efee6856a37b520fc2a1fc | 4,496 |
def parse_range_header(specifier, len_content):
"""Parses a range header into a list of pairs (start, stop)"""
if not specifier or '=' not in specifier:
return []
ranges = []
unit, byte_set = specifier.split('=', 1)
unit = unit.strip().lower()
if unit != "bytes":
return []
... | 2a408abe816684bf42b2253495088338bf4cac2b | 4,497 |
def acf(x, lags=None):
""" Computes the empirical autocorralation function.
:param x: array (n,), sequence of data points
:param lags: int, maximum lag to compute the ACF for. If None, this is set to n-1. Default is None.
:return gamma: array (lags,), values of the ACF at lags 0 to lags
"""
ga... | 9d47df88255ec8c9ae373c501f8b70af8f3c4ebc | 4,498 |
import os
import functools
def copyInfotainmentServerFiles(tarName, targetId=None):
"""
Stuff the server binary into a tar file
"""
# grab the pre-built binary
osImage = getSetting('osImage', targetId=targetId)
infotainmentBinDir = getBinDir('infotainment-server', targetId=targetId)
cpFile... | 53d7d586e74281f3ac9061e8b1028d3efb62be07 | 4,499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.