content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def trial_division_5(n):
"""试除法,境界5层"""
prime_number_list = []
for i in range(2, n):
for j in prime_number_list:
# if j > int(i**0.5)+1:
# break
if i % j == 0 and j < int(i**0.5)+1:
break
else:
prime_number_list.append(i)
... | ed5235f4a09f0ff9a46d7af5a90486a6c7aefdb5 | 42,400 |
from typing import Type
def _type(array: Array) -> Type | None:
"""Get the type object associated with an array.
Parameters
----------
array : dask_awkward.Array
The collection.
Returns
-------
Type
The awkward type object of the array; if the array does not
conta... | 16fe65aa7d857ae4d7abf282b3e2aa847f31c333 | 42,401 |
def dcgan_discriminator(x, flags, scope=None, reuse=None, return_acts=False):
"""DCGAN-style discriminator network."""
nonlinearity = nonlinearity_fn(flags.nonlinearity_d, True)
ds_fs = flags.downsample_conv_filt_size
x_fs = flags.extra_conv_filt_size
acts = []
with tf.variable_scope(scope, reuse=reuse):
... | 69fe5199083d94b5d5b95e797b9363118969c67d | 42,402 |
def reconstruct_cfcoeffcients(output_dict, atomtype=None):
"""
Reconstruct the CFCoefficient list from the output dictionary
of the FleurCFCoeffWorkChain
:param output_dict: output dictionary node or the corresponding
dictionary
:param atomtype: int of the atomtype to recons... | 8a9f365d140537b370632f0894a008ec1744f7b5 | 42,403 |
def test_map_args_size():
"""
Feature: Check the size of inputs of map.
Description: The size of inputs of map must be greater than 1.
Expectation: The size of inputs of map must be greater than 1.
"""
class MapNet(Cell):
def __init__(self):
super().__init__()
sel... | 7944831bcd81e7b5598970b9146f217809f2790e | 42,404 |
def get_int_forms(ref_group, isomorphisms):
"""Return a list of integer forms ('permutations') for a list of isomorphisms,
i.e., mappings, based on a reference group."""
return [get_integer_form([iso[elem] for elem in ref_group.elements])
for iso in isomorphisms] | 73f23085b8818233c4081f7829ad6691b8618c6c | 42,405 |
def header_string(key_length=0, number_of_seconds=2):
""" return a header string for the output file """
header_string = '#'
header_string += ' ' * (key_length+8)
header_string += ' 1 2 3 ' * number_of_seconds + '\n'
header_string += '#'
header_string += ' ' * (key_l... | 8da90fa3171be1f3ce20932777835c5f2239d4a0 | 42,406 |
import requests
def send_message(gmess, address):
"""
Envia un mensaje usando un request y retorna la respuesta como
un grafo RDF
"""
msg = gmess.serialize(format='xml')
r = requests.get(address, params={'content': msg})
# Procesa la respuesta y la retorna como resultado como grafo
gr... | c6f6e09e312fa01f1f36b5a679b2b803f743c77b | 42,407 |
def main(global_config, **settings):
""" This function returns a Pyramid WSGI application.
"""
config = Configurator(settings=settings)
config.include('pyramid_chameleon')
log.info('Starting RaspiServer...')
config.add_static_view('static', 'static', cache_max_age=3600)
config.add_route('hom... | cb1d37e2b5ccaba271dedc3836d110e0d245f6f4 | 42,408 |
def sparse_average_precision_at_k(y_true: csr_matrix, y_scores: csr_matrix, k: int = 5) -> float:
"""
Computes the average precision at k for sparse binary matrices.
:param y_true: grounded truth in binary format (n_samples, n_labels)
:param y_scores: predictions in representation that can be ranked (e.... | 6ca71dcc4d91bc315bddafb01b651aff2442e29c | 42,409 |
import os
import logging
def load_checkpoint(checkpoint, name, basepath="", use_student_settings=False):
""" Restores Checkpoint
Args:
checkpoint: tf.train.Checkpoint object to restore.
name: name of the checkpoint to restore.
basepath: base directory where checkpoint is located.
... | 9b4b9c3776a837c38cc3138dd4577e50887ac9e5 | 42,410 |
import array
def calc_contour_normals_2d(pts,seg):
"""calc 2d normals of contour pts
assume the pts are clockwise around the object
(row,col)
"""
pset = set([tuple(x) for x in pts])
normals = empty((len(pts),2),int)
j=0
for i in xrange(len(seg)):
p1,p2,p3 = [array(seg[x]) for x... | c68f72307f4c4e7e993684bbed795dcc583a2212 | 42,411 |
def build_model(X_train, X_test, y_train, y_test):
"""Build and evaluate a model. Also returns the test-set predictions."""
count_vect = sktext.CountVectorizer()
X_train_counts = count_vect.fit_transform(X_train)
tfidf_transformer = sktext.TfidfTransformer()
X_train_tfidf = tfidf_transformer.fit_tra... | d20d99b4dcb8f4887c9007ca267f5832fb2f1707 | 42,412 |
from typing import Optional
def int_to_comma_hex(n: int, blength: Optional[int] = None) -> str:
"""
int_to_comma_hex
Translates an integer in its corresponding hex string
:type n: ``int``
:param n: Input integer
:type blength: ``Optional[int]``
:param blength: Add padding to reach length... | a1833b68b4c179070f454bb675909b3e3495b8cf | 42,413 |
import json
def load_sqlalchemy_response_from_json(filename):
""" Load a sqlalchemy response from a json file """
with open(filename, 'r', encoding="utf-8") as tmp:
data = json.load(tmp)
return load_sqlalchemy_response_from_object(data) | b74b9b3321d17cfdcae02977cfeda75c259ff539 | 42,414 |
def get_peaks(runs, signal_type, version='xenonnt_v7', output_folder='/project2/lgrandi/yuanlq/xenonnt/', **kargs):
"""wrapper around get_array to get peaks of a certain source. Now supporting KrS1A, KrS1B, Ar37.
Args:
runs (str or 1darray): runs to extract certain signal. Assumed all type of runs if p... | 850856b8eac7cabd451722d106b297d72521cc00 | 42,415 |
def imshow(image, ax=None, title=None):
"""
Print the given image
"""
if ax is None:
fig, ax = plt.subplots()
# PyTorch tensors assume the color channel is the first dimension
# but matplotlib assumes is the third dimension
image = image.transpose((1, 2, 0))
# Undo... | 3f889b5d228fa0700f6f12ca326c5fb5170c2f13 | 42,416 |
def svn_wc_diff_callbacks3_invoke_dir_opened(*args):
"""
svn_wc_diff_callbacks3_invoke_dir_opened(svn_wc_diff_callbacks3_t _obj, svn_wc_adm_access_t adm_access,
svn_boolean_t tree_conflicted, char path,
svn_revnum_t rev, void diff_baton) -> svn_error_t
"""
return apply(_wc.svn_wc_diff_call... | 6f58cf86b66b7fc05e3fa3bfaeebcef9fb461d0b | 42,417 |
def get_reset_password():
"""Get the user name and email address to reset the password.
:returns: the html form for resetting password
:rtype: str
"""
return template('get_reset_code.html') | 56dfa000b4c7b91f1019f431791981df79303e64 | 42,418 |
def update_config(original, update):
"""
Recursively update a dict.
Parameters must be specified in original to be overwritten
"""
for basekey, baseval in original.items():
if isinstance(baseval, dict):
for key, val in baseval.items():
if key in update:
... | cff13b8b5a36fae226d81dfca5e0599466f77f36 | 42,419 |
import os
def buildNamesPaths(dataRoot, resultsRoot, size, tissue, cellList, runFolder, shortFolderName):
"""Construct paths and stem names for files"""
dataPathList = []
resultsPathList = []
nameList = [] # more concise name for file
for cell in cellList:
# input data paths
currD... | be6cf307c8cee15ec1a1113aa466391d31535049 | 42,420 |
def get_request_id():
"""
获取request_id
"""
try:
return get_request().request_id
except AttributeError:
return "" | c697e1cf872e8e7e6334aeae88c7dd702e56c6b1 | 42,421 |
import base64
def create_message(to, subject, message_text):
"""Create a message for an email and return a dictionary
object with its "raw" field containing a base64url encoded
string
{'raw': str}
Example for MIMEText object
>>> message = email.mime.text.MIMEText("Hello world")
>>> messa... | 921302ed31240bb860e826e1696c0a2ad6b3bd3b | 42,422 |
def adcm_api_credentials() -> dict:
"""ADCM credentials for use in tests"""
return {"user": "admin", "password": "admin"} | a2efa47ee588086b0d5dc089728e18b9108964a8 | 42,423 |
import copy
def unfill_isogeny_matrix(M):
"""
Reverses the action of ``fill_isogeny_matrix``.
INPUT:
- ``M`` -- a square symmetric matrix of integers.
OUTPUT:
(matrix) a square symmetric matrix obtained from ``M`` by
replacing non-prime entries with `0`.
EXAMPLES::
sage: ... | 5ccfa256198d689d366fd3950de5eb68e6d798a1 | 42,424 |
import os
def expanded_filename():
"""Return the full absolute path to the STACK_TRACE_FILENAME with any environment
variables ($VAR) and users (~user) expanded."""
return os.path.abspath(
os.path.expanduser(
os.path.expandvars(
os.getenv(ENV_STACK_TRACE_FILENAME, DEFAULT_STACK_TRACE_FILENAME)))) | 60b241eaa1e266c336a97e0c0627dbafcab58e8b | 42,425 |
def _from_csr_ss(csr: _CSR, rsp, rep):
"""
Convert a subset of a Numba CSR to an MKL sparse matrix handle.
"""
_sp = ffi.from_buffer(csr.rowptrs)
_cols = ffi.from_buffer(csr.colinds)
_vals = ffi.from_buffer(csr.values)
return _lk_mkl_spsubset(rsp, rep, csr.ncols, _sp, _cols, _vals) | 5db405aaee625af29e8f036c9912df8548dfa7a1 | 42,426 |
import pydantic
def dc(cls: type):
"""Pydantic dataclass decorator with custom configuration and auto update forward references"""
cls = pydantic.dataclasses.dataclass(config=Config)(cls)
cls.__pydantic_model__.update_forward_refs()
return cls | 6a409111500d1e423378eb37c7642dd7abae18f5 | 42,427 |
def register_game_events(window):
"""
Function used to register all prepared methods inside window property of GameWindow object.
:param window: GameWindow object
"""
@window.window.event
def on_draw():
on_draw_factory(window)()
@window.window.event
def on_mouse_motion(x, y, dx,... | 2ed235bdb40355203f4da77acd40da5779b4a185 | 42,428 |
def get_contour_data(model, pipeline, n_points=1000):
"""Create the data used to show the boundary of the decision function."""
x0s = np.linspace(X_AXIS[0], X_AXIS[1], n_points)
x1s = np.linspace(Y_AXIS[0], Y_AXIS[1], n_points)
x0, x1 = np.meshgrid(x0s, x1s)
X = np.c_[x0.ravel(), x1.ravel()]
... | 2079abaca7e25e865396d7ade60467527766ce92 | 42,429 |
def parse_args():
""" parse_args """
parser = ArgumentParser(description="resnet50 example")
parser.add_argument("--model", type=str, default="resnet50",
help="the network architecture for training or testing")
parser.add_argument("--phase", type=str, default="test",
... | a92a72a89584a7aa5a87ebb521615d58729e34ae | 42,430 |
from typing import Dict
from typing import Union
import threading
def test__synchronized_on_instance__class__no_parentheses() -> None:
"""Test `@synchronized_on_instance` with no parentheses."""
# pylint: disable=missing-function-docstring
@synchronized_on_instance
class _Class:
def method(s... | 885f20bdea0201c3a840c019363c94775929b716 | 42,431 |
import os
def get_stacktrace(testcase, stack_attribute='crash_stacktrace'):
"""Returns the stacktrace for a test case.
This may require a blobstore read.
"""
result = getattr(testcase, stack_attribute)
if not result or not result.startswith(data_types.BLOBSTORE_STACK_PREFIX):
return result
# For App... | 0053a9481524828cea06e178ce54eace2f9645c8 | 42,432 |
def edit_blogpost(request,blogpost_id):
"""编辑已有条目"""
blogpost = BlogPost.objects.get(id = blogpost_id)
title = blogpost.title
#确认请求的主题属于当前登陆的用户,使用函数check_blog_owner
check_blog_owner(request,title)
if request.method !='POST':
#初次请求,使用当前条目填充表单
form = BlogPostForm(instance = blogpost)
else:
#POST提交的数据,对数据进行处理
... | 4a4bf61cadb8ef1abe47801275ca1bfce37b907a | 42,433 |
import warnings
def get_points_simple(**kwargs):
"""Load a DataFrame of points with the most typical query
Parameters
----------
**kwargs
Optional arguments that are passed to get_credentials()
Returns
-------
points_df : pandas DataFrame
DataFrame of all points
"""
... | d108db09eeb3dda02270d4d028588e652defca12 | 42,434 |
def run_text_query(cand_provider,
top_qty,
query_text,
query_id=FAKE_QUERY_ID, field_name=TEXT_FIELD_NAME):
"""Run a text query.
:param cand_provider: a candidate provider object
:param top_qty: a number of top-scored entries to return
:param que... | b62222f1088daaa7baa88e34a8640d6481822715 | 42,435 |
def all_scatter_plots(data):
"""
Generate scatter plots for all hard-coded variable pairs
Arguments:
data: pandas dataframe
Returns: scripts, divs
scripts: list of scripts, each as returned by scatter_plot()
divs: list of divs, each as returned by scatter_plot()
"""
# ... | 06041d1f340bad932e13c92f992105d076beb1fd | 42,436 |
def make_predictions(*, input_data, save_as: str) -> dict:
"""Predict probability of device failure for the test data
Parameters
----------
input_data : _type_
A csv file containing the test data
save_as : str, optional
name to save the file as, by default None
Returns
----... | 121a700a545cd72361283a39a41f71264f48280e | 42,437 |
def analyze_mds(mds, files):
"""
Return dictionary with names of package`s type
===================ARGUMENTS==================
mds - list of mds
files - list of files that situated in cwd
"""
builtin = check_builtin(mds)
local = parse_local(mds, files)
outside = parse_outside(mds, lo... | aac20962f294f8573d9c63a2ac06ca1487bc96d2 | 42,438 |
def init_serializer(serializer=None, **kwargs):
"""Initialize a serializer from a name, class, or instance"""
serializer = serializer or 'pickle'
# Backwards=compatibility with 0.6; will be removed in 0.8
if serializer == 'safe_pickle' or (serializer == 'pickle' and 'secret_key' in kwargs):
seri... | b38ddd32ebe06cda5ced69ab1855a952ca5c19e9 | 42,439 |
import json
def load_json_dataset(path):
"""Load json file and store fields separately."""
# Read dataset
data = []
with open(path, encoding='utf-8') as f:
dataset = json.load(f)
# Iterate and write question-answer pairs
for article in dataset['data']:
doc_truth = [utils.normal... | b84bd9d4fcb27b10e8d51d2e919db91b60a903d8 | 42,440 |
def create_single_mnist(samples=60000, dataset="training", noise=False):
""" Create a dataset where a single MNIST digit is located in the middle of a long image. """
# Extract images and labels from base MNIST files
images, labels = load_mnist(dataset)
new_images = []
new_labels = []
if sample... | 6f7105abbc1cd83bb2e17bd206f96d8f34e31d31 | 42,441 |
def get_policy_group(description=None,display_name=None,domain=None,id=None,opts=None):
"""
Use this data source to access information about an existing resource.
"""
__args__ = dict()
__args__['description'] = description
__args__['displayName'] = display_name
__args__['domain'] = domain
... | 5461adccb4349e0e12f8b3838dfc874e1110386d | 42,442 |
def get_rot_from_mat(m_mat):
"""
Extracts the rotation from a given MMatrix.
Args:
m_mat
Return:
rot
"""
trans_matrix = oMa.MTransformationMatrix(m_mat)
rot = trans_matrix.rotation()
return rot | b5f604b5187cc00cb59b90700cf1d307fb49f802 | 42,443 |
def _dH_df(bss_data, freq_range=None):
"""
Median frequency derivative value of the PS representation of the BSS
components
Parameters
----------
bss_data : numpy.ndarray
Array containing source signals. It must have dimensions CxTxE, where C
is the number of components, T the n... | 8fdce6c1279c759180fc6d5186ffaac9d78d6352 | 42,444 |
def ask_support_exchanges(intent, session):
""" responds support exchanges.
"""
session_attributes = {}
reprompt_text = None
card_title = intent['name']
session_attributes = {}
should_end_session = False
speech_output = "Latest prices are updated from all major crypto currency exchanges... | 37823b10eae58fd7de9a3723e33a2dc33e0580b8 | 42,445 |
import re
def Language_req(description):
"""Create a function that captures the language requirements from the job description"""
description = description.lower()
matches = re.findall(r"\benglish\sand\sgerman\b|\bgerman\sand\senglish\b\benglisch\sund\sdeutsch\b|\benglish\b|\benglisch\b|\bgerman\b|\bdeuts... | cb6ce14d3cba497f668c701d16c13fdfd78f5dc5 | 42,446 |
def LogN(mu, sigma, tag=None):
"""
A Log-Normal random variate
Parameters
----------
mu : scalar
The location parameter
sigma : scalar
The scale parameter (must be positive and non-zero)
"""
assert sigma>0, 'Sigma must be positive'
return uv(rv=ss.lognorm(sigma, ... | 504668be43fe9c56ec0ceb77ff5624b17cd5a35e | 42,447 |
import logging
def matrix_hits(binary_matrix):
"""Gets the number of cells with value 1 in matrix."""
logging.info("Counting how many contacts are predicted.")
count = 0
(n1, n2) = binary_matrix.shape
for i in range(n1):
for j in range(n2):
if j > i:
count += ... | 0242b2844fb2f761e6ba542031f6b188e7d5286e | 42,448 |
def svn_wc_create_notify_url(*args):
"""svn_wc_create_notify_url(char url, svn_wc_notify_action_t action, apr_pool_t pool) -> svn_wc_notify_t"""
return _wc.svn_wc_create_notify_url(*args) | 1f6789ccee5c76e0c11133eb004c96778cef5a1a | 42,449 |
import os
def erpnext_ebay_save_file_on_filesystem_hook(*args, **kwargs):
"""Intercept all write_file events, and mogrify images
Replaces the standard write_file event. Obtains the filename, content_type
etc. Calls the normal backup 'save_file_on_filesystem' with all arguments.
If we do not handle th... | 1418a450b7546ac9a8aa3a0f7c84fe172a889f7d | 42,450 |
import os
def main( input_df, name, detailed=False ):
"""
Each OTU is now ordered by centrality and the AUC of each is calculated.
:param input_df: Important features and OTUs that have been passed on to be ordered
:param name: name attached to all detailed output
:param detailed: Output helper ta... | 2c4dd694b679ee11342589607e6deda11c1568b2 | 42,451 |
def cal_wordInCategory_fre(train_file):
"""
:param trian_file: 训练文件 : 分为两列 <label,doc_words>
:return:
"""
# 统计每个类别中,每个词的词频
wordInCategory_dict = {} # key:label value: dict{key:word value:count}
with open(train_file,'r',encoding='utf-8') as f:
for line in f.readlines():
... | c2240708d4c22e3d0fc7f860c5410f2c1e70a2bd | 42,452 |
import time
def get_elapsed_time_ms(start_time_in_seconds: float):
"""
Returns the elapsed time in millis from the given start time.
"""
end_time = time.time()
return int((end_time - start_time_in_seconds) * 1000) | 72853679a2793b0cb09e83287ab3e3510ec8502d | 42,453 |
def to_rgba(color):
"""
Convert from `colRGB`.
`colRGB` is a `wxPython` type which is basically `BGR`. We don't want to work with
`BGR`, so being able to simply convert `RGB` is preferable.
The algorithm is actually the same swapping in either direction, but having a clear name
makes it obviou... | 0cc76f266421a1939abf4665a669114b59c921ad | 42,454 |
def days_in_month_366(month, year=0):
"""Days of the month (366 days calendar).
Parameters
----------
month : int
numerical value of the month (1 to 12).
year : int, optional
(dummy value).
Returns
-------
out : list of int
days of the month.
Notes
----... | 868500d7022c102562688345b46313203b7ba79b | 42,455 |
def connectedvmware_extension_list(
client: MachineExtensionsOperations,
resource_group_name,
vm_name,
expand=None
):
"""
List all the vm extension of a given vm.
"""
return client.list(resource_group_name=resource_group_name,
name=vm_name,
... | f0fce17339fc6eb8d165857a51b59f1afce9a72f | 42,456 |
def plot_energy_from_initial_source(
energy_bins=np.linspace(0, 20e6, 50),
input_filename='initial_source.h5'):
"""makes a plot of the energy distribution of the source"""
f = h5py.File(input_filename,'r')
dset = f['source_bank']
e_values = []
for particle in dset:
e_value... | 92c3509ff24c88b148a9643739537a1594e33ccf | 42,457 |
from datetime import datetime
def _get_date_from_yyyymmdd(original_date):
""" if date is in YYYYMMDD format, return date """
valid_date = ""
try:
valid_date = datetime.datetime.strptime(original_date, '%Y%m%d')
except ValueError:
pass
return valid_date | b83f7122d1cb8327cce171a80bc3029aa9b405e5 | 42,458 |
import os
def plot_raw_spikes_in_rows(waveforms, assignments, spacing=1, width=1, vscale=1,
subplot_adj=0.9, colors=DEFAULT_COLORS, figtitle="",
figdir="./", fname_postfix="", show=True):
"""Plot raw spikes, each spike in a separate row and each channel in... | 32867a672058938ce21724251bef38daa9dd0f22 | 42,459 |
import requests
import time
import numpy as np
def run_request(bunch, url):
"""Run and time a request with the python requests library
"""
try:
time.sleep(np.random.random_sample()*10)
start = time.time()
response = requests.post(url=url, json=bunch)
assert response.status_... | 8cdf2328fce74b3daeb538e62317a829aa15a496 | 42,460 |
def numeric_plots(df):
"""
Creating a matrix of correlation plots with the numeric features.
Parameters
----------
df: pandas.dataframe
A pandas dataframe
Returns
-------
splom: Altair chart object
The Altair object for the plots
Example
-------
... | 63c7ed0c9f28afa14a6654104738a6428f89d976 | 42,461 |
def _kv_read_checked(conf, key, default=None):
# type: (dict, str, obj) -> obj
"""Read a key as some value with a check against None and length
:param dict conf: configuration dict
:param str key: conf key
:param obj default: default to assign
:rtype: obj or None
:return: value of key
""... | bb04276daa624db8b48f591760351874c848ecc1 | 42,462 |
import base64
def authorization(request, user_name):
""" 메일로 발송된 인증 url로 요청했을 때 작동하는 views """
name = base64.b64decode(user_name.encode('utf-8')) # 인코딩되었던 email name 부분을 디코딩
email = name.decode('utf-8') + '@knu.ac.kr' # 뒤에 knu.ac.kr를 붙여서 완전한 메일 구성
user = User.objects.get(email=email)
user.is... | eddeefa4f58610f3aa7ebedd0edc5387e7902b32 | 42,463 |
from typing import Dict
import os
def registry() -> Dict[str, Dict]:
"""
Return a dictionary of problems of the form:
`{
"problem name": {
"params": ...,
},
...
}`
where `flexs.landscapes.RosettaFolding(**problem["params"])` instantiates the
rosetta folding... | acf7dc0edb4d241d345c5b22a1caf387416951f9 | 42,464 |
import ctypes
def _Cfunction(name, flags, *types):
"""(INTERNAL) New ctypes function binding.
"""
if hasattr(dll, name):
p = ctypes.CFUNCTYPE(*types)
f = p((name, dll), flags)
_Cfunctions[name] = f
return f
raise NameError('no function %r' % (name,)) | 06c28696e4d3125be66438c592b95300028010af | 42,465 |
import copy
def no_alpha(rv, host, companion, limits, new_x=None, normalize=True):
"""Entangled spectrum model with entrinsic flux ratio.
Need to make sure to mulitply by the radius**2 of the respective star.
Parameters
----------
rv: float
rv offset of the companion spectrum.
host: ... | 79b560f2bc181b9feff7bfb0bfca96a4e739c135 | 42,466 |
def intersect_models(dict1, dict2):
"""Combine two dictionaries that are returned from a source method call to
keep only those models that are present in both. It assumes that the models
present in both dictionaries are identical and takes them for the first
input dictionary.
:param dict1: The firs... | 41e98f58823b7894d2f98129bd9bd0c8da1e8a5d | 42,467 |
def post_multipart(site, address, fields, files, cookies):
""" Post fields and files to an http host as multipart/form-data.
@param fields: sequence of (name, value) elements for regular form fields.
@param files: sequence of (name, filename, value) elements for data to be
uploaded as files
@re... | d0388ebdcdacc2b910369306b6f267ae8f398673 | 42,468 |
import math
def hex2meter(level, hex_x, hex_y):
"""hex xy to meter"""
h_len = HEX_LEN / math.pow(3, level)
y = (hex_x + hex_y) * h_len * math.sqrt(3) / 2.0
x = (hex_x - hex_y) * h_len * 3.0 / 2.0
return x, y | ef585f590d3ce30875c5e4480d4ba91dc7935a67 | 42,469 |
import os
def create_root_analysis(tool=None, tool_instance=None, alert_type=None, desc=None, event_time=None,
action_counts=None, details=None, name=None, remediation=None, state=None,
uuid=None, location=None, storage_dir=None, company_name=None, company_id=None,
... | 61a109ac9b2cac3170a0815573efc7eb7e55bac7 | 42,470 |
def _extract_base_type(typed):
"""Extracts the name of the type from a _GenericAlias
Assumes that the derived types are only of length 1 as the __args__ are [0] recursed... this is not true for
tuples
Args:
typed: the type of the parameter
Returns:
name of type
"""
if hasa... | 29b20155f97990eeab17b48e515121a5758b0d14 | 42,471 |
def _UploadFileToObjectResumable(src_url, src_obj_filestream,
src_obj_size, dst_url, dst_obj_metadata,
preconditions, gsutil_api, logger):
"""Uploads the file using a resumable strategy.
Args:
src_url: Source FileUrl to upload. Must not be a st... | 3ca1a7959bce07b58acbdcf1c96e8005572b6c81 | 42,472 |
def get_openstack_connection_raw(auth_args):
"""obtains an OpenStack connection from a supplied dictionary of auth args"""
print("Connecting to Openstack at {0}".format(auth_args['auth_url']))
conn = connection.Connection(**auth_args)
return conn | 7c60f6bc38e5a138df52ffa82a56a85a75a8ca99 | 42,473 |
def recent_feed_like(bot: InstaBot):
"""
Automatically fetches ank like recent_feed_likes
:param bot:
:return:
"""
# first check if self.media_on feed has length zero.
if len(bot.media_to_like) == 0:
print("Refreshing New Media")
if bot.startup:
first_init(bot)
... | 5bc6d42bad606ac96886abd6675461c56290c2db | 42,474 |
def light_probe_sampling_variance_minimization_Viriyothai2009(
light_probe, lights_count=16, colourspace=RGB_COLOURSPACES['sRGB']):
"""
Sample given light probe to find lights using *Viriyothai (2009)* variance
minimization light probe sampling algorithm.
Parameters
----------
light_pro... | c74fd4ad700d9abef2d8f48f0eab78e644ed0296 | 42,475 |
def view_diff(request, uid):
"""
View most recent diff to a post.
"""
# View most recent diff made to a post
post = Post.objects.filter(uid=uid).first()
diffs = Diff.objects.filter(post=post).order_by('-pk')
# Post has no recorded changes,
if not diffs.exists():
return ajax_su... | b506adcee3ca709d8967e5848069fff89cc1c7fc | 42,476 |
def str2bool(val):
"""Convert string to boolean value
"""
try:
if val.lower() in ['false', 'off', '0']:
return False
else:
return True
except AttributeError:
raise TypeError('value {0} was not a string'.format(type(val))) | 01d97b141686a79d310ab59a4acb318250b0746b | 42,477 |
import torch
def make_gaussian_filter_tensor(single_filter, angles, device='cuda'):
"""
Generates 3D tensor of size (M, M, number_angles) with stack of rotated Fourier filters to be used for
datacube extraction.
:param single_filter: Initial filter as numpy array of size (M, M)
:param angles: list... | 1b48fe94e240525f367af42e59192d1dedd3f87c | 42,478 |
def remove_outliers(df):
"""Summary Line.
Extended description of function.
Args:
arg1: Function will remove 1.5 IQR outliers from data set.
Returns:
Will return a data set with outliers within the 1.5 IQR range removed.
"""
q1 = df.quantile(0.25)
q3 = df.quantile(0.75)
iq... | 6333665ddfc4f77b12604c4161ba56c0818663eb | 42,479 |
def GetOdomFromState(state, spot_wrapper, use_vision=True):
"""Maps odometry data from robot state proto to ROS Odometry message
Args:
data: Robot State proto
spot_wrapper: A SpotWrapper object
Returns:
Odometry message
"""
odom_msg = Odometry()
local_time = spot_wrapper... | 22ccd33a04c3d7bebe8ed73efdff1e87b71a05fa | 42,480 |
def loadfactory(theclass, *args):
"""Returns an extended instance of `theclass` initiated from dlite
instance or storage.
If `*args` is a dlite instance, the returned object is initiated form
it. Otherwise `*args` is passed to dlite.Instance()
"""
inst = args[0] if isinstance(args[0], Instance... | 1d59a7eacab9acc126cdbf40d84dc2e8f8de0d84 | 42,481 |
def find_diagonal_blocks(mat: np.ndarray) -> np.ndarray:
"""
Find perfect diagonal sub-blocks in a block-diagonalized binary matrix.
Parameters
----------
mat : (n,n) np.ndarray
binary matrix
Returns
-------
inds : (n,) np.ndarray[int]
all elements comprising a unique p... | aa149a15c433c04e9801ed05ed2dac8c2177f72e | 42,482 |
def categorical_evaluation(prediction: np.ndarray, target: np.ndarray, metric_name: str, mask=None) -> pd.DataFrame:
"""
Evaluates a regression prediction with the F1 score
on quantile-based categories
Args:
prediction: shape [n_classes, X]
target: shape [n_classes, ... | 10c03240d6751b33386c6f12a14f4b7259775f59 | 42,483 |
def get_layers(net_param):
"""Get layers information.
Parameters
----------
net_param : caffe_pb2.NetParameter
A pretrined network description.
Returns
-------
layers : list
description of the layers.
version : string
version information of the pretrained model.
... | 6af46460f0ba9fa41111e265cd5e63a14b8ad5cb | 42,484 |
from pathlib import Path
def get_project_root() -> Path:
"""
Get project root directory with assumed structure as:
${PACKAGE_ROOT}/core/common/path.py
"""
return Path(__file__).resolve().parent.parent.parent | 89dde9a9257c8c3a97104cb883a2ee92a1e9d011 | 42,485 |
def cvSubdiv2DEdgeOrg(edge):
"""CvSubdiv2DPoint cvSubdiv2DEdgeOrg( CvSubdiv2DEdge edge )
Returns edge origin
[ctypes-opencv] returns None if no point is found
"""
ev = edge.value
e = pointer(CvQuadEdge2D.from_address(ev & ~3))
return pointee(e[0].pt[ev & 3]) | f01fc5a4081ce8e1f48b607296c6390a23afad7a | 42,486 |
async def kill_process(op: Operation, host: ObservedHost, pid: int, job_run_until_success) -> bool:
"""
Kills the specified process pid on the desired host
Args:
op: The operation currently being run
host: The host to run the command on
pid: The pid to kill
job_run_until_succ... | 31984551c360b3e9c8c7a5a4607df770f8f0526a | 42,487 |
def delete(consul_url=None, token=None, key=None, **kwargs):
"""
Delete values from Consul
:param consul_url: The Consul server URL.
:param key: The key to use as the starting point for the list.
:param recurse: Delete values recursively beginning at the value of key.
:param cas: This flag is u... | 4743e821ec2ffb27f3170937599b1d0dc032d340 | 42,488 |
import sys
def read_forcing(forc_filename, start_time, end_time,
dt=1800.0, na_values='NaN', sep=';'):
"""
Reads forcing data from to dataframe
Args:
forc_filename (str): forcing file name
start_time (str): starting time [yyyy-mm-dd], if None first date in
file... | 615eb353ec6a13fbe5790a48befdcfc04dc1e08e | 42,489 |
def indexCube(nodes, gridSize, n=None):
"""
Returns the index of nodes on the mesh.
Input:
nodes - string of which nodes to return. e.g. 'ABCD'
gridSize - size of the nodal grid
n - number of nodes each i,j,k direction: [ni,nj,nk]
Output:
index - index in th... | e7fda79032b8cbb4c9242d4d67aa29c9f1e81f90 | 42,490 |
def encode_cf_datetime(dates, units=None, calendar=None):
"""Given an array of datetime objects, returns the tuple `(num, units,
calendar)` suitable for a CF compliant time variable.
Unlike `date2num`, this function can handle datetime64 arrays.
See also
--------
netcdftime.date2num
"""
... | 9c950904f32b4fb6ba663bf484b581e585988957 | 42,491 |
def aggclus(X, THRESHOLD):
"""
agglomerative clustering using single link
X is the n x m vector where n is the number of samples
uses euclidian distance
"""
clustering = AgglomerativeClustering(n_clusters=None, distance_threshold=THRESHOLD).fit(X)
return clustering.labels_,clustering.n_clust... | a6d41762bd6b5132e4348845b13c13fe9f91c3f0 | 42,492 |
def calc_pval(x, y, nulls):
"""
Calculates p-values for simulations in `x` and `y` using `spatnull`
Parameters
----------
{x, y} : (N,) array_like
Simulated GRF brain maps
nulls : (N, P) array_like
Null versions of `y` GRF brain map
Returns
-------
pval : float
... | 382e1b52d75c9770c680b64004a8e7d183af9ba5 | 42,493 |
import os
def getstatusoutput(cmd):
"""Return (status, output) of executing cmd in a shell."""
pipe = os.popen('{ ' + cmd + '; } 2>&1', 'r')
text = pipe.read()
sts = pipe.close()
if sts is None:
sts = 0
if text[-1:] == '\n':
text = text[:-1]
return (
sts, text) | 981aa4c1aadf1f95cf6f95c576a36cc7b4dfbdee | 42,494 |
def norm_bbox(img, bbox, x_corr=0.025, y_corr=0.025):
"""Add adition value for bbox results in x and y-axis
In order to ensure the detected region can cover all the table, we will add an addition value for both x and y axis of the bbox
Using the correlation value x_corr for x-axis and y_corr for y-axis
... | 193e0a9dd13ca2b2b212c23ea73724e9a5e0c121 | 42,495 |
from os.path import dirname
def module_dir():
"""directory of the current module"""
module_dir = dirname(module_path())
if module_dir == "": module_dir = "."
return module_dir | 51eca2f8937dd520d9f1316a32de310748e23d8d | 42,496 |
def get_latest_draft_version(version):
"""Get latest draft version of version object
"""
drafts = Version.objects.filter_by_content_grouping_values(version.content).filter(
state=DRAFT
)
return drafts.first() | d10789125a0906687dff7547f66d40c6ec5e6076 | 42,497 |
from typing import Optional
def delete_datasource_mapping(connection: Connection, id: str, error_msg: Optional[str] = None):
"""Delete a datasource mapping based on id.
Args:
connection: MicroStrategy REST API connection object
id (string): ID of the mapping meant to be deleted.
error... | cd77c4ed46c11d5c2c4fd05967928b04dedb16b4 | 42,498 |
from typing import Union
from typing import Mapping
from typing import Any
from typing import Sequence
def _build_entity_object_ids(entities: Union[str, Mapping[str, Any], Sequence[str]]) -> str:
"""
Builds the string of object ids as required by the GetObject transaction request. See
section 5.3 for the ... | 95d15f23377046f573a0853f612ab87b75d552c4 | 42,499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.