content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import os
import re
def name_from_cmakelists(cmakelists):
""" Get a project name from a CMakeLists.txt file
"""
if not os.path.exists(cmakelists):
return None
res = None
# capture first word after project(), excluding quotes if any
regexp = re.compile(r'^\s*project\s*\("?(\w+).*"?\)',... | e18b214cbc4453f96989931ec9d4501cdbd1b718 | 3,621,200 |
import time
import json
import requests
def catch_distribution():
"""抓取行政区域确诊分布数据"""
data = dict()
url = "https://view.inews.qq.com/g2/getOnsInfo?name=wuwei_ww_area_counts&callback=&_=%d" %int(time.time()*1000)
for item in json.loads(requests.get(url=url).json()["data"]):
if item["area"] not ... | 4ce28940e9a3852a7622ceec489c186429fc9745 | 3,621,201 |
from settings import SECRET_KEY
def create_securityhash(action_tuples):
"""
Create a SHA1 hash based on the KEY and action string
"""
action_string = "".join(["_%s%s" % a for a in action_tuples])
security_hash = sha1(action_string + SECRET_KEY).hexdigest()
return security_hash | db2444a8b2e07a9afe6f947974968cc0a301602b | 3,621,202 |
def mae(
original,
prediction,
hinge: float = 0):
"""
Mean Absolute Error (mean over channels and batches)
:param original:
:param prediction:
:param hinge: hinge value
"""
d = tf.abs(original - prediction)
if hinge != 0.0:
d = keras.layers.ReLU(threshold... | 47c4d47a9cc14a8132284329d23055d072b66588 | 3,621,203 |
def record_to_index(record):
"""Route the given record to the right index and document type."""
def doc_type(alias):
try:
return list(current_search_client.indices.get_alias(index=alias, ignore=[404]).keys())[0]
except:
return alias
if is_deposit(record.model):
... | e3b03d1631f3a1d8c329c3c2635b4dde053fce94 | 3,621,204 |
def build_contextData(version, community, server_config):
"""
create ContextData instance based on the SNMP's version
for SNMP v1/v2c, use the default ContextData with contextName as empty string
for SNMP v3, users can specify contextName, o.w. use empty string as contextName
@params version: str, "... | 4c39cdd56e52a2d287198ac4707eb4f2dd4b4b9d | 3,621,205 |
def get_two_point_vel_corr_roll(ui, x, y, z=None, roll_axis=1, n_bins=None,
x0=None, x1=None, y0=None, y1=None,
z0=None, z1=None,
t0=None, t1=None,
coarse=1.0, coarse2=0.2,
... | 5629fe51437103cf3a7707b505ce8cd64a292e57 | 3,621,206 |
from typing import Dict
import torch
from typing import Union
from typing import Tuple
def random_year_img(dataset: Dict[str, torch.Tensor],
writer: Union[int, None] = None,
rand: np.random.RandomState = np.random.RandomState(seed=1234),
**kwargs) -> Tuple[t... | 72fe81110389f2b55a448f5af09ff5751120e719 | 3,621,207 |
def registration_ptpln(src, tgt, downsampling_voxelsize=2, toggledebug = False):
"""
registrate two point clouds using global registration + local icp
the correspondence checker for icp is point to plane
:param src:
:param tgt:
:param downsampling_voxelsize:
:param icp_distancethreshold:
... | e824825370045df516014a05ba55d379454ad688 | 3,621,208 |
import random
def encrypt(sk, b, mbits=N):
"""Encrypt a bit into a Q-bit integer based on the provided key."""
# Random N-bit integer with the same parity as b
m = (random.randint(2**(mbits-2), 2**(mbits-1) -1) << 1) + b
# Random Q-bit integer
q = random.randint(2**(Q-1), 2**Q) - 1
... | 7366d1239190ccf0fc9bbd6308139a63436ac02e | 3,621,209 |
import json
def english_to_french(english_text):
"""Translate eng to french"""
translation = language_translator.translate(
text=english_text,
model_id='en-fr').get_result()
print(json.dumps(translation, indent=2, ensure_ascii=False))
return french_text | 0acee15db440fb3d347704c8fd66ad457a53abe2 | 3,621,210 |
def rebin_data(x, y, dx_new, method='sum'):
"""Rebin some data to an arbitrary new data resolution. Either sum
the data points in the new bins or average them.
Parameters
----------
x: iterable
The dependent variable with some resolution dx_old = x[1]-x[0]
y: iterable
The inde... | a1115268f67cc3ff7452dc235cb2882ab5eb5204 | 3,621,211 |
def register():
"""Register new user."""
form = RegisterForm(request.form)
if form.validate_on_submit():
User.create(username=form.username.data, email=form.email.data, password=form.password.data, active=True)
flash('Thank you for registering. You can now log in.', 'success')
return... | d07cc4d6886a555bfdabaf690513e3ebefd62ec4 | 3,621,212 |
def rnaseq_metrics_df(analysis_dir, num_seps=1, sep="."):
"""
Generates RNA-seq metrics
Args:
analysis_dir: directory to pull information from
num_seps: number of seperators to join back to get the name of the item
sep: seperator to split / join on to get full name
Returns:
"... | 9d3e8cfd8de7291b89e22a109c05151325c1434a | 3,621,213 |
import json
def _ParseFioJson(fio_json):
"""Parse fio json output.
Args:
fio_json: string. Json output from fio comomand.
Returns:
A list of sample.Sample object.
"""
samples = []
for job in json.loads(fio_json)['jobs']:
cmd = job['fio_command']
# Get rid of ./fio.
cmd = ' '.join(cmd... | 61acc14ab815061125ddb5756d3e22ae2a90c459 | 3,621,214 |
from typing import Optional
import textwrap
def dedent(text: str, num_spaces: Optional[int] = None) -> str:
"""Wrapper around textwrap.dedent
Dedents at most num_spaces. If num_spaces is not specified, dedents as much as possible.
Args:
text: Text that will be dedented.
num_spaces... | 3c86dd9073fd9cf385de3806f0fc8462ab4972bc | 3,621,215 |
from ihome import api_1_0
from ihome.web_html import html
def create_app(config_name):
"""
创建flask的应用对象
:param config_name: str 配置模式的模式的名字 ("develop", "product")
:return:
"""
app = Flask(__name__)
# 根据配置模式的名字获取配置参数的类
config_class = config_map.get(config_name)
app.config.from_obj... | 6d18018167113e9bd37dbd39c99f845f3be039f4 | 3,621,216 |
import struct
def cyclic_pattern_offset(value, pattern=None):
"""
Search a value if it is a part of cyclic pattern
Args:
- value: value to search for (String/Int)
Returns:
- offset in pattern if found
"""
pattern = pattern or cyclic_pattern().encode()
if isinstance(value, i... | 965e85cfd9221e478fc3599bd428e79d02a31c23 | 3,621,217 |
def lookup_file():
"""Uses listify_ticked and select_file to query the session
database. Returns all file information for all files tagged
with tags selected in Properties prefixed with
'Tags to filter'.
"""
if not session:
no_session_warning()
return None
taglist = listify_t... | b44335114e49f75ea3f6964d77fd8f7fc42ee67d | 3,621,218 |
def _find_and_set_index(data_frame: TfsDataFrame) -> TfsDataFrame:
"""
Looks for a column with a name starting with the index identifier, and sets it as index if found.
The index identifier will be stripped from the column name first.
Args:
data_frame (TfsDataFrame): the ``TfsDataFrame`` to loo... | b91b878ad4f3877be635cb12290f662bf42fb184 | 3,621,219 |
def default_adv_xxx_bigram_polarity(bigram, negation=None, prior_polarity_score=False, linear_score=None):
"""Calculates the bigram polarity based on a empirical factor from each adverb group
and SENTIWORDNET word polarity
"""
second_word_polarity = word_polarity(bigram['second_word'],
bigram['second_wor... | e4d938832db2e6cb1bcdd3be77aa37355776953b | 3,621,220 |
import sys
def extract_entity_text(text: str, offset: int, length: int) -> str:
"""
Get entity value.
:param text: Full message text
:param offset: Entity offset
:param length: Entity length
:return: Returns required part of the text
"""
if sys.maxunicode == 0xFFFF:
return tex... | 773426ffbf3cc186447594c9ddd50cd461c82316 | 3,621,221 |
import tqdm
def convert_examples_to_dualfeatures(examples, label_list, max_seq_length, tokenizer, output_mode):
"""Loads a data file into a list of dual input features."""
'''
output_mode: classification or regression
'''
features = []
for (ex_index, example) in enumerate(tqdm(examples)):
if ex_index % 10000... | 04433ae65ab897416cdd0b6afd58497ee083c102 | 3,621,222 |
def _configure_lat_type(spec, loader):
""" configures latitude type """
return _configure_geo_type(spec, loader, -90.0, 90.0, '_lat') | 5d3af830214bf61023d2c0d0a43852910617216c | 3,621,223 |
def read_csv_input(csv_file, isotopes):
"""
Read the csv input file creating a pandas dataframe
Use the matches from the light, heavy channel or both based on the user preferences
"""
df = pd.read_csv(csv_file)
# Applies the filter of light/heavy ions specified by the user
if isotopes == 'l... | b297e8dad1fc191245695d79c107682cc3554021 | 3,621,224 |
def _mutual_info(lab1, lab2):
"""Call sklearn's mutual info function."""
return mutual_info_score(lab1, lab2) | 959ee5cade5ce84559646a8862a8b69c796d9de5 | 3,621,225 |
def decrypt_in_cbc(ciphertext, key=None, IV=None):
""" Arguments must be bytes strings. """
key = key if key else bytes([0] * 16)
IV = IV if IV else bytes([0] * len(key))
block_size = len(key)
block_count = int(len(ciphertext) / block_size)
cipher = AESEncryption(key, 'ECB')
plaintext = b... | 95354836a679400952cb17ee0fbea9723c7ab766 | 3,621,226 |
from typing import Dict
from typing import Any
def websocket_to_response(response_dict: Dict[str, Any]) -> Response:
"""Converts a WebSocket API response from the rippled server into a Response object.
Args:
response_dict: A dictionary representing the contents of the WebSocket API
... | d1858166989d3e4da3fa78221167a41c8c3c12d7 | 3,621,227 |
def rowFeaturise(row, features, timeSeriesName, wavelet, level):
"""
Input:
- row: pandas Series
The row of the features table that is going to be processed.
- features: pandas DataFrame
Table with pointers to JSON files that is going to have new columns with the extracte... | aa6a9679a824b9aae8085a81fd8ade408995826d | 3,621,228 |
import tqdm
def q5_plot_chromatic_num_bounds_by_prob(n, prange, pstep, k=None, clique_finder=greedy_find_clique_number):
"""Plots a graph of number of colours against edge probability, for each of the various lower/upper bounds
of chromatic number"""
probs = np.arange(prange[0], prange[1], pstep)
prin... | 87478f5b80c4201c3a88c93aadae9fdd47efdbfd | 3,621,229 |
def reconstructTypeFunctionType(typeFunction, args, kwargs):
"""Reconstruct a type from the values returned by 'isTypeFunctionType'"""
#note that our 'key' objects are dict-in-tuple-form, because dicts are
#not hashable. So to keyword-call with them, we have to convert back to a dict...
return typeFunc... | e57658bb7e4b368a8caf86a72db05157b689500e | 3,621,230 |
def draw_bounding_box(img, line, color=(255, 0, 0)):
"""
:param line: (xmin, ymin, xmax, ymax)
"""
img = cv2.line(img, (line[0], line[1]), (line[2], line[1]), color)
img = cv2.line(img, (line[2], line[1]), (line[2], line[3]), color)
img = cv2.line(img, (line[2], line[3]), (line[0], line[3]), col... | c5a72bc07c72d3ac4bb11fcf0b8257814d98cf42 | 3,621,231 |
def flatnonzero(a):
"""Return indices that are non-zero in the flattened version of a.
This is equivalent to a.ravel().nonzero()[0].
Args:
a (cupy.ndarray): input array
Returns:
cupy.ndarray: Output array,
containing the indices of the elements of a.ravel() that are non-zero.
... | 4fd5a088e3eb2daf63454d2add9db1327483b554 | 3,621,232 |
def create_optim_modifier_trainable(project_id: str, optim_id: str):
"""
Route for creating a new trainable modifier for a given project optim.
Raises an HTTPNotFoundError if the project or the optim are not found
in the database.
:param project_id: the id of the project to create a trainable modif... | 84e915108495fa89ed3fb738d5acde1ebd58c56a | 3,621,233 |
import logging
def get_logger(name=None, level=logging.INFO):
"""
Return a logger with the specific name, creating it if necessary.
If no name is specified, return the root logger.
Args:
name (str, optional): logger name. Defaults to None.
Returns:
Logger : the specified logger.... | ce576c61df026deb6dda3f5474690c8be412a801 | 3,621,234 |
import socket
def find_data_gateway():
"""
Returns 200 or 404, depending on whether the data-gateway is reachable or not
:return: 200 or 404
"""
try:
socket.gethostbyname('data-gateway')
return jsonify('success'), 200
except socket.gaierror as e:
return jsonify(str(e)... | b98f15f69f621b13201db6f16840f80a83873866 | 3,621,235 |
def str_to_dict(
text: str,
/,
*keys: str,
sep: str = ",",
) -> dict[str, str]:
"""
Parameters
----------
text: str
The text which should be split into multiple values.
keys: str
The keys for the values.
sep: str
The separator for the values.
Returns
... | 0b34ea1b47d217929fd9df760231f4786150e661 | 3,621,236 |
def get_list_control_ranges(data):
"""Build a list of extended regions around given ranges that doesn't overlap with any given range
Parameters
----------
data: `pd.DataFrame()`
Likely coming from pd.DataFrame() it should contain ["chrom", "start", "end", "dna_string", "score", "bound"]
... | faa364d068648501f3629e83c9e9ba9ab87fcdaa | 3,621,237 |
def test_disabledimmingresolvestorelay(FW):
"""
When dimming changes to the value 'disallowed' the crownstone must change from
IGBT mode to relay.
"""
print("##### test_disabledimmingresolvestorelay #####")
result = []
for intensity in [0,50,100]:
result += [test_disabledimmingresol... | 8ca4a75fad7101cbebcd0878d058240f0d2999fb | 3,621,238 |
import requests
def change_password(client: Client, user_id: str, password: str) -> bool:
"""Changes password for child user account
via the `/users/{user_id}/password` endpoint.
:param client: Client object
:param user_id: The ID of the user account
:param password: New password
:return: `Tr... | 0a2b2479da6714c4ee4cc7ee1ab5ef6d24e3d79b | 3,621,239 |
def keyset():
"""
Creates a set of numeric keys centered around 0
Provides a comparison function based on numeric closeness of the
keys
"""
class KeySet:
extent = 10
def __init__(self):
self.key = "0"
self.all = [self.key]
for i in range(KeyS... | ebdc08f13d9b82136042dae9b02206e4c6bb30d9 | 3,621,240 |
def enable(include_pyrin=True, include_app=True):
"""
enables locale management for the application.
:param bool include_pyrin: specifies that it should extract pyrin localizable
messages. defaults to True if not provided.
:param bool include_app: specifies that it shoul... | d00a101517d44b81599fb21e9b7e266154fa0e9f | 3,621,241 |
def autoencoder(X, X_test, encoding_dim):
"""
Parameters: X: training data, X_test: testing data, encoding_dim: dimension of most hidden layer
Return hidden layer representions of training and testing data.
"""
# this is our input placeholder
input_X = Input(shape=(36,))
encoded = Dense(24, activation='rel... | 483f64e95cac157a455e0c1e1c87c0892adeac65 | 3,621,242 |
from datetime import datetime
import logging
def add_point(slug):
"""Create a new point based on get parameters."""
try:
timestamp = None
str_timestamp = request.args.get('time', None)
if str_timestamp:
timestamp = datetime.strptime(str_timestamp, "%Y-%m-%dT%H:%M:%S.%fZ")
... | 9dbf64cd6c18c07f25671ef61e7ff0dc7a7f69d0 | 3,621,243 |
def sp_conv3x3_block(in_channels,
out_channels):
"""
3x3 version of the SuperPointNet specific convolution block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
"""
return SPConvBlock(... | ec16079ce9b1d4792a29837e2408209b78e03325 | 3,621,244 |
def correlation(a: np.ndarray, b: np.ndarray, missing: float, method="pearson"):
""" Calculate correlation similarity between two vectors"""
assert a.shape == b.shape
assert method in CORR_METHODS
threshold = a.shape[0] * missing
values = ~np.logical_or(np.isnan(b), np.isnan(a)) # find missing valu... | e7f4026d011e821f7404aabf949177278c2459d6 | 3,621,245 |
from typing import Counter
import base64
import json
def mfa_backup_tokens(backup_secret):
""" Writes MFA secrets encrypted with backup_secret and base64 encoded to stdout. """
tokens = []
for token in list_mfa_tokens():
token_data = mfa_read_token(token)
if token_data['token_secret'].star... | 0218b794b5c81baaa2310c8572be770a6ad895e5 | 3,621,246 |
def create_content():
"""
Generate fake content to populate the email with
Generates textual contents that are randomly generated and defined to include 5 random IPs, 5 random URLs,
5 random sha1 hashes, 5 random sha256 hashes, 5 random md5 hashes, 5 random email addresses, 5 random domains
and 100... | a97feb2fa01dace5fdb1f87fc7f8663c50b4bba5 | 3,621,247 |
def Mresnet(**kwargs):
"""Constructs a modified ResNet model.
"""
model = ResNet(BasicBlock, [1, 1, 1, 1], **kwargs)
return model | ee991ee945047f28afc59921f9b8c3331003de1b | 3,621,248 |
def getschemasbyuuid():
"""Get all schemas by uuid.
:rtype: dict
"""
return _REGISTRY.getschemasbyuuid() | 00006546a2a0e3393e85bd86204ac86357888581 | 3,621,249 |
def get_dynamic_db_settings(server_root, username, password, dbname, installed_apps):
"""
Get dynamic database settings. Other apps can use this if they want to change
settings
"""
server = get_server_url(server_root, username, password)
database = "%(server)s/%(database)s" % {"server": server... | b40bf8b06426f3282323904eda30093553a6ffad | 3,621,250 |
import numpy
def calc_fm_3d_by_density(mult_i, den_i, np, volume, moment_2d, phase_3d):
"""
Calculate magnetic structure factor.
[hkl, points, symmetry]
F_M = V_uc / (Ns * Np) mult_i den_i moment_2d[i, s] * phase_3d[hkl, i, s]
V_uc is volume of unit cell
Ns is the number of symmetry element... | 40f807f00422af17897ec4fa15c5826e1b73abd8 | 3,621,251 |
def parse_args(apps: str, tables: str) -> t.List[FixtureConfig]:
"""
Works out which apps and tables the user is referring to.
"""
finder = Finder()
app_names = []
if apps == "all":
app_names = finder.get_sorted_app_names()
elif "," in apps:
app_names = apps.split(",")
e... | 405455bb8608904694643730e43eeae25e682db1 | 3,621,252 |
def get_randoms(n, m):
"""Create n random integers out of m."""
if n > m:
n = m
res = []
for i in range(n):
while True:
int = randint(0, m - 1)
if not int in res:
res.append(int)
break
return res | 0e758234260b2d29f5df2e74bafd05cddde48a23 | 3,621,253 |
def install_compiler(spec: str) -> None:
"""Install a compiler based on a spack specification e.g. gcc@9.3.0"""
run_subprocess('spack', 'compiler', 'find')
stdout, _ = run_subprocess('spack', 'compilers')
for line in stdout:
if spec in line:
return # Found the correct compiler!
... | f1aeb6b6d22c2418ac1cf7f0276f69a9c205305d | 3,621,254 |
from typing import List
from re import T
from typing import Union
def stree(
source: List[T], func: Union[Func, QueryFunction] = QueryFunction.SUM
) -> AbstractSegmentTree:
"""
Automatically detects the type of input container, and uses the
fastest possible segment tree implementation.
"""
try... | 713ae7ff2ed4ebc4b58c4bebd7b965caa18106d7 | 3,621,255 |
import warnings
def deprecated(func):
"""
This function is a decorator, which diplays a deprecation warning.
"""
@wraps(func)
def __inner(*args, **kwargs):
warnings.simplefilter('always', DeprecationWarning)
warnings.warn("{}".format(func.__name__), DeprecationWarning, stacklevel=2... | 9c89656fee8f4a5fa051a5f7eb59a798f103ea24 | 3,621,256 |
def softmax_loss_naive(W, X, y, reg):
"""
Softmax loss function, naive implementation (with loops)
Inputs have dimension D, there are C classes, and we operate on minibatches
of N examples.
Inputs:
- W: A numpy array of shape (D, C) containing weights.
- X: A numpy array of shape (N, D) co... | 72f16bd1f950154c92297240d0043fa3973399d3 | 3,621,257 |
def radial_histogram(r, weights=None, nbins=1000):
""" Performs histogramming of the varibale r using non-equally space bins """
r2 = r*r
dr2 = (max(r2)-min(r2))/(nbins-2);
r2_edges = np.linspace(min(r2), max(r2) + 0.5*dr2, nbins);
dr2 = r2_edges[1]-r2_edges[0]
edges = np.sqrt(r2_edges)
... | afbf637b2eb4a93d8eb977b4229e18d833eccf5d | 3,621,258 |
import functools
def dict_to_function(arg_dict):
"""
We need functions for Tensorflow ops, so we will use this function
to dynamically create functions from dictionaries.
"""
def inner_function(lookup, **inner_dict):
return inner_dict[lookup]
new_function = functools.partial(inner_fu... | b6bfb0a11393eeb93733cc41fe7395ce99136713 | 3,621,259 |
def resreid_train(images, num_class=751, trainable=True):
"""use resnet50 as backbone, modify the stride of last layer to be 1 for rich person features """
with flow.scope.namespace("base"):
stem = layer0(images, trainable=trainable)
body = resnet_conv_x_body(stem, lambda x: x, trainable=trainab... | fa977b2a8342988192746e5b4301e75837e56d0c | 3,621,260 |
import math
def _g(rd):
""" See page 3 at http://www.glicko.net/glicko/glicko.pdf """
return 1 / math.sqrt(1 + 3 * (Q ** 2) * (rd ** 2) / (math.pi ** 2)) | 9d6c23cee114f6699bc53b0dd0d7f129ebb504f1 | 3,621,261 |
def ecdh_reply(p,g,ag):
"""
Generates a random integer b, then computes the shared secred ab*g.
Input:
p A prime number
g An ECPt
ag An ECPt multiple of g
Output:
A tuple (int, ECPt, ECPt) = (b, b*g, ab*g).
Remarks:
This routine... | ed8a4077176fe6c1d018d563dc2209933acc3cc1 | 3,621,262 |
def get_instance(context, pvm_uuid):
"""Get an instance, if there is one, that corresponds to the PVM UUID
Not finding the instance can be a pretty normal case when handling events.
Don't log exceptions for those cases.
:param pvm_uuid: PowerVM UUID
:return: OpenStack instance or None
"""
... | bbd3bad7c817b419562d270ec1526b0af14312dc | 3,621,263 |
def findStars_old(imgData,apertureType='radius',maxima_size=5,maxima_sigma=2,maxima_footprint=None,aperture_radii=[],threshold=None,
saturate=None,margin=None,binStruct=None,fit_method='elliptical moffat',id=None):
"""
Detect possible sources in an image and attempt to fit them to a specified pr... | 35aa612480c03f894334e214212c4d3e569cb175 | 3,621,264 |
def run(factory, method: str, **kwargs):
"""hook to call event list factory
call any function
Args:
factory: :obj:`design_db_manager.events.EventManager` or :obj:`str`
method (str): 取得の仕方. 'get' or 'get_all'
kwargs (dict): kwargs for method selected by args
date or (yea... | c865787f3b85175e83307a347ac18be32312d6ba | 3,621,265 |
def arr_2_tio_image(arr):
"""
ScalarImage(shape: (c, w, h, d))
dtype: torch.DoubleTensor
"""
arr = arr.swapaxes(0,3)
return tio.ScalarImage(tensor=arr) | b4338c5ce507bf065bd6bd09a8ea55b193682ded | 3,621,266 |
from sys import path
def create_table_of_contents_github_or_gitlab():
"""
Read from file and returns list of (Original Text, Table of Contents List).
"""
md_text_toc_pairs = []
valid_filepaths = []
for filepath in params['name']:
name, ext = path.splitext(filepath)
if ext.low... | dfb30976a938a091e5218e7a2f23edf75bc8c9b0 | 3,621,267 |
def get_data_type(name):
"""Extract the data type name from an ABC(...) type name."""
return name.split('(', 1)[0] | 7565b30e1e2469de929b377fde1f186d28080f94 | 3,621,268 |
from typing import Tuple
import math
def rytz_axis_construction(d1: Vec3, d2: Vec3) -> Tuple[Vec3, Vec3, float]:
"""The Rytz’s axis construction is a basic method of descriptive Geometry
to find the axes, the semi-major axis and semi-minor axis, starting from two
conjugated half-diameters.
Source: `W... | 4256b510f5cf62e6a54d34aefd719d8ee0eee241 | 3,621,269 |
def moving_average(time_series, window_size=20, fwd_fill_to_end=0):
"""
Computes a Simple Moving Average (SMA) function on a time series
:param time_series: a pandas time series input containing numerical values
:param window_size: a window size used to compute the SMA
:param fwd_fill_to_end: index ... | d71931867c419f306824e8b240a9b1bb3fff2fdd | 3,621,270 |
def format_timestamp(df):
"""
Reformat timestamps to ISO 8601
Args:
df: input dataframe
Return:
input dataframe with timestamps formatted as ISO 8601
"""
return df.withColumn(
"timestamp",
F.date_format(
F.to_timestamp("timestamp"), "yyyy-MM-dd'T'HH:m... | fd9efdc2b563a90aafdc0204e339cd8735423b2d | 3,621,271 |
def FE(obs, mod, axis=None):
""" Fractional Error (%)"""
return (old_div(np.ma.abs(mod - obs), (mod + obs))).mean(axis=axis) * 2. * 100. | 86442208d49a13dd7f51c5c719fb406e7821fb28 | 3,621,272 |
def run_query(db_config_file, query, columns, **kwargs):
"""
General function to run a query against MLWH.
Parameters
----------
db_config_file : str
Path to MySQL config file.
query : str
SQL query.
columns : list of str
Column names for output.
**kwargs
... | 70571921d4cf6ad5a2f32d2774ffabadecb97782 | 3,621,273 |
import time
def compute_distribution_shift(index, df_wgt, Y, X, method, hist_len, freq=None, tic=0):
""" Y:target (unobserved), X:data (observed) """
N = Y.shape[1]
p = _normalize_distribution(Y)
q = _normalize_distribution(X)
if method.lower() in ['kl', 'kl-divergence']:
eps_ratio = (1-... | da8dda9fd66f9b7bb7b537282f08915e3ff65d54 | 3,621,274 |
from pathlib import Path
from typing import Sequence
def load_input(path: Path) -> Sequence[int]:
"""Loads the input data for the puzzle."""
with open(path, "r") as f:
depths = tuple(int(d) for d in f.readlines())
return depths | 35472eadcd2deefbbae332b3811be7d731cb2478 | 3,621,275 |
def create_user(email, password):
"""Create and return a new user."""
user = User(email=email, password=password)
db.session.add(user)
db.session.commit()
return user | 6f7d2a7ee8de6481dc0b7ab7e9e4ea2f0650d1b2 | 3,621,276 |
def forgiving_state_copy(target_net, source_net):
"""
Handle partial loading when some tensors don't match up in size.
Because we want to use models that were trained off a different
number of classes.
"""
net_state_dict = target_net.state_dict()
loaded_dict = source_net.state_dict()
new... | cea46fdc0fd123517ea2a678968d19e8716ccbdf | 3,621,277 |
def _get_query_results(job, splunk_client, limit):
""" Get results from a complete Splunk query """
# Get the results and display them
response = splunk_client.get_results(job, limit)
# Replace "null" with ""
if response:
response = remove_nulls(response)
return response | cfa85de524620cebd52f4654fa8839e94e12706d | 3,621,278 |
import asyncio
def patched_auth_failed_open_connection(auth_failed_prepared_stream_reader, event_loop):
"""Return a tuple of patched stream_reader and stream_writer."""
stream_writer = MagicMock()
if asyncio.iscoroutinefunction(stream_writer):
# Python 3.8.2 and later
return_value = (auth_... | 9dd44bb9178c4967c6c3fded392abf94b4710fd0 | 3,621,279 |
def has_permissions(**perms):
"""
A decorator that checks if the author has the required permissions.
Examples
--------
::
@has_permissions(administrator=True)
async def setup(ctx):
print("Success")
"""
async def predicate(ctx):
"""
Parameters
... | b0a579f61aca6a3ec24dbfc5cc474cdee8e8bb9d | 3,621,280 |
import os
import glob
import pprint
def run_qc_checks(project_dirs, machine_type):
"""main function"""
qcfails = []
assert len(project_dirs) >= 1
# determine all all/all/all/lane.html in project subdirs of given demux_dir
#
demux_html_files = []
for d in project_dirs:
g = os.path.... | f193ccbdd3ddd0d5cc1cc0baccbee8d1173ee1f8 | 3,621,281 |
def warning(text, render=1):
""" display a warning
Args:
text (str): warning message
render (bool, optional): Defaults to True. render or return settings
Returns:
str: setting value if render=False, None otherwise
"""
color = 'yellow'
s = "[Warning] %s" % text
writ... | 58b298d5ef3b72da60e6c10a18246a82295ed98d | 3,621,282 |
def _ratio_enum(anchor, ratios):
""" Enumerate a set of anchors for each aspect ratio wrt an anchor."""
w, h, x_ctr, y_ctr = _whctrs(anchor)
size = w * h
size_ratios = size / ratios
ws = np.round(np.sqrt(size_ratios))
hw = np.round(ws * ratios)
anchors = _mkanchors(ws, hs, x_ctr, y_ctr)
... | d40a6f24485b10347ea84059b6f922e3fa8a8be9 | 3,621,283 |
def dummy_filefield_as_sequence(toformat_name):
"""Simple helper method to fill a models.FileField"""
return factory.Sequence(lambda n: get_dummy_uploaded_image(toformat_name % n)) | 2f570f76f7ada1c87bc1e59885909c5dc2c74220 | 3,621,284 |
import logging
def intersect(bed, truth, chromosome, prefix):
"""
Perform bed intersection at chromosome level
:param bed: str
Bed file path
:param truth: str
Truth vcf path
:param chromosome: str
Chromosome
:param prefix: str
Prefix of the output file
... | b5fb39f001e974b1fa2ff7ceee3956d6ae316334 | 3,621,285 |
def read_model(hdf5_file_name):
"""Reads model from HDF5 file.
:param hdf5_file_name: Path to input file.
"""
return keras.models.load_model(hdf5_file_name) | 5c82b28ea06253f21bb8121c720972b58f8d7c81 | 3,621,286 |
from io import StringIO
def image(server, hash_string):
"""Handle image, use redis to cache image."""
image_url = 'https://{0}.zhimg.com/{1}'.format(server, hash_string)
cached = Config.redis_server.get(image_url)
if cached:
buffer_image = StringIO(cached)
buffer_image.seek(0)
else... | d90ad5740d8f2e4c4ac52c41a8c1b24fef04c5d9 | 3,621,287 |
def address(interface):
"""
Get the IPv4 address assigned to an interface.
Example::
import fabtools
# Print all configured IP addresses
for interface in fabtools.network.interfaces():
print(fabtools.network.address(interface))
"""
with settings(hide('running'... | c365992939efc1d452292e46d9b9fd235a5aa47f | 3,621,288 |
def nearest_griddata(x, y, z, xi, yi):
"""
Nearest Neighbor Interpolation Method.
Nearest-neighbor interpolation (also known as proximal interpolation or, in some contexts, point sampling) is a simple method of multivariate interpolation in one or more dimensions.<br/>
Interpolation is the problem of ... | 57d5d8c1caa8e23515bce3c2e796725dc5122233 | 3,621,289 |
import os
def path_to_label(path, pkgroot):
"""Substitute one pkgroot for another relative one to obtain a label."""
if path.find("${pkgroot}") != -1:
return os.path.normpath(path.strip("\"").replace("${pkgroot}", topdir)).replace('\\', '/')
topdir_relative_path = path.replace(pkgroot, "$topdir")... | e2ce2bffbd735880f47c8cda7e43ea8977a46055 | 3,621,290 |
def clean_invite_embed(line):
"""Makes invites not embed"""
return line.replace("discord.gg/", "discord.gg/\u200b") | 05b73197150e892ed2284d9c6ac8b0eebeb492b1 | 3,621,291 |
def invalid_name(statement):
"""Identifies invalid identifiers when a name begins with a number"""
first = statement.prev_token
second = statement.bad_token
# New in Python 3.10
if (
statement.highlighted_tokens is not None
and len(statement.highlighted_tokens) > 1
):
fir... | 714c54f95cf5cdcd3b58746e0bc18e75aca5d723 | 3,621,292 |
def bbox_iou(bboxes1, bboxes2):
"""
@param bboxes1: (a, b, ..., 4)
@param bboxes2: (A, B, ..., 4)
x:X is 1:n or n:n or n:1
@return (max(a,A), max(b,B), ...)
ex) (4,):(3,4) -> (3,)
(2,1,4):(2,3,4) -> (2,3)
"""
bboxes1_area = bboxes1[..., 2] * bboxes1[..., 3]
bboxes2_area =... | c5e4a437fc25836c6f6bd41dcc3293245fcce6d1 | 3,621,293 |
import tqdm
def get_album_audio_analysis(sp, album_name, album_name_dict, album_info_path):
"""Get audio analysis data for all albums for the given artists and pickle the data-frames
:param sp: Spotify object
:type sp: object
:param album_name: List of album names
:type album_name: list
:para... | 2e21e16ec4d5f544ff14baa3bec3515dad8ca2f3 | 3,621,294 |
def fit_and_sample(lagged_zvalues:[[float]],num:int, copula=None, fig_file=None, labels=None ):
""" Example of fitting a copula function, and sampling
lagged_zvalues: [ [z1,z2,z3] ] Data with roughly N(0,1) margins
copula :
returns: [ [z1, z2, z3] ] representative sample
... | 5e4cc13b305fa333b355a634d63068b4e8dea2cb | 3,621,295 |
from typing import Dict
from typing import List
from typing import cast
def set_errors_to_event(event_uuid: str, errors: Dict[str, List[str]]) -> bool:
"""Adds the list of errors provided into the event.
Arguments:
event_uuid {str} -- The UUID for the event to add errors to.
errors {List[str]... | f93d698a4ad97edf788745ee2988989296659285 | 3,621,296 |
def createQueryFilters(filters):
"""
Takes in filters from the frontend and creates a query that elasticsearch can use
Args: filters with the fields below
verified - if the user is verified
topics - list of topics we want to see
pov - point of view
lang - the langauge the tw... | ed1238f3f72a556eae3a1bc0d1afadef3bf67abb | 3,621,297 |
import torch
def compute_dual_subgradient(weights, dual_vars, lbs, ubs, l_preacts, u_preacts):
"""
Given the network layers, post- and pre-activation bounds as lists of
tensors, and dual variables (and functions thereof) as DualVars, compute the subgradient of the dual objective.
:return: DualVars ins... | a5b11272af838d5f6713fa8b06429627cc3ae266 | 3,621,298 |
import torch
def plot_surface_density_profile(model: astro_dynamo.model.DynamicalModel,
ax: SubplotBase = None,
target_values: torch.Tensor = None) -> SubplotBase:
"""Plots the azimuthally averaged surface density of a model.
The model must con... | ebf142b63256632ebefd558da66ce8e6aecd64ab | 3,621,299 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.