content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def get_potentially_supported_ops():
"""Gets potentially supported ops.
Returns:
list of str for op names.
"""
supported_ops = _get_potentially_supported_ops()
op_names = [s.op for s in supported_ops]
return op_names | 4fcbc8fd8e10f28d7c10e8b7a9b9d9475ef6b4b6 | 3,633,400 |
def hard_sigmoid_me(input_, inplace: bool = False):
"""jit-scripted hard_sigmoid_me function"""
return HardSigmoidJitAutoFn.apply(input_) | 83cb4ed8802b5e6a275167c3a44e51719efe6212 | 3,633,401 |
def demoji(tokens):
"""
This function describes each emoji with a text that can be later used for vectorization and ML predictions
:param tokens:
:return:
"""
emoji_description = []
for token in tokens:
detect = emoji.demojize(token)
emoji_description.append(detect)
retur... | ab0a200fca87b3b1dc22dfd6bbf374d35d7b8b50 | 3,633,402 |
from pathlib import Path
async def get_journal_entries_by_permalink_handler(
journal_permalink: str = Path(...),
entry_permalink: str = Path(...),
db_session: Session = Depends(db.yield_connection_from_env),
) -> RedirectResponse:
"""
Get specific journal entry by short link.
"""
try:
... | d6dcd12b7db6a57f518621212fda72c769e671aa | 3,633,403 |
def ignore_pre_big_bang(run):
"""
Remove metrics before timestamp 0.
"""
return [m for m in run if m[TS] >= 0]
#return [m for m in run if m[TS] >= 0 and m[TS] < MAX_TIME] | b5ff1cf5f3f67618c31da1defa5a397fbea8f9bb | 3,633,404 |
def signUp():
"""Sign up a new user.
:field phone [int]: user phone number
:field name [str]: user name
:field password [str]: user password (will be encrypted)
:returns [dict]: newly created user's info with auth token
"""
phone = handler.parse('phone', int)
name = handler.parse('name'... | 0ad7bb71135e86fe3f4d3873e510d4bb375c061c | 3,633,405 |
def next_player(player,list_player_names,player_index,open_card,given_card):
""" returns the next player
>>> list_player_names=['Mark','John','Harry','Henry']
>>> player_index=0
>>> player='Mark'
>>> next_player(player,list_player_names,player_index,('A', '♥', 11))
'John'
>>> player_index=3
... | 7c56bd1983b60ed2177914cc4203462c9b83f375 | 3,633,406 |
def loss_function(image, idx, c, omega):
"""
:param last_image: the previous generated frame
:param outputs: Generated image
:return: The sum of the style and content loss
"""
outputs = extractor(image)
style_outputs = outputs["style"]
content_outputs = outputs["content"]
style_loss... | 2c6dee61f1af7e48be34cbc47501062a0dc7fa03 | 3,633,407 |
def bra(seq, dim=2):
"""
Produces a multiparticle bra state for a list or string,
where each element stands for state of the respective particle.
Parameters
----------
seq : str / list of ints or characters
Each element defines state of the respective particle.
(e.g. [1,1,0,1] o... | 1199ac8336963a785e2d258416733612dc7a5558 | 3,633,408 |
import os
def file_exists(filepath):
"""Check whether a file exists by given file path."""
return os.path.isfile(filepath) | 157caa4e5ce39243b46dda915808de79d7cf76c0 | 3,633,409 |
def rmse_diff(model_data, subj_data):
"""this rmse only consider diff"""
R = np.array(model_data)
D = np.array(subj_data)
r_DIFF = np.round([np.mean(R[0:2])-np.mean(R[2:4]),
R[0]-R[1], R[2]-R[3]], 4)
d_DIFF = np.round([np.mean(D[0:2]) - np.mean(D[2:4]),
D[0] - D[1... | f9b06e74a95663ad3036b7c658bb55880eba1a03 | 3,633,410 |
def preparation_time_in_minutes(number_of_layers: int) -> int:
"""Calculate the preparation time per layer.
.:param number_of_layers: int number of layers.
.:return: int time in minutes derived from 'PREPARATION_TIME'.
Function that takes the actual number of layer of the lasagna and
return how muc... | 3377dbb30ef7f1ffdd41680b7f270baffb81a2ef | 3,633,411 |
def eliminate(board, i, j):
"""
Propagates the effects of fixing a cell to the affected neighbors
within the same square and vertical and horizontal lines
"""
value = board[i][j][0]
# Horizontal propagation
for k in range(n):
if j!=k and value in board[i][k]:
board[i][k].... | dd860418a1e57ed2484c20cf5765d926a653c9ab | 3,633,412 |
def prep_tweet_body(tweet_obj, args, processed_text):
""" Format the incoming tweet
Args:
tweet_obj (dict): Tweet to preprocess.
args (list): Various datafields to append to the object.
0: subj_sent_check (bool): Check for subjectivity and sentiment.
1: subjectivity (num... | 9163d7bb10e3bb31849090d8ebfe4d00c19db2df | 3,633,413 |
import zlib
import time
import logging
def send_mfg_inspector_data(inspector_proto, credentials, destination_url,
payload_type):
"""Upload MfgEvent to steam_engine."""
envelope = guzzle_pb2.TestRunEnvelope()
envelope.payload = zlib.compress(inspector_proto.SerializeToString())
enve... | e809e49c2babe215c547960f60d6edca495601d4 | 3,633,414 |
def cache_lookup_only(key):
"""Turns a function into a fallback for a cache lookup.
Like the `cache` decorator, but never actually writes to the cache.
This is good for when a function already caches its return value
somewhere in its body, or for providing a default value for a value
that is suppos... | c142de5fb967860f8a5108d9b65cf21e32e9e674 | 3,633,415 |
def social_distancing_policy():
"""
Real Name: b'social distancing policy'
Original Eqn: b'1-PULSE(social distancing start, FINAL TIME-social distancing start+1)*social distancing effectiveness'
Units: b'dmnl'
Limits: (None, None)
Type: component
b''
"""
return 1 - functions.pulse(
... | 8cd71fb4cdfcffb11bb488beee6f33a5495e2eeb | 3,633,416 |
def mersenne_prime(n_max):
""" This is the description of the function 4 ~ Loves it + 3
Parameters
----------
n_max : int
for p up to n_max
Returns
-------
list
list of q
"""
primes = []
for a in range(0,n_max):
b = 2**a - 1
i... | 4aff17a7ed6c22b2817d0c37d1fb6b9dbaf243c2 | 3,633,417 |
def import_locus_intervals(path,
reference_genome='default',
skip_invalid_intervals=False,
contig_recoding=None,
**kwargs) -> Table:
"""Import a locus interval list as a :class:`.Table`.
Examples
---... | 3d27332ac4194f5f823bb234016d3941751e2072 | 3,633,418 |
def speech_tagging(test_data, model, tags):
"""
Inputs:
- test_data: (1*num_sentence) a list of sentences, each sentence is an object of line class
- model: an object of HMM class
Returns:
- tagging: (num_sentence*num_tagging) a 2D list of output tagging for each sentences on test_data
"""
tagging = []
######... | 8390fc6ff0b1008d50b248da0d348ac31b42626a | 3,633,419 |
def evaluate_if(hook_dict: dict, context: 'Context', append_hook_value: bool) -> bool:
"""Evaluate the when condition and return bool."""
if hook_dict.get('for', None) is not None and not append_hook_value:
# We qualify `if` conditions within for loop logic
return True
if hook_dict.get('if',... | b9d733568abf9d4bd7e7b7ed6e1ac43582728080 | 3,633,420 |
def find_vgg_layer(arch, target_layer_name):
"""Find vgg layer to calculate GradCAM and GradCAM++
Args:
arch: default torchvision densenet models
target_layer_name (str): the name of layer with its hierarchical information. please refer to usages below.
target_layer_name = 'features... | 97e578e061a592f5762313f4b7aecc42cda39cb7 | 3,633,421 |
def plain_bst():
"""Returns a plain binary search tree and a tuple of its nodes. The tree has the same structure as ref_bst."""
t = Tree.tree()
n1 = Tree.tree().treeNode(1)
n3 = Tree.tree().treeNode(3)
n4 = Tree.tree().treeNode(4)
n6 = Tree.tree().treeNode(6)
n7 = Tree.tree().treeNode(7)
... | 81667b4b122c88ec29146b5b739b44cbafda6c0f | 3,633,422 |
def test_confirm_name(monkeypatch, single_with_trials):
"""Test name must be confirmed for update"""
def incorrect_name(*args):
return "oops"
monkeypatch.setattr("builtins.input", incorrect_name)
execute("db set test_single_exp status=broken status=interrupted", assert_code=1)
def correc... | 9b9aee3fccda50d886d5c3362e5f3e19806a1929 | 3,633,423 |
import torch
def get_one_hot_reprs(batch_stds):
""" Get one-hot representation of batch ground-truth labels """
batch_size = batch_stds.size(0)
hist_size = batch_stds.size(1)
int_batch_stds = batch_stds.type(torch.cuda.LongTensor) if gpu else batch_stds.type(torch.LongTensor)
hot_batch_stds = tor... | 84dbf251039144b2bad5f461f40cec830d9331ca | 3,633,424 |
import os
import click
import socket
import requests
import time
def ursula(config,
action,
rest_port,
rest_host,
db_name,
checksum_address,
debug,
teacher_uri,
min_stake
) -> None:
"""
Manage and run an Ursula ... | 27460deb03aa600474c6bc8c10c2e6133a882266 | 3,633,425 |
from typing import Tuple
def absolute_confusion_from_incidence(true_incidence, predicted_incidence) -> Tuple[float, float, float, float]:
"""Return the absolute number of true positives, true negatives, false positives and false negatives.
Parameters
----------
true_incidence: numpy.ndarray
t... | d235363a249523347087940d803e7dfbfc01a6de | 3,633,426 |
def test_every_iteration_model_updater_with_cost():
"""
Tests that the model updater can use a different attribute from loop_state as the training targets
"""
class MockModel(IModel):
def optimize(self):
pass
def set_data(self, X: np.ndarray, Y: np.ndarray):
sel... | 5775c0f2141f75cad46b143310f1fed64b508f37 | 3,633,427 |
def correlating_weight2_data(shots_discr, idx_qubit_ro, correlations, num_segments):
"""
"""
correlations_idx = [
[idx_qubit_ro.index(c[0]), idx_qubit_ro.index(c[1])] for c in correlations]
correl_discr = np.zeros((shots_discr.shape[0], len(correlations_idx)))
correl_avg = np.zeros((num_seg... | 4afb8c95f081e70fe50ed2b209e8e930ea0c4825 | 3,633,428 |
def create_test_network_6():
"""Aligned network with dropout for test.
The graph is similar to create_test_network_1(), except that the right branch
has dropout normalization.
Returns:
g: Tensorflow graph object (Graph proto).
"""
g = tf.Graph()
with g.as_default():
# An input test ima... | 820bea3f33b0f56d1d6148ee55764eb504bb977a | 3,633,429 |
import time
def timedcall(fn, *args):
"""
Run a function and measure execution time.
Arguments:
fn : function to be executed
args : arguments to function fn
Return:
dt : execution time
result : result of function
Usage example:
You want to time the function call "C = foo(A... | 60779c4f4b63796995d722133c304edf519ecd8f | 3,633,430 |
from pybind11_tests import ord_char, ord_char16, ord_char32, ord_wchar, wchar_size
def test_single_char_arguments():
"""Tests failures for passing invalid inputs to char-accepting functions"""
def toobig_message(r):
return "Character code point not in range({0:#x})".format(r)
toolong_message = "E... | dce3ef537fcc312d92b9f5ff5eb2ac00ff731a5e | 3,633,431 |
def tokuda_gap(i):
"""Returns the i^th Tokuda gap for Shellsort (starting with i=0).
The first 20 terms of the sequence are:
[1, 4, 9, 20, 46, 103, 233, 525, 1182, 2660, 5985, 13467, 30301, 68178, 153401, 345152, 776591, 1747331, 3931496, 8845866, ...]
h_i = ceil( (9*(9/4)**i-4)/5 ) for i>=0.
If ... | 710633e924cb6e31a866683b91da6489c781ba4a | 3,633,432 |
import os
def product_codes_with_parent(parent_code):
"""
Returns a python dictionary with all entries that belong to parent_code.
"""
if not os.path.exists('classificationHS.csv'):
download_product_codes_file()
df = load_product_codes_file()
mask = df.parent == parent_code
return ... | ed9e975110754061615c180d81eb5331d00f875c | 3,633,433 |
def trimf(x, p):
"""
Triangular membership function generator.
Parameters
----------
x : any sequence
Independent variable.
p: list of 4 values
lower than p[0] and higher than p[3] it returns 0
between p[1] and p[2] it returns 1
Returns
-------
y : 1d array
... | 7df01e466e55186c4d9e74466440077a0824eb47 | 3,633,434 |
def band_atom_orbitals_spin_polarized(
folder,
atom_orbital_dict,
output='band_atom_orbitals_sp.png',
display_order=None,
scale_factor=5,
color_list=None,
legend=True,
linewidth=0.75,
band_color='black',
unprojected_band_color='gray',
unprojected_linewidth=0.6,
fontsize=1... | 8ed107df12d8ef037116f0e87e8a62b6794ecbbb | 3,633,435 |
from typing import List
def _interpolate(mesh_1: Mesh, mesh_2: Mesh, steps: int = 1) -> List[Mesh]:
"""Interpolate two alike meshes.
This is suitable to fill the blank frames of an animated object
This function makes the assumption that same indices will be forming
the same triangle.
This functi... | 7209e00ac3cfc7996ec7e8cd1b0184b6ada40dea | 3,633,436 |
def dataset_service():
""" :rtype: dart.service.dataset.DatasetService """
return current_app.dart_context.get(DatasetService) | f2c8a3dfc39454449554930d2939cc45ed06f109 | 3,633,437 |
def calculate_concordance(aei_pvalues, eqtl_pvalues, threshold=0.05):
""" Returns
"""
eqtl_pvalues_i = np.nanargmin(eqtl_pvalues)
print(eqtl_pvalues_i)
print(aei_pvalues.iloc[eqtl_pvalues_i])
if aei_pvalues.iloc[eqtl_pvalues_i] <= threshold:
return(True)
else:
return(False) | f0371c81096ad9f1598c1291d853d717002e09e0 | 3,633,438 |
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 os
def main(src_features, src_labels, subset_index, column,
class_map, num_background, outdir, weak_null_classes=None,
prefix='', random_state=None):
"""Produce a filtered subset given a dataset and a set of IDs.
Parameters
----------
src_features : np.ndarray, shape=(n, d)
... | e14e303b465da64b57d5da005edc9ebf394de256 | 3,633,442 |
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 |
import sys
def tcex():
"""Return an instance of tcex."""
# create log structure for feature/test (e.g., args/test_args.log)
config_data_ = dict(_config_data)
config_data_['tc_log_file'] = _tc_log_file()
# clear sys.argv to avoid invalid arguments
sys.argv = sys.argv[:1]
return TcEx(config... | e6d8f20b2bc0086f141293f40ca8f44b372c1608 | 3,633,446 |
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 |
from typing import OrderedDict
import os
import configparser
def load_cfg_files(cfg_files):
"""Load config from config files."""
cfg = {"main": OrderedDict(), "output": {}, "watcher": {}}
cfg_timestamps = {}
for filepath in cfg_files:
cfg_timestamps[filepath] = None
actual_filepath = ... | 7dcbfcfc966a5ff61872ec60377cdf6613acbe52 | 3,633,456 |
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 |
import scipy.sparse as sps
import numpy as np
import pandas as pd
import os
def read_UCM_cold_all_with_user_act(num_users, root_path="../data/"):
"""
:return: all the UCM in csr format
"""
# Reading age data
df_age = pd.read_csv(os.path.join(root_path, "data_UCM_age.csv"))
user_id_list = df_a... | 968e21fa006c130ed33cef90943d6c0f1cadcc6b | 3,633,468 |
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 |
import os
def annotation_to_dataframe(annotation_number,filename):
"""
input:
- the number of the annotation (written in the xml)
- the filename (ex: tumor_110)
output:
'dataframe with 3 columns:
1_ the order of the vertex
2_ the value of the X coordinate of the vertex
3_... | 52b766d14ddf476c1017ae084cf91a31cfa715e3 | 3,633,481 |
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 |
import os
def check_documentation(gvar):
"""
Check for complete documentation.
"""
if gvar['retrieve_options']:
return []
def scan_1_doc_dir(gvar, man_path):
for fn in os.listdir(man_path):
if os.path.isdir('%s/%s' % (man_path, fn)):
scan_1_doc_dir(gva... | f38a4c31948e212d98f4a78905454d807ac4e78f | 3,633,485 |
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 |
import os
from typing import Dict
import types
def computeCMSstats( Ddata, thinSfx,
scenario,
putativeMutPop = None, sampleSize = 120,
pop2name = pop2name,
pop2sampleSize = {},
oldMerged = False,
... | 2f430c03e5fb4707caaa3d0430b02768808a3e61 | 3,633,491 |
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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.