content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def turn_xyz_into_llh(x,y,z,system):
"""Convert 3D Cartesian x,y,z into Lat, Long and Height
See http://www.ordnancesurvey.co.uk/gps/docs/convertingcoordinates3D.pdf"""
a = abe_values[system][0]
b = abe_values[system][1]
e2 = abe_values[system][2]
p = math.sqrt(x*x + y*y)
long = math.atan(y/x)
lat_init... | 5,329,600 |
def _TileGrad(op, grad):
"""Sum reduces grad along the tiled dimensions."""
input_shape = array_ops.shape(op.inputs[0])
# We interleave multiples and input_shape to get split_shape,
# reshape grad to split_shape, and reduce along all even
# dimensions (the tiled dimensions) to get the result
# with sh... | 5,329,601 |
def obj_spatial_error_sum_and_naturalness_jac(s, data):
""" jacobian of error function. It is a combination of analytic solution
for motion primitive model and numerical solution for kinematic error
"""
# Extract relevant parameters from data tuple.
# Note other parameters are used for calli... | 5,329,602 |
def test_setup_logger_with_label(tmpdir, output):
"""Test behaviour when label is not None.
This should produce a log file.
"""
if output:
output = str(tmpdir.mkdir(output))
logger = setup_logger(label='test', output=output)
if output is None:
output = '.'
assert os.path.exi... | 5,329,603 |
def today():
"""Ritorna il giorno di oggi in formato YYYYMMDD"""
today = datetime.date.today()
return today.strftime("%Y%m%d") | 5,329,604 |
def recognize(img, lang, *, hints=None):
"""
识别图像中的文本并返回 OcrResult
:param img: 需要识别的图像, PIL.Image.Image 对象
:param lang: 需要识别的语言,BCP-47 格式字符串
:param hints: 对 OCR 引擎的提示,OcrHint 中定义的值的列表
:returns: OcrResult
OcrResult = {
lines: Tuple[OcrLine],
extra: Any # 引擎返回的额外信息
}
... | 5,329,605 |
def check_missing_requirements ():
"""This list of missing requirements (mencoder, mplayer, lame, and mkvmerge).
Returns None if all requirements are in the execution path.
"""
missing = []
if which("mencoder") is None:
missing.append("mencoder")
if which("mplayer") is None:
miss... | 5,329,606 |
def getExpMat(xy, shape, start, end, r, repeats=5):
"""
Get the expected interaction contact matrix.
xy is [[x,y]]
shape is () shape from the observed matrix.
r is resolution
"""
mat = []
i = 0
while i < repeats:
a = xy[:, 0]
b = xy[:, 1]
np.random.shuffle(a)
... | 5,329,607 |
async def test_save_timestamped_image(hass, mock_image, mock_detections, mock_now):
"""Save a processed image."""
valid_config_save_ts_file = deepcopy(VALID_CONFIG)
valid_config_save_ts_file[ip.DOMAIN].update({sh.CONF_SAVE_FILE_FOLDER: TEST_DIR})
valid_config_save_ts_file[ip.DOMAIN].update({sh.CONF_SAVE... | 5,329,608 |
async def student_decline_offer(uid: str, username=Depends(auth_handler.auth_wrapper)):
"""
Student to decline the offer in an Application
Require: Student-self or Admin-write
"""
logger.debug(f"{username} trying to decline the offer in an ApplicationForm")
_updated = student_update_application... | 5,329,609 |
def test_constraint_compatibility():
"""
Test compatibility v1.6.1 and earlier
"""
dl_col = DdlParseColumn(
name='Col',
data_type_array={'type_name': ['INT']},
)
dl_col.constraint = "PRIMARY KEY COMMENT 'foo'"
# Check column constraint
assert dl_col.not_null is True
... | 5,329,610 |
def main():
"""Run module tests, for now just doctests only."""
from crds.tests import test_table_effects, tstmod
return tstmod(test_table_effects) | 5,329,611 |
def get_relative_path(full_path: str) -> str:
"""
Extract the relative path from the data folder
:param full_path: The full path
:return: Relative path from data folder
>>> get_relative_path(path.join(DATA_PATH, 'MIDI/001-001.mid'))
'MIDI/001-001.mid'
"""
return path.relpath(full_path,... | 5,329,612 |
def etminan(C, Cpi, F2x=3.71, scale_F2x=True):
"""Calculate the radiative forcing from CO2, CH4 and N2O.
This function uses the updated formulas of Etminan et al. (2016),
including the overlaps between CO2, methane and nitrous oxide.
Reference: Etminan et al, 2016, JGR, doi: 10.1002/2016GL071930
... | 5,329,613 |
def render_manage_data_store_pages(request, html_file):
"""
Generate management pages for data_stores.
"""
# initialize session
session_maker = app.get_persistent_store_database('main_db',
as_sessionmaker=True)
session = session_maker()
... | 5,329,614 |
def validate_password_form(p1, p2, is_open, btn, sp1, sp2):
"""Validade password form
Returns
Output('password1', 'invalid'),
Output('password2', 'invalid'),
Output('password1', 'title'),
Output('password2', 'title'),
"""
invalid = {'p1':sp1, 'p2':sp2}
title = {'p1':N... | 5,329,615 |
def cardinal_spline(points,tension=0.5):
"""Path instructions for a cardinal spline. The spline interpolates the control points.
Args:
points (list of 2-tuples): The control points for the cardinal spline.
tension (float, optional): Tension of the spline in the range [0,1]. Defaults to 0.5.
... | 5,329,616 |
def extract(x, *keys):
"""
Args:
x (dict or list): dict or list of dicts
Returns:
(tuple): tuple with the elements of the dict or the dicts of the list
"""
if isinstance(x, dict):
return tuple(x[k] for k in keys)
elif isinstance(x, list):
return tuple([xi[k] for ... | 5,329,617 |
def get_source_config_from_ctx(_ctx,
group_name=None,
hostname=None,
host_config=None,
sources=None):
"""Generate a source config from CTX.
:param _ctx: Either a NodeInstance or a Relati... | 5,329,618 |
def index(request):
"""Show welcome to the sorting quiz."""
template = loader.get_template("ggpoll/index.html")
context = {}
return HttpResponse(template.render(context, request)) | 5,329,619 |
def cnn_dropout_mnist(args):
"""
Main function
"""
# %%
# IMPORTS
# code repository sub-package imports
from artificial_neural_networks.utils.download_mnist import download_mnist
from artificial_neural_networks.utils.generic_utils import save_classif_model
from artificial_... | 5,329,620 |
def _download(
out_path
):
"""Function for downloading all data and results related to this tool's paper"""
out_path = Path(out_path)
out_path.mkdir(parents=True, exist_ok=True)
logging.info(f"Downloading and extracting datasets and models to {str(out_path)}.")
r = requests.get(URLs["tango_repr... | 5,329,621 |
def get_all_random_experiment_histories_from_files(experiment_path_prefix, net_count):
""" Read history-arrays from all specified npz-files with net_number from zero to 'net_count' and return them as
one ExperimentHistories object. """
assert net_count > 0, f"'net_count' needs to be greater than 0, but is {... | 5,329,622 |
def is_gcloud_oauth2_token_cached():
"""Returns false if 'gcloud auth login' needs to be run."""
p = os.path.join(os.path.expanduser('~'), '.config', 'gcloud', 'credentials')
try:
with open(p) as f:
return len(json.load(f)['data']) != 0
except (KeyError, IOError, OSError, ValueError):
return False | 5,329,623 |
def convert_index_to_indices(index_ls, shape):
"""
将 index_ls 格式的坐标列表转换为 indices_ls 格式
"""
assert index_ls.size <= np.prod(shape)
source = np.zeros(shape=shape)
zip_indices = np.where(source >= 0)
indices_ls = convert.zip_type_to_indices(zip_indices=zip_indices)
indices_ls = indices... | 5,329,624 |
def get_funnels_list(connector: MixpanelAPI) -> pd.DataFrame:
"""
This function returns the whole list of funnels in a table containing the funnel ID and the funnel name
:param connector: the connector to the Mixpanel service
:return: a pandas DataFrame
"""
# TODO: change dataframe to simple di... | 5,329,625 |
def _gen_off_list(sindx):
"""
Given a starting index and size, return a list of numbered
links in that range.
"""
def _gen_link_olist(osize):
return list(range(sindx, sindx + osize))
return _gen_link_olist | 5,329,626 |
def report_operation_log_list(request):
"""
返回常规操作的日志列表
:param request:
:return:
"""
return administrator.report_operation_log_list(request) | 5,329,627 |
def connect_redis(redis_host, redis_port, redis_db):
""" connect to redis """
global _conn
if _conn is None:
print "connect redis %s (%s)" % ("%s:%s" % (redis_host, redis_port),
os.getpid())
_conn = redis.Redis(host=redis_host, port=redis_port,
db=redis_db)
... | 5,329,628 |
def debug(*args: Any) -> None:
"""Print args to the console if the "debug" setting is True."""
if log_debug:
printf(*args) | 5,329,629 |
def test_caching_policy_strict_mod(openshift, api_client, service):
"""
Tests:
- if response with valid credentials as before have status_code == 200
- sets backend-listener to the starting value
- sets the auth caching policy of an API to None.
- promotes the configuration to th... | 5,329,630 |
def deploy_blog(blog: BST) -> None:
"""Deploy blog content json files."""
path = Path("./public/blog")
for b in blog:
bpath = path / "blog" / str(b["blog_path"])
os.makedirs(bpath.parent.as_posix(), exist_ok = True)
with bpath.open("w") as f:
json.dump(b, f) | 5,329,631 |
def species_production_reaction(data_dir, spe='OH', top_n=50, norm=False):
"""
count species production reactions in pathway,
multiply by accurate pathwap probability
"""
ps.species_production_reaction(data_dir, spe=spe, top_n=top_n, norm=norm) | 5,329,632 |
def custom_static1(filename):
""" Request to access specific files in the backup directory
.. :quickref: Get backup files; Get a specific file from a directory in the DAQBroker backup directory
"""
scoped = daqbrokerSettings.getScoped()
session = scoped()
#connection = connect(request)
sco... | 5,329,633 |
def loadSV(fname, shape=None, titles=None, aligned=False, byteorder=None,
renamer=None, **kwargs):
"""
Load a delimited text file to a numpy record array.
Basically, this function calls loadSVcols and combines columns returned by
that function into a numpy ndarray with stuctured dtype. A... | 5,329,634 |
def write_int8_8_by_8_not_aligned():
"""
>>> import numpy
>>> int8s = ones(44100 * 2 * 2, int8)
>>> stream = BitStream(4 * [True])
>>> for i in range(len(int8s) / 8):
... stream.write(int8s[8*i:8*(i+1)])
""" | 5,329,635 |
def rationalize_quotes_from_table(table, rationalizeBase=10000):
"""
Retrieve the data from the given table of the SQLite database
It takes parameters:
table (this is one of the Quote table models: Open, High, Low, or Close)
It returns a tuple of lists
"""
first_row = table.select().limit(... | 5,329,636 |
def test_serder_suber():
"""
Test SerderSuber LMDBer sub database class
"""
with dbing.openLMDB() as db:
assert isinstance(db, dbing.LMDBer)
assert db.name == "test"
assert db.opened
sdb = subing.SerderSuber(db=db, subkey='bags.')
assert isinstance(sdb, subing.S... | 5,329,637 |
def task_figures():
"""Make all figures. Each figure is a sub-task."""
# Make figure 1: plot of the CSD matrices.
yield dict(
name='csd',
task_dep=['connectivity_stats'],
file_dep=[fname.epo(subject=subjects[0]),
fname.csd(subject=subjects[0], condition='face')],
... | 5,329,638 |
def k(func):
"""定义一个装饰器函数"""
def m(*args, **kw):
print('call %s():' % func.__name__)
return func(*args, **kw)
return m | 5,329,639 |
def get_playlist_object(playlist_url, access_token):
"""
playlist_url : url of spotify playlist
access_token : access token gotten from client credentials authorization
return object containing playlist tracks
"""
playlist_id = playlist_url.split("/")[-1]
playlist_endpoint = f"https://a... | 5,329,640 |
def guess_identifiers(fuzzy_base_name: str) -> Tuple[str, str]:
"""
Given a fuzzy base name, guess the corresponding (item ID, base name)
identifier pair.
:param fuzzy_base_name: The base name to be matched.
:return: The identifier pair with the closest matching base name.
"""
sql = 'SELECT... | 5,329,641 |
def test_clean_skip_false(mocker):
"""
Validate that the output directory is deleted from disk.
Validate that a new output directory is created.
"""
mock_mkdirs = mocker.patch('os.makedirs')
mock_rmtree = mocker.patch('shutil.rmtree')
output_dir_name = 'find/me/NOW'
manifest = {'output... | 5,329,642 |
def part_2(filename: Path):
"""Part two of day 13. (print code)"""
points, instructions = read_instruction(filename)
points = fold(points, instructions)
num_columns = max([*zip(*points)][0]) + 1
num_rows = max([*zip(*points)][1]) + 1
grid = [[0] * num_columns for i in range(num_rows)]
for x... | 5,329,643 |
def make_image(center=(.1,-.4),dpi=500,X_cut_min = -.59 -xcut_offset,Y_cut_max = 1.61
+ ycut_offset,X_cut_max = .12-xcut_offset,Y_cut_min = .00 +ycut_offset,bands=23 ):
"""make visual count it by area then have hist values for normalization wih movement data
to be exported and then can be cou... | 5,329,644 |
def read_answer_patterns(pattern_file_path):
"""load answer patterns into qid2patterns dictionary
"""
qid2patterns = {}
last_qid = None
with open(pattern_file_path) as f:
for line in f :
qid, pattern = line.strip().split("\t")
if qid != last_qid : # start collectin... | 5,329,645 |
def fitness(coords, solution):
"""
Total distance of the current solution path.
"""
N = len(coords)
cur_fit = 0
for i in range(N):
cur_fit += dist(coords[solution[i % N]], coords[solution[(i + 1) % N]])
return cur_fit | 5,329,646 |
def f_of_sigma(sigma,A=0.186,a=1.47,b=2.57,c=1.19):
"""
The prefactor in the mass function parametrized
as in Tinker et al 2008. The default values
of the optional parameters correspond to a mean
halo density of 200 times the background. The
values can be found in table 2 of
Tinker 2008 ApJ... | 5,329,647 |
def create_role(
role_name: str,
base_session: boto3.Session,
region: str,
auto_trust_caller_identity=True,
allowed_services: Sequence[str] = [],
allowed_aws_entities: Sequence[str] = [],
external_id: str = None,
):
"""
Creates a role that lets a list of specified services assume the... | 5,329,648 |
def get_auto_switch_state(conn):
"""Get the current auto switch enabled / disabled state"""
packet = _request(conn, GET_AUTO_SWITCH_STATE)
if not _validate_packet(packet):
raise ChecksumError()
return _decode_toggle(packet) | 5,329,649 |
def SGD(X, y, lmd, gradient, n_epochs, M, opt = "SGD", eta0 = None, eta_type = 'schedule', t0=5, t1=50, momentum = 0., rho = 0.9, b1 = 0.9, b2 = 0.999):
"""Stochastic Gradient Descent Algorithm
Args:
- X (array): design matrix (training data)
- y (array): output dataset (training data)
... | 5,329,650 |
def get_last_oplog_entry(client):
"""
gets most recent oplog entry from the given pymongo.MongoClient
"""
oplog = client['local']['oplog.rs']
cursor = oplog.find().sort('$natural', pymongo.DESCENDING).limit(1)
docs = [doc for doc in cursor]
if not docs:
raise ValueError("oplog has no... | 5,329,651 |
def schmidt_quasi_norm(size):
"""
Returns an array of the Schmidt Quasi-normalised values
Array is symmetrical about the diagonal
"""
schmidt = square_array(size)
for n in range(size):
for m in range(n + 1):
if n == 0:
double = 1
else:
... | 5,329,652 |
def _merge_jamos(initial, medial, final=None):
"""Merge Jamos into Hangul syllable.
Raises:
AssertionError: If ``initial``, ``medial``, and ``final`` are not in
``INITIAL``, ``MEDIAL``, and ``FINAL`` respectively.
"""
assert initial in INITIALS
assert medial in MEDIALS
final = "∅" if final is Non... | 5,329,653 |
def azimuth(wspr_data):
"""Display the contacts azimut / distance."""
filename = os.path.join(Config.target, 'azimuth.png')
logging.info('Drawing azimuth to %s', filename)
data = []
for node in wspr_data:
data.append((math.radians(int(node.azimuth/Config.granularity) * Config.granularity),
... | 5,329,654 |
def get_feature_set(eq, features):
"""Get features from their strings
Arguments:
eq {Equity} -- equity to build around
features {string array} -- features and params to use
Returns:
list -- list of ndarray of floats
"""
feature_set = []
for feature in features:
... | 5,329,655 |
def class_http_endpoint(methods: METHODS, rule_string: str, side_effect: Optional[HTTP_SIDE_EFFECT] = None, **kwargs):
"""
Creates an HTTP endpoint template. Declare this as a class variable in your webserver subclass to automatically add
the endpoint to all instances. Can be used as a decorator.
Args:... | 5,329,656 |
def value(iterable, key=None, position=1):
"""Generic value getter. Returns containing value."""
if key is None:
if hasattr(iterable, '__iter__'):
return iterable[position]
else:
return iterable
else:
return iterable[key] | 5,329,657 |
def test_derive_course_code_from_course_on_save():
"""The course code should be derived from the course foreign key."""
course = CourseFactory(course_code='TMA4130')
exam = DocumentInfo.objects.create(course=course)
assert exam.course_code == 'TMA4130' | 5,329,658 |
def find_aa_seqs(
aa_seq: str,
var_sites: str,
n_flanking: int = 7
):
"""Grabs the flanking AA sequence around a given location in a protein sequence string.
Args:
aa_seq: Protein sequence string.
var_sites: Integer location of the site of interest (1-indexed, not 0-inde... | 5,329,659 |
def test_by_id_with_invalid_param(get_user, user_repository_spy, fake_user):
"""
Testando o erro metodo by_id.
Utilizando um valor invalido para o parametro user_id.
Deve retornar uma mensagem negativa de sucesso e None.
"""
response = get_user.by_id(user_id=fake_user.name)
# Testando a en... | 5,329,660 |
def main(fn, tmp=False):
"""sorting the lines of the file and write the result to a new file"""
if tmp:
fnew = os.path.join(TMP, os.path.basename(fn))
else:
fnew = '_sorted'.join(os.path.splitext(fn))
with open(fn) as _in, open(fnew, "w") as _out:
regels = _in.readlines()
... | 5,329,661 |
def compact_interval_string(value_list):
"""Compact a list of integers into a comma-separated string of intervals.
Args:
value_list: A list of sortable integers such as a list of numbers
Returns:
A compact string representation, such as "1-5,8,12-15"
"""
if not value_list:
return ''
value_li... | 5,329,662 |
def _mk_asm() -> str:
"""
Generate assembly to program all allocated translation tables.
"""
string = ""
for n,t in enumerate(table.Table._allocated):
string += _mk_table(n, t)
keys = sorted(list(t.entries.keys()))
while keys:
idx = keys[0]
entry = t.e... | 5,329,663 |
def getNuitkaModules():
""" Create a list of all modules known to Nuitka.
Notes:
This will be executed at most once: on the first time when a module
is encountered and cannot be found in the recorded calls (JSON array).
Returns:
List of all modules.
"""
mlist = []
for m ... | 5,329,664 |
def run_model(network):
"""
Runs a model with pre-defined values.
"""
model = network(vocab_size+1, EMBEDDING_SIZE)
model.cuda()
EPOCHS = 20
train_model(model, train, epochs=EPOCHS, echo=False)
return model | 5,329,665 |
def is_prime(num):
""" Assumes num > 3 """
if num % 2 == 0:
return False
for p in range(3, int(num**0.5)+1, 2): # Jumps of 2 to skip odd numbers
if num % p == 0:
return False
return True | 5,329,666 |
def test_nonregistered_units_raise_error():
"""Test that an error is raised when trying to get unit of function that is not registered"""
units = Unit.unit_factory(__name__)
with pytest.raises(exceptions.UnitError):
units("not_registered") | 5,329,667 |
def verify_password(email_or_token, password):
"""
电子邮件和密码是由User模型中现有的方法验证,如果登录密令正确,这个验证回调函数就返回True;
验证回调函数把通过认证的用户保存在Flask的全局对象g中,如此一来,视图函数便能进行访问。
注意:匿名登录时,这个函数返回True并把Flask-login提供的AnonymousUser类实例赋值给g.current_user
:param email:
:param password:
:return:
"""
if email_or_token == ''... | 5,329,668 |
def get_charges_from_recent_text():
"""This function parces the recent text field and extracts the listed charges."""
t0, i = time.time(), 0
needs_charges_formula = "AND(charges_updated = '', html != '', recent_text != '', hours_since_verification < 72, DONT_DELETE != 'no charges')"
records = airtab.get... | 5,329,669 |
def is_valid_orcid_id(orcid_id: str):
"""adapted from stdnum.iso7064.mod_11_2.checksum()"""
check = 0
for n in orcid_id:
check = (2 * check + int(10 if n == "X" else n)) % 11
return check == 1 | 5,329,670 |
def train_model(args, model):
""" Train the model """
os.makedirs(args.output_dir, exist_ok=True)
writer = LogWriter(logdir=os.path.join("logs", args.name))
args.train_batch_size = args.train_batch_size // args.gradient_accumulation_steps
# Prepare dataset
train_loader, test_loader = get_loade... | 5,329,671 |
def copy_file(src, dest):
""" Copies 'src' file to 'dest'
Args:
src (string): file name to be copied from
dest (string): file name to be copied to
"""
shutil.copyfile(src, dest) | 5,329,672 |
def extract_entity(entities, entity_type=_PERSON):
"""
Extract name from the entity specified in entity_type.
We use the JSON format to extract the entity information:
-
:param entities:
:param entity_type:
:return:
"""
if not entity_type:
raise ValueError('Invalid entit... | 5,329,673 |
def ReadBDAFile(bdafile):
""" Read BDA file
:param str bdafile: file name
:return: natm - number of atoms
:return: molnam - name of molecule
:return: frgdat - [bdadic,frgnamlst,frgatmdic,frgattribdic]
bdalst:[[bda#,baa#,bda atmnam,baa atmnam,
... | 5,329,674 |
def reconstruct_from_patches(img_arr, org_img_size, stride=None, size=None):
"""[summary]
Args:
img_arr (numpy.ndarray): [description]
org_img_size (tuple): [description]
stride ([type], optional): [description]. Defaults to None.
size ([type], optional): [description]. Defa... | 5,329,675 |
def process_highlight(entry, img_width):
"""
Function processing highlights extracted from DOM tree. Downloads image based
on its url and scales it. Prettifies text by inserting newlines and
shortening author lists.
Parameters
----------
entry : dict of str
Dictionary created by ex... | 5,329,676 |
def urlopen_with_tries(url, initial_wait=5, rand_wait_range=(1, 60),
max_num_tries=10, timeout=60, read=False):
"""
Open a URL via urllib with repeated tries.
Often calling urllib.request.urlopen() fails with HTTPError, especially
if there are multiple processes calling it. The reason is that N... | 5,329,677 |
def SE3ToROSPose(oMg):
"""Converts SE3 matrix to ROS geometry_msgs/Pose format"""
from geometry_msgs.msg import Pose, Point, Quaternion
xyz_quat = pin.SE3ToXYZQUATtuple(oMg)
return Pose(position=Point(*xyz_quat[:3]), orientation=Quaternion(*xyz_quat[3:])) | 5,329,678 |
def send_emails_tentative(recipients):
""" given list of email addresses, sends emails to each recipient indicating a match """
EMAIL_ADDRESS = "ypool.official@gmail.com"
EMAIL_PASSWORD = "rekcyzrrpcdgfmfl"
with smtplib.SMTP_SSL("smtp.gmail.com", 465) as smtp:
smtp.login(EMAIL_ADDRESS, EMAIL_PA... | 5,329,679 |
def calib_graph_to_infer_graph(calibration_graph_def, is_dynamic_op=False):
"""Convert an existing calibration graph to inference graph.
Args:
calibration_graph_def: the calibration GraphDef object with calibration data
is_dynamic_op: whether to create dynamic static engines from calibration
Returns:
... | 5,329,680 |
def demo():
"""Run this implementation"""
f_1 = Fraction(2, 4)
f_2 = Fraction(60, 90)
f_3 = f_1 + f_2
print(f_3.num)
print(f_3.den) | 5,329,681 |
def test10Instruments():
"""Uses Preprocess to convert the audio data into mel-frequency cepstral coefficients.
Feeds these coefficients into NeuralNet.
Ten instruments are used in this example
"""
# Get preprocessed training data
P = Preprocess()
P.loadData('preprocessed/instr_test_... | 5,329,682 |
def calc_minimum_angular_variance_1d(var_r, phi_c, var_q):
"""Calculate minimum possible angular variance of a beam achievable with a correction lens.
Args:
var_r (scalar): real space variance.
phi_c (scalar): real-space curvature - see above.
var_q (scalar): angular variance of the bea... | 5,329,683 |
def grid_subsampling(points, features=None, labels=None, ins_labels=None, sampleDl=0.1, verbose=0):
"""
CPP wrapper for a grid subsampling (method = barycenter for points and features)
:param points: (N, 3) matrix of input points
:param features: optional (N, d) matrix of features (floating number)
... | 5,329,684 |
def test_histcontrol(xonsh_builtins):
"""Test HISTCONTROL=ignoredups,ignoreerr"""
FNAME = 'xonsh-SESSIONID.json'
FNAME += '.append'
hist = History(filename=FNAME, here='yup', **HIST_TEST_KWARGS)
xonsh_builtins.__xonsh_env__['HISTCONTROL'] = 'ignoredups,ignoreerr'
assert len(hist.buffer) == 0
... | 5,329,685 |
def delete_all_collections_from_collection(collection, api_key=None):
"""
Delete *ALL* Collections from a Collection.
:param collection: The Collection to remove *all* Collections from.
:type collection: str
:param api_key: The API key to authorize request against.
:type api_key: str
:retur... | 5,329,686 |
def weights_init(net: nn.Module) -> None:
"""Takes as input a neural network net that will initialize all its weights.
:param torch.nn net: a neural network, which is Generator or Discriminator
"""
classname = m.__class__.__name__
if classname.find('Conv') != -1:
m.weight.data.normal_(0.0, ... | 5,329,687 |
def generate_kbit_random_tensor(size, bitlength=None, **kwargs):
"""Helper function to generate a random k-bit number"""
if bitlength is None:
bitlength = torch.iinfo(torch.long).bits
if bitlength == 64:
return generate_random_ring_element(size, **kwargs)
rand_tensor = torch.randint(0, 2... | 5,329,688 |
def AnimalsWithAttributes2(path: str) -> Dataset:
"""`Animals with attributes 2 <https://cvml.ist.ac.at/AwA2/>`_ dataset.
The file structure should be like::
<path>
classes.txt
predicates.txt
predicate-matrix-binary.txt
JPEGImages/
<class... | 5,329,689 |
def create_from_matrix_market(out_file: str, sample_id: str, layer_paths: Dict[str, str], row_metadata_path: str, column_metadata_path: str, delim: str = "\t", skip_row_headers: bool = False, skip_colums_headers: bool = False, file_attrs: Dict[str, str] = None, matrix_transposed: bool = False) -> None:
"""
Create a .... | 5,329,690 |
def cache_by_sha(func):
""" only downloads fresh file, if we don't have one or we do and the sha has changed """
@wraps(func)
def cached_func(*args, **kwargs):
cache = {}
list_item = args[1]
dest_dir = kwargs.get('dest_dir')
path_to_file = list_item.get('path', '')
fi... | 5,329,691 |
def rewrite_by_assertion(tm):
"""
Rewrite the tm by assertions. Currently we only rewrite the absolute boolean variables.
"""
global atoms
pt = refl(tm)
# boolvars = [v for v in tm.get_vars()] + [v for v in tm.get_consts()]
return pt.on_rhs(*[top_conv(replace_conv(v)) for _, v in atoms.items... | 5,329,692 |
def hash_cp_stat(fdpath, follow_symlinks=False, hash_function=hash):
""" Returns hash of file stat that can be used for shallow comparision
default python hash function is used which returns a integer. This
can be used to quickly compare files, for comparing directories
see hash_walk().
"""
sta... | 5,329,693 |
def multi_label_head(n_classes,
label_name=None,
weight_column_name=None,
enable_centered_bias=False,
head_name=None,
thresholds=None,
metric_class_ids=None,
loss_fn=None):
... | 5,329,694 |
def render_macros(line, macros):
"""Given a line of non-preprocessed code, and a list of macros, process macro expansions until done.
NOTE: Ignore comments"""
if line.startswith(";"):
return line
else:
while [macro_name for macro_name in macros.keys() if macro_name in line]:
... | 5,329,695 |
def init_LR_XR(args, feat_dim = 1, class_dim = 10, debug = False):
"""
To build lr_xr
:param args: intput arguments
:param feat_dim: dimension of feature
:param class_dim: dimension of class label
:param debug: debug option (True: ON)
:return: init lr_xr using tensorflow build
"""
t... | 5,329,696 |
def calc_qpos(x, bit = 16):
"""
引数の数値を表現できる最大のQ位置を返す。
:param x: float
:return: int
"""
for q in range(bit):
maxv = (2 ** (q - 1)) - 1
if x > maxv:
continue
return bit - q
return bit | 5,329,697 |
def yamlcheck(python):
"""Return True if PyYAML has libyaml support, False if it does not and None if it was not found."""
result = json.loads(raw_command([python.path, os.path.join(ANSIBLE_TEST_TOOLS_ROOT, 'yamlcheck.py')], capture=True)[0])
if not result['yaml']:
return None
return result['c... | 5,329,698 |
def test_how_many_measurements(coins, result):
"""Test that function how_many_measurements returns a defined result."""
from counterfeit import how_many_measurements
assert how_many_measurements(coins) == result | 5,329,699 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.