content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
from typing import Dict
from typing import Pattern
import re
def get_xclock_hints() -> Dict[str, Pattern]:
"""Retrieves hints to match an xclock window."""
return {"name": re.compile(r"^xclock$")} | 99e1fe51b46cb5e101c2a1c86cf27b2b60c0a38e | 3,633,439 |
def calciteSaturationAtFixedPCO2(
logPCO2, phreeqcInputFile, PHREEQC_PATH, DATABASE_FILE, newInputFile=None
):
"""
Function used in root finding of saturation PCO2.
Function is used by findPCO2atCalciteSaturation(). As a stand alone function, it's
better to use phreeqcRunSetPCO2().
Parameters
... | 2b805c31ee80230a71e6c8eff27d5b8ed6167d20 | 3,633,440 |
import math
def fnCalculate_ReceivedPower(P_Tx,G_Tx,G_Rx,rho_Rx,rho_Tx,wavelength,RCS):
"""
Calculate the received power at the bistatic radar receiver.
equation 5 in " PERFORMANCE ASSESSMENT OF THE MULTIBEAM RADAR
SENSOR BIRALES FOR SPACE SURVEILLANCE AND TRACKING"
Note: ensure that the dis... | 944fb485e9d9a3d2da130e4ddc415e63ab814380 | 3,633,441 |
import time
def datetime_creator():
"""
返回标准格式的datetime
Returns:
"""
return time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) | 1d55b0f3f93bcc850f961902d74a0f7fd8200f27 | 3,633,443 |
def get_l2_loss(excluded_keywords=None):
"""Traverse `tf.trainable_variables` compute L2 reg. Ignore `batch_norm`."""
def _is_excluded(v):
"""Guess whether a variable belongs to `batch_norm`."""
keywords = ['batchnorm', 'batch_norm', 'bn',
'layernorm', 'layer_norm']
if excluded_keywords ... | 7ec4a42d92f652f40ac3bdf939490edf2912697d | 3,633,444 |
from datetime import datetime
def tzdt(fulldate: str):
"""
Converts an ISO 8601 full timestamp to a Python datetime.
Parameters
----------
fulldate: str
ISO 8601 UTC timestamp, e.g. `2017-06-02T16:23:14.815Z`
Returns
-------
:class:`datetime.datetime`
Python datetime ... | e327c23f9aecf587432fa0170c8bcd3a9a534bd1 | 3,633,445 |
def join_data(msg_fields):
"""
Helper method. Gets a list, joins all of it's fields to one string divided by the data delimiter.
:param msg_fields: (int) times the fields in the message.
:return: string that looks like cell1#cell2#cell3
"""
msg = ""
for word in msg_fields:
msg += DAT... | 09afba0944dce292ad701f7342f28576bc4d156a | 3,633,447 |
def MDA(input_dims, encoding_dims):
"""Multi-modal autoencoder.
"""
# input layers
input_layers = []
for dim in input_dims:
input_layers.append(Input(shape=(dim, )))
# hidden layers
hidden_layers = []
for j in range(0, len(input_dims)):
hidden_layers.append(Dense(encodin... | 8c8b777668e3dbdedf815da280e10c6567619d58 | 3,633,448 |
import math
def lat2y(latitude):
"""
Translate a latitude coordinate to a projection on the y-axis, using
spherical Mercator projection.
:param latitude: float
:return: float
"""
return 180.0 / math.pi * (math.log(math.tan(math.pi / 4.0 + latitude * (math.pi / 180.0) / 2.0))) | 59a0a111c22c99dd23e80ed64d6355b67ecffd42 | 3,633,449 |
def normalize(train_data, test_data):
""" Calculate the mean and std of each feature from the training set
"""
feature_means = np.mean(train_data, axis=(0, 2))
feature_std = np.std(train_data, axis=(0, 2))
train_data_n = train_data - feature_means[np.newaxis, :, np.newaxis] / \
n... | 42538164a6a1bfdae43e986134bc408a72aa3621 | 3,633,450 |
def buildDataForm(form=None, type="form", fields=[], title=None, data=[]):
"""
Provides easier method to build data forms using dict for each form object
Parameters:
form: xmpp.DataForm object
type: form type
fields: list of form objects represented as dict, e.g.
[{"var": "cool", "type": "text-single",
... | 91773c2fc91766715133b01550c295e746963a27 | 3,633,451 |
import re
def calc(equation):
"""Evaluates an equation, accepting time values."""
items = [i for i in re.split(r'([\d\:]+)', equation) if i]
has_time = False
for i, v in enumerate(items):
if ':' in v:
has_time = True
items[i] = to_sec(v)
result = eval(''.join(map(str, items)))
if has_time... | 3e40e28421527627d14efb70b3da3beb8b047ff6 | 3,633,452 |
def format_input_crf(data, destination_file, model=None, distance_threshold=None, window=None):
""" This procedure takes in input the train and test set and then annotates with iob notation with the specified
wordToVec model, window and threshold
:param data: the data dictionary with keys, list of sentences... | 6224e0270cacbb331853a7aa9be5bd0f9a489e8f | 3,633,453 |
def _GetSecurityAttributes(handle) -> win32security.SECURITY_ATTRIBUTES:
"""Returns the security attributes for a handle.
Args:
handle: A handle to an object.
"""
security_descriptor = win32security.GetSecurityInfo(
handle, win32security.SE_WINDOW_OBJECT,
win32security.DACL_SECURITY_INFORMATION... | bfaeaa72d7912c5826f6f504076c58c45ef6b39a | 3,633,454 |
def evalMatrix(false_friends, devectors, envectors, vm, model,
output=True, n=5):
""" Evaluates the quality of a matrix """
average_diff = 0
similarities = []
# Calulating the average difference of a false-friend-pair
for pair in false_friends:
try:
if devectors[pair[1]] == []: continue
elif envector... | 80e8384be6ace9ab2bc014dbeaac0eec82ef18f5 | 3,633,455 |
async def get_all_terms():
"""All terms with frequency count."""
try:
return workflow.get_all_terms()
except HarperExc as exc:
raise HTTPException(status_code=exc.code, detail=exc.message) | 05b7ec9289b4cca88ef19f84277075036e44f31e | 3,633,457 |
def update(callback=None, path=None, method=Method.PUT, resource=None, tags=None, summary="Update specified resource.",
middleware=None):
# type: (Callable, Path, Methods, Resource, Tags, str, List[Any]) -> Operation
"""
Decorator to configure an operation that updates a resource.
"""
def... | 8b68084cce64073a1012317f27375106c91954cb | 3,633,458 |
def start_shared_memory_manager() -> SharedMemoryManager:
"""Starts the shared memory manager.
:return: Shared memory manager instance.
"""
smm = create_shared_memory_manager(address=("", PORT), authkey=AUTH_KEY)
smm.start()
return smm | 026e9e59661566d680cbe2d58842636d0e4b1050 | 3,633,459 |
def filenameValidator(text):
"""
TextEdit validator for filenames.
"""
return not text or len(set(text) & set('\\/:*?"<>|')) == 0 | 435032f32080b52165756cf147830308537e292d | 3,633,460 |
def add_post():
"""Upload a new post to the website
:return: add_post.html
"""
if request.method == 'POST':
if request.form['submit'] == "preview":
title = request.form['title']
markdown_text = request.form['markdown_text']
html = filter_markdown(markdown_tex... | a4202c81f4c303f58780e3bfd836298c06089f45 | 3,633,461 |
def split_model(y, X,
sigma=1,
lam_frac=1.,
split_frac=0.9,
stage_one=None):
"""
Fit a LASSO with a default choice of Lagrange parameter
equal to `lam_frac` times $\sigma \cdot E(|X^T\epsilon|)$
with $\epsilon$ IID N(0,1) on a proportion... | 23f02d0baedf4800d0f4a4eaaff95cd37db104a3 | 3,633,462 |
def makepdb(title,parm,traj):
"""
Make pdb file from first frame of a trajectory
"""
cpptrajdic ={'title':title,'parm':parm,'traj':traj}
cpptrajscript="""parm {parm}
trajin {traj} 0 1 1
center
rms first @CA,C,N
strip :WAT
strip :Na+
strip :Cl-
trajout {title}.pdb pdb
... | 8ca8c95adef74525ac6018146418dd5e2314ff94 | 3,633,463 |
def get_face_position_with_eye(image):
"""
get face position with eye
"""
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
face_list = FACE_CASCADE.detectMultiScale(gray, scaleFactor=1.3, minNeighbors=5, minSize=(50, 50))
ret = []
for (x, y, w, h) in face_list:
gray_face = gray[y:y+h,... | 4a54ef0b5be36bfb9f5b6539458d1f997f5c5f70 | 3,633,464 |
def get_pandas_df(data, validate=True):
"""
GetPandasDF reads all observations in a SDMX file as Pandas Dataframe(s)
:param data: Path, URL or SDMX data file as string
:param validate: Validation of the XML file against the XSD (default: True)
:return: A dict of `Pandas Dataframe \
<https://p... | 1ee1edc9ce2931066675ebe8b0f57ff920749bd3 | 3,633,465 |
def basic_collate(batch):
"""Puts batch of inputs into a tensor and labels into a list
Args:
batch: (list) [inputs, labels]. In this simple example, I'm just
assuming the inputs are tensors and labels are strings
Output:
minibatch: (Tensor)
targets: (list[str])
... | 7e5f36e20125effaa310654856dc84199dbcb169 | 3,633,466 |
import random
def secure_randint(min_value, max_value, system_random=None):
""" Return a random integer N such that a <= N <= b.
Uses SystemRandom for generating random numbers.
(which uses os.urandom(), which pulls from /dev/urandom)
"""
if not system_random:
system_random = rand... | f4b61457c6e384e6185a5d22d95539001903670d | 3,633,467 |
def get_runner_image_url(benchmark, fuzzer, cloud_project):
"""Get the URL of the docker runner image for fuzzing the benchmark with
fuzzer."""
base_tag = experiment_utils.get_base_docker_tag(cloud_project)
if is_oss_fuzz(benchmark):
return '{base_tag}/oss-fuzz/runners/{fuzzer}/{project}'.format... | ce958eb66743f265edb81b9e11e40a34ba718660 | 3,633,469 |
def extend_gmx_npt_prod(job):
"""Run GROMACS grompp for the npt step."""
# Extend the npt run by 1000 ps (1 ns)
extend = "gmx convert-tpr -s npt_prod.tpr -extend 1000 -o npt_prod.tpr"
mdrun = _mdrun_str("npt_prod")
return f"{extend} && {mdrun}" | 1775d63dce08b590c8feeacf966cb40e24f32d14 | 3,633,470 |
from operator import mul
from operator import inv
def is_rotation(R,tol=1e-5):
"""Returns true if R is a rotation matrix, i.e. is orthogonal to the given tolerance and has + determinant"""
RRt = mul(R,inv(R))
err = vectorops.sub(RRt,identity())
if any(abs(v) > tol for v in err):
return False
... | 4d1c9ba52ca49ba5977ce6e85974abb3962f1a5b | 3,633,471 |
import time
def date():
"""
Return date string
"""
return time.strftime("%B %d, %Y") | b26cf8a5012984bbd76f612b19f79a3c387b9d27 | 3,633,472 |
def contained_circle_aq(poly):
"""
The contained circle areal quotient is defined by the
ratio of the area of the
largest contained circle and the shape itself.
"""
pointset = _get_pointset(poly)
radius, (cx, cy) = _mcc(pointset)
return poly.area / (_PI * radius ** 2) | a019405ae2a34b25cc34574a83c30dfe577a044c | 3,633,473 |
def kubernetes_clusters(request, tenant):
"""
On ``GET`` requests, return a list of the deployed Kubernetes clusters for the tenancy.
On ``POST`` requests, create a new Kubernetes cluster.
"""
if not cloud_settings.CLUSTER_API_PROVIDER:
return response.Response(
{
... | f928a2b438fcf57bf1e74ce277ab8bc921cdc28d | 3,633,474 |
def clip_to_spec(value, spec):
"""Clips value to a given bounded tensor spec.
Args:
value: (tensor) value to be clipped.
spec: (BoundedTensorSpec) spec containing min. and max. values for clipping.
Returns:
clipped_value: (tensor) `value` clipped to be compatible with `spec`.
"""
return tf.clip_b... | 9f09cb09d00f6fd3bcf6f2dccd982befd26510e3 | 3,633,475 |
def publish_dataset(
datalad_dataset_dir,
dryrun=False
):
"""
Function that publishes the dataset repository to GitHub and the annexed files to a SSH special remote.
Parameters
----------
datalad_dataset_dir : string
Local path of Datalad dataset to be published
dryrun : bool
... | 1f65749e2d4bbc26d8929684791e38e8579c2c58 | 3,633,476 |
import math
def convert_weight(prob):
"""Convert probility to weight in WFST"""
weight = -1.0 * math.log(10.0) * float(prob)
return weight | d9f6c38fd2efa49ddd515878a0943f9c82d42e1a | 3,633,477 |
def is_exception(ocdid):
"""Check whether given ocdid is contained in the exception list
Keyword arguments:
ocdid -- ocdid value to check if exists in the exception list
Returns:
True -- ocdid exists
False -- ocdid not found (could be candidate for new ocdid)
"""
if ocdid in exception... | bde5beaf3e9f5eff4489972036820cf5b758ceea | 3,633,478 |
import numpy
def retrieve_m_hf(eri):
"""Retrieves TDHF matrix directly."""
d = eri.tdhf_diag()
m = numpy.array([
[d + 2 * eri["knmj"] - eri["knjm"], 2 * eri["kjmn"] - eri["kjnm"]],
[- 2 * eri["mnkj"] + eri["mnjk"], - 2 * eri["mjkn"] + eri["mjnk"] - d],
])
return m.transpose(0, 2, ... | ad407f0294f906125ef6b5ecd7f8300114afb4a5 | 3,633,479 |
def laplacian(A):
"""
Returns the laplacian matrix from a given adjacency matrix
Parameters
----------
A : Tensor
an adjacency matrix
Returns
-------
Tensor
the laplacian matrix
"""
return degree(A)-A | 75fd7985572a3612b238fbd90ad706b7d2c9d503 | 3,633,480 |
def GetDiv(number):
"""Разложить число на множители"""
#result = [1]
listnum = []
stepnum = 2
while stepnum*stepnum <= number:
if number % stepnum == 0:
number//= stepnum
listnum.append(stepnum)
else:
stepnum += 1
if number > 1:
... | fbbd4b9e73ebe9af6ef6dcc0151b8d241adbb45d | 3,633,482 |
def my_decorator(view_func):
"""定义装饰器"""
def wrapper(request, *args, **kwargs):
print('装饰器被调用了')
return view_func(request, *args, **kwargs)
return wrapper | 1e857263d6627f1a2216e0c2573af5935ba58637 | 3,633,483 |
def make_rect_containing(points: [Point]):
"""
Computes the smallest rectangle containing all the passed
points.
:param points: `[Point]`
:return: `Rect`
"""
if not points:
raise ValueError('Expected at least one point')
first_point = points[0]
min_x, max_x = first_point.x,... | b3dbcad3473551837e72ea7ac4257b07276ed5de | 3,633,484 |
def check_login():
"""检查登陆状态"""
# 尝试从session中获取用户的名字
name = session.get("user_name")
# 如果session中数据name名字存在,则表示用户已登录,否则未登录
if name is not None:
return jsonify(errno=RET.OK, errmsg="true", data={"name": name})
else:
return jsonify(errno=RET.SESSIONERR, errmsg="false") | f650c054ffaa23164e2697de706246072aba3146 | 3,633,486 |
def calc_delta(startdate: dt.date, enddate: dt.date, no_of_ranges: int) -> dt.timedelta:
"""Find the delta between two dates based on a desired number of ranges"""
date_diff = enddate - startdate
steps = date_diff / no_of_ranges
return steps | 3522e6059c69dbae175c768104c9fe1c55f9d764 | 3,633,487 |
def get_email_config():
"""Returns email notifier related configuration."""
email_config = {}
email_config["hostname"] = context.config["SMTP_HOSTNAME"]
email_config["port"] = context.config["SMTP_PORT"]
email_config["username"] = context.config["SMTP_USERNAME"]
email_config["password"] = contex... | 7ede3901ba8896f1b0ad49ab726d23c541548510 | 3,633,488 |
from typing import List
def check_status_instances(instance_names: List[str] = None,
filters: List[str] = None,
secrets: Secrets = None,
force: bool = False,
status: str = None,
confi... | 5cadd77aa453335da416938799223e21a4de5535 | 3,633,489 |
def format_seconds(seconds: int) -> str:
"""
Convert seconds to a formatted string
Convert seconds: 3661
To formatted: " 1:01:01"
"""
# print(seconds, type(seconds))
hours = seconds // 3600
minutes = seconds % 3600 // 60
seconds = seconds % 60
return f"{hours:4d}:{minutes:02d}... | 766d244b9927cca21ea913e9c5e1641c16f17327 | 3,633,490 |
def build_ddsc(inputs, num_classes, preset_model='DDSC', frontend="ResNet101", weight_decay=1e-5, is_training=True, pretrained_dir="models"):
"""
Builds the Dense Decoder Shortcut Connections model.
Arguments:
inputs: The input tensor=
preset_model: Which model you want to use. Select which Re... | 4cb126dd5814816026f6141474dd029865e08040 | 3,633,492 |
def bitstring_to_bytes(bitstring):
"""Convert PyASN1's strings of 1s and 0s to actual bytestrings."""
if len(bitstring) % 8 != 0:
raise ValueError("Unaligned bitstrings cannot be converted to bytes")
integer = int(''.join(str(x) for x in bitstring), 2)
return bytes(int_to_bytearray(integer)) | a037a485e082c813b768f8162f031b0ca45ec7ab | 3,633,493 |
def plot_corr(fig, ax, corr, labels=None):
"""
Plot a correlation matrix with a heatmap.
"""
ax = sns.heatmap(corr, vmin=-1, vmax=1, center=0,
cmap=sns.diverging_palette(10, 240, as_cmap=True),
cbar=True,
square=True, ax=ax,
... | 1b40b85bfcb646ca2dc8539018c43d727882083f | 3,633,494 |
def once(f):
"""
Return a function that will be called only once, and it's result cached.
"""
cached = None
@wraps(f)
def wraped():
nonlocal cached
if cached is None:
cached = Some(f())
return cached.val
return wraped | 00fac90ddc4083ad28738284b8e0471381db1994 | 3,633,495 |
def from_greatfet_error(error_number):
"""
Returns the error class appropriate for the given GreatFET error.
"""
error_class = GREATFET_ERRORS.get(error_number, GreatFETError)
message = "Error {}".format(error_number)
return error_class(message) | 18460872c797e2f7ec93e1d7174afe6848a1bad9 | 3,633,496 |
def compute_all_distances_to_nucleus_centroid3d(heightmap: np.ndarray, nucleus_centroid: np.ndarray,
image_width=None, image_height=None) -> np.ndarray:
"""
Compute distances within the cytoplasm between all points and nucleus_centroid in a
IMAGE_WIDTH x IMAGE... | 677566894f2b37686f81b8d7e1fac97ada0d9162 | 3,633,497 |
import re
def strip_md_links(md):
"""strip markdown links from markdown text md
Args:
md: str, markdown text
Returns:
str with markdown links removed
Note: This uses a very basic regex that likely fails on all sorts of edge cases
but works for the links in the osxphotos... | fc730b88d536ec23ec8a1c9c3465fca2adb85b74 | 3,633,498 |
def tf_distort_color(image):
""" Distorts color. """
image = image / 255.0
image = image[:, :, ::-1]
brightness_max_delta = 16. / 255.
color_ordering = tf.random.uniform([], maxval=5, dtype=tf.int32)
if tf.equal(color_ordering, 0):
image = tf.image.random_brightness(image, max_delta=b... | 8949e3efdb0057abe7830c7d35ec1da4dc9ee2dc | 3,633,499 |
import cplex
import io
def run_and_read_cplex(n, problem_fn, solution_fn, solver_logfile,
solver_options, warmstart=None, store_basis=True):
"""
Solving function. Reads the linear problem file and passes it to the cplex
solver. If the solution is successful it returns variable solu... | 77a9e12509cde2e40287bab49ffb7f226ce3c2e2 | 3,633,500 |
def deharmonize(audio_data, sfreq, shift, high=False,
audio_min_freq=200.0, decompose="none"):
"""Deharmonize audio data using full signal FFT
Args:
audio_data(numpy.ndarray): Audio data in a NumPy array
sfreq(float): Sampling frequency in Hz
shift(float): Linear shift i... | 4e7f05d42673ca7cb9c468a9de14d35d83166ee0 | 3,633,501 |
def get_max_sushi(m, features, combs, rank_dict):
"""
Specifically for DTS
:param model: gpflow model
:param features: sushi features
:param rank_dict: dictionary from sushi idx to place in ranking
:return: tuple (index of max sushi, rank)
"""
y_vals = m.predict_y(combs)[0]
num_discr... | a1e214c00db7df45d231e9a3f4aa8da544037dc9 | 3,633,502 |
def is_watchman_supported():
""" Return ``True`` if watchman is available."""
if WIN:
# for now we aren't bothering with windows sockets
return False
try:
sockpath = get_watchman_sockpath()
return bool(sockpath)
except Exception:
return False | 7681ba911456196ad01774e0607bd81872e4b82a | 3,633,504 |
def geolocation(data_base, year, latitude, longitude, geofunc):
"""
Function for geolocating points from database and calculating distance from them to
the given user point.
>>> 33.5 <= geolocation(pd.DataFrame([["Film1", 2020, "Some info",\
"Los Angeles California USA"]], columns \
= ["name",... | ecd619b23d0f72c29b164f7fdbf498b41f25c0f0 | 3,633,505 |
from typing import OrderedDict
def read_dig_polhemus_isotrak(fname, ch_names=None, unit='m'):
"""Read Polhemus digitizer data from a file.
Parameters
----------
fname : str
The filepath of Polhemus ISOTrak formatted file.
File extension is expected to be '.hsp', '.elp' or '.eeg'.
... | d048f1f83844bc591a301c046f3c25494ffd0339 | 3,633,508 |
def gt_comparison_plot(data, mu=None, sig=None, k=3.3e11, x_c = None):
"""
Generate the comparison Zipf plot for the data.
Parameters
----------
data : array_like
Size of each firm, where size is measured by sales, value added,
number of employees or some other variable.
k : f... | 64a30fd6bf77edbd89ed3194838e518a1022cc11 | 3,633,509 |
def make_cache_key(instance):
"""Construct a cache key for the instance."""
prefix = '{}:{}:{}'.format(
instance._meta.app_label,
instance._meta.model_name,
instance.pk
)
return '{}:{}'.format(prefix, str(uuid4())) | 6a83d20c94e26ece5ca3d98ad8cb70dd17fa5ea7 | 3,633,510 |
def CalculateMediationPEEffect(PointEstimate2, PointEstimate3):
"""Calculate derived effects from simple mediation model.
Given parameter estimates from a simple mediation model,
calculate the indirect effect, the total effect and the indirect effects
Parameters
----------
PointEstimate2 : ... | d2247985e46a78bc3333983e09a1030fd59f139d | 3,633,512 |
def get_engine(db_dir_name, echo=False, path_str=None):
"""数据库引擎"""
if path_str:
path = path_str
else:
path = db_path(db_dir_name)
engine = create_engine('sqlite:///' + path, echo=echo)
return engine | c3f35e7a52619c9ef5e1414efdbebcaebb8b8bd3 | 3,633,513 |
def init_websauna(config_uri: str, sanity_check: bool=False, console_app=False, extra_options=None) -> Request:
"""Initialize Websauna WSGI application for a command line oriented script.
:param config_uri: Path to config INI file
:param sanity_check: Perform database sanity check on start
:param con... | 2d56ce6afa1ede2c69c92422cb360e856d84b007 | 3,633,514 |
def ts_glm_ridge_pipeline():
"""
Return pipeline with the following structure:
glm \
-> ridge -> final forecast
lagged - ridge /
Where glm - Generalized linear model
"""
node_glm = PrimaryNode("glm")
node_lagged = PrimaryNode("lagged")
node_ridge_1 = S... | 41a6ce2e280ca6a89ba482715ab9bcdc807c0d29 | 3,633,515 |
def norm1to1(operator, n_samples=10000, mxBasis="gm", return_list=False):
"""
Returns the Hermitian 1-to-1 norm of a superoperator represented in
the standard basis, calculated via Monte-Carlo sampling. Definition
of Hermitian 1-to-1 norm can be found in arxiv:1109.6887.
"""
if mxBasis == 'gm':
... | f0ad0d6a89ab9c3ec275c5ea5ce1a343d275f625 | 3,633,517 |
def _load_image_gdal(image_path, value_scale=1.0):
""" using gdal to read image, especially for remote sensing multi-spectral images
:param image_path: string, image path
:param value_scale: float, default 1.0. the data array will divided by the 'value_scale'
:return: array of shape (height, width, ban... | 94d8ce48f069bc311637237d805fd140604cffc2 | 3,633,518 |
def f1_chantler(element, energy, _larch=None, **kws):
"""returns real part of anomalous x-ray scattering factor for
a selected element and input energy (or array of energies) in eV.
Data is from the Chantler tables.
Values returned are in units of electrons
arguments
---------
element: at... | 76b5143e3d9be69ae6f7f8ee246669ee3da9fe08 | 3,633,519 |
def rgb_to_hex(red_component=None, green_component=None, blue_component=None):
"""Return color as #rrggbb for the given color tuple or component
values. Can be called as
TUPLE VERSION:
rgb_to_hex(COLORS['white']) or rgb_to_hex((128, 63, 96))
COMPONENT VERSION
rgb_to_hex(64, 183, 22)
... | 37f5216f7f22f82072db6980541a815d87d02ef3 | 3,633,520 |
def remove(predicate, seq):
""" Return those items of sequence for which predicate(item) is False
>>> def iseven(x):
... return x % 2 == 0
>>> list(remove(iseven, [1, 2, 3, 4]))
[1, 3]
"""
return filterfalse(predicate, seq) | 2953386f289894e4f5a052d1f67087dcf4631a3a | 3,633,521 |
def average_coords(coords_list):
"""Calculate average coords
Parameters
----------
coords_list : list[skrobot.coordinates.Coordinates]
Returns
-------
coords_average : skrobot.coordinates.Coordinates
"""
q_list = [c.quaternion for c in coords_list]
q_average = averageQuaternion... | 3a3e59685311042a91295760ec025e12916c34d5 | 3,633,522 |
def lowpassfilter(input_vect, width=101):
"""
Computes a low-pass filter of an input vector.
This is done while properly handling NaN values, but at the same time
being reasonably fast.
Algorithm:
provide an input vector of an arbitrary length and compute a running NaN
median over a box o... | 1b71ac8f0a2fc61b0cd3d5ab9e1f218471b3569c | 3,633,523 |
def n_keywords(data):
"""Return the number of keywords.
Arguments
---------
data: asreview.data.ASReviewData
An ASReviewData object with the records.
Return
------
int:
The statistic
"""
if data.keywords is None:
return None
return np.average([len(keywor... | d2692c1e040cf659dcc6eb1aa7c5718d52a345d8 | 3,633,524 |
def flatten_reshape(variable, name=''):
"""Reshapes high-dimension input to a vector.
[batch_size, mask_row, mask_col, n_mask] ---> [batch_size, mask_row * mask_col * n_mask]
Parameters
----------
variable : a tensorflow variable
name : a string or None
An optional name to attach to thi... | 933ec231c15f91122db755f9bac98679cdf9864e | 3,633,525 |
def register_command(data):
"""Remote command registration service.
This has to be enabled by liquer.commands.enable_remote_registration()
WARNING: Remote command registration allows to deploy arbitrary python code on LiQuer server,
therefore it is a HUGE SECURITY RISK and it only should be used if oth... | c9b764e6f2758ad4cc90aced854421d7d83ece9e | 3,633,526 |
import json
def add_noise(dgen_list, noise):
"""Add noise decorators to the DataGenerators from `dgen_list` list.
Parameters
----------
dgen_list : list of IDataGenerator
A list of DataGenerators to be decorated.
noise : list of dict or dict or None
Noise configuration.
If... | f716211ad9f1d35e66845e0887aafa5955575b4b | 3,633,527 |
from pathlib import Path
def open(table_file: str, table_map_file: str = None) -> pd.DataFrame:
"""
Opens a dynamo table file, returning a DynamoTable object
:param table_file:
:return: dataframe
"""
# Read into dataframe
df = pd.read_csv(table_file, header=None, delim_whitespace=True)
... | 7dca5cfc2c3c6201730b99db13680bed81b51a4b | 3,633,529 |
def _evaluate_tags(pcluster_config, preferred_tags=None):
"""
Merge given tags to the ones defined in the configuration file and convert them into the Key/Value format.
:param pcluster_config: PclusterConfig, it can contain tags
:param preferred_tags: tags that must take the precedence before the confi... | d23e4c29b463736fa23a65c977e16734b235c4c9 | 3,633,530 |
def dict_view(request):
"""
字典管理
"""
return render_mako_context(request, '/system_permission/dictmgr.html') | 56b8b80fb56c032f319f23754c3926cadf74ddc6 | 3,633,531 |
def rot_ETA(eta: float) -> np.ndarray:
"""Return rotation matrix corresponding to eta axis.
Parameters
----------
eta: float
eta axis angle
Returns
-------
np.ndarray
Rotation matrix as a NumPy array.
"""
return z_rotation(-eta) | 07e3c42f40bba0d73b4718eaa2d56b17e3dffd8e | 3,633,532 |
def show_lists(chat_id):
"""
It shows all the lists of the given user
:param chat_id:
:return:
"""
lists = notelistmodel.find_all_lists(mongodb, chat_id)
return {"text": monkeyview.lists_view(lists), "parse_mode": "Markdown"} | b72df596357e0174294589eab413fa1f8f8da840 | 3,633,533 |
from re import T
def import_string(path: str) -> T.Any:
"""
Import a dotted Python path to a class or other module attribute.
``import_string('foo.bar.MyClass')`` will return the class ``MyClass`` from
the package ``foo.bar``.
"""
name, attr = path.rsplit('.', 1)
return getattr(import_modu... | 3475a6081d64f656ec2c50b74f9314d519d18dee | 3,633,535 |
from re import T
def inbox():
"""
RESTful CRUD controller for the Inbox
- all Inbound Messages are visible here
"""
if not auth.s3_logged_in():
session.error = T("Requires Login!")
redirect(URL(c="default", f="user",
args = "login",
... | 486640ebdb1a142f22ac146479fa36c289a8e1be | 3,633,536 |
def glorot_uniform_sigm(shape):
"""
Glorot style weight initializer for sigmoid activations.
Like keras.initializations.glorot_uniform(), but with uniform random interval like in
Deeplearning.net tutorials.
They claim that the initialization random interval should be
+/- sqrt(6 / (fan_in... | 4cd3a3f40e276aba5b16726af4ce28adefe25748 | 3,633,537 |
def params(kernels, time, target, target_frame, observer, corr):
"""Input parameters from WGC API example."""
return {
'kernels': kernels,
'times': time,
'target': target,
'target_frame': target_frame,
'observer': observer,
'aberration_correction': corr,
} | d030ad459b294a268c8bc3a851a32495dcbf5c02 | 3,633,539 |
def group_activity_list(
group_id: str,
limit: int,
offset: int,
include_hidden_activity: bool = False,
) -> list[Activity]:
"""Return the given group's public activity stream.
Returns activities where the given group or one of its datasets is the
object of the activity, e.g.:
"{USER}... | aaab03202571e3eb562fc3b8ec663ac58cc69ab0 | 3,633,541 |
def rotMatrixfromXYZ(station, mode='LBA'):
"""Return a rotation matrix which will rotate a station to (0,0,1)"""
loc = station.antField.location[mode]
longRotMat = rotationMatrix(0., 0., -1.*np.arctan(loc[1]/loc[0]))
loc0 = np.dot(longRotMat, loc)
latRotMat = rotationMatrix(0., np.arctan(loc0[0,2]/l... | a6df1bc5bc0cd8752cbd71c025a1b5208d1b8a34 | 3,633,542 |
import logging
def geo_info_for_geo_name(
geo_name: str, username: str = CONFIG["geonames_username"]
) -> GeoInfo:
"""Get geo information (latitude and longitude) for given region name."""
logging.info("Decoding latitude and longitude of '{}'...".format(geo_name))
gn = geocoders.GeoNames(username=user... | e6827ae4b0e3297311dd16fc3a98865bcc7fc252 | 3,633,543 |
def char_accuracy(predictions, targets, rej_char, streaming=False):
"""Computes character level accuracy.
Both predictions and targets should have the same shape
[batch_size x seq_length].
Args:
predictions: predicted characters ids.
targets: ground truth character ids.
rej_char: the character id use... | caccf28fab0aa4127da7b30d95f380452b713974 | 3,633,544 |
import json
def read_cities_db(fname="world-cities_json.json"):
"""Read a database file containing names of cities from different countries.
Source: https://pkgstore.datahub.io/core/world-cities/world-cities_json/data/5b3dd46ad10990bca47b04b4739a02ba/world-cities_json.json
"""
with open(fname) as f:
... | 1edb970e329e7781cebb61853a13a6f45d349250 | 3,633,545 |
def ConcatWith(x, dim, tensor):
"""
A wrapper around `tf.concat` to support `LinearWrap`
:param x: the input tensor
:param dim: the dimension along which to concatenate
:param tensor: a tensor or list of tensor to concatenate with x. x will be
at the beginning
:return: tf.concat(dim, [x]... | 8d15e008f8e2ec70c2d875a9bb5dcb1786d011ed | 3,633,546 |
def strip_df(data: pd.DataFrame) -> np.ndarray:
"""Strip dataframe from all index levels to only contain values.
Parameters
----------
data : :class:`~pandas.DataFrame`
input dataframe
Returns
-------
:class:`~numpy.ndarray`
array of stripped dataframe without index
""... | 3cd04b6b6cf144ac63854fbbab5ffa3784ccd707 | 3,633,547 |
def isRef(obj):
""" """
if isinstance(obj, dict) == True and '_REF' in obj:
return obj['_REF']
else:
return False | 0f1ad92cfafff5dcbc9e90e8544956b05c3452ec | 3,633,548 |
from pathlib import Path
from typing import Dict
from typing import Tuple
import pickle
def collect_genes_with_confidence(
query: str,
*,
cache_file: Path = None,
client: Neo4jClient,
) -> Dict[Tuple[str, str], Dict[str, Tuple[float, int]]]:
"""Collect gene sets based on the given query.
Para... | 18f949c1613f05b242a27dff7d16722af4d6bbf6 | 3,633,549 |
import copy
def intervals_disjoint(intvs):
"""
Given a list of complex intervals, check whether they are pairwise
disjoint.
EXAMPLES::
sage: from sage.rings.polynomial.complex_roots import intervals_disjoint
sage: a = CIF(RIF(0, 3), 0)
sage: b = CIF(0, RIF(1, 3))
sage... | ebe3208f1af22f7001d3dee10a2dca6a68558cc8 | 3,633,550 |
def _get_registered_typelibs(match='HEC River Analysis System'):
"""
adapted from pywin32
# Copyright (c) 1996-2008, Greg Stein and Mark Hammond.
"""
# Explicit lookup in the registry.
result = []
key = win32api.RegOpenKey(win32con.HKEY_CLASSES_ROOT, "TypeLib")
try:
num = 0
... | 88d5cf576454793678b275826d4087e5bcd263e4 | 3,633,551 |
def head(content, accesskey:str ="", class_: str ="", contenteditable: str ="",
data_key: str="", data_value: str="", dir_: str="", draggable: str="",
hidden: str="", id_: str="", lang: str="", spellcheck: str="",
style: str="", tabindex: str="", title: str="", transla... | 6ed2622a53b3e3df8254cd6bfbc41cad296dea8c | 3,633,552 |
def standardize(dataset, verbose=True):
""" remove all source-specific columns, keeping only those that occur in all repo sources.
also adds extra columns with default values """
found = False
for source, extra_features in EXTRA_FEATURES.items():
if all(feat in dataset.features for feat in extr... | f057c9d98c0525f4536053c20c0467ae2e8b6287 | 3,633,553 |
def mark(tv,stars=None,rad=3,auto=False,color='m',new=False,exit=False):
""" Interactive mark stars on TV, or recenter current list
Args :
tv : TV instance from which user will mark stars
stars = : existing star table
auto= (bool) : if True, recentroid from existing posit... | 66a291c564329a878aea7658cd9fc071cc303d0b | 3,633,554 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.