content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def test_single_char_arguments():
"""Tests failures for passing invalid inputs to char-accepting functions"""
from pybind11_tests import ord_char, ord_char16, ord_char32, ord_wchar, wchar_size
def toobig_message(r):
return "Character code point not in range({0:#x})".format(r)
toolong_message = ... | 5,320,600 |
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 ... | 5,320,601 |
def ensure_connection():
"""Fail all tests in this module if DynamoDB is not running"""
import boto3
client = boto3.client('dynamodb', **AWS_OPTIONS)
client.describe_limits() | 5,320,602 |
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 df.text[mask... | 5,320,603 |
def prediction_model(
model_version,
start_date=None,
end_date=None,
database=None,
force=False,
session=None,
save_to_db=True,
verbose=True,
capture_output=False,
):
"""Run a model version's prediction_command to generate new metrics values with the
specified dataset inputs.... | 5,320,604 |
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
... | 5,320,605 |
async def test_get_current_run(
decoy: Decoy,
mock_engine_store: EngineStore,
mock_run_store: RunStore,
subject: RunDataManager,
engine_state_summary: StateSummary,
run_resource: RunResource,
) -> None:
"""It should get the current run from the engine."""
run_id = "hello world"
deco... | 5,320,606 |
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... | 5,320,607 |
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 function returns at least 3 mesh... | 5,320,608 |
def dataset_service():
""" :rtype: dart.service.dataset.DatasetService """
return current_app.dart_context.get(DatasetService) | 5,320,609 |
async def leaderboard(ctx, type="total"):
"""Affiche les dix premiers annonceurs d'un serveur.
Utilisation:!leaderboard [type]
Types acceptés: raids, oeufs, exraids, wilds, recherche"""
trainers = copy.deepcopy(guild_dict[ctx.guild.id]['trainers'])
leaderboard = []
rank = 1
field_value = ... | 5,320,610 |
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:
retu... | 5,320,611 |
def test_coverageeligibilityrequest_2(base_settings):
"""No. 2 tests collection for CoverageEligibilityRequest.
Test File: coverageeligibilityrequest-example-2.json
"""
filename = (
base_settings["unittest_data_dir"] / "coverageeligibilityrequest-example-2.json"
)
inst = coverageeligibil... | 5,320,612 |
def get_xclock_hints() -> Dict[str, Pattern]:
"""Retrieves hints to match an xclock window."""
return {"name": re.compile(r"^xclock$")} | 5,320,613 |
def describe():
"""Get a summary of data."""
dataset = utilities.opencsv()
data = pd.read_csv(dataset)
description = data.describe()
description.to_csv('description.csv', encoding='utf-8') | 5,320,614 |
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
... | 5,320,615 |
def test_load_backoff_callable_absolute():
"""Load backoff callable with absolute name: package.module.class."""
f = backoffcache.load_backoff_callable(
'tests.arbpack.arbcallables.ArbCallable')
callable_ref = f('ctor in')
assert callable_ref('arg in 1') == 'from callable: ctor in arg in 1'
... | 5,320,616 |
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 distances ... | 5,320,617 |
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)
The f... | 5,320,618 |
def main():
"""
Purpose:
Produce to a Kafka Topic
"""
logging.info("Starting Get User Input")
for user_input in user_input_helpers.get_input_from_user(max_input=999):
logging.info(f"User Input: {user_input}")
logging.info("Get User Input Complete") | 5,320,619 |
def datetime_creator():
"""
返回标准格式的datetime
Returns:
"""
return time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) | 5,320,620 |
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 ... | 5,320,621 |
def register_ad_cb():
"""
Callback if registering advertisement was successful
"""
if isDebugAll() is True:
BLINKER_LOG('Advertisement registered') | 5,320,622 |
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 representing ISO timestamp.
... | 5,320,623 |
def org_members_count() -> None:
"""Count the number of members in the configured organisation."""
rstate = cache.load()
members = schema.org_members(rstate)
print(len(members)) | 5,320,624 |
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=config_data_... | 5,320,625 |
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... | 5,320,626 |
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... | 5,320,627 |
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))) | 5,320,628 |
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... | 5,320,629 |
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",
... | 5,320,630 |
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:
result... | 5,320,631 |
def example_create():
"""deque 的初始化
"""
# 双向列表占用空间大,但插入删除速度快
l = [1, 2, 3]
d = deque([1, 2, 3])
assert sys.getsizeof(l) < sys.getsizeof(d)
# 像一个大小为3的 FIFO 一样,按照顺序填充deque
d = deque([1, 2, 3, 4], 3)
assert list(d) == [2, 3, 4] | 5,320,632 |
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... | 5,320,633 |
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... | 5,320,634 |
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... | 5,320,635 |
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 = os.path.expanduser(filepath)
if not os.path.exists(actu... | 5,320,636 |
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) | 5,320,637 |
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... | 5,320,638 |
async def test_rate_limiter_unclaim_bundle(config, mocker):
"""Test that _unclaim_bundle attempts to update the LTA DB."""
logger_mock = mocker.MagicMock()
lta_rc_mock = mocker.patch("rest_tools.client.RestClient", new_callable=AsyncMock)
p = RateLimiter(config, logger_mock)
await p._unclaim_bundle(... | 5,320,639 |
def lines_plot(plots_path, all_lines, CGS_units, lx, ly, a):
"""Plot the computed current lines"""
print '\nPlotting lines...'
fig = plt.figure()
ax = fig.add_subplot(111, aspect='equal')
if CGS_units == 0:
ax.set_xlabel(r'$r~[a]$')
ax.set_ylabel(r'$z~[a]$')
ax.set_xlim((0, ... | 5,320,640 |
def test_condroz():
"""Test module condroz.py by downloading
condroz.csv and testing shape of
extracted data has 428 rows and 2 columns
"""
test_path = tempfile.mkdtemp()
x_train, metadata = condroz(test_path)
try:
assert x_train.shape == (428, 2)
except:
shutil.rmtree(test_path)
raise() | 5,320,641 |
def restart_apache():
"""Restart the Apache process"""
cwd = os.getcwd()
# no try/except, just let it fail
os.chdir('work/httpd')
p = subprocess.Popen(['./stop'],
close_fds=True)
time.sleep(5)
p = subprocess.Popen(['./start'],
close_fds=True... | 5,320,642 |
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 | 5,320,643 |
def filenameValidator(text):
"""
TextEdit validator for filenames.
"""
return not text or len(set(text) & set('\\/:*?"<>|')) == 0 | 5,320,644 |
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... | 5,320,645 |
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... | 5,320,646 |
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
... | 5,320,647 |
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,... | 5,320,648 |
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... | 5,320,649 |
def write_lines_to_file(file_name, lines):
"""Write given lines into given file.
Raise exception if it takes longer than 10s to write file.
"""
fhandle = None
try:
ensure_dir(file_name)
with open(file_name, 'w+') as fhandle:
fhandle.write('\n'.join(lines))
fha... | 5,320,650 |
def trace_breadth() -> NoReturn:
"""
User is presented with a random set of vertices and edges
user must sketch out graph (on paper) & provide breadth trace
"""
# Init. random graph & breadth trace
rugraph = return_rugraph()
breadth = list_to_string(rugraph.breadth())
# Question
text... | 5,320,651 |
def single_shot(func, vskip=3):
"""
func is either precessing_vortex_core or toroidal_vortex
"""
_, ax = plt.subplots(1, 1, figsize=(6, 6))
v_array = func
v_x = v_array[0, :]
v_y = v_array[1, :]
ax.quiver(X[::vskip, ::vskip], Y[::vskip, ::vskip], v_x[::vskip, ::vskip],
v_y[... | 5,320,652 |
async def unload(ctx, extension):
"""Unloads a specified extension."""
client.unload_extension(f"cogs.{extension}")
await ctx.send("Unloaded successfully.") | 5,320,653 |
def vis_char(filename, char_to_vis):
"""find and visualize images of a specific character
and the words that contain them"""
image_sample = util.load(filename)
for line_idx, line_pos in enumerate(image_sample.result):
for word_pos in line_pos.result.result:
for char_pos in word_pos... | 5,320,654 |
def benchmark():
""" Function to benchmark job """
mcf = read_master_config_file()
jd_opt, jd_opt_pl = read_namd_job_details(mcf["EquilibrateConfScript"])
print(("{} Setting up jobs for benchmarking based on current job config files.".format(DEFAULT))) | 5,320,655 |
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])
... | 5,320,656 |
def misclassifications(parser):
"""Prints misclassifications."""
parser.add_argument(
'-r', '--run', type=str, required=True,
help='name of run')
parser.add_argument(
'-n', '--num_samples', type=int, default=10,
help='number of misclassifications printed per sample')
pars... | 5,320,657 |
def test_one_to_divide(
assert_errors,
parse_ast_tree,
expression,
default_options,
):
"""Testing that `1 / any number` is the correct expression."""
tree = parse_ast_tree(expression)
visitor = UselessOperatorsVisitor(default_options, tree=tree)
visitor.run()
assert_errors(visitor,... | 5,320,658 |
def test_string_list_inequality():
"""Test equality error for different string values."""
param1 = uvp.UVParameter(name="p1", value=["Alice", "Eve"])
param2 = uvp.UVParameter(name="p2", value=["Bob", "Eve"])
assert param1 != param2 | 5,320,659 |
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 = random.SystemRandom(... | 5,320,660 |
def test_assert_num_bins_double_histogram_incorrect(pt_hist_overlapping):
"""Tests that assert_num_bins() correctly fails with overlapping
histograms"""
with pytest.raises(
AssertionError, match="Expected 5 bins in histogram, instead found 6."
):
pt_hist_overlapping.assert_num_bins(5)
... | 5,320,661 |
def read_UCM_cold_all_with_user_act(num_users, root_path="../data/"):
"""
:return: all the UCM in csr format
"""
import scipy.sparse as sps
import numpy as np
import pandas as pd
import os
# Reading age data
df_age = pd.read_csv(os.path.join(root_path, "data_UCM_age.csv"))
user_... | 5,320,662 |
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... | 5,320,663 |
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}" | 5,320,664 |
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
if det(R) < 0:
return False
return T... | 5,320,665 |
def max_nb_robots(nb): #py:set_max_nb_robots
"""Surtout destiné aux créateurs de mondes,
ceci permet de limiter le nombre de robots
permis dans un monde donné.
"""
RUR._set_max_nb_robots_(nb) | 5,320,666 |
def date():
"""
Return date string
"""
return time.strftime("%B %d, %Y") | 5,320,667 |
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) | 5,320,668 |
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(
{
... | 5,320,669 |
def _check_geo_nan(data, file_name):
"""
Check if they are some NaN geo features
"""
geo_features = ['IRIS', 'COM', 'DEP', 'REG']
for col in geo_features:
col_nan = pd.isnull(data[col]).sum()
if col_nan == 0:
"[OK] No NaN value for "+ col + " in " + file_name
... | 5,320,670 |
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... | 5,320,671 |
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
... | 5,320,672 |
def convert_weight(prob):
"""Convert probility to weight in WFST"""
weight = -1.0 * math.log(10.0) * float(prob)
return weight | 5,320,673 |
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... | 5,320,674 |
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, 1, 3).reshape(
... | 5,320,675 |
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 | 5,320,676 |
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_ the value o... | 5,320,677 |
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:
... | 5,320,678 |
def my_decorator(view_func):
"""定义装饰器"""
def wrapper(request, *args, **kwargs):
print('装饰器被调用了')
return view_func(request, *args, **kwargs)
return wrapper | 5,320,679 |
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,... | 5,320,680 |
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(gvar, '%s/%s' %... | 5,320,681 |
def test_view_has_result_from_database_security(dummy_request, testapp):
"""Securitynewsdata should have date stored correctly."""
sample_security = SecurityNewsData(
title='Security Yo',
articleContent='This is an article about cyber security',
date='11/17/2017',
url='www.securi... | 5,320,682 |
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") | 5,320,683 |
def set_file_metadata(ase, metadata, timeout=None):
# type: (blobxfer.models.azure.StorageEntity, dict, int) -> None
"""Set file metadata
:param blobxfer.models.azure.StorageEntity ase: Azure StorageEntity
:param dict metadata: metadata kv pairs
:param int timeout: timeout
"""
dir, fpath, _ ... | 5,320,684 |
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 | 5,320,685 |
def test_emd_transport_class(nx):
"""test_sinkhorn_transport
"""
ns = 150
nt = 200
Xs, ys = make_data_classif('3gauss', ns)
Xt, yt = make_data_classif('3gauss2', nt)
Xs, ys, Xt, yt = nx.from_numpy(Xs, ys, Xt, yt)
otda = ot.da.EMDTransport()
# test its computed
otda.fit(Xs=Xs... | 5,320,686 |
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... | 5,320,687 |
def clear_temp():
"""Resets the folder in which raws are mixed."""
if not baselines.find_vanilla_raws(False):
log.e('Could not clear temp: baseline raws unavailable')
return
if os.path.exists(paths.get('baselines', 'temp')):
shutil.rmtree(paths.get('baselines', 'temp'))
shutil.co... | 5,320,688 |
def check_status_instances(instance_names: List[str] = None,
filters: List[str] = None,
secrets: Secrets = None,
force: bool = False,
status: str = None,
configuration: Configuration = ... | 5,320,689 |
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}... | 5,320,690 |
def computeCMSstats( Ddata, thinSfx,
scenario,
putativeMutPop = None, sampleSize = 120,
pop2name = pop2name,
pop2sampleSize = {},
oldMerged = False,
DdataMerged = None,
outF... | 5,320,691 |
def create_applications_link(mount_directory: Path) -> None:
"""
Create link to /Applications in the given location
"""
print('Creating link to /Applications')
command = ('ln', '-s', '/Applications', mount_directory / ' ')
subprocess.run(command) | 5,320,692 |
def test_compress(minion_opts, local_salt):
"""
Test the `compress` Jinja filter.
"""
rendered = render_jinja_tmpl(
"{% for val in 'ABCDEF' | compress([1,0,1,0,1,1]) %}{{ val }} {% endfor %}",
dict(opts=minion_opts, saltenv="test", salt=local_salt),
)
assert rendered == "A C E F ... | 5,320,693 |
def test_find_bindpath(tmp_path):
"""Parse input JSON file to recursively get all the files defined in it.
For found local abspaths, find common root directories for those.
This is necessary for singularity to bind paths (similar to mounting directories
in docker).
Input JSON file has one TSV file... | 5,320,694 |
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... | 5,320,695 |
def create(size, filename):
"""Create a new encrypted environment"""
passphrase = click.prompt("Passphrase for encrypted environment",
hide_input=True,
confirmation_prompt=True)
output = subprocess.check_output(["hdiutil", "create",
... | 5,320,696 |
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)) | 5,320,697 |
async def main():
"""Fonction qui s'exécuter lors du lancement du script python"""
from db.db import db
data_manager = DataManager(db, keep_data=False)
data, _ = await data_manager.data
rec_rnn = RecFactory(data)
model = rec_rnn.build_model(CFModel)
model.train(num_iterations=2000, learning... | 5,320,698 |
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,
... | 5,320,699 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.