content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
from math import factorial
def combinations(n, k):
"""
nCk
>>> combinations(52, 2)
1326
"""
return permutations(n, k) // factorial(k) | 8ead280e3a542cdf09ea2e2d863b99ed4c1c0201 | 64,699 |
def extra_vascular_magnetic_field_shift(r, cylinder, Bo, delta_chi):
"""Returns the magnetic field at position `r` due to an infinite cylinder
Parameters
----------
r : 3-vector
Point to estimate field at
cylinder : Cylinder
Parameters describing the infinite cylinder
Bo : 3-vect... | 3481e0b65bc06336df0cf1ad40eeb4e5fc99ede6 | 64,700 |
def do_include_maybe(parser, token):
"""
A template helper to optionally include a template partial, and catch the
exception if it fails.
Source: http://stackoverflow.com/a/18951166/15690
"""
bits = token.split_contents()
if len(bits) < 2:
raise template.TemplateSyntaxError(
... | f22344c569f6b39cd690c57989cefdc9328142ec | 64,702 |
import six
def rev_comp( seq, molecule='dna' ):
""" DNA|RNA seq -> reverse complement
"""
if molecule == 'dna':
nuc_dict = { "A":"T", "B":"V", "C":"G", "D":"H", "G":"C", "H":"D", "K":"M", "M":"K", "N":"N", "R":"Y", "S":"S", "T":"A", "V":"B", "W":"W", "Y":"R" }
elif molecule == 'rna':
nuc_dict = { "A":"U", "... | 2e42ccf5f37992d0fbe3a25afd70a04e6fc0c225 | 64,703 |
def generate_all_decomp_prehash(seq, open_to_close, open_to_node):
"""
Like :func:`generate_all_decomp` but additionally returns the
precomputed hashes of the sequences.
"""
all_decomp = {}
stack = [seq]
while stack:
seq = stack.pop()
if seq:
# key = hash(seq)
... | 9008faf3fc5bd385eeaf1d9bb34d73080e8832d1 | 64,704 |
def get_grad(R, Y_dists, Y, optim = "fast"):
"""Compute the t-SNE gradient.
Inputs:
R - n*n matrix of difference between high/low dimensional affinities.
Y_dists - n*n matrix of embedded similarities.
Y - n*d matrix of current embeddings.
optim - "none", "fast", or "fastest"... | 61d073a461d5e2189a3c6885ebffa516a424e09c | 64,705 |
import math
def encoding_evidence(evidence, qe_comm, ee_comm, q_encoding, e_lstm_dim,
word_vec_dim, com_vec_dim, drop_rate, wordvecs,
default_init_std, default_l2_rate):
"""
Define network for encoding evidence
:param qe_comm: qe.ecomm features
:type qe_com... | 9944283e5cd4c398700c339ebe3081d29134bd73 | 64,706 |
def parseBytes(bytes,type="u16"):
"""
Parses bytes based on specified type.
"""
if type=="u16":
return bytes[0] << 0 | bytes[1] << 8
if type=="u32":
return bytes[0] << 0 | bytes[1] << 8 | bytes[2] << 16 | bytes[3] << 24
if type=="f32":
return np.array(bytes, dtype=np.uint... | 4d319f05c860a9d6bb797072e078883f51e2098a | 64,707 |
def data_refractor(record):
"""
data_record:single line of result_set, dict
"""
# 自定义逻辑
feature_list = []
label_list = []
data_feature_colums = [
"feature_1",
"feature_2",
"feature_3",
"feature_4",
"feature_5",
"feature_6",
"feature_7",... | b51e6b080eb2676524dc6a264887340bd6cbf968 | 64,709 |
def balanced_recall(predictions, labels):
"""Computes the balanced recall between the predictions from a model
and the real labels.
Parameters
---------
predictions : pd.DataFrame
Predicted classes for multiple objects.
Must contain a 'classALeRCE' column.
labels : pd.DataF... | e316566eb5d3065fdfbdd4a8dfe53df5e7608336 | 64,710 |
def is_security_provider_location(location):
"""
Does the current location refer to a security provider (e.g., SAMLAuthenticator?
:param location: the location
:return: True, if the location refers to a security provider, False otherwise
"""
return location.get_folder_path() in SECURITY_PROVIDER... | 67ecbedcca74ffc9b0c05f4d23457e34376c2ded | 64,711 |
def getThreshValuebyHistogram(img, weight, is_handle=True):
"""
根据权重预测阈值
"""
img = moveNoise(img, 7) # 去噪
histogram = getHistogram(img) # 获得直方图
if is_handle:
histogram = np.mat(histogram)
histogram = handleHistogram(histogram)
mean_value = getMean(img)
data = np.mat(histo... | 65e1d6d72fd5bee8e601c5ad87e31c29511fbfa8 | 64,712 |
import math
def iters_close(iter1, iter2):
"""Assert that the given iterators are near-equal."""
iter1, iter2 = list(iter1), list(iter2)
if len(iter1) != len(iter2):
return False
for i in range(len(iter1)):
a = iter1[i]
b = iter2[i]
if math.isnan(a) and (isinstance(b, c... | efaaaced7260642b0bcd14eed54f02803e61c9ad | 64,713 |
import copy
def get_component_run_information(component_run_id: str) -> ComponentRun:
"""Returns a ComponentRun object."""
store = Store(_db_uri)
cr = store.get_component_run(component_run_id)
if not cr:
raise RuntimeError(f"Component run with id {id} not found.")
inputs = [
IOPoin... | 4c5e1450b3cd3d901a78e7a81d51ec3a949c1279 | 64,714 |
def dense_model_moments(Inputs,nclasses,nregressions,dropoutRate=0.25):
"""
Dense matrix, defaults similat to 2016 training. Adaptation for moment-based domain adaptation
"""
if nregressions: raise ValueError(
'The dense model does not support regression, only classification')
#set_trace()
# Here add e.g. the... | 3832a395f3a4101ab988eff0c7bdf7a62484e766 | 64,716 |
def revoke_lf_permissions(principal_json, table_json, tableWithColumns_json, perm_json):
"""
Revokes the specified permissions to the Pricncipal on the Respective resources
Arguments:
principal_json {dict} -- Principal which requries grant
table_json {... | fb22211849e4b5f60897358b525fe4e20a684e1a | 64,717 |
def sigmoid(current_z):
"""
sigmoid function.
:param current_z: input Z, numpy arrays or numbers
:return: result A, caches for following calculations, numpy arrays or numbers, dictionaries
"""
a = 1 / (1 + np.exp(-current_z))
cache = current_z
return a, cache | 18a1f9c36c4d6b60546020cbb3521e66affb8e09 | 64,718 |
def readu16(fd, loc=None):
"""
Read an unsigned 16-bit number
:param fd: file handle
:param loc: seek location
:return: a 4-byte number
"""
if loc is not None:
fd.seek(loc)
data = fd.read(4)
return data[0] + 256 *data[1] | f738464518b9b8bb37ffef8d1ba5669b0b6c107a | 64,720 |
def pe57(limit=1000):
"""
>>> pe57()
153
"""
n, d = 3, 2
cnt = 0
for a in range(limit + 1):
# n, d = n + (d << 1), n + d
nn = n
n += d << 1
d += nn
if len(str(n)) > len(str(d)):
cnt += 1
return cnt | ae898b427c8061d63d401957441a5c42e78238f7 | 64,722 |
def findall_deep(node, selector, ns, depth=0, maxDepth=-1):
"""
recursively find all nodes matching the xpath selector
:param node: the input etree node
:param selector: the xpath selector
:param ns: a dict of namespaces
:param depth: the current depth
:param maxDepth: the maximum number of... | f93d413dd205acf5be0e5f76dd6c599f54bfac57 | 64,723 |
from operator import add
def create_resblock (channels, inputs):
""" a convelution block with residual connection """
x = BatchNormalization (momentum = 0.9)(inputs)
x = LeakyReLU (0)(x)
x = Conv2D (channels, 3, padding='same', use_bias = False)(x)
x = BatchNormalization (momentum = 0.9)(x)
x ... | 2056e5394bb163275fc5f18a5f341f16ca29585c | 64,724 |
def get_rod(num, organized=False):
"""
Returns a list of Wyckoff positions for a given 1D Rod group. Has option to
organize the list based on multiplicity (this is used for
random_crystal_1D.wyckoffs)
For an unorganized list:
- 1st index: index of WP in layer group (0 is the WP with l... | 60be0fc659782b8b8504b5904689157a21dca51f | 64,725 |
def update_version_py () :
"""Update `VERSION.py` in current directory with git version info."""
d_v = git_date_version ()
if d_v :
date, tagged_version = d_v
version_py = version_py_fmt % dict \
(date = date, tagged_version = tagged_version)
with open ("VERSION.py", "w",... | 273c607a658da391e7d029af1105fda2ed683d04 | 64,726 |
from algs.node import Node
def tournament_two_losers(A):
"""
Returns two largest values in A. Only works for lists whose length
is a power of 2. Each winner accumulates list of the values it beat,
from which you call max() to find the second largest.
"""
if len(A) < 2:
raise ValueError... | ce9ea0c1673f864f45b507e679824a4e36b21503 | 64,729 |
def getDArray_( valsstr ):
""" Provides float equivalence of input. Converts input or element of input into floats
Parameters:
* valsstr (int, float, list of int/float)
Returns:
* float, list of float
"""
if isinstance(valsstr,list) and len(valsstr) > 1:
ret = list()
for valstr in valsstr:
... | 51fc2381bcaff1111fa2a3869a273fd38ea15e6e | 64,730 |
def ModelAddMetadataBuffer(builder, metadataBuffer):
"""This method is deprecated. Please switch to AddMetadataBuffer."""
return AddMetadataBuffer(builder, metadataBuffer) | 9ac93fe44375caeddf97e3e1a809625db0189b4d | 64,731 |
def about_page(request):
"""
Function to handle requests on the about us page.
:param request: The HTML request to handle.
:return: Renders the about us algorithm page.
"""
if request.session.get('delete'):
del request.session['delete']
if request.session.get('content_compare'):
... | 936eb5ab3d59bcef1188e18d96daac68fb5a0f19 | 64,732 |
def true_select_atoms(u, sel='protein', ignh=True, norm=True):
"""
Create "true selection" (atomgroup copy in NEW universe) after applying
- norm_ids()
- norm_resids()
Note that atom indices are reassigned according to range(0, len(u.atoms))
Args:
u (str, universe, atomgrp): struc... | 292ec73777826d26cc353c04b4cebf3476360a92 | 64,733 |
def extract_labels(path):
"""
Loads labeled dataframe and extract list of labeled subtitle ids.
"""
labeled_df = pd.read_csv(path)
labeled_df['IDSubtitle'] = labeled_df['IDSubtitle'].astype(int)
return labeled_df.IDSubtitle.astype(str).values | 201f81734900a09f9c521cd42f9e2179d2610576 | 64,734 |
def circle(m, centerlon, centerlat, radius, *args, **kwargs):
"""
Return lon, lat tuples of a "circle" which matches the chosen Basemap projection
Takes the following arguments:
m = basemap instance
centerlon = originating lon
centrelat = originating lat
radius = radius
"""
glon1 = ... | 7bb8be8f4af2478544b57f357f5a9281c500d926 | 64,735 |
def OpenS3Client(cred_path: str, region: str = 'us-east-2'):
"""
Open a boto3 S3 client using the specified credentials in the specified region
:param cred_path: Path to the credentials file
:param region: region to open the client in
:return: The opened s3 client
"""
session = OpenSession(... | dda174e6023947a709db4e62de15b51878b34ab7 | 64,737 |
import ctypes
def get_comm(name='main'):
"""get_comm
:param name:
"""
comm = Comm()
if isinstance(name, str):
rdc._LIB.RdcGetCommunicator(
ctypes.byref(comm.handle), name.encode('utf-8'))
elif isinstance(name, bytes):
rdc._LIB.RdcGetCommunicator(ctypes.byref(comm.h... | 67de30a4eb6265bb4b97d96067bce79e2942f0d8 | 64,738 |
def get_horizontal_direction_parameters(n, region_points, cl_points, beta):
"""
Find directions for manipulation
in the horizontal direction.
Args:
n (ndarray): Normal vector to plane through clipping points.
region_points (ndarray): Clipping points.
cl_points (ndarray): Points ... | e6e761d0b6ed4472f2e57e4d62595b0401ea7e35 | 64,739 |
from typing import Optional
from typing import Mapping
import base64
def inline_img(type: str, b64_data: Optional[bytes]=None, img_fname: str=None, attrs: Mapping[str, str]={}) -> Markup:
"""Creates an image tag for inline representation.
Requires its type (e.g., png, gif), either base64 data or file na... | 52f9fc7ce946cf8bfa01d850b89256b364527d12 | 64,740 |
def reflow_quoted_text(text, width=72):
"""Reflow text with 'soft' (SP CR LF) newlines according to rfc2646
Text paragraphs containing 'soft' newlines are reflowed for a maximum
line length of @width characters.
Only non-quoted text is reflowed (Lines not starting with '>').
>>> reflow_quoted_... | bee68c7c02ae302debc7287ac8e8b8a6cf9a7cc3 | 64,741 |
def get_rms(infile, xcent, ycent, xsize, ysize=None, outfile=None,
verbose=True):
"""
Gets the rms in the requested region of the input file. The region is
defined by its central pixel location (xcent, ycent) and its size in
pixels (xsize and, optionally, ysize). If ysize is not given, th... | 50147f0fd4bc990aed868f8a3e01a8274d9f4bf8 | 64,742 |
def dWtophatkspacedR ( kR ,R ) :
"""
Returns the derivative of the Fourier Transform of the real space
top hat window function which is 1 when r < R, and 0 otherwise with
respect to R.
args:
kR : unit less quantity.
R : Radius
returns:
array like derivative of Wtophatkspace with respect to R
"""
... | 23eb95cf2ae3a9bfb2b5cc3993f59b341848c4c7 | 64,743 |
from typing import Union
from typing import List
def table_insert(name: str, field_names: Union[str, List[str]]) -> str:
"""Return command to add a record into a PostgreSQL database.
:param str name: name of table to append
:param field_names: names of fields
:type: str or list
:return: command ... | a50aadebe655118c255ccb81c3c0852646057ff4 | 64,744 |
def get_epidist(x1,x2, M, type='symmetric'):
"""
Adapted from https://github.com/vcg-uvic/learned-correspondence-release
Get an epipolar distance metric of keypoint correspondences between 2 images
using the correspondence matrix M.
Inputs
------
x1: np.array (Nx2)
normalized camer... | 3c23d87d19c7429219035a4822a8dee76e7e40fd | 64,745 |
import torch
def kg_neg_loss(entity_head_embed, entity_tail_embed, entity_head_idxs, entity_tail_idxs,
relation_vec, relation_bias_embed, num_samples, distrib):
"""Compute negative sampling loss for triple (entity_head, relation, entity_tail).
Args:
entity_head_embed: Tensor of size [... | 4bb0afd986d2b7fbd89921479644d7407f4ded69 | 64,747 |
def health() -> Response:
"""Return a 200 OK response. Used for automated health checks
Returns
-------
flask.Response
200 OK response
"""
return jsonify({"status": "ok"}) | 76b40477d5334047ced9b8cbb85a4c33591b3001 | 64,749 |
def __normalize(variable):
"""
Scale a variable to mean zero and standard deviation 1
Parameters
----------
variable : xarray.DataArray or np.ndarray
Returns
-------
xarray.DataArray or np.ndarray
"""
mean = variable.mean()
std = variable.std()
if std != 0:
resu... | 7d6329ef6454deb04b041a630a7f1f084f237b57 | 64,750 |
def final_time():
"""
Real Name: b'FINAL TIME'
Original Eqn: b'365'
Units: b'Day'
Limits: (None, None)
Type: constant
b'The final time for the simulation.'
"""
return 365 | 10cd388e6840ac42cd6017f27e43746e62f0e135 | 64,751 |
from typing import Iterable
def ngrams(iterable: Iterable, n=3):
"""
Generate an iterator returning a sequence of adjacent items
in the iterable.
s -> (s0, s1, s2), (s1, s2, s3), (s2, s3, s4), ...
A generalization of the pairwise function from
https://docs.python.org/3/library/itertools.html#... | e64f758b58bef3ef586fa2eee373f052154184bd | 64,752 |
def delay_mat(mat, delays):
"""delays a matrix by a set of delays d.
a row t in the returned matrix has the concatenated:
row(t-delays[0],t-delays[1]...t-delays[last] ).
"""
new_mat = np.concatenate([delay_one(mat, d) for d in delays],axis = -1)
return new_mat | 661f10f327d2ea4759bba4673c7aa09b1b92af03 | 64,754 |
def get_y_true(task_name, true_data_dir):
"""
Read file to obtain y_true.
All of five tasks of VLSP 2018 use the test set of task-BERT-pair-NLI-M to get true labels.
"""
df = pd.read_csv(true_data_dir,sep='\t',header=None).values
y_true=[]
for i in range(len(df)):
label = df[i][1]
... | 8a28822367bee3c1cae5d7ff5ce06101f2eff975 | 64,755 |
import io
def load_bson_img(bson_file, img_metadata, grayscale=False, target_size=(64, 64)):
"""
Note:
This implementation is just taking the first image for the product, sometimes there are up to 4 images
"""
bson_file.seek(img_metadata['offset'])
item_data = bson_file.read(img_metadata['length'])
item = bso... | 57e7856fb5c2e5b4cd58915b8ab9043a194aea37 | 64,756 |
def zeroline(canv):
""" returns a dashed, gray horizontal line at zero
"""
zline = get_line(0, canv)
zline.SetLineColor(rt.kGray)
zline.SetLineStyle(9)
return zline | e0d58427fefa24045fb80487ca5ce9b86b4be5bf | 64,757 |
import torchvision
def _dataset(dataset_type: str, train=True):
"""
Dataset:
mnist: MNIST
cifar10: CIFAR-10
cifar100: CIFAR-100
"""
if dataset_type == "mnist":
dataset = torchvision.datasets.MNIST(
root=ROOT, train=train, download=False,
transform=None
... | 2e657f20d308765dec2720781f673288337c4576 | 64,758 |
def get_old_prim_signals(signals):
"""
create a dict of primary signals and the secondary signals they control
data is compiled from the 'secondary_signals' field on primary signals
this field is populated by this Python service
Args:
signals (TYPE): Description
Returns:
... | a37c4b2837beb2a8354be30f1247f9555319edac | 64,759 |
def rshift(char, shifts):
"""Shifts the given character by the given number of shifts"""
temp = ord(char) + (shifts % 26)
# if the shift reaches an edge, circle back around
if not chr(temp).isalpha() or (char.isupper() and chr(temp).islower()):
shifts = 26 - (shifts % 26)
temp = ord(cha... | b8d811757ee9e0876d0f7b4b28e2b863dd5f7885 | 64,760 |
def _constant_speed_and_yaw_rate(kinematics_data: KinematicsData,
sec_from_now: float, sampled_at: int) -> np.ndarray:
"""
Computes a baseline prediction for the given time window and frequency, under
the assumption that the (scalar) speed and yaw rate are constant.
:par... | 8911fa4030636523c0ceb0003fcb4c1484ab4d48 | 64,762 |
def six_agents():
"""Six agents
"""
a_1 = Agent(AGENT_ARGS, start_pos=[0.0, 0.0, 0.0], goal=[1.5, 3.0, 0.0])
a_2 = Agent(AGENT_ARGS, start_pos=[2.0, 0.0, 0.0], goal=[0.0, 4.0, 0.0])
a_3 = Agent(AGENT_ARGS, start_pos=[1.0, 2.5, 0.0], goal=[4.0, 0.0, 0.0])
a_4 = Agent(AGENT_ARGS, start_pos=[4.0, 4... | 2dca61f7d0b4861b1cfcc3b9cc3af3c8658bc60f | 64,763 |
def get_proj(ds):
"""
Read projection information from the dataset.
"""
# Use geopandas to get the proj info
proj = {}
maybe_crs = ds.geometry.crs
if maybe_crs:
maybe_epsg = ds.geometry.crs.to_epsg()
if maybe_epsg:
proj["proj:epsg"] = maybe_epsg
else:
... | 4ed68d8733285cdea92c1b167a3d7f59024845db | 64,764 |
def do_migration() -> bool:
"""Do actual migration"""
token = generate_token()
ret = change_ca_passwords(token)
if ret:
create_ca_ini(token)
return ret | 1d0b2d31249ccb3400d0c73be940d7c2f84204c7 | 64,765 |
def nameFormat(name):
""" Edits the name of the column so that it is properly formatted with a space between the words, and each word capitalized."""
space = name.find("l") + 1
firsthalf = name[:space]
secondhalf = name[space:]
name = firsthalf.capitalize() + " " + secondhalf.capitalize()
return... | d93b54d6a18347aeb32657c1f8880965d01db7f2 | 64,766 |
def download_libsvm(dataset, destination, replace=False):
"""Download a dataset from LIBSVM website."""
url = ("https://www.csie.ntu.edu.tw/~cjlin/libsvmtools/datasets/" +
NAMES[dataset])
path = download(url, destination, replace=replace)
return path | 5610d3cbb00b4cfe6533310ef0294b2702a7a0fa | 64,767 |
def invert_cd_path(graph, path, c, d):
"""
Switch the colors of the edges on the cd-path: c to d and d to c.
:param graph: nx.Graph(); each edge should have an attribute "color"
:param path: nx.Graph() representing cd-path
:param c: integer smaller then the degree of "graph" or None; represents a co... | 53455f3e442a10ee403d499fe9c5b6f2e86a6e7f | 64,768 |
def observe_state(obsAction, oppID, oppMood, stateMode):
"""Keeping this as a separate method in case we want to manipulate the observation somehow,
like with noise (x chance we make an observational mistake, etc)."""
# print('oppmood', oppMood)
state = []
if stateMode == 'stateless':
state.... | ad3417a724982679a8abf653b456a00c4129ef48 | 64,769 |
import warnings
import scipy
def resize_mask(mask, scale, padding, crop=None):
"""
Re-sizes a mask using the given scale and padding.
Typically, you get the scale and padding from resize_image() to
ensure both, the image and the mask, are resized consistently.
scale: mask scaling factor
paddi... | 3a3e2cb0aa8667863ab72d4526eeb7e2cf969820 | 64,770 |
def rotate_pairs(word_list):
"""Return list of all rotate pairs found in word_list.
word_list: list of words
"""
rotate_pairs = {}
for word in word_list:
first_letter = word[0]
if first_letter.isupper():
ref_letter = ord('A')
elif first_letter.islower():
... | 1386f857c6661c1caae4c75decb0810b4441cced | 64,771 |
def hamming(n, normalize=1):
"""Hamming window
Parameters
----------
n : int
Window length
normalize : int, optional
Normalization flag
(0) don't normalize
(1) normalize by power
(2) normalize by magnitude
Default is 1.
Returns
... | fe473e4b4024aec7d46ced53fb47956e12ce2452 | 64,773 |
import math
def SDT(hits, misses, fas, crs):
""" returns a dict with d-prime measures given hits, misses, false alarms, and correct rejections"""
# Floors an ceilings are replaced by half hits and half FA's
half_hit = 0.5 / (hits + misses)
half_fa = 0.5 / (fas + crs)
# Calculate hit_rate and avoid... | 5d1cad9e35efe9cccba42847a136058ea7978bf0 | 64,774 |
def bbox_compute_targets(ex_rois, gt_rois, normalize):
"""
Compute bounding-box regression targets for an image
Parameters:
-----------
ex_rois: ROIs from external source (anchors or proposals)
gt_rois: ground truth ROIs
normalize: whether normalize box (since RPN doesn't need to normalize)
... | 464aa945e25a19184a2e9787f7f5fc595a0737fa | 64,775 |
from typing import Iterable
def delete_statistics_runs_rows(
statistics_runs: Iterable[int],
) -> StatementLambdaElement:
"""Delete statistics_runs rows."""
return lambda_stmt(
lambda: delete(StatisticsRuns)
.where(StatisticsRuns.run_id.in_(statistics_runs))
.execution_options(sync... | 0be693b69700f8d0aa804978ed292088d256fc2c | 64,777 |
def pascal_triangle(n):
"""
eturns a list of lists of integers
representing the Pascal’s triangle of n
"""
if n <= 0:
return []
res = []
l = []
for x in range(n):
row = []
for y in range(x + 1):
if x == 0 or y == 0 or x == y:
row.append... | 49f0474083cd347177bbe963af811fbe6a8a15d8 | 64,778 |
def image_crosscorr_plot(spike_depths, spike_times, chn_coords, t_bin=0.05, d_bin=40,
cmap='viridis', display=False):
"""
Prepare data for 2D cross correlation plot of data across depth
:param spike_depths:
:param spike_times:
:param chn_coords:
:param t_bin: t_bin: tim... | 3c743fa9aae17cd363f5ee36df77d19ec0428a18 | 64,779 |
from typing import List
from typing import Dict
import types
def get_node_map(meta_graph_def: meta_graph_pb2.MetaGraphDef, prefix: Text,
node_suffixes: List[Text]
) -> Dict[types.FPLKeyType, Dict[Text, CollectionDefValueType]]:
"""Get node map from meta_graph_def.
This is designe... | 237ad32b759b71e11e01db608717ead64c7d26f4 | 64,780 |
def get_pred_closing_price(df, test, scaler, model):
"""
Predict stock price using past 60 stock prices
INPUT:
df - dataframe that has been preprocessed
scaler - instantiated object for MixMaxScaler()
model - fitted model
OUTPUT:
closing_price - predicted closing price using fitted mod... | 56e3f4d41c7aef3fa7e01e354490857a80add619 | 64,781 |
def getall(oc_user,params):
"""获取所有材料
"""
user_material_obj = UserMaterial.get_instance(oc_user.uid)
return 0, {"msg": user_material_obj.materials} | b728ab42bc817c16253caabe9c1c18d86aba11d5 | 64,782 |
def _initialise_notable_eids(db):
"""Returns set of eids corresponding to "notable" entities."""
rows = db.query("""
SELECT eid FROM entity_flags
WHERE political_entity=TRUE;
""")
notable_eids = set(row["eid"] for row in rows)
print('[OK] Received %d notable eIDs.' % len(notable_eids))
... | c11306395937fc58dadbd3e9d129f7f6d7b4b576 | 64,783 |
import math
def sampling(x_row, y_column, lateral_step, longitudinal_step):
"""
:param x_row: s采样个数
:param y_column: lateral采样个数
:param lateral_step: 采样步长
:param longitudinal_step: 纵向采样步长
:return:
"""
end_set = np.empty(shape=[x_row, y_column, 3])
for i in range(x_row):
... | 8d8c4f9cb66a2de51fcc949bd59eae046cadb3de | 64,784 |
def create_switch_with_spray_level(accessory):
"""Define battery level characteristics."""
service = accessory.add_service(ServicesTypes.OUTLET)
spray_level = service.add_char(
CharacteristicsTypes.Vendor.VOCOLINC_HUMIDIFIER_SPRAY_LEVEL
)
spray_level.perms.append("ev")
spray_level.valu... | 1f8d36d28962c0f60e7eeadfdf813f7a7dcae789 | 64,786 |
import click
def sprompt(prompt_msg, color=CLI_STATUS, **prompt_args):
"""
:py:func:`click.prompt`, but with colored prompt text.
See :py:func:`click.style` for supported colors.
Args:
prompt_msg (str): Prompt message
color (str): Color for prompt message
\\*\\*prompt_args (di... | a855054654e21a7b09320acff7c6b3edb0610ca5 | 64,787 |
def get_vector22():
"""
Return the vector with ID 22.
"""
return [
0.50000000,
0.25000000,
0.25000000,
] | 20fcd0ccb42dad295c5b09e85c9071bbe6413512 | 64,788 |
def ldm(self, operand: int) -> int:
"""
Name: Load Accumulator Immediate.
Function: The 4 bits of immediate data are loaded into
the accumulator.
Syntax: LDM <value>
Assembled: 1101 <DDDD>
Symbolic: DDDD --> ACC
Execution: 1 word, ... | ee76ddd7e14dbc6cc03d586a82421bbccc38d83c | 64,789 |
import re
def extract_url_keywords(url, stem=False):
"""Return keyword extracted from URL.
Useful for figuring out what keywords a URL is targeting."""
rv = False
if good_url(url):
parts = urlparse(url)
keywords = re.split("\W+", parts.path)
keywords = " ".join([x for x in key... | b55190e3b440fa7b5c96e1ded62a9c596db214ba | 64,790 |
def reference_contexts_for_variant(
variant,
context_size,
transcript_id_whitelist=None):
"""
variant : varcode.Variant
context_size : int
Max of nucleotides to include to the left and right of the variant
in the context sequence.
transcript_id_whitelist : set, ... | 3117608be6ffca1fc08b8653c13bff3ce3e0bdcd | 64,791 |
def GetColorHistogram(image, ignore_color=None, tolerance=0):
"""Computes a histogram of the pixel colors in this image.
Args:
ignore_color: An RgbaColor to exclude from the bucket counts.
tolerance: A tolerance for the ignore_color.
Returns:
A ColorHistogram namedtuple with 256 integers in each fiel... | ff3109bbd68c31d717e7a7376b204c9276f2f421 | 64,792 |
def register():
"""View function for Register."""
# Create the form object for RegisterForm.
form = RegisterForm()
# Create the form object for OpenIDForm.
openid_form = OpenIDForm()
# Send the request for login to relay party(URL).
if openid_form.validate_on_submit():
return openi... | 712bf628490b9d09548427f0b61f0066470d2a23 | 64,794 |
def _comma_separated_list_validator(value: str | list[str]) -> list[str]:
"""Validate a comma separated list."""
if isinstance(value, list):
return value
return value.split(",") | f19c98f4b16eada3220fba74f38272a45ad382c0 | 64,795 |
def get_phase_diagram_points(pops, discard_gens=1, dimensions=2):
"""
Convert a DataFrame of values from the model into a set of xy(z) points.
Arguments
---------
pops: DataFrame
population data output from the model
discard_gens: int
number of rows to discard before keeping poi... | b5fe3a9a6aa46ef179e37c553a8ed21795f68cc4 | 64,796 |
def get_share_backend_id(share):
"""Get backend share id.
Try to get backend share id from path in case this is managed share,
use share['id'] when path is empty.
"""
backend_share_id = None
try:
export_locations = share['export_locations'][0]
path = export_locations['path']
... | e52d3daed0223fdf9c9e760879021e937ac309ce | 64,797 |
def get_current_package_name():
"""
获取当前应用的包名
返回包名
:return: str
"""
return get_ui_device().get_current_package_name() | dbda678123fbe8fc21ac6c2a9b561a748e7f23a8 | 64,798 |
import operator
def longest_common_balanced_embedding(
seq1, seq2, open_to_close, open_to_node=None, node_affinity="auto", impl="auto"
):
"""
Finds the longest common balanced sequence embedding between two sequences
This is used as a subproblem to solve the maximum common embedded subtree
proble... | 900c52b16f0a60e064431a58a23a1dfd826979ef | 64,799 |
def _bytes_chr_py3(i):
"""
Returns a byte string of length 1 whose ordinal value is i in Python 3.
Do not call directly, use bytes_chr instead.
"""
return bytes([i]) | b6cd1e5e7214d02c29a594e639fbddac901a1362 | 64,800 |
import array
def rot_arbit(angle, u_v):
"""Takes an angle in radians and a unit vector and outputs a rotation matrix around that vector
Arguments:
angle (int): Angle in radians.
u_v (list): Unit vector
Returns:
(array): Rotation matrix
"""
rot_mat = array(
[
... | d10731ab62b5fc30d81c035509f5ca60bc9a3fa6 | 64,801 |
def complete(request, reason=None, attempt_num=None, questionpaper_id=None):
"""Show a page to inform user that the quiz has been compeleted."""
user = request.user
if questionpaper_id is None:
message = reason or "An Unexpected Error occurred. Please contact your '\
'instructor/administ... | e4cbbfe08e3d8004d1bb6bd0803d68ca7791e307 | 64,802 |
def isPublic(ip_addr):
"""
description: 检测是否公有ip
param {str} ip_addr - [ip地址]
return {bool} 是否为公有ip
author: Senkita
"""
if IP(ip_addr).iptype() == 'PUBLIC':
return True
logger.warning('{} - Private.'.format(ip_addr))
return False | ec160f6da8d7b3260d6bfeb726982b710883a12d | 64,803 |
def makeDASRunNested(dasrun_ingredients):
"""
Used by the multiprocessing module within getDASRuns to more quickly build DASRun objects
"""
config_path, schema_name = dasrun_ingredients
return DASRunNested(config_path) | 40a9ada0497c77accd436054f940029fbb49e61b | 64,805 |
def _to_channel_first_bias(b):
"""Reshape [c] to [c, 1, 1]."""
channel_size = int(b.shape[0])
new_shape = (channel_size, 1, 1)
# new_shape = [-1, 1, 1] # doesn't work with tensorRT
return tf.reshape(b, new_shape) | 040d2cbda192998449e6e5727ff6632004057979 | 64,806 |
def Compile(text: str) -> str:
"""A preprocessor which attempts to compile the given code.
Args:
text: Code to compile.
Returns:
The input code, unmodified.
"""
clang.CompileLlvmBytecode(text, ".cpp", CLANG_ARGS)
return text | 9b02f6ef71eb8a33aee766d4736510059e838da0 | 64,807 |
def cart2pol(x, y):
"""
helper function for coordinate conversion of Cartesian to polar coordinates. See cart2pol in Matlab. From http://stackoverflow.com/a/26757297
:param x: x values
:param y: y values
:return: radius rho and angle phi
"""
rho = np.sqrt(x ** 2 + y ** 2) # radius
phi =... | 4ecbbc674cfd29f89b36a66caa6b8a2dfcaa53da | 64,808 |
def create_change(outputs: dict, total_selected: int, address: str, total_outputs: int, fees: int) -> (dict, int):
"""
Identify the change and create if necessary.
Change the outputs adding the change.
:param outputs: Dict with the outputs.
:param total_selected: Sum of the selected UTXO.
:param address: Address ... | 09945f0a2ada582ddd8763c7d165c2c26348580c | 64,809 |
def parseDownloadRange(rangeStr : str):
"""Parse and get the download range indices"""
# validate first if it is a valid range format
if not validateRange(rangeStr):
return None
# get range specifiers
ranges = rangeStr.split(",")
try:
rangeFrom = None if ranges[0] == "" else i... | afc0a3dca18f4b78e1c342c5fd5a38f6425fa0f9 | 64,811 |
def state_changed(func):
"""Decorator indicating a function which changes the state
Parameters
----------
func : callable
The function to wrap.
Returns
-------
callable
The wrapped function.
"""
@wraps(func)
def wrapped(self, *args, **kwargs):
ret = fun... | d171e07c081d71deeba23f00f71fc36a62156d02 | 64,814 |
def linux_provisioners(**kwargs):
"""Linux specific provisioners."""
# Setup vars from kwargs
vagrant_box = kwargs['data']['vagrant_box']
build_scripts_dir = kwargs['data']['build_scripts_dir']
template = kwargs['data']['template']
scripts = [
f'{build_scripts_dir}/base.sh',
f'... | 7627205c94ca8c1d445a8d8af3fd7fb7e062226c | 64,815 |
def bin_points(XYZ_cms, map_size, z_bins, xy_resolution):
"""Bins points into xy-z bins
XYZ_cms is ... x H x W x3
Outputs is ... x map_size x map_size x (len(z_bins)+1)
"""
sh = XYZ_cms.shape
XYZ_cms = XYZ_cms.reshape([-1, sh[-3], sh[-2], sh[-1]])
n_z_bins = len(z_bins) + 1
counts = []
... | fee13961f841d44ecb6d291f713806ba4e42b0b6 | 64,816 |
def grade(quiz_code):
"""
Grades the instance according to the options selected using the answer method
:param quiz_code:
:return: json representing the quiz or with a custom error
"""
text_response = controller.grade_quiz(quiz_code)
return text_response | d4094c00cd9445824adc4a993717da4aa03c0241 | 64,818 |
def summarize_obo(obo_file):
"""summarize content from an obo into a list
:param obo_file: path to obo file
:return: dictionary mapping ids to objects with
data, aux_pos, aux_neg components
"""
result = []
obo = Obo(obo_file)
for id in obo.ids():
term = obo.terms[id]
... | 573cf046698692b32638841c187bac8adedc6a8f | 64,821 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.