content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def compare_album(left_album: Album, right_album: Album):
"""Compare two album items and return True if they match."""
# do not match on year and albumtype as this info is often inaccurate on providers
if (
left_album.provider == right_album.provider
and left_album.item_id == right_album.ite... | fb26aaae45da19eea74399c24ba0ca58ffee484e | 38,600 |
def get_elw_ticker_name(ticker: str) -> str:
"""종목 이름 조회
Args:
ticker (str): 티커
Returns:
str: 종목명
>> get_elw_ticker_name("58F194")
KODEX 200
"""
return krx.get_etx_name(ticker) | 7d06e8589e5d37aaa2c62905ded6f6f16a89329c | 38,601 |
from typing import Callable
from typing import Tuple
def smart_implicit_midpoint_proposal_factory(vector_field: Callable, thresh: float=1e-6, max_iters: int=1000) -> Callable:
"""This proposal distribution for Hamiltonian Monte Carlo uses the smart
implicit midpoint integrator.
Args:
vector_field... | c98313a844b5398877e47f9379f9d06a2c7d9848 | 38,602 |
def get_block_symbol_data(editor, block):
"""
Gets the list of ParenthesisInfo for specific text block.
:param editor: Code editor instance
:param block: block to parse
"""
def list_symbols(editor, block, character):
"""
Retuns a list of symbols found in the block text
... | 7e6f486e209c686000c8c605ea352a1ceeab7c3c | 38,603 |
def is_windows() -> bool:
"""Determine if the current platform is Windows or not."""
return _system() == "Windows" | 05cf690ed82c63b761b1c002a97b242c9cd4063c | 38,604 |
import re
def jieba_clear_text(text):
"""
jieba分词,并使用自定义停用词表去除停用词以及长度为1的词
"""
text_n= "".join(re.findall(u"[\u4e00-\u9fa5]", text))
raw_result = "$".join(jieba.cut(text_n))
myword_list = []
#去除停用词
for myword in raw_result.split('$'):
if myword not in stopwords:
myw... | 6b9f3c8be4799cec20ecda64dd62334a851e807d | 38,605 |
def prepare_data(train_file_idxs, test_file_idxs, mel_list,
target_list):
"""
modified prepare_framewise_data() in classify.py of the baseline code
"""
X_train = []
y_train = []
for idx in train_file_idxs:
X_train.append(mel_list[idx])
y_train.append(target_list[idx])
train_idxs = np.random.perm... | f21d1a68ccc689b4d0c31351db05f9be08179c17 | 38,606 |
import zipfile
def unzip(zip_address, file_name, encoding='UTF-8'):
"""解压zip数据包
:param zip_address: 压缩包的地址
:param file_name: 压缩包里面文件的名字
:param encoding: 文件的编码
:return: 压缩包里面的数据:默认编码的UTF-8
"""
f = zipfile.ZipFile(zip_address)
fp = f.read(file_name)
lines = fp.decode(encoding)
r... | ba71fd6f923c2c410b0461796da513583c15b9aa | 38,607 |
def parse() -> dict:
"""Parse command line arguments"""
parser = ArgumentParser()
parser.add_argument('-p', '--publish', action='store_true', default=False)
return vars(parser.parse_args()) | bfc6be67dbfa5f83b07f5191d2cc67d61ca1fdf5 | 38,608 |
def gen_text (lm, seed, nletters=1000):
"""Same as generate_text, except now handles keys its not seen before"""
for k in lm.keys():
order = len(k)
if len(seed) < order:
seed = ' ' * order + seed
history = seed[-order:]
out = []
for i in range(nletters):
if history not ... | f023e05a6b02c4511a15fffa4b41ab219c185638 | 38,609 |
import math
import random
def parse(image, origin_anchors):
"""
:param image: input picture, shape like (H, W, 3)
:param origin_anchors: text like ["201,162,207,229",
"208,162,223,229",
"224,162,239,229"]
... | df30c459554f147819c9ebd2a6e25c4be1c69fac | 38,610 |
def has_name_keywords(ustring):
"""是否含有名称的标识字符"""
if (u'店名' in ustring) or \
(u'店家' in ustring) or \
(u'名字' in ustring):
return True
return False | e009e567ecf060b0b225802de523dea60ab8a02e | 38,611 |
def evaluate_df(df_true, df_subm):
"""
Score submitted dataframe wrt the true dataframe
Policy:
- If everything is perfect, 100%
- Else, we look at the F1 score. This score takes into account
whether the submitted solution contains everything it should,
while it also pen... | 8045e343db75cbaa8eedfab4692d8c1abb41dedb | 38,612 |
def process_data(input_file):
"""
Parse the complete stroke trial database and retain relevant columns.
Data cleaning phase
"""
f = open(input_file, 'r')
header = f.readline().split(",")
data = []
for line in f:
data.append(map(float, line.split(",")))
return header, np.array(data) | 557c06799b9c141fe4b1de07ce5029ec5c34bf38 | 38,613 |
from typing import List
def get_error_string_for_multiple_dbs(tables: List[Table]):
"""
Get error string for tables belonging to multiple databases.
:param tables: list of table
:return: String: error string
"""
return f'Tables should belong to same db {", ".join([f"{table.table_name}: {table.... | 216fabd7de3a68d348501f6be88ca7a94e57a188 | 38,614 |
def list_endpoints_formatted_text():
"""List all endpoints for the app."""
return flask.jsonify(
[
f"{entry['endpoint']:50s} {entry['methods']:25s} {entry['route']}"
for entry in sitemap_builder()
]
) | 38933dc33149b659d6728ce57cd8ec93538a1873 | 38,615 |
def db_with_transactions(db_2_accounts):
"""Inserts 2 accounts of 8 transactions each."""
accounts_db = select_accounts(db_2_accounts)
for account_db in accounts_db:
transactions = make_transactions(8, account_uuid=account_db.uuid)
for transaction in transactions:
db_2_accounts.t... | a111128fd954f75c9e25bc12bd1251edbd72735b | 38,616 |
def integer_schedule(x, name="undefined"):
"""Deserializes an integer schedule."""
if type(x) == dict:
if x["type"] == "constant":
return lambda i: x["value"]
elif x["type"] == "geometric":
return lambda i: x["coefficient"] * (x["base"]**i)
elif x["type"] == "list... | a9233daaf7e7ad5bef236c80dfee922f156e4ba3 | 38,617 |
def point_set_to_vtk(pse, origin=(0.0, 0.0, 0.0)):
"""Convert the point set to a :class:`pyvista.PolyData` data object.
Args:
pse (:class:`omf.pointset.PointSetElement`): The point set to convert
Return:
:class:`pyvista.PolyData`
"""
points = np.array(pse.geometry.vertices)
out... | 2742d5bd73a847b8419ca09192cadd87cba0a8d6 | 38,618 |
def find_all_primes(x=22):
"""Find all the primes up to x"""
allprimes = []
for i in range(2, x + 1):
if is_prime(i):
allprimes.append(i)
print("There are %d primes between 2 and %d" % (len(allprimes), x))
return allprimes | efb358cc6ed8d9ece8bad067ad323e7d1db2da8d | 38,619 |
def op_number(space, bN):
"""
Todo:
Make this basis-independent
"""
assert bN.basis == "Fock"
M = op_ladder_dn(space, bN=bN)
return M.A @ M | 01580e2a345443d47381ef5a4557de0f98832bdb | 38,620 |
def bbox_flip(bbox, width, flip_x=False):
"""
invalid value in bbox_transform if this wrong (no overlap), note index 0 and 2
also note need to save before assignment
:param bbox: [n][x1, y1, x2, y2]
:param width: cv2 (height, width, channel)
:param flip_x: will flip x1 and x2
:return: flippe... | 485496752c83e0e8424b9f67a56a861373db5fc5 | 38,621 |
def diff_pd(df1, df2):
"""Identify differences between two pandas DataFrames"""
assert (df1.columns == df2.columns).all(), \
"DataFrame column names are different"
if any(df1.dtypes != df2.dtypes):
"Data Types are different, trying to convert"
df2 = df2.astype(df1.dtypes)
if df1.... | a6a56a1735497357f6474d2f540941ff93e06b5f | 38,622 |
def is_learned_based_on_exercise_outcomes(exercise_log):
"""
:return:
"""
if exercise_log.is_empty():
return False
return (
exercise_log.last_exercise().is_too_easy() or
len(exercise_log.most_recent_correct_dates())
>= CORRECTS_IN_DISTINCT_DAYS_FOR_... | 8d4d6769c36eda61e854f6a3a4800d6b6f19f88e | 38,623 |
def greeting(): # OK
"""Beschreibung:
Dient zum besonderen aussehen
:return: gibt die eingegebenen Zeichen decodiert aus
Details:
print(b'\xe2\x95\x94'.decode('utf-8')) ergibt ╔ die linke obere Ecke
print(b'\xe2\x95\x91'.decode('utf-8')) ergibt ║
somit lassen sich "Rahmen bau... | 4800675329568bda9015782bb2f30513fb842931 | 38,624 |
def openmooc_settings(request):
"""The context processor function"""
copy_attrs = ('INSTANCE_URL',
'INSTANCE_TITLE',
'INSTANCE_NAME',
'FULL_ASKBOT_URL',
)
custom_settings = {}
for key in copy_attrs:
custom_settings[key] = g... | 04b1b3cafc14b00626e82f34280f4655d8add346 | 38,625 |
def cbpowerspectrum( transferfile,
Omegacdm ,
Omegab ,
h ,
Omeganu = 0.0,
As = None,
ns = None ,
koverh = None ):
"""
Returns the baryon- CDM matter power spectrum using the transfer function
output, usng the cosmological parameters As, ns, h, Omegab, Omegacdm
args:
As : If As is None, a default va... | b53616af621d3251e9435b1d15485eba41050f53 | 38,626 |
import logging
import json
def read_json_file_into_memory(json_file):
"""
Purpose:
Read properly formatted JSON file into memory.
Args:
json_file (String): Filename for JSON file to load (including path)
Returns:
json_object (Dictonary): Dictonary representation JSON Object
... | 70c2e6ab6180700ce77469b8afa0d0df8e0eee95 | 38,627 |
def load(trainFile, testFile):
"""
Builds various numpy arrays from the given .csv format training
and test tests.
Args:
trainFile: file name/path for the input training set
testFile: file name/path for the input test set
Returns:
y_train: labels in the training set as a nu... | 6ac7414432f4695e863c046e607fff9f8bebc19a | 38,628 |
from datetime import datetime
def process_arguments(args):
"""
This receives all arguments from calls to the public API functions so it
can validate and, if necessary, modify them. In particular, it can be used
to translate older style API calls into newer ones so as to maintain
backwards compatib... | 8a48f733bc4b3f19c4baac054cd982fa62691ba4 | 38,629 |
from typing import List
def print_trace(m,route: List[List[float]]):
"""
Save the map with route locally.
:param Location: list of latitude and longtitude of all locations on the route.
List[float] : the length is 2, while the first element is latitude
... | f351e4dcd6d73f8391efff61d28c0a7be69156a6 | 38,630 |
import ipaddress
def validateIP(ipaddressToValidate):
"""
Description: validates an IP address
Input: IP to be validated (string)
Return: True or False (boolean)
"""
try:
ipaddress.ip_address(ipaddressToValidate)
return True
except Exception:
... | 9c4ad0d8a82c7ac8ae0888be58cb7e643571cbba | 38,631 |
def calc_mean_dff(data, *args):
""" Return the mean dF/F value, and the SEM of all neurons in the data matrix.
Subtracts the offset of each cell before the computation.
"""
min_vec = np.atleast_2d(np.nanmin(data, axis=1)).T
data_no_offset = data - min_vec
return np.nanmean(data_no_offset, axis=1... | 61692a1b74e100642bc54bfd96a86ba49c88dd83 | 38,632 |
def tweet(auth, interval=1800, ignore=None):
"""
Decorator wrapping a string-returning function that returns
a function that tweets the results of calling the function
:param auth: Twitter auth object
:param interval: how long to wait between tweets
:param ignore: an optional list of Twitter API... | 15a39e7754f927d172d050a0000ca32125488d18 | 38,633 |
def to_base_10(num: str, from_base: int, key="0123456789abcdefghijklmnopqrstuvwxyz", digits=100, minus_sign="-") -> int:
"""Convert a num in from_base to base 10."""
if len(key) < from_base:
raise ValueError("Must have key length > base")
if num == key[0]:
return 0
if num[0] == minus_s... | 128127fe1f55250f46e057fa92f72d25966be626 | 38,634 |
def find_nearp(position, path):
""" Finds and returns the closes point in the path to the given position"""
x=path[0]
y=path[1]
z=path[2]
dx=position[0]-x
dy=position[1]-y
dz=position[2]-z
distance=np.sqrt(dx*dx+dy*dy+dz*dz) #caculate distance between position and every points in the pa... | e00a2fbe7002b7c43b932effe139c4a482e71f4f | 38,635 |
def unshard_env_batch(pytree):
"""Reshapes all arrays in the pytree.
`[ndev, env_s, bs, ...]` --> `[host_bs, env_s, ...]
Args:
pytree: A pytree of arrays to be sharded.
Returns:
Sharded data.
"""
def _unshard_array(array):
ndev, envs, bs = array.shape[:3]
new_shape = (envs, ndev * bs) +... | b94cd6e117ab897b4ca91a31e9777c3d2aa39dfc | 38,636 |
def guided_filter(p, i, r, e):
"""
:param p: input image
:param i: guidance image
:param r: radius
:param e: regularization
:return: filtering output q
"""
# 1
mean_I = cv2.boxFilter(i, cv2.CV_64F, (r, r))
mean_p = cv2.boxFilter(p, cv2.CV_64F, (r, r))
corr_I = cv2.boxFilter(i... | 437aa4ea3e7ac37d3b707be4844b637eeba320e4 | 38,637 |
from typing import Any
from typing import List
from typing import Tuple
from typing import Type
def _get_suffix_value_pairs(
tree_or_leaf: Any) -> List[Tuple[str, Type["Module"]]]:
"""Helper for naming pytrees of submodules."""
dict_or_leaf = serialization.to_state_dict(tree_or_leaf)
if not isinstance(dict_... | e83064b4657054ab7b33921811a55da3cc1f44bf | 38,638 |
def ffmpegFormats(select = 'E'):
"""Expects ffmpeg to output something like:
File formats:
D. = Demuxing supported
.E = Muxing supported
--
D 3dostr 3DO STR
E 3g2 3GP2 (3GPP2 file format)
E 3gp 3GP (3GPP file format)
D 4xm 4X Technologies
E a64 a... | a14da6886956cc552b9c9ddcb18bd6c71bdce18b | 38,639 |
def week_menu():
"""Меню расписания на неделю"""
kb = InlineKeyboardMarkup()
monday = InlBtn(text="Пн", callback_data="get_monday_schedule")
tuesday = InlBtn(text="Вт", callback_data="get_tuesday_schedule")
wednesday = InlBtn(text="Ср", callback_data="get_wednesday_schedule")
thursday = InlBtn(t... | aca7ebf922176c027d1d6fdb3f7f50b2bbce14b2 | 38,640 |
import posixpath
def sanitize_path(path):
"""Make path absolute with leading slash to prevent access to other data.
Preserve potential trailing slash.
"""
trailing_slash = "/" if path.endswith("/") else ""
path = posixpath.normpath(path)
new_path = "/"
for part in path.split("/"):
... | 03837bf40926341ef0982cf7543339b6168f40ff | 38,641 |
def hour_angle (sid_UT, loc, ra) :
"""Hour angle for sidereal_time `sid_UT`, location `loc`, and
right ascension `ra`.
`sid_UT` and `ra` must be Angle_D/Angle_R instances.
"""
### J. Meeus, p. 92
lon = loc.longitude_meuss
ha = (sid_UT - lon - ra).degrees
if abs (ha) >= 360.0 :
... | 55839e5afac00a2fa12256f559c688244bbcff12 | 38,642 |
def gaussian_mle_1d(x, photon_count, pixel_size, initial_position=None, initial_sigma=0.250):
"""Calculate the maximum likelihood estimate of the model parameters given measured photon count for 1D data.
Parameters
----------
x : array-like
Position data at which the function is to be evaluated... | 7722f23f433ec268386bba3b398abbb58afbc0f4 | 38,643 |
def compute_num_sim_ftrs(sim_func_names, num_doc_fields, num_user_fields, num_deep):
"""Computes the number of similarity features
:param num_doc_fields Number of document fields
:param num_user_fields Number of user fields
:param num_deep Number of deep features
:param sim_func_names Similarity fu... | 9700b14bbe4c550c3c3161d995ed87012d9356af | 38,644 |
def brent(f, a, b, args=(), max_iteration=100, tolerance=1e-8):
"""
Calculate roots using Brent's method.
Parameters
----------
f: function
Objective function.
a: float
Lower bound for the roots.
b: float
Upper bound for the roots.
args: tuple, optional
A... | a9648956b7bd5bafa15d971cf389cacfcc0b2413 | 38,645 |
import subprocess
def pipeRun(binaryName,
inputStream,
args):
"""Run a program, providing input as the standard input.
Parameters
----------
binaryName : string
Name of the program to run. This will be passed as-is to which()
inputStream : file
Source for t... | 24e00c10c9b2a15d287ed6d70663c7de979b97d6 | 38,646 |
def square_slerp(xy, base_pts):
"""Transforms a square in [0,1]^2 to a spherical quadrilateral
defined by base_pts, using spherical linear interpolation
Args:
xy: Array, shape [..., 2]. XY coordinates on the square.
base_pts: Array, shape [4, ..., 3]. Coordinates of the square.
... | ada12eb806f16d087772c9dfff24683de2cd8597 | 38,647 |
def encrypted(text, key):
"""Ceasarchifferskryptering
Args:
text (_str_): Den text som ska krypteras.
key (_int_): Hur många steg ska vi skifta?
"""
encrypted = ""
# loop through the message char by char
for char in text:
# check if it's an upper case letter
... | 46f85f9db742daf02e67030eb75f7bf035b073d8 | 38,648 |
import torch
def dist(batch_reprs, eps = 1e-16, squared=False):
"""
Efficient function to compute the distance matrix for a matrix A.
Args:
batch_reprs: vector representations
eps: float, minimal distance/clampling value to ensure no zero values.
Returns:
distance_matrix, clamped to ensure no zero values ... | be4d50e35ed11255eef2dc1acb4645de1453964c | 38,649 |
def check_write_entity(entity, authz):
"""Implement the cross-effects of mutable flag and the authz
system for serialisers and API."""
if authz.is_admin:
return True
collection_id = ensure_dict(entity.get("collection")).get("id")
collection_id = entity.get("collection_id", collection_id)
... | 3b12d562940af03e447fc30cb2ffa08058785354 | 38,650 |
import array
def get_timed_data(wb,sheetname):
"""
Get the data from Tsys vs time data sheet
"""
sheet = wb.get_sheet_by_name(sheetname)
date_nums = date2num(array(get_column(sheet,"Date/Time")))
ras = get_column(sheet,"R.A.")
decs = get_column(sheet,"Decl.")
azs = get_column(sheet,"A... | 78ecab215dc88886ceee1c0518742279d90aa907 | 38,651 |
def juniper_items_to_list_of_dicts(module, data):
"""Recursively convert Juniper PyEZ Table/View items to list of dicts.
"""
resources = []
# data.items() is a list of tuples
for table_key, table_fields in data.items():
# sample:
# ('fxp0', [('neighbor_interface', '1'), ('local_inter... | 2415d6608bb182dcf5c5fd45c067b4a8c34ca898 | 38,652 |
def unquote(s):
"""Strip single quotes from the string.
:param s: string to remove quotes from
:return: string with quotes removed
"""
return s.strip("'") | 15d29698e6a3db53243fc4d1f277184958092bc6 | 38,653 |
def construct_banded_matrix_from_band(
num_lower_diagonals: int, num_upper_diagonals: int, rect_mat: np.ndarray
) -> np.ndarray:
"""
Constructs a square banded matrix from a representation of the band.
:param num_lower_diagonals: aka ``l``
:param num_upper_diagonals: aka ``u``
:param rect_mat: ... | 0c93a6af563a93bf9885e42ae62a5bd3d17f0741 | 38,654 |
def create_jet_model_image(width, j_length, cj_length, max_flux, imsize,
center, gauss_peak=0.001, dist_from_core=24,
gauss_bmaj=10, gauss_e=1., gauss_bpa=0.,
gauss_peak_jet=0.0, dist_from_core_jet=24,
gauss_bmaj... | 396f080f987c1628df110bbf79e55ea65394d3b6 | 38,655 |
def choose_square(empty_squares,
row_candidates, col_candidates, square_candidates):
"""
Iterates through all the squares, and returns the most constrained squares.
Constrained factor is defined as length of intersection of that
square's row, column and encompassing sq... | 6c0dc97fe8e5d370c155be0abadbc02927da47e1 | 38,656 |
def use_network_group(cli, organization: object, group: str = None, spinner: object = None):
"""
Use a network group.
:param spinner: the spinner object from parent flow is used and returned
:param organization: the netfoundry.Organization object representing the current session
:param str group: n... | c40ca9a120ec4b0af6318504bac9a498960d62a3 | 38,657 |
import string
def normalize(text):
""" Remove all punctuation for now """
return ''.join('' if c in string.punctuation else c for c in text) | 9332583adb0ff3bfbe37170b2acdd58f09b3fe5e | 38,658 |
def zyz_unitary(ϕ, θ, λ):
"""
Unitary decomposed as Rz, Ry, Rz rotations.
Angles are in matrix order, not in circuit order!
"""
return expm(-0.5j*ϕ*pZ)@expm(-0.5j*θ*pY)@expm(-0.5j*λ*pZ) | bd0f4a394893717486fe68a88419c45266bdc9fa | 38,659 |
def build_model(idkey):
"""
Default parameters:
ImageTransformer(leak=0,
norm_type='batch',
DWS=True,DWSFL=False,
outerK=3,resgroups=1,
filters=[8,16,16],
shuffle=False,
blocks=[2,2,... | 614de0669a77c5959291c9cd91df8f2d6e0e61f2 | 38,660 |
def p_AB(A, b, L):
"""
Numerator of function f.
"""
a11, a12, a13, a21, a22, a23, a31, a32, a33 = \
A[0, 0], A[0, 1], A[0, 2], \
A[1, 0], A[1, 1], A[1, 2], \
A[2, 0], A[2, 1], A[2, 2]
b1, b2, b3 = b[0, 0], b[1, 0], b[2, 0]
return L**4*(-a11*a22*b3**2 + a11*a23*b2*b3 + a11*a32... | 530655f0e6e56ef6aca4ad82d5076543caec0ddb | 38,661 |
def disqus_num_replies(context, shortname=''):
"""
Return the HTML/js code which transforms links that end with an
#disqus_thread anchor into the threads comment count.
"""
shortname = getattr(settings, 'DISQUS_WEBSITE_SHORTNAME', shortname)
return {
'shortname': shortname,
'con... | 64e5fd5f12c2ec7e3ad4b28cdf4fdaeccf08fd06 | 38,662 |
def infer_flags(bytecode, is_async=None):
"""Infer the proper flags for a bytecode based on the instructions.
Because the bytecode does not have enough context to guess if a function
is asynchronous the algorithm tries to be conservative and will never turn
a previously async code into a sync one.
... | 02744153c3af35468268cfe9eb0353c8039ac351 | 38,663 |
def form_generic_id(request, id1, template_name=None, form_class=None,
request_url_post=None, request_url_get=None,
success_msg=lambda desc: _('Success'), ask_msg=lambda x: '', confirmation=_('Yes'),
request_url_both=None, ajax_success_status=0, id_key=None):
... | 7809d7eefbc311244f94c1420b7c27d794c66a8c | 38,664 |
def gromov_barycenters(N, Cs, ps, p, lambdas, loss_fun, epsilon,
max_iter=1000, tol=1e-9, verbose=False, log=False, init_C=None):
"""
Returns the gromov-wasserstein barycenters of S measured similarity matrices
(Cs)_{s=1}^{s=S}
The function solves the following optimization prob... | 51bc85b192c34514e803e5a5ab5f1b3caad6273a | 38,665 |
def check_elemental_balance(model, r_id, tol=1e-6):
""" Check elemental balance of a reaction in a model.
Notes:
Since some metabolites can have multiple formulas associated, it will check if at least one possible
combination of all formulas results in a balanced reaction.
Args:
mo... | 8a0344b4e2ccbd82aba63b63397cee7ec3804d1c | 38,666 |
def BB_flux(E1, E2, T):
"""
Wrapper to compute black body flux given minimum and
maximum energies (in eV) and a black body temperature.
"""
x1 = E1 / (const.k_boltz * T) / const.eV_erg
x2 = E2 / (const.k_boltz * T) / const.eV_erg
A = 2.0 * const.k_boltz**4 * T**4 / (const.h**3 * const.c**... | a76381c9a033bf65e403adb9dfe08d5cc021ed97 | 38,667 |
def asn1_parse(template, data):
"""Parse a data structure according to an ASN.1 template.
@param template: tuples comprising the ASN.1 template
@param data: byte string data to parse
@return: decoded structure
"""
data = bytearray(data)
r = []
i = 0
try:
for t in template:
... | 308bdc1864dffa13d2f94f67910cb21cb54882a6 | 38,668 |
def open_connection(config):
"""
Use the parameters in the "account" block of the configuration file
to establish an IMAP connection, optionally using SSL.
Returns: imaplib connection object
"""
for i in [ S_HOSTNAME, S_USERNAME, S_PASSWORD ]:
if config.has_option(S_ACCOUNT, i) == False:... | f9d61a2bdf4dbd7ec3111f2d070bce822d707640 | 38,669 |
import re
def _parse_faces(obj_faces):
"""Parse the OBJ encoding of the face attribute index buffers.
A value of -1 in the index array of the texture means the index is
undefined (i.e. no texture is mapped to this face corner).
Returns:
faces
faces_texture
faces_normals
"... | d9d22f70fd98de28b3bbfbeb080e52ed60cca03f | 38,670 |
def binary_to_decimal(binary):
"""
Converts a binary number into a decimal number.
"""
decimal = 0
index = 0
while binary > 0:
last = binary % 10
binary = binary / 10
decimal += (last * (2 ** index))
index += 1
return decimal | f1efdf19c802345e6badfed430dd82e3f067a419 | 38,671 |
def namelist(names: list) -> str:
"""
Format a string of names like 'Bart, Lisa & Maggie'
:param names: an array containing hashes of names
:return: a string formatted as a list of names separated
by commas except for the last two names, which
should be separated by an ampersa... | b0b931f3f9365824931173c2aec3ac213342e0c3 | 38,672 |
import functools
def update_wrapper():
"""Copy wrapped function information."""
def do_nothing(): "Doing nothing."
def wrapper():
"""Wraps a function that does nothing."""
return do_nothing()
wrapper_alias = functools.update_wrapper(wrapper, do_nothing)
return wrapper_alias is w... | bf629c54a0c8205de5041fafd5cb042acfc3bcce | 38,673 |
def makeFlowField(a,b,c):
""" Make a vector from 3 components
<div class=jython>
makeVector(a,b,c) = [a,b,c]
</div>
"""
return DerivedGridFactory.createFlowVectors(a,b,c) | 2f1ea8b2283f850c01d527b344858cddc28935b9 | 38,674 |
import numpy
def arraytodk3d(x):
"""
Convert back 1d array of independent elements to correct complex array fft-style
"""
nmesh = round(x.shape[0]**(1/3.))
y = numpy.zeros((nmesh, nmesh, nmesh/2+1), dtype = numpy.complex128)
# Structure saved-
# - first the real and complex part of N*N*... | 54d29be8a70069430e8e9f3ac43eef05687c5327 | 38,675 |
def handler(context, inputs):
"""
Create IPAM object,
define deaalocate_ip function
and start deallocation function
"""
ipam = IPAM(context, inputs)
IPAM.do_deallocate_ip = do_deallocate_ip
return ipam.deallocate_ip() | a107971aa45959e715c3d242dce16038ca94bae0 | 38,676 |
def _n_centred_onedgaussian_Inorm(pars, I=None, sigma=None):
"""
Returns a function that provides the sum
over N 1D gaussians, where N is the length of
I,sigma *OR* N = len(pars) / 2
The background "height" is assumed to be zero (you must "baseline" your
spectrum before fitting)
pars - a... | 3860656a23ef8b81a652ae3a1b21af9e13aa4f08 | 38,677 |
def prepare_plot_dir(dirpath):
"""
Add a trailing / to the plot dir if missing and creat dir if needed.
:param dirpath: path of existing or planned directory
:return: dirpath with / as the final character
"""
# add a slash to filename if it wasn't provided.
if dirpath[-1] != '/':
di... | 95b136e0e74d767f46610f051f48e4c250969422 | 38,678 |
def o목록(message):
"""제가 지원하는 기능들을 알려줘요."""
return ', '.join(_목록()) +" 같은게 있어요!" | 86c9e633c8d33cbae94d68aff143fcd0ef7955e1 | 38,679 |
def testvolc(compareto,volcfiles,runshortname):
"""Performing the volcanic test
Input: compaareto = the flag to decide whether to compare to LENS2 or B1850 or both
volcfiles = the file listing for the volcanic test for your test case
runshortname = the shortname for labelling the test case... | 729199b0e0fa09d2687aa545bf9ae5817a30ac7a | 38,680 |
def parse_select_job_input_file(file):
""" INPUT
file = micrographs_ctf.star file used as input to the Select job
RETURNS
ordered_list_of_micrographs = list of entries as they appear in the input file, e.g.: [ _rlnMicrographName1, _rlnMicrographName2, ... ]
"""
print(" >>> P... | cc4fa7d9fd51f67892f3a7bd33ed69eff56ca367 | 38,681 |
def selectordialog(args):
"""
Emulates a selector control that is lvalues compatible for subsequent conditionals in Kodi settings
args is a list of strings that is kwarg 'like'.
'id=myid': (Required) where myid is the settings.xml id that will be updated
The plain id will contain the actual inde... | bfed44f866c01c100485ce6e5b8d5400df706ea2 | 38,682 |
def create_hmac_hash(hmac_payload: str, hmac_secret_key: str) -> str:
"""Returns sha256 HMAC hexdigest."""
if hmac_secret_key is None:
raise RuntimeError('hmac_secret_key cannot be None, please set a secret for the application in dotenv file!')
return new(
hmac_secret_key.encode('utf-8'),
... | 84775b9c1550420ab829ba31c6f8d322efda2fbb | 38,683 |
def loadIUPACcompatibilities(IUPAC, useGU):
"""
Generating a hash containing all compatibilities of all IUPAC RNA NUCLEOTIDES
"""
compatible = {}
for nuc1 in IUPAC: # ITERATING OVER THE DIFFERENT GROUPS OF IUPAC CODE
sn1 = list(IUPAC[nuc1])
for nuc2 in IUPAC: # ITERATING OVER THE D... | 931f2a765ec9499b8553d13d7de93c6b261622de | 38,684 |
def update_offer_viewed(offer_counter, merged_data, consumer_id, offer_id, offer_end):
"""
Update the dataframe with information related to an offer
being viewed.
"""
i = get_row_indices(merged_data, consumer_id, offer_id)
merged_data.at[i[offer_counter], "offer_viewed"] = True
retu... | c523bb34470333d7244333f867750f367c7b55e1 | 38,685 |
from typing import Callable
import inspect
import argparse
def autoparse(fn: Callable, verbose: bool=False) -> dict:
"""
Parse parameters from the command line, according to the signature and
docstring of a function
:param fn: callable with type hints and docstring
:param verbose: if True, will p... | 5dae90168b2b071ddeaad392756cb58c96075014 | 38,686 |
def to_fullspec(rs, es, hds):
"""
Rotationally symmetric dump of a list of each to fullspec
"""
output = []
for idx in range(0, len(rs)):
row = {"r": [rs[idx]], "e": [es[idx]], "d": hds[idx] * 2}
output.append(row)
return output | 98cac8ba938249d6af0decfeffedf594ab1d6660 | 38,687 |
import subprocess
def try_run(cmd):
"""Try running the command and return its output on success, None on failure"""
logger.debug("running: %s", ' '.join(cmd))
try:
return subprocess.check_output(cmd, stderr=subprocess.STDOUT)
except subprocess.CalledProcessError:
return None | a986299a053d704d3443ead889e32ca6132bfaaa | 38,688 |
def command_generation():
"""Adds a generate cell to Notebook."""
return jsonify(generate(request.json["query"], request.json["context"])) | 6a1263ca26b77babd79a4d71d3ba7453a5965437 | 38,689 |
import os
import pickle
import shutil
def summarize_text(df):
"""Summarize the text in the dataframe. Uses cache where possible
Fills in the gaps otherwise.
Performs this replacement in-place.
"""
ID_TO_SUMMARY_PATH = "cord_uid_to_summaries_short.pkl"
with open(os.path.join(DATA_DIR, ID_TO... | 5f5a649a0c4f2736dafdca75e7b878725fa01874 | 38,690 |
from django.db.models.fields.related import ManyToManyField
def rubric_model_to_dict(obj, fields=None, exclude=None, ct_id=None):
"""
Returns a dict containing the data in ``instance`` suitable for passing as
a Form's ``initial`` keyword argument.
``fields`` is an optional list of field names. If pro... | e9beed1a4d472997384c15853553d9783c674cf0 | 38,691 |
def get_uniq_list(data):
"""
列表去重并保持顺序(数据量大时效率不高)
:param data: list
:return: list
"""
ret = list(set(data))
ret.sort(key=data.index)
return ret | d4a43acd42608210c022317999673bd281e5e247 | 38,692 |
import re
import sys
def parse_mval_string(fa_mval_s, fa_mode):
"""Parse formamide m-value string.
Args:
fa_mval_s (str): formamide m-value string.
fa_mode (str): formamide mode (see FA_MODE_LABELS).
Returns:
str, fun: formamide m-value string and function for parsing.
"""
... | f21bbb036302e3b126a505a14e48df55041d7c39 | 38,693 |
def train_val_test_split(messages, labels, split_frac, random_seed=None):
"""
Zero Pad input messages
:param messages: Input list of encoded messages
:param labels: Input list of encoded labels
:param split_frac: Input float, training split percentage
:return: tuple of arrays train_x, val_x, tes... | db7a24a9ffdf00185dafd115877c8eafd584b378 | 38,694 |
import fastapi
import pydantic
import http
async def delete_anime(
*,
session: aio_session.AsyncSession = fastapi.Depends(
dependencies.get_session),
anime_id: pydantic.UUID4,
current_patron: patron_model.Patron = fastapi.Depends( # pylint: disable=unused-argument
dependencies.get_cur... | 1ee8b4ca5f7290387fbb3bf7342e158f5fb6a2e1 | 38,695 |
def jaccard_similarity(mat):
"""
get jaccard similarity matrix
:param mat: scipy.sparse.csc_matrix
:return: similarity matrix of nodes
"""
# make it a binary matrix
mat_bin = mat.copy()
mat_bin.data[:] = 1
col_sum = mat_bin.getnnz(axis=0)
ab = mat_bin.dot(mat_bin.T)
aa = np.... | 69a8cdcb890275a9b44ac1587ece56325884e23d | 38,696 |
from typing import Optional
from typing import Dict
def mnist_dataset(
split: str,
has_labels: bool,
flatten_images: bool,
device_batch_size: int,
repeat: bool,
shuffle: bool,
drop_remainder: bool,
seed: Optional[int] = None,
multi_device: bool = True,
reshuffle_each_iteration:... | 7a064572ce272e178983f293a266365238ce0a7e | 38,697 |
def favorite_mange(manga_id):
"""
endpoint: /manga/<manga_id>/favorite
method: POST
response:
total: total_favorited
status: False
"""
user = User.query.get(g.uid)
user_manga = UsersManga.query.filter_by(
user_uid=g.uid,
manga_id=manga_id
).first()
if ... | b6e78310e3a5f2dc081c391aa537de444a5bf82b | 38,698 |
import networkx as nx
import rhasspynlu
from .train import WordCasing
import argparse
import typing
import os
import sys
import gzip
import json
import dataclasses
async def recognize(args: argparse.Namespace, core: Voice2JsonCore) -> None:
"""Recognize intent from sentence(s)."""
# Make sure profile has bee... | 8c17651a7ddb8a0d6955a59c28e280f9450ec068 | 38,699 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.