content
stringlengths 35
762k
| sha1
stringlengths 40
40
| id
int64 0
3.66M
|
---|---|---|
import re
def isrest(peak):
"""Determine whether the first 512 bytes are written in reST."""
try:
a, b = re.match('^(.+?)\n((?:-|=|#)+)', peak).groups()
except (ValueError, AttributeError):
return False
return len(b) >= len(a)
|
2ba2f65611118e8de19542f10a8a9668cd1b03a3
| 34,095 |
def load_raw(stream):
""" Load a schism YAML
"""
# First round to get environmental variables
loader = RawLoader(stream)
try:
data = loader.get_single_data()
finally:
loader.dispose()
stream.seek(0)
# Second round with substitution
env = {}
for key in substitute_keywords:
if key in data:
env.update(data[key])
substitute_env(env)
loader = SubstituteRawLoader(stream, env)
try:
data = loader.get_single_data()
return data
finally:
loader.dispose()
|
ab150dfac1d557b96f5e8e1b4ad6e186d786a6a9
| 34,096 |
def compare_time_stats(grouped, ref_grouped):
"""Given two nested dictionaries generated by get_dict_from_json, after running
calculate_time_stats on both, compare the performance of the given run to a reference
run.
A string will be returned with instances where there is a significant performance
difference
"""
regression_table_data = list()
improvement_table_data = list()
full_comparison_str = str()
for workload_scale_key, workload in grouped.items():
for query_name, file_formats in workload.items():
for file_format, results in file_formats.items():
ref_results = ref_grouped[workload_scale_key][query_name][file_format]
change_significant, is_regression = check_perf_change_significance(
results, ref_results)
if change_significant:
full_comparison_str += build_perf_change_str(
results, ref_results, is_regression) + '\n'
full_comparison_str += build_exec_summary_str(results, ref_results) + '\n'
change_row = build_perf_change_row(results, ref_results, is_regression)
if is_regression:
regression_table_data.append(change_row)
else:
improvement_table_data.append(change_row)
try:
save_runtime_diffs(results, ref_results, change_significant, is_regression)
except Exception as e:
print 'Could not generate an html diff: %s' % e
return full_comparison_str, regression_table_data, improvement_table_data
|
cb6512533ca64c1f59af4a02a4f53f3996e95b0c
| 34,097 |
from typing import Tuple
from typing import Type
from typing import Dict
from typing import Any
def task_name_to_model_class(name: str) -> Tuple[Type[GraphTaskModel], Dict[str, Any]]:
"""
Map task name to a model class and default hyperparameters for that class.
"""
task_info = TASK_NAME_TO_DATASET_AND_MODEL_INFO.get(name.lower())
if task_info is None:
raise ValueError("Unknown task type '%s'" % name)
return task_info.model_class, task_info.model_default_hypers
|
ba7e391de5510c06fbb72abb2d0891931dce1ffd
| 34,098 |
def compute_pairwise_similarities(string_series_1: pd.Series,
string_series_2: pd.Series,
**kwargs) -> pd.Series:
"""
Computes the similarity scores between two Series of strings row-wise.
:param string_series_1: pandas.Series. The input Series of strings to be grouped
:param string_series_2: pandas.Series. The input Series of the IDs of the strings to be grouped
:param kwargs: All other keyword arguments are passed to StringGrouperConfig
:return: pandas.Series of similarity scores, the same length as string_series_1 and string_series_2
"""
return StringGrouper(string_series_1, string_series_2, **kwargs).dot()
|
79a12c261f4b687689ab4747fcb04500a6b7258d
| 34,099 |
def blur(img):
"""
:param img: the original image
:return: img, the blurred image
This function make image blurred
"""
old_image = img
blurred = SimpleImage.blank(old_image.width, old_image.height)
for y in range(old_image.height):
for x in range(old_image.width):
count = 0
sum_r = 0
sum_g = 0
sum_b = 0
for i in range(-1, 2, 1): # 1step, i= -1,0,1
for j in range(-1, 2, 1): # 1step, j = -1,0,1
pixel_x = x + j # neighbor pixel
pixel_y = y + j # neighbor pixel
if 0 <= pixel_x < old_image.width:
if 0 <= pixel_y < old_image.height:
pixel = old_image.get_pixel(pixel_x, pixel_y)
count += 1
sum_r += pixel.red
sum_g += pixel.green
sum_b += pixel.blue
new_pixel = blurred.get_pixel(x, y)
new_pixel.red = sum_r / count
new_pixel.green = sum_g / count
new_pixel.blue = sum_b / count
return blurred
|
6ddd8dd896b419d0d776aa36f249af93e5049a73
| 34,100 |
def _validator(record_type, ref):
"""
Create a DataValidator instance.
"""
if record_type == mds.STATUS_CHANGES:
return mds.DataValidator.status_changes(ref=ref)
elif record_type == mds.TRIPS:
return mds.DataValidator.trips(ref=ref)
else:
raise ValueError(f"Invalid record_type: {record_type}")
|
5e5eb3288304ba9a3fa7635d698370e041a731bd
| 34,102 |
def create_gif(pictures: list, watermark: str,
user_id: int, private=0) -> BytesIO:
"""
Creates gif with watermark from list of PIL images and adds it to database.
Returns BytesIO object
:param pictures: list of PIL.Image objects
:param watermark: watermark text, takes from user name
:param user_id: user id
:param private: defsult False, points out if the gif
available for download by other users
:return: BytesIO
"""
resized_pictures = resize_picture(pictures)
gif = save_gif(resized_pictures)
watermarked_gif = add_watermark(gif, watermark)
minio_storage_manager.add_gif_to_storage(
"gifs", file=watermarked_gif, user_id=user_id, private=private
)
watermarked_gif.seek(0)
return watermarked_gif
|
ff5fd0aeaf9e0b02ee99e7f75624d2a1340c0272
| 34,103 |
def ret_comb_index(bi_tot, get_indices=False, isotope=None):
"""
:param bi_tot:
:return:
"""
bi_1 = int(str(bi_tot)[-2:])
bi_2 = int(str(bi_tot)[0:-2])
if get_indices:
return (bi_1, bi_2 - 1, isotope)
else:
return (bi_1, bi_2 - 1)
|
5647b273d4807aa876f6cd3bd28d287f60cf6296
| 34,106 |
def run_list(arg):
"""
Convert a :class:`~list` to a `RUN` instruction.
:param arg: List that represents instruction arguments.
:return: Fully-qualified `RUN` instruction.
"""
indent = len(run_list.instruction_name) + 1
return formatting.list_with_conditional_command_line_breaks(arg, indent=indent)
|
a2652abed5df8ec5bcdc0df678a57b6d2425fe49
| 34,107 |
def count_loops(G):
"""
Count the loop edges in a graph.
Parameters
----------
G : NetworkX graph
"""
loops = get_loops(G)
return len(loops)
|
58fdcf8aac09fa7a52d59f9fbbcba170313408ab
| 34,108 |
async def post_projectversion_toggle_ci(request):
"""
Toggles the ci enabled flag on a projectversion.
---
description: Toggles the ci enabled flag on a projectversion.
tags:
- ProjectVersions
consumes:
- application/x-www-form-urlencoded
parameters:
- name: projectversion_id
in: path
required: true
type: integer
produces:
- text/json
responses:
"200":
description: successful
"500":
description: internal server error
"""
db = request.cirrina.db_session
projectversion_id = request.match_info["projectversion_id"]
try:
projectversion_id = int(projectversion_id)
except (ValueError, TypeError):
return ErrorResponse(400, "Incorrect value for projectversion_id")
projectversion = db.query(ProjectVersion).filter(ProjectVersion.id == projectversion_id).first()
if not projectversion:
return ErrorResponse(400, "Projectversion#{projectversion_id} not found".format(
projectversion_id=projectversion_id))
projectversion.ci_builds_enabled = not projectversion.ci_builds_enabled
db.commit()
result = "enabled" if projectversion.ci_builds_enabled else "disabled"
logger.info("continuous integration builds %s on ProjectVersion '%s/%s'",
result,
projectversion.project.name,
projectversion.name)
return OKResponse("Ci builds are now {}.".format(result))
|
f9c50607e90f0f910503b6557bd324ad3adba43e
| 34,109 |
def edit_item(category, item):
"""App route function to edit an item."""
# Verify user login. If not, redirect to login page.
login_status = None
if 'email' in login_session:
login_status = True
else:
flash('Please log in.')
return redirect(url_for('home'))
# Query database with SQLAlchemy to display categories on page
categories = session.query(Categories).all()
if request.method == 'POST':
# Query database with SQLAlchemy and store queries as objects
category = (session.query(Categories)
.filter_by(name=category.replace('-', ' '))
.one())
item = (session.query(Items)
.filter_by(name=item.replace('-', ' '))
.one())
# Get form fields submitted by user, or retain item info
name = request.form['name'] if request.form['name'] else item.name
url = request.form['url'] if request.form['url'] else item.url
if request.form['photo_url']:
photo_url = request.form['photo_url']
else:
photo_url = item.photo_url
if request.form['description']:
description = request.form['description']
else:
description = item.description
category = request.form['item_category']
# Retrieve the database ID of the item's category
category_id = (session.query(Categories)
.filter_by(name=category.replace('-', ' '))
.one())
# Get user's database ID
user_db_id = (session.query(Users)
.filter_by(email=login_session['email'])
.one()).id
# Get database ID of creator
creator_db_id = item.creator_db_id
print("Current user's database primary key id is {}."
.format(user_db_id))
print("Item creator's database primary key id is {}."
.format(creator_db_id))
print('Item to edit is "{}".'.format(item.name))
# Only allow creator to edit. If not, redirect to login.
if user_db_id != creator_db_id:
flash('Only the creator can edit. Please log in as creator.')
return redirect(url_for('home'))
# Store edits in an object
edited_item = Items(name=name,
url=url,
photo_url=photo_url,
description=description,
category_id=category_id.id,
creator_db_id=user_db_id)
# Overwrite item object with new info from edited_item object
item.name = edited_item.name
item.url = edited_item.url
item.photo_url = edited_item.photo_url
item.description = edited_item.description
item.category_id = edited_item.category_id
session.add(item)
session.commit()
print('Item "{}" edited.'.format(edited_item.name))
# Return to homepage
return redirect(url_for('home'))
else:
# Query database with SQLAlchemy to display categories on page
categories = session.query(Categories).all()
# Render webpage
return render_template('edit_item.html',
categories=categories,
item=item,
login_status=login_status)
|
e8300e083da286544d58c5e4aaa59cdc126414ac
| 34,110 |
def sanity_check_gcon():
"""Sanity check gcon."""
cmd = gcon_py + " --help"
errmsg = gcon_py + " is not installed."
execute(cmd=cmd, errmsg=errmsg)
return gcon_py
|
11585da8701edc482ab2d0588f1d983d32b5e1c4
| 34,111 |
import requests
import json
def get_Cust_Bookings_Hours(request, *args, **kwargs):
"""Request Chart Points per Themes"""
bookings_H_tmp = requests.get('http://127.0.0.1:5000/customer/bookings/hours').text
bookings_Hours_list = json.loads(bookings_H_tmp)
bookings_Hours = [
['Heures', 'Nombre de réservations', {"role": "annotation"}]
]
for elem in bookings_Hours_list:
hours = elem['_id']['hours'] + ":00"
nb = elem['total']
bookings_Hours_tmp = [hours, nb, nb]
bookings_Hours.append(bookings_Hours_tmp)
return JsonResponse(bookings_Hours, safe=False)
|
9463cb31da46f751014a14d6daeb28df3d0c8cfe
| 34,113 |
def judo_turnier():
"""Show participants for judo turnier."""
participants = Participant.query.filter_by(user_id=current_user.id,
event=EVENT_JUDO_TURNIER).all()
form = ParticipantDeleteForm(request.form)
return render_template('events/judo-turnier.html', form=form, participants=participants)
|
78614761f183d1280eeb80e08e17500fed62d25a
| 34,116 |
def preprocess_mapper(features, params, lookup_table):
"""Model-specific preprocessing of features from the dataset."""
features["question_inputs"] = text_utils.build_text_inputs(
text=features["question"],
length=params["question_length"],
lookup_table=lookup_table)
features["context_inputs"] = text_utils.build_text_inputs(
text=features["context"],
length=params["context_length"],
lookup_table=lookup_table)
# Remove extra inputs.
features = {f: features[f] for f in features if f in KEYS}
return features
|
5454cf1149982ddc3314fb9793123b16e70e1381
| 34,118 |
import logging
def get_user_playlists():
"""Return all of the user's playlists"""
logging.info("fetching user playlists")
url = "https://api.spotify.com/v1/me/playlists"
return get_all_pages(url)
|
17d96f81ccf78cc0d9210968deb6a9550f82f34c
| 34,119 |
def set_circuit_ic_mrucc(n_qubits, v_n, a_n, c_n, DS, theta_list, ndim1, a2a):
"""
"""
circuit = QuantumCircuit(n_qubits)
if DS:
circuit = icmr_ucc_singles(circuit,v_n, a_n, c_n, theta_list, 0)
circuit = icmr_ucc_doubles(circuit,v_n, a_n, c_n, theta_list, ndim1, a2a)
else:
circuit = icmr_ucc_doubles(circuit,v_n, a_n, c_n, theta_list, ndim1, a2a)
circuit = icmr_ucc_singles(circuit,v_n, a_n, c_n, theta_list, 0)
return circuit
|
7a3fc8474f07b926b49980b467cbb8c19a24d8b8
| 34,120 |
def dct2spatial(image):
"""
Rearrange DCT image from [H//8, W//8, 64] to [H,W]
"""
assert image.shape[2] == 64
block_view = (image.shape[0], image.shape[1], 8, 8)
image_shape = (image.shape[0] * 8, image.shape[1] * 8)
block_permute = 0, 2, 1, 3
result = image.reshape(block_view).transpose(*block_permute).reshape(image_shape)
return result
|
a1052b2f851a59eabb28c672f01547b5c4797bbc
| 34,121 |
def theta2rotx(theta: np.ndarray) -> np.ndarray:
"""
Rx = [[1, 0, 0],
[0, c(t), -s(t)],
[0, s(t), c(t)]]
:param theta: angle(s) in degrees, positive is counterclockwise
:return: rotation_matrices
"""
theta = np.deg2rad(np.asarray(theta).reshape(-1))
rotation_matrices = np.zeros((theta.shape[0], 3, 3), dtype=np.float)
cos_theta = np.cos(theta)
sin_theta = np.sin(theta)
rotation_matrices[:, 0, 0] = 1
rotation_matrices[:, (1, 2), (1, 2)] = cos_theta[:, np.newaxis]
rotation_matrices[:, 1, 2] = -sin_theta
rotation_matrices[:, 2, 1] = sin_theta
return rotation_matrices
|
48aaa4a84b49495f2106fba7dc70749865001811
| 34,122 |
from datetime import datetime
def json_serializer(obj):
"""JSON serializer for objects not serializable by default json code"""
if isinstance(obj, datetime):
# Serialize datetime as the ISO formatted string
serial = obj.isoformat()
return serial
raise TypeError("Type not serializable")
|
dfc2ebf9f254cd9f3723144b4d97839159a428f7
| 34,124 |
def leaves_f(prog, typ):
"""Doc."""
return list(filter(lambda it: type(it), leaves(prog)))
|
4119e92c2bd5c910b5a9b5badca69fd09dedc429
| 34,126 |
def imshow_xy(axes, coord, data,
xy_limits=None, xy_pad=0.02, add_lines=False,
step_kw=None, line_kw=None, **kwargs):
""" Show data as an image in ax, with slices at x and y in
the subplots axy and axx.
img = ax.imshow(data)
step_x = axx.step(data[coord[1], :])
step_y = axy.step(data[:, coord[0]])
args:
axes # (ax, axx, axy)
coord # position (x, y)
data # 2D numpy.ndarray
xy_limits=None # None or "auto" / (min, max) / "data" / "match" / "clim"
xy_pad=0.02 # padding of the xy vertical range
# (active for xy_limits="data" or "clim")
add_lines=False # mark coords with lines
line_kw=None # dict() of kwargs for ax.axhline()
step_kw=None # dict() of kwargs for axx.step()
kwargs:
passed to matplotlib.pyplot.imshow()
returns:
img, step_x, step_y
"""
ax, axx, axy = axes
x, y = coord
# xy slices
if isinstance(data, np.ndarray):
assert data.ndim == 2
ny, nx = np.shape(data)
if "extent" in kwargs:
xmin, xmax, ymin, ymax = kwargs["extent"]
dx = (xmax - xmin) / nx
xmin += dx / 2.0
xmax -= dx / 2.0
dy = (ymax - ymin) / ny
ymin += dy / 2.0
ymax -= dy / 2.0
xi = int(np.round((x - xmin) / dx))
yi = int(np.round((y - ymin) / dy))
else:
xmin, xmax, ymin, ymax = 0, nx - 1, 0, ny - 1
dx = dy = 1
xi, yi = int(np.round(x)), int(np.round(y))
xvals = np.linspace(xmin, xmax, nx)
xdata = data[yi, :]
yvals = np.linspace(ymin, ymax, ny)
ydata = data[:, xi]
else:
raise TypeError("data must be a 2D numpy array")
# xy step plots
if step_kw is None:
step_kw = {}
step_x = step_plot(axx, xvals, xdata,
orientation="horizontal",
**step_kw)
step_y = step_plot(axy, yvals, ydata,
orientation="vertical",
**step_kw)
# plot image
img = ax.imshow(data, **kwargs)
# lines
if add_lines:
if line_kw is None:
line_kw = {}
ax.axvline(coord[0], **line_kw)
ax.axhline(coord[1], **line_kw)
# autorange
axx, axy = autorange_xy(img, axx, axy, data, xy_limits, xy_pad)
return img, step_x, step_y
|
e8727c5a7c3dd114e6beda1c171156f636e08b28
| 34,127 |
import re
def create_endpoint(project_id: str, region: str, endpoint_name: str) -> str:
"""
Create an endpoint on Vertex AI
:param project_id:
:param region:
:param endpoint_name:
:return:
"""
try:
endpoint = aiplatform.Endpoint.create(display_name=endpoint_name, project=project_id, location=region)
return endpoint.resource_name
except PermissionDenied as error:
try:
permission = re.search("Permission '(.*)' denied", error.args[0]).group(1)
raise EdgeException(
f"Endpoint '{endpoint_name}' could not be created in project '{project_id}' "
f"because you have insufficient permission. Make sure you have '{permission}' permission."
) from error
except AttributeError as attribute_error:
raise error from attribute_error
|
383fb8961050e31270f5f4c9b68008864ce34ae9
| 34,128 |
import logging
def get_warning_logger() -> logging.Logger:
"""
Set up a logger to capture warnings and log them
"""
logging.captureWarnings(True)
warning_logger = logging.getLogger('py.warnings')
if warning_logger.handlers: warning_logger.handlers = []
return warning_logger
|
5cdf76ff66963851715b3302c02681340d2f6a72
| 34,129 |
def check_type_match(actual_val, expected_val) -> bool:
"""Check actual_val matches type of expected_val
The exception here is that expected_val can be
float, and in that case actual_val can be either
int or float
Args:
actual_val (Any): Actual type
expected_val (Any): Expected type
Returns:
bool: Whether the type matches
"""
if type(actual_val) == type(expected_val):
return True
# Make an exception here since int can be represented as float
# But not vice versa (for example, index)
if type(expected_val) == float and type(actual_val) == int:
return True
return False
|
90f74b1978deb0c55b65a4faa2569f54fe6bceee
| 34,130 |
from typing import Callable
from typing import Tuple
def _single_step_smart_generalized_leapfrog(
grad_log_posterior: Callable,
metric: Callable,
grad_metric: Callable,
grad_log_posterior_and_metric_and_grad_metric: Callable,
zo: Tuple[np.ndarray],
step_size: float,
thresh: float,
max_iters: int,
cache: dict
) -> Tuple:
"""Implements the 'smart' generalized leapfrog integrator which avoids
recomputing redundant quantities at each iteration.
Args:
log_posterior: Function to compute the log-posterior.
grad_log_posterior: Function to compute the gradient of the log-posterior.
metric: Function to compute the Fisher information metric.
grad_metric: Function to compute the gradient of the Fisher information
metric.
grad_log_posterior_and_metric_and_grad_metric: A function that returns
all of the gradient of the log-posterior, the Riemannian metric, and
the derivatives of the metric.
zo: Tuple containing the position and momentum variables in the original
phase space.
step_size: Integration step_size.
thresh: Convergence tolerance for fixed point iterations.
max_iters: Maximum number of fixed point iterations.
Returns:
qn: The terminal position variable.
pn: The terminal momentum variable.
num_iters: The number of fixed point iterations to find the fixed points
defining the generalized leapfrog algorithm.
success: Boolean flag indicating successful integration.
"""
# Precompute the half step-size and the number of dimensions of the
# position variable.
half_step = 0.5 * step_size
num_dims = len(zo[0])
# Create partial functions to eliminate dependencies on the terminal
# condition.
termcond = partial(cond, thresh=thresh, max_iters=max_iters)
# Precompute necessary quantities.
qo, po = zo
delta = np.ones_like(po) * np.inf
Id = np.eye(num_dims)
if 'aux' in cache:
glp, iG, dG = cache['aux']
else:
glp, G, dG = grad_log_posterior_and_metric_and_grad_metric(qo)
iG = solve_psd(G, Id)
nglp = -glp
dG = dG.swapaxes(0, -1)
dld = 0.5*np.trace(np.asarray(np.hsplit([email protected](dG), num_dims)), axis1=1, axis2=2)
fixed = (po, nglp, iG, dG, dld)
# The first step of the integrator is to find a fixed point of the momentum
# variable.
val = (po, delta, 0)
momstep = partial(momentum_step, half_step=half_step, fixed=fixed)
pm, delta_mom, num_iters_mom = while_loop(termcond, momstep, val)
success_mom = np.all(delta_mom < thresh)
# The second step of the integrator is to find a fixed point of the
# position variable. The first momentum gradient could be conceivably
# cached and saved.
val = (qo, delta, 0)
iGp = iG@pm
fixed = (qo, pm, iGp)
posstep = partial(position_step, half_step=half_step, metric=metric, fixed=fixed)
qn, delta_pos, num_iters_pos = while_loop(termcond, posstep, val)
success_pos = np.all(delta_pos < thresh)
success = np.logical_and(success_mom, success_pos)
# Increment the number of iterations by one since the final momentum update
# requires computing the gradient of the potential function again.
num_iters = num_iters_pos + num_iters_mom + 1
# Last step is to do an explicit half-step of the momentum variable.
glp, G, dG = grad_log_posterior_and_metric_and_grad_metric(qn)
iG = solve_psd(G, Id)
cache['aux'] = (glp, iG, dG)
dG = dG.swapaxes(0, -1)
o = iG@pm
a = -glp
b = 0.5*np.trace(np.asarray(np.hsplit([email protected](dG), num_dims)), axis1=1, axis2=2)
c = -0.5*o@dG@o
gph = a + b + c
pn = pm - half_step * gph
return (qn, pn), cache, num_iters, success
|
f091280bcda175ec0b1b399825a484e5d725c82a
| 34,131 |
def real_sph_harm(l, zero_m_only=True, spherical_coordinates=True):
"""
Computes formula strings of the the real part of the spherical harmonics up to order l (excluded).
Variables are either cartesian coordinates x,y,z on the unit sphere or spherical coordinates phi and theta.
"""
if not zero_m_only:
S_m = [0]
C_m = [1]
for i in range(1, l):
x = sym.symbols('x')
y = sym.symbols('y')
S_m += [x * S_m[i - 1] + y * C_m[i - 1]]
C_m += [x * C_m[i - 1] - y * S_m[i - 1]]
P_l_m = associated_legendre_polynomials(l, zero_m_only)
if spherical_coordinates:
theta = sym.symbols('theta')
z = sym.symbols('z')
for i in range(len(P_l_m)):
for j in range(len(P_l_m[i])):
if type(P_l_m[i][j]) != int:
P_l_m[i][j] = P_l_m[i][j].subs(z, sym.cos(theta))
if not zero_m_only:
phi = sym.symbols('phi')
for i in range(len(S_m)):
S_m[i] = S_m[i].subs(x, sym.sin(
theta) * sym.cos(phi)).subs(y, sym.sin(theta) * sym.sin(phi))
for i in range(len(C_m)):
C_m[i] = C_m[i].subs(x, sym.sin(
theta) * sym.cos(phi)).subs(y, sym.sin(theta) * sym.sin(phi))
Y_func_l_m = [['0'] * (2 * j + 1) for j in range(l)]
for i in range(l):
Y_func_l_m[i][0] = sym.simplify(sph_harm_prefactor(i, 0) * P_l_m[i][0])
if not zero_m_only:
for i in range(1, l):
for j in range(1, i + 1):
Y_func_l_m[i][j] = sym.simplify(
2 ** 0.5 * sph_harm_prefactor(i, j) * C_m[j] * P_l_m[i][j])
for i in range(1, l):
for j in range(1, i + 1):
Y_func_l_m[i][-j] = sym.simplify(
2 ** 0.5 * sph_harm_prefactor(i, -j) * S_m[j] * P_l_m[i][j])
return Y_func_l_m
|
cff7053e02600934f8b00a4d74fffeb6223fc1d3
| 34,132 |
def drsky(x, ecc, omega, inc):
"""Function whose roots we wish to find to obtain time of secondary
(and primary) eclipse(s)
When one takes the derivative of equation (5) in Winn
(2010; https://arxiv.org/abs/1001.2010v5), and equates that to zero
(to find the minimum/maximum of said function), one gets to an
equation of the form g(x) = 0. This function (drsky) is g(x), where
x is the true anomaly.
Parameters
----------
x : float
True anomaly
ecc : float
Eccentricity of the orbit
omega : float
Argument of periastron passage (in radians)
inc : float
Inclination of the orbit (in radians)
Returns
-------
drsky : float
Function evaluated at x, ecc, omega, inc
"""
sq_sini = np.sin(inc) ** 2
sin_o_p_f = np.sin(x + omega)
cos_o_p_f = np.cos(x + omega)
f1 = sin_o_p_f * cos_o_p_f * sq_sini * (1. + ecc * np.cos(x))
f2 = ecc * np.sin(x) * (1. - sin_o_p_f ** 2 * sq_sini)
return f1 - f2
|
03238e267760e081f4f69367e7e37f46877072cf
| 34,133 |
from typing import List
import types
from typing import Iterator
from typing import Tuple
from typing import Dict
from typing import Any
def ComputeQueryBasedMetrics( # pylint: disable=invalid-name
extracts: beam.pvalue.PCollection,
prediction_key: str,
query_id: str,
combine_fns: List[beam.CombineFn],
) -> beam.pvalue.PCollection:
"""Computes metrics and plots using the EvalSavedModel.
Args:
extracts: PCollection of Extracts. The extracts MUST contain a
FeaturesPredictionsLabels extract keyed by
tfma.FEATURE_PREDICTIONS_LABELS_KEY and a list of SliceKeyType extracts
keyed by tfma.SLICE_KEY_TYPES_KEY. Typically these will be added by
calling the default_extractors function.
prediction_key: Key in predictions dictionary to use as the prediction (for
sorting examples within the query). Use the empty string if the Estimator
returns a predictions Tensor (not a dictionary).
query_id: Key of query ID column in the features dictionary.
combine_fns: List of query based metrics combine functions.
Returns:
PCollection of (slice key, query-based metrics).
"""
missing_query_id_counter = beam.metrics.Metrics.counter(
constants.METRICS_NAMESPACE, 'missing_query_id')
def key_by_query_id(extract: types.Extracts,
query_id: str) -> Iterator[Tuple[str, types.Extracts]]:
"""Extract the query ID from the extract and key by that."""
features = extract[constants.FEATURES_PREDICTIONS_LABELS_KEY].features
if query_id not in features:
missing_query_id_counter.inc()
return
feature_value = features[query_id][encoding.NODE_SUFFIX]
if isinstance(feature_value, tf.compat.v1.SparseTensorValue):
feature_value = feature_value.values
if feature_value.size != 1:
raise ValueError('Query ID feature "%s" should have exactly 1 value, but '
'found %d instead. Values were: %s' %
(query_id, feature_value.size(), feature_value))
yield ('{}'.format(np.asscalar(feature_value)), extract)
def merge_dictionaries(
dictionaries: Tuple[Dict[str, Any], ...]) -> Dict[str, Any]:
"""Merge dictionaries in a tuple into a single dictionary."""
result = dict()
for d in dictionaries:
intersection = set(d.keys()) & set(result.keys())
if intersection:
raise ValueError('Overlapping keys found when merging dictionaries. '
'Intersection was: %s. Keys up to this point: %s '
'keys from next dictionary: %s' %
(intersection, result.keys(), d.keys()))
result.update(d)
return result
# pylint: disable=no-value-for-parameter
return (extracts
| 'KeyByQueryId' >> beam.FlatMap(key_by_query_id, query_id)
| 'CreateQueryExamples' >> beam.CombinePerKey(
CreateQueryExamples(prediction_key=prediction_key))
| 'DropQueryId' >> beam.Map(lambda kv: kv[1]._replace(query_id=kv[0]))
| 'CombineGlobally' >> beam.CombineGlobally(
beam.combiners.SingleInputTupleCombineFn(*combine_fns))
| 'MergeDictionaries' >> beam.Map(merge_dictionaries)
| 'AddOverallSliceKey' >> beam.Map(lambda v: ((), v)))
# pylint: enable=no-value-for-parameter
|
ee3907109a8ff0c67f02e5d9b2296c3955bd501f
| 34,134 |
def get_brier_scores(at_time_intervals, censored_indicator=1.0):
"""Construct Brier score metrics for survival probability predictions."""
metrics = []
for t in at_time_intervals:
metric = partial(
brier_score, t=t, censored_indicator=censored_indicator)
metric.__name__ = 'bs_at_%d' % t
metrics.append(metric)
return metrics
|
58a23d2c7706761a68bfd375b20400dc075a4c96
| 34,135 |
def create_id_maps(session):
"""
Create a large universal map of maps that carries common items like
"Allegiance" or "Government" onto the id expected to be inserted into the db.
Returns: A adict of dicts that ultimately points to integer ids in the db.
"""
maps = {
'Allegiance': {x.eddn: x.id for x in session.query(cogdb.eddb.Allegiance)},
'ConflictState': {x.eddn: x.id for x in session.query(cogdb.eddb.ConflictState)},
'Economy': {x.eddn: x.id for x in session.query(cogdb.eddb.Economy)},
'FactionState': {x.eddn: x.id for x in session.query(cogdb.eddb.FactionState)},
'Government': {x.eddn: x.id for x in session.query(cogdb.eddb.Government)},
'Happiness': {x.eddn: x.id for x in session.query(cogdb.eddb.FactionHappiness)},
'Powers': {x.eddn: x.id for x in session.query(cogdb.eddb.Power)},
'PowerplayState': {x.eddn: x.id for x in session.query(cogdb.eddb.PowerState)},
'Security': {x.eddn: x.id for x in session.query(cogdb.eddb.Security)},
'StationType': {x.eddn: x.id for x in session.query(cogdb.eddb.StationType)},
}
maps['PowerplayState']['HomeSystem'] = maps['PowerplayState']['Controlled']
return maps
|
ae5f30fc4338c61b26087b3d6d5f30d87e7b97cd
| 34,136 |
def _box_without_row_and_column_of(row, col, width, height):
"""Return some coordinates in the square of (col, row) as a list.
The coordinates in the same row and column are removed.
This is an internal function and should not be used
outside of the coordinates module.
"""
grid_x = col - (col % width)
grid_y = row - (row % height)
return [(grid_y + i, grid_x + j) for i, j in product(
range(height), range(width))
if grid_y + i != row and grid_x + j != col]
|
e7dc91611788fb5e22a70d30edcda5708f751085
| 34,137 |
def fieldtype(field):
"""Get the type of a django form field (thus helps you know what class to apply to it)"""
return field.field.widget.__class__.__name__
|
e2d68cbdd72219de1a23095100c054a46c6c191b
| 34,138 |
def fitToIntervals(areas: list, num_of_bins: int):
"""
fitting the area of each contour to the suitable interval.
:param areas: a list of contour areas.
:param num_of_bins: the number of intervals.
:return: a list containing each suitable interval for a given area.
"""
intervals = findIntervals(areas=areas, num_of_bins=num_of_bins)
interval_ranges = []
for area in areas:
interval_ranges.append(
str([interval for interval in intervals if area in interval][0]))
return interval_ranges
|
aa731e7ed298c55649242923a774e07da308b757
| 34,140 |
def get_team_repo(remote_url):
"""
Takes remote URL (e.g., `[email protected]:mozilla/fireplace.git`) and
returns team/repo pair (e.g., `mozilla/fireplace`).
"""
if ':' not in remote_url:
return remote_url
return remote_url.split(':')[1].replace('.git', '')
|
5e0120881557e9d95b697ab194fd7a8e8a84c68d
| 34,144 |
def ajax_request(func):
"""
If view returned serializable dict, returns JSONResponse with this dict as content.
example:
@ajax_request
def my_view(request):
news = News.objects.all()
news_titles = [entry.title for entry in news]
return {'news_titles': news_titles}
Taken from django-annoying
"""
@wraps(func)
def wrapper(request, *args, **kwargs):
response = func(request, *args, **kwargs)
if isinstance(response, (dict, list, tuple)):
return JsonResponse(response)
else:
return response
return wrapper
|
a672e3164af2c282fa301d351434ce863e7b2204
| 34,145 |
def load_collection_from_file(resource, filename, content_type=None):
"""
Creates a new collection for the registered resource and calls
`load_into_collection_from_file` with it.
"""
coll = create_staging_collection(resource)
load_into_collection_from_file(coll, filename,
content_type=content_type)
return coll
|
c85eb82ee3633c69bef5ceb8b2954ea0fd700798
| 34,146 |
import requests
import time
def get_fxa_token(*, code=None, refresh_token=None, config=None):
"""Given an FxA access code or refresh token, return dict from FxA /token endpoint
(https://git.io/JJZww). Should at least contain `access_token` and
`id_token` keys.
"""
assert config, 'config dict must be provided to get_fxa_token'
assert (
code or refresh_token
), 'either code or refresh_token must be provided to get_fxa_token'
log_identifier = f'code:{code}' if code else f'refresh:{refresh_token[:8]}'
log.info(f'Getting token [{log_identifier}]')
with statsd.timer('accounts.fxa.identify.token'):
if code:
grant_data = {'grant_type': 'authorization_code', 'code': code}
else:
grant_data = {'grant_type': 'refresh_token', 'refresh_token': refresh_token}
response = requests.post(
settings.FXA_OAUTH_HOST + '/token',
data={
**grant_data,
'client_id': config['client_id'],
'client_secret': config['client_secret'],
},
)
if response.status_code == 200:
data = response.json()
if data.get('access_token'):
log.info(f'Got token for [{log_identifier}]')
data['access_token_expiry'] = time.time() + data.get('expires_in', 43200)
return data
else:
log.info(f'No token returned for [{log_identifier}]')
raise IdentificationError(f'No access token returned for {log_identifier}')
else:
log.info(
'Token returned non-200 status {status} {body} [{code_or_token}]'.format(
code_or_token=log_identifier,
status=response.status_code,
body=response.content,
)
)
raise IdentificationError(f'Could not get access token for {log_identifier}')
|
d0e0b70fd4b6adc7f944b68eb0788b82eed6344d
| 34,148 |
def merge_connected_components(conn_components, ingoing, outgoing):
"""
Merge the unconnected connected components
Parameters
-------------
conn_components
Connected components
ingoing
Ingoing dictionary
outgoing
Outgoing dictionary
Returns
-------------
conn_components
Merged connected components
"""
i = 0
while i < len(conn_components):
conn1 = conn_components[i]
j = i + 1
while j < len(conn_components):
conn2 = conn_components[j]
if check_if_comp_is_completely_unconnected(conn1, conn2, ingoing, outgoing):
conn_components[i] = set(conn_components[i]).union(set(conn_components[j]))
del conn_components[j]
continue
j = j + 1
i = i + 1
return conn_components
|
15dda42103aab964a9a67ca763e17ba63d552457
| 34,149 |
def create_doc_index(ui_mat_rdd,
export=False):
"""
Indexes the docs and saves the index in a dictionary. The indexes are
then saved to disk. The indexing allows us to use internal integer IDs
for the users and documents instead of real IDs. The internal IDs are used
to index the different model matrices efficiently.
Args:
ui_mat_rdd: The UI matrix in an RDD.
Returns:
doc_index: A dictionary with the indexes.
"""
doc_index = ui_mat_rdd.map(lambda (usrId,docId,value): docId) \
.distinct() \
.zipWithIndex() \
.collect()
doc_index = dict(zip([doc[0] for doc in doc_index],[doc[1] for doc in doc_index]))
if export:
with open('/local/agidiotis/ui_data/doc_index.json', 'w') as fp:
json.dump(doc_index, fp)
return doc_index
|
97874b0effaa93b35760330abaa1fc23628389d6
| 34,151 |
def read_markers_from_file(filepath, ext=None):
"""
Read a cell marker file from accepted file formats.
Currently supported: csv, tsv.
See doc for formatting.
"""
# Get extension
if ext is None:
ext = filepath.split('.')[-1]
dict_format = {"csv":read_markers_csv, "tsv":read_markers_tsv, "gmt":read_markers_gmt}
# Read with correct function
marker_df = dict_format[ext](filepath)
# To dict
return marker_df
|
5c2a34bf3d568d1b0f9e81c23d23eba315059ee3
| 34,152 |
def get_user_id_from_email(email):
""" Pulls the user from the MDB (or dies trying). Returns its email. """
u = utils.mdb.users.find_one({'login': email.lower().strip()})
if u is None:
raise AttributeError("Could not find user data for %s" % email)
return u['_id']
|
c81d9d62bc3ecd9d37afef3f38b5735b5bb0215b
| 34,153 |
def _object_exists(key):
"""Verify if a given key (path) exists, using the S3 API."""
try:
app.s3.head_object(Bucket=app.config.get("AWS_S3_BUCKET_NAME"),
Key=key)
except ClientError as e:
if e.response["Error"]["Code"] == "404":
return False
raise e
else:
return True
|
65ca7932412f988518f40a6830d512049e40fe31
| 34,154 |
def dpgmm_predict(data:pd.DataFrame,
code=None,
indices:pd.DataFrame=None,) -> np.ndarray:
"""
(假设)我们对这条行情的走势一无所知,使用机器学习可以快速的识别出走势,划分出波浪。
DPGMM聚类 将整条行情大致分块,这个随着时间变化会有轻微抖动。
所以不适合做精确买卖点控制。但是作为趋势判断已经足够了。
"""
sub_offest = 0
nextsub_first = sub_first = 0
nextsub_last = sub_last = 1199
ret_cluster_group = np.zeros(len(data.close.values))
while (sub_first == 0) or (sub_first < len(data.close.values)):
# 数量大于1200bar的话无监督聚类效果会变差,应该控制在1000~1500bar之间
if (len(data.close.values) > 1200):
highp = np.nan_to_num(data.high.values[sub_first:sub_last], nan=0)
lowp = np.nan_to_num(data.low.values[sub_first:sub_last], nan=0)
openp = np.nan_to_num(data.open.values[sub_first:sub_last], nan=0)
closep = np.nan_to_num(data.close.values[sub_first:sub_last], nan=0)
if (sub_last + 1200 < len(data.close.values)):
nextsub_first = sub_first + 1199
nextsub_last = sub_last + 1200
else:
nextsub_first = len(data.close.values) - 1200
nextsub_first = 0 if (nextsub_first < 0) else nextsub_first
nextsub_last = len(data.close.values) + 1
else:
highp = data.high.values
lowp = data.low.values
openp = data.open.values
closep = data.close.values
sub_last = nextsub_first = len(data.close.values)
nextsub_last = len(data.close.values) + 1
if (ST.VERBOSE in data.columns):
print('slice:', {sub_first, sub_last}, 'total:{} netx_idx:{} unq:{}'.format(len(data.close.values),
sub_offest,
len(np.unique(ret_cluster_group))))
# DPGMM 聚类
X, idx = features_formatter_k_means(closep) #[i, closep[i], minP, maxP, low, high] 通过close价格扩展维度,用以标签训练
dpgmm = mixture.BayesianGaussianMixture(n_components=min(len(closep) - 1, max(int(len(closep) / 10), 16)),
max_iter=1000,
covariance_type='spherical',
weight_concentration_prior_type='dirichlet_process')
# 训练模型不含最后一个点
try:
dpgmm.fit(X[:-1])
except:
print(u' {} 分析样本历史数据太少({})'.format(code, len(closep) - 1))
try:
y_t = dpgmm.predict(X)
except:
print(u'{} "{}" 前复权价格额能存在np.nan值,请等待收盘数据接收保存完毕。'.format(QA_util_timestamp_to_str(),
data.index.get_level_values(level=1)[0]),
len(X), len(X[:-1]), X[-1:], data[-1:])
ret_cluster_group[sub_first:sub_last] = y_t + int(sub_offest)
sub_offest = int(np.max(ret_cluster_group) + 1)
if (sub_last >= len(data.close.values)):
break
else:
sub_first = min(nextsub_first, nextsub_last)
sub_last = max(nextsub_first, nextsub_last)
# DPGMM 聚类分析完毕
return ret_cluster_group
|
b12365f50a498d2ece6be65a0a284aad9c235274
| 34,155 |
from typing import List
def list_ep(server: Server, path: str, r_type: OT = OT.DOMAIN, scope: EPScope = None) -> List[str]:
"""
List elements under an object fitting a type.
:param Server server: server object
:param str path: path to object
:param OT r_type: type of ep to return (default is domain)
:param EPScope scope: restrict scope to children or parts
:return: list of sub elements
"""
ls = server.get_ep(path, r_type=r_type, output=[OP.NAME], scope=scope, fmt=FMT.PLAIN).rstrip(';').split('; ')
if len(ls[0]) == 0:
return list()
return ls
|
ccf90a435b72e4e822ef2c580304c889bc4f4136
| 34,156 |
import re
def check_if_partial(comments):
"""
Checks if comments contain info about Dat being a part of a series of dats (i.e. two part entropy scans where first
part is wide and second part is narrow with more repeats)
Args:
comments (string): Sweeplogs comments (where info on part#of# should be found)
Returns:
bool: True or False
"""
assert type(comments) == str
comments = comments.split(',')
comments = [com.strip() for com in comments]
part_comment = [com for com in comments if re.match('part*', com)]
if part_comment:
return True
else:
return False
|
6f565bae6fe1cf5da4a11e0d511a25daa07aadd1
| 34,157 |
def cardChunk(key, chunk):
"""
Parse Card Chunk Method
"""
for line in chunk:
values = []
sline = line.strip().split()
for idx in range(1, len(sline)):
values.append(sline[idx])
return {'card': sline[0],
'values': values}
|
84b8a12f701078f2ebcf19a5c1902b1e370b16e6
| 34,159 |
def update_outline(outline, filename=None, message=None):
"""
Updates the the outline from active instances in the workspace
"""
if not message:
message = "Automated update via presalytics.lib.tools.workflows.update_outline()"
update_components(filename=filename)
for p in range(0, len(outline.pages)):
page = outline.pages[p]
page_key = "page.{}.{}".format(page.kind, page.name)
page_inst = presalytics.COMPONENTS.get_instance(page_key)
if page_inst:
outline.pages[p] = page_inst.serialize()
for w in range(0, len(page.widgets)):
widget = outline.pages[p].widgets[w]
widget_key = "widget.{}.{}".format(widget.kind, widget.name)
widget_inst = presalytics.COMPONENTS.get_instance(widget_key)
if widget_inst:
outline.pages[p].widgets[w] = widget_inst.serialize()
for t in range(0, len(outline.themes)):
theme = outline.themes[t]
theme_key = "theme.{}.{}".format(theme.kind, theme.name)
theme_inst = presalytics.COMPONENTS.get_instance(theme_key)
if theme_inst:
outline.themes[t] = theme_inst.serialize()
outline.info.revision_notes = message
return outline
|
3582d47b641c4e554f2b2f0e38110fd98343476c
| 34,160 |
def slave_hub_factory(config, comm_class, comm_config):
"""Factory of management bus slave hub instances
Args:
config (dict): management bus master config
comm_class (string): communication backend.
Unused, ZMQRedis is always used
comm_config (dict): config of the communication backend.
Returns:
Instance of minemeld.mgmtbus.MgmtbusSlaveHub class
"""
_ = comm_class # noqa
return MgmtbusSlaveHub(
config,
'ZMQRedis',
comm_config
)
|
b421c065158aa3e7fd07fc28ccdd72ffc24045ec
| 34,161 |
def rgb565_to_rgb(arr, out=None):
"""
Convert a numpy :class:`~numpy.ndarray` in RGB565 format (unsigned 16-bit
values with 5 bits for red and blue, and 6 bits for green laid out
RRRRRGGGGGGBBBBB) to RGB format (structured floating-point type with 3
values each between 0 and 1).
"""
check_rgb565(arr)
if out is None:
out = np.empty(arr.shape, color_dtype)
else:
check_rgb(out)
if out.shape != arr.shape:
raise ValueError("output array has wrong shape")
out['r'] = ((arr & 0xF800) / 0xF800).astype(np.float32)
out['g'] = ((arr & 0x07E0) / 0x07E0).astype(np.float32)
out['b'] = ((arr & 0x001F) / 0x001F).astype(np.float32)
return out
|
5c660169cdfd47a0d513a833356c82557ff636bb
| 34,162 |
def run_highstate_tests(saltenv="base"):
"""
Lookup top files for minion, pass results to wrapped run_state_tests for copy and run
"""
top_states = __salt__["state.show_top"]().get(saltenv)
state_string = ",".join(top_states)
ret = run_state_tests(state_string, saltenv)
return ret
|
3e12d102a44e8233eb539c1636f19eebb23da266
| 34,163 |
def varianceOfLaplacian(img):
""" Compute the Laplacian of the image and then return the focus measure,
which is simply the variance of the Laplacian.
Source: A.Rosebrock, https://www.pyimagesearch.com/2015/09/07/blur-detection-with-opencv/
"""
return cv2.Laplacian(img, cv2.CV_64F).var()
|
8a80c40f24c1a282ae7a46c521e4cb3a975451ee
| 34,164 |
def show(tournament, participant_id, **params):
"""Retrieve a single participant record for a tournament."""
return api.fetch_and_parse(
"GET", "tournaments/%s/participants/%s" % (tournament, participant_id), **params
)
|
bf1e43ab2b071343405a09659580d5d8311d0dff
| 34,166 |
def logsubexp(A, B):
"""
Numerically stable log(exp(A) - exp(B))
"""
# Just adding an epsilon here does not work: the optimizer moves it out
result = A + tt.log(1 - tt.clip(tt.exp(B - A), epsilon, 1-epsilon))
return result
|
0bd07fec6cfe3247e7dffd0af1794306f34601f1
| 34,167 |
import collections
def sort_dict(d: dict, by: str = 'key',
allow_duplicates: bool = True) -> collections.OrderedDict:
"""
Sort a dictionary by key or value.
The function relies on
https://docs.python.org/3/library/collections.html#collections.OrderedDict .
The dulicated are determined based on
https://stackoverflow.com/questions/9835762/find-and-list-duplicates-in-a-list .
Parameters
----------
d : dict
Input dictionary
by : ['key','value'], optional
By what to sort the input dictionary
allow_duplicates : bool, optional
Flag to indicate if the duplicates are allowed.
Returns
-------
collections.OrderedDict
Sorted dictionary.
>>> sort_dict({2: 3, 1: 2, 3: 1})
OrderedDict([(1, 2), (2, 3), (3, 1)])
>>> sort_dict({2: 3, 1: 2, 3: 1}, by='value')
OrderedDict([(3, 1), (1, 2), (2, 3)])
>>> sort_dict({'2': 3, '1': 2}, by='value')
OrderedDict([('1', 2), ('2', 3)])
>>> sort_dict({2: 1, 1: 2, 3: 1}, by='value', allow_duplicates=False)
Traceback (most recent call last):
...
ValueError: There are duplicates in the values: {1}
>>> sort_dict({1:1,2:3},by=True)
Traceback (most recent call last):
...
ValueError: by can be 'key' or 'value'.
"""
if by == 'key':
i = 0
elif by == 'value':
values = list(d.values())
if len(values) != len(set(values)) and not allow_duplicates:
duplicates = find_duplicates(values)
raise ValueError("There are duplicates in the values: {}".format(duplicates))
i = 1
else:
raise ValueError("by can be 'key' or 'value'.")
return collections.OrderedDict(sorted(d.items(), key=lambda t: t[i]))
|
59ea66e44b9a41161e38e243f49e5a20df20093f
| 34,168 |
def read_file_info(filename):
"""
Read an info file.
Parameters
----------
filename : string
The name of file with cross-sectional area and length information.
Returns
-------
info : dict
The values of cross-sectional area and length of the specimens,
"""
fd = open(filename, 'r')
info = {}
for line in fd:
if line and (not line.isspace()) and (line[0] != '#'):
key, val = line.split()
info[key] = float(val)
fd.close()
return info
|
c3f8c106126b45845c1202b34b19cad2ce2ae036
| 34,169 |
def search_to_new_ids(index, query, k):
"""
this function maps the result ids to the ones ordered by the ivf clusters
to be used along with a re-ordered metadata
"""
distances, indices = index.search(query, k)
opq2 = faiss.downcast_VectorTransform(index.chain.at(0))
xq = opq2.apply(query)
_, l = faiss.extract_index_ivf(index).quantizer.search(xq, faiss.extract_index_ivf(index).nprobe)
il = faiss.extract_index_ivf(index).invlists
list_sizes = [il.list_size(i) for i in range(il.nlist)]
starting_offset = []
c = 0
for i in list_sizes:
starting_offset.append(c)
c += i
old_id_to_new_id = dict()
for i in l[0]:
i = int(i)
ids = il.get_ids(i)
list_size = il.list_size(int(i))
items = faiss.rev_swig_ptr(ids, list_size)
for nit, it in enumerate(items):
old_id_to_new_id[it] = starting_offset[i] + nit
il.release_ids(ids=ids, list_no=i)
ids = np.array([old_id_to_new_id[i] if i != -1 else -1 for i in indices[0]])
return distances, ids
|
62fc04b67bfa3aaf6ceed5a5f8bd65e1e7783cc9
| 34,170 |
import itertools
def build_simplex_lattice(factor_count, model_order = ModelOrder.quadratic):
"""Builds a Simplex Lattice mixture design.
This design can be used for 2 to 30 components. A simplex-lattice mixture
design of degree m consists of m+1 points of equally spaced values between
0 and 1 for each component. If m = 2 then possible fractions are 0, 1/2, 1.
For m = 3 the possible values are 0, 1/3, 2/3, 1. The points include the
pure components and enough points between them to estimate an equation of
degree m. This design differs from a simplex-centroid design by having
enough points to estimate a full cubic model.
:param factor_count: The number of mixture components to build for.
:type factor_count: int
:param model_order: The order to build for. ModelOrder.linear will choose
vertices only (pure blends). ModelOrder.quadratice will
add binary blends, and ModelOrder.cubic will add blends
of three components.
:type model_order: dexpy.model.ModelOrder
"""
run_count = factor_count # pure blends
if model_order == ModelOrder.quadratic:
run_count += count_nk(factor_count, 2) # 1/2 1/2 blends
elif model_order == ModelOrder.cubic:
# 2/3 1/3 blends (and vice versa)
run_count += count_nk(factor_count, 2) * 2
if factor_count > 2:
run_count += count_nk(factor_count, 3) # 1/3 1/3 1/3 blends
factor_names = design.get_factor_names(factor_count)
factor_data = pd.DataFrame(0, columns=factor_names,
index=np.arange(0, run_count))
row = 0
# always do pure blends
for combo in itertools.combinations(factor_names, 1):
factor_data.loc[row, combo] = 1.0
row += 1
if model_order == ModelOrder.quadratic:
# 1/2 1/2 binary blends
for combo in itertools.combinations(factor_names, 2):
factor_data.loc[row, combo] = 0.5
row += 1
elif model_order == ModelOrder.cubic:
# 2/3 1/3 blends
for combo in itertools.combinations(factor_names, 2):
factor_data.loc[row, combo] = [2/3, 1/3]
row += 1
factor_data.loc[row, combo] = [1/3, 2/3]
row += 1
# 1/3 1/3 1/3 triple blend
if factor_count > 2:
for combo in itertools.combinations(factor_names, 3):
factor_data.loc[row, combo] = 1/3
row += 1
return factor_data
|
9a6861a211b6829b971cf76ab8f1bbcb2bb668ae
| 34,171 |
def position_specializations(position_block):
"""
:param bs4.Tag position_block: position block
:return: list
"""
position_block = position_block.find("div", {"class": "bloko-gap bloko-gap_bottom"})
profarea_name = position_block.find("span", {"data-qa": "resume-block-specialization-category"})
profarea_name = profarea_name.getText()
profarea_specializations = position_block.find("ul")
profarea_specializations = profarea_specializations.findAll("li", {"class": "resume-block__specialization",
"data-qa": "resume-block-position-specialization"})
profarea_specializations = [item.getText() for item in profarea_specializations]
profarea_specializations = [{"name": specialization_name, "profarea_name": profarea_name}
for specialization_name in profarea_specializations]
return profarea_specializations
|
c37a43b2c139780d0bcb0db2cb758165d155a526
| 34,172 |
def GetElement(layers, locations):
"""
Return the node(s) at the location(s) in the given layer(s).
This function works for fixed grid layers only.
* If layers contains a single GID and locations is a single 2-element
array giving a grid location, return a list of GIDs of layer elements
at the given location.
* If layers is a list with a single GID and locations is a list of
coordinates, the function returns a list of lists with GIDs of the nodes
at all locations.
* If layers is a list of GIDs and locations single 2-element array giving
a grid location, the function returns a list of lists with the GIDs of
the nodes in all layers at the given location.
* If layers and locations are lists, it returns a nested list of GIDs, one
list for each layer and each location.
Parameters
----------
layers : tuple/list of int(s)
List of layer GIDs
locations : [tuple/list of floats | tuple/list of tuples/lists of floats]
2-element list with coordinates of a single grid location,
or list of 2-element lists of coordinates for 2-dimensional layers,
i.e., on the format [column, row]
Returns
-------
out : tuple of int(s)
List of GIDs
See also
--------
GetLayer : Return the layer to which nodes belong.
FindNearestElement: Return the node(s) closest to the location(s) in the
given layer(s).
GetPosition : Return the spatial locations of nodes.
Notes
-----
-
**Example**
::
import nest.topology as tp
# create a layer
l = tp.CreateLayer({'rows' : 5,
'columns' : 4,
'elements' : 'iaf_psc_alpha'})
# get GID of element in last row and column
tp.GetElement(l, [3, 4])
"""
if not nest.is_sequence_of_gids(layers):
raise TypeError("layers must be a sequence of GIDs")
if not len(layers) > 0:
raise nest.NESTError("layers cannot be empty")
if not (nest.is_iterable(locations) and len(locations) > 0):
raise nest.NESTError(
"locations must be coordinate array or list of coordinate arrays")
# ensure that all layers are grid-based, otherwise one ends up with an
# incomprehensible error message
try:
topology_func('{ [ /topology [ /rows /columns ] ] get ; } forall',
layers)
except:
raise nest.NESTError(
"layers must contain only grid-based topology layers")
# SLI GetElement returns either single GID or list
def make_tuple(x):
if not nest.is_iterable(x):
return (x, )
else:
return x
if nest.is_iterable(locations[0]):
# layers and locations are now lists
nodes = topology_func(
'/locs Set { /lyr Set locs { lyr exch GetElement } Map } Map',
layers, locations)
node_list = tuple(
tuple(make_tuple(nodes_at_loc) for nodes_at_loc in nodes_in_lyr)
for nodes_in_lyr in nodes)
else:
# layers is list, locations is a single location
nodes = topology_func('/loc Set { loc GetElement } Map', layers,
locations)
node_list = tuple(make_tuple(nodes_in_lyr) for nodes_in_lyr in nodes)
# If only a single layer is given, un-nest list
if len(layers) == 1:
node_list = node_list[0]
return node_list
|
6fecffa20aa9d4722153c50572c9ded26035c1f3
| 34,173 |
def create_sampling_strategy(param_variation_model,
sampling_strategy_configuration):
"""
A factory method that creates a
memosampler.strategies.SamplingStrategy object from a
memosampler.sampler.ParameterVariationModel and a
memomodel.SamplingStrategy configuration object.
:param param_variation_model: a ParameterVariationModel object,
that contains variabilites for all constant and varying parameters
:param sampling_strategy_configuration: a
memomodel.SamplingStrategy configuration object.
:return: A memosampler.strategies.SamplingStrategy object, ready to
be used within a sampler. the concrete class of the object depends
on type information in the configuration.
"""
# build a map of all known SamplingStrategy subclasses
strategies_by_name = RecursiveSubClassFinder.find_subclasses(
memosampler.SamplingStrategy
)
# choose a class by name
strategy_name = sampling_strategy_configuration.name
strategy_class = strategies_by_name[strategy_name]
# convert the argument list to a dictionary
kwargs = {arg.key: arg.value
for arg in sampling_strategy_configuration.arguments}
# create the new SamplingStrategy object with keyword arguments
instance = strategy_class(param_variation_model, **kwargs)
return instance
|
f93451eb1b3739ac2985bd4a2b8bb84ed0b6f9f5
| 34,174 |
def json_to_hps(dct):
"""Translate the params dict to HyperparameterSpace object.
:param dict dct: params dict.
:return: HyperparameterSpace.
:rtype: HyperparameterSpace or None
"""
if "hyperparameters" in dct:
hps = HyperparameterSpace()
for hp_dict in dct["hyperparameters"]:
hp_name = hp_dict.get("key")
hp_slice = hp_dict.get('slice')
hp_type = PARAM_TYPE_MAP[hp_dict.get("type").upper()]
hp_range = hp_dict.get("range")
hp = HyperParameter(param_name=hp_name, param_slice=hp_slice,
param_type=hp_type, param_range=hp_range)
hps.add_hyperparameter(hp)
if "condition" in dct:
for cond_dict in dct["condition"]:
cond_child = hps.get_hyperparameter(
cond_dict.get("child"))
cond_parent = hps.get_hyperparameter(
cond_dict.get("parent"))
cond_type = CONDITION_TYPE_MAP[cond_dict.get("type").upper()]
cond_range = cond_dict.get("range")
cond = Condition(cond_child, cond_parent, cond_type, cond_range)
hps.add_condition(cond)
if "forbidden" in dct:
for forbidden_dict in dct["forbidden"]:
forbidden_list = []
for forb_name, forb_value in forbidden_dict.items():
forbidden_list.append(ForbiddenEqualsClause(
param_name=hps.get_hyperparameter(forb_name),
value=forb_value))
hps.add_forbidden_clause(
ForbiddenAndConjunction(forbidden_list))
return hps
return None
|
0f80da7d4fb5d3d548cc23edf7761976db727654
| 34,175 |
def phone_number(update: Update, context: CallbackContext):
"""Добавляет номер телефона в контекст пользователя и предлагает ввести ИНН"""
logger.info(f"User with chat_id {update.effective_user.id} sent phone number [{update.message.text}]")
context.user_data[State.PHONE_NUMBER] = update.message.text
update.message.reply_text(messages.inn, parse_mode=ParseMode.HTML)
context.user_data["state"] = State.INN
return State.INN
|
b41cebc8b47e9e3ef729ddd7ebea560f143be071
| 34,176 |
from typing import Optional
from typing import Union
def downsample_adata(adata: AnnData,
mode: str = 'total',
n_cells: Optional[int] = None,
by: Optional[str] = None,
balance_cell_type: bool = False,
random_state: int = 0,
return_index: bool = True) -> Union[AnnData, np.ndarray]:
"""
Downsample cells to a given number (either in total or per cell type).
Parameters
----------
adata
An :class:`~anndata.AnnData` object representing the input data.
mode
The way downsampling is performed. Default to downsampling the input cells to a total of `n_cells`.
Set to `each` if you want to downsample cells within each cell type to `n_cells`.
(Default: `total`)
n_cells
The total number of cells (`mode = 'total'`) or the number of cells from each cell type (`mode = 'each'`) to sample.
For the latter, all cells from a given cell type will be selected if its cell number is fewer than `n_cells`.
by
Key (column name) of the input AnnData representing the cell types.
balance_cell_type
Whether to balance the cell type frequencies when `mode = 'total'`.
Setting to `True` will sample rare cell types with a higher probability, ensuring close-to-even cell type compositions.
This argument is ignored if `mode = 'each'`.
(Default: `False`)
random_state
Random seed for reproducibility.
return_index
Only return the downsampled cell indices.
Setting to `False` if you want to get a downsampled version of the input AnnData.
(Default: `True`)
Returns
----------
Depending on `return_index`, returns the downsampled cell indices or a subset of the input AnnData.
"""
np.random.seed(random_state)
if n_cells is None:
raise ValueError(f"🛑 Please provide `n_cells`")
if mode == 'total':
if n_cells >= adata.n_obs:
raise ValueError(f"🛑 `n_cells` ({n_cells}) should be fewer than the total number of cells ({adata.n_obs})")
if balance_cell_type:
if by is None:
raise ValueError(f"🛑 Please specify the cell type column if you want to balance the cell type frequencies")
labels = adata.obs[by]
celltype_freq = np.unique(labels, return_counts = True)
len_celltype = len(celltype_freq[0])
mapping = pd.Series(1 / (celltype_freq[1]*len_celltype), index = celltype_freq[0])
p = mapping[labels].values
sampled_cell_index = np.random.choice(adata.n_obs, n_cells, replace = False, p = p)
else:
sampled_cell_index = np.random.choice(adata.n_obs, n_cells, replace = False)
elif mode == 'each':
if by is None:
raise ValueError(f"🛑 Please specify the cell type column for downsampling")
celltypes = np.unique(adata.obs[by])
sampled_cell_index = np.concatenate([np.random.choice(np.where(adata.obs[by] == celltype)[0], min([n_cells, np.sum(adata.obs[by] == celltype)]), replace = False) for celltype in celltypes])
else:
raise ValueError(f"🛑 Unrecognized `mode` value, should be one of `total` or `each`")
if return_index:
return sampled_cell_index
else:
return adata[sampled_cell_index].copy()
|
d1de9ac6c347750ed4ebfb1b8f870b8bc613f20d
| 34,178 |
def parse_blob(value, offset=0, **kwargs):
"""Return a blob from offset in value."""
size = calcsize('>i')
length = unpack_from('>i', value, offset)[0]
data = unpack_from('>%iQ' % length, value, offset + size)
return data, padded(length, 8)
|
855b55394d8fbe5a3e05e98997185d87051b56a2
| 34,179 |
from datetime import datetime
def _get_now(utc: bool = False) -> datetime.datetime: # pragma: nocover
"""Workaround over datetime C module to be able to mock & patch in tests.
"""
if utc:
return datetime.datetime.utcnow()
return datetime.datetime.now()
|
7b71266bf46d464bb8515d5552752f2b7739262e
| 34,180 |
def dilation(image, selem, out=None, shift_x=False, shift_y=False):
"""Return greyscale morphological dilation of an image.
Morphological dilation sets a pixel at (i,j) to the maximum over all pixels
in the neighborhood centered at (i,j). Dilation enlarges bright regions
and shrinks dark regions.
Parameters
----------
image : ndarray
Image array.
selem : ndarray
The neighborhood expressed as a 2-D array of 1's and 0's.
out : ndarray
The array to store the result of the morphology. If None, is
passed, a new array will be allocated.
shift_x, shift_y : bool
shift structuring element about center point. This only affects
eccentric structuring elements (i.e. selem with even numbered sides).
Returns
-------
dilated : uint8 array
The result of the morphological dilation.
Examples
--------
>>> # Dilation enlarges bright regions
>>> import numpy as np
>>> from skimage.morphology import square
>>> bright_pixel = np.array([[0, 0, 0, 0, 0],
... [0, 0, 0, 0, 0],
... [0, 0, 1, 0, 0],
... [0, 0, 0, 0, 0],
... [0, 0, 0, 0, 0]], dtype=np.uint8)
>>> dilation(bright_pixel, square(3))
array([[0, 0, 0, 0, 0],
[0, 1, 1, 1, 0],
[0, 1, 1, 1, 0],
[0, 1, 1, 1, 0],
[0, 0, 0, 0, 0]], dtype=uint8)
"""
if image is out:
raise NotImplementedError("In-place dilation not supported!")
image = img_as_ubyte(image)
selem = img_as_ubyte(selem)
return cmorph._dilate(image, selem, out=out,
shift_x=shift_x, shift_y=shift_y)
|
2485ddf865f4476dc0c46f89bc789948d9c47153
| 34,181 |
def nice_layer_name(weight_key):
"""Takes a tuple like ('weights', 2) and returns a nice string like "2nd layer weights"
for use in plots and legends."""
return "Layer {num} {name}".format(num=weight_key[1] + 1, name=weight_key[0])
|
c88dd554c2a3cf35e6d6e96131833738c19766ac
| 34,183 |
def categories(request, structure_slug, structure):
"""
Retrieves structure categories list
:type structure_slug: String
:type structure: OrganizationalStructure (from @is_manager)
:param structure_slug: structure slug
:param structure: structure object (from @is_manager)
:return: render
"""
title = _('Gestione categorie')
template = 'manager/categories.html'
# sub_title = _("gestione ufficio livello manager")
categories = TicketCategory.objects.filter(organizational_structure=structure)
d = {'categories': categories,
'structure': structure,
# 'sub_title': sub_title,
'title': title,}
return render(request, template, d)
|
c322b754de2ed36e98088a1d494f807589d1fbc2
| 34,184 |
def do_quantize_training_on_graphdef(input_graph, num_bits):
"""A general quantization scheme is being developed in `tf.contrib.quantize`.
Consider using that instead, though since it is in the tf.contrib namespace,
it is not subject to backward compatibility guarantees.
Args:
input_graph: A `GraphDef`.
num_bits: The number of bits for quantize training.
Returns:
The graph with quantize training done.
"""
graph = graph_pb2.GraphDef()
result_graph_string = DoQuantizeTrainingOnGraphDefHelper(
input_graph.SerializeToString(), num_bits)
graph.ParseFromString(result_graph_string)
return graph
|
868a2c67d7c69270039af69e82110951a987480c
| 34,186 |
from typing import List
from typing import Tuple
def get_session_triplets(
sessions: List[int], match_types: List[int]
) -> Tuple[List[int], List[int], List[int]]:
"""Generate all possible triplets for each session.
:param sessions: A list of integers denoting session label
:param match_types: A list of integers denoting match type - 0 for anchor, 1 for
postive match and -1 for negative match)
:return: three list of integers, holding the anchor index, positive index and
negative index of each triplet, respectively
"""
anchor_ind, pos_ind, neg_ind = [], [], []
labels_index = [
(sess, match_type, index)
for index, (sess, match_type) in enumerate(zip(sessions, match_types))
]
sorted_labels_with_index = sorted(labels_index, key=lambda x: x[0])
for _, group in groupby(sorted_labels_with_index, lambda x: x[0]):
anchor_pos_session_indices = []
neg_session_indices = []
for _, session_label, session_index in group:
if session_label >= 0:
anchor_pos_session_indices.append(session_index)
else:
neg_session_indices.append(session_index)
for anchor, pos in permutations(anchor_pos_session_indices, 2):
anchor_ind += [anchor] * len(neg_session_indices)
pos_ind += [pos] * len(neg_session_indices)
neg_ind += neg_session_indices
return anchor_ind, pos_ind, neg_ind
|
39992557bc788f4b8bb5248cd66f56bf4276d99c
| 34,187 |
def _rotation_matrix_hme_to_hee(hmeframe):
"""
Return the rotation matrix from HME to HEE at the same observation time
"""
# Get the Sun-Earth vector
sun_earth = HCRS(_sun_earth_icrf(hmeframe.obstime), obstime=hmeframe.obstime)
sun_earth_hme = sun_earth.transform_to(hmeframe).cartesian
# Rotate the Sun-Earth vector about the Z axis so that it lies in the XZ plane
rot_matrix = _rotation_matrix_reprs_to_xz_about_z(sun_earth_hme)
# Tilt the rotated Sun-Earth vector so that it is aligned with the X axis
tilt_matrix = _rotation_matrix_reprs_to_reprs(sun_earth_hme.transform(rot_matrix),
CartesianRepresentation(1, 0, 0))
return matrix_product(tilt_matrix, rot_matrix)
|
157378316058b4898b9ecccb8acf673c4170c03b
| 34,188 |
def get_image(microscopy_collection, series):
"""Return microscopy image."""
image = microscopy_collection.image(s=series)
image = image[:, :, 0]
return image
|
d95b213c8db49e89d2bcaa3f7b69c0f4d546ac1c
| 34,189 |
def process_aa_snvs(aa_snv_dict, name, defs):
"""
Parameters
----------
aa_snv_dict: dict
name: str
defs: pandas.DataFrame
- genes or proteins dataframe from genes_and_proteins.py
"""
aa_snv = (
pd.DataFrame.from_dict(aa_snv_dict, orient="index", columns=["id"])
.reset_index()
.rename(columns={"index": "snp_str"})
)
aa_snv = aa_snv.join(
aa_snv["snp_str"]
.str.split("|", expand=True)
.rename(columns={0: name, 1: "pos", 2: "ref", 3: "alt"})
).set_index("id")
aa_snv.loc[:, "pos"] = aa_snv["pos"].astype(int)
aa_snv["color"] = get_snv_colors(aa_snv.index.values)
aa_snv["snv_name"] = aa_snv["snp_str"].apply(format_aa_snv)
def get_nt_pos(snv):
segment_ind = [
i
for i, segment in enumerate(defs.at[snv[name], "aa_ranges"])
if snv["pos"] >= segment[0] and snv["pos"] <= segment[1]
][0]
return defs.at[snv[name], "segments"][segment_ind][0] + (
(snv["pos"] - defs.at[snv[name], "aa_ranges"][segment_ind][0]) * 3
)
aa_snv["nt_pos"] = aa_snv.apply(get_nt_pos, axis=1)
return aa_snv
|
f9dbf499bc7baf311e2c1063167e40570f40d218
| 34,191 |
def use_file(filename):
""" Return a decorator which will parse a kicad file
before running the test. """
def decorator(test_method):
""" Add params to decorator function. """
@wraps(test_method)
def wrapper(self):
""" Parse file then run test. """
self.design = get_design(filename)
test_method(self)
return wrapper
return decorator
|
c381fa417ae3226f7a4a5bac3fa907821dd76876
| 34,192 |
def create_autoscaler(gce, mig, params):
"""
Create a new Autoscaler for a MIG.
:param gce: An initialized GCE driver object.
:type gce: :class: `GCENodeDriver`
:param mig: An initialized GCEInstanceGroupManager.
:type mig: :class: `GCEInstanceGroupManager`
:param params: Dictionary of autoscaling parameters.
:type params: ``dict``
:return: Tuple with changed stats.
:rtype: tuple in the format of (bool, list)
"""
changed = False
as_policy = _gen_gce_as_policy(params['policy'])
autoscaler = gce.ex_create_autoscaler(name=params['name'], zone=mig.zone,
instance_group=mig, policy=as_policy)
if autoscaler:
changed = True
return changed
|
1be818388aa48b70f4252937a4db44671d03581e
| 34,193 |
from typing import List
def chromium_all(*, min_major_version: int = 90, min_minor_version: int = 40) -> List[str]:
"""get chrome versions"""
resp = Request.get(CHROME_REP_URL)
versions = RE_CHROMIUM.findall(resp)
versions = [v for v in versions if len(v.split(".")) > 2 and (int(v.split(".")[-1]) >= min_minor_version
and int(v.split(".")[0]) >= min_major_version)]
return versions
|
900e4b24417e3c778218614c65787931631d2fbd
| 34,194 |
def setup(hass, config):
"""Setup platfrom"""
async def async_auto_scale(call):
"""Call auto scale service handler."""
await async_handle_auto_scale_service(hass, call)
hass.services.register(
DOMAIN,
SERVICE_AUTO_SCALE,
async_auto_scale,
schema=AUTO_SCALE_SERVICE_SCHEMA,
)
return True
|
61cc3d2b0461bb78a745a53dee1dc5bfb1a4a75f
| 34,195 |
from re import X
from datetime import datetime
def train_linear_clf(n_fits):
"""Called by the `/train` HTTP GET method in `logic.py` module.
Parameters
----------
n_fits : int
Number of partial fits applied to the linear estimator.
Returns
-------
dict
measured_accuracy : float
Accuracy of the linear classifier after application of the specified number of partial fits.
start_time : datetime.datetime
Time when the function starts the process of partial fiting.
training_time : float
Training time in seconds.
"""
clf = get_estimator_from_file(join_paths(PATH, CONFIG["model_persistence_file"])) \
or SGDClassifier(**CONFIG["estimator"]).fit(X, y)
start_time = datetime.datetime.now()
[clf.partial_fit(X, y) for _ in range(n_fits)]
end_time = datetime.datetime.now().timestamp()
persist(clf, join_paths(PATH, CONFIG["updated_model_persistence_file"]))
return {
"measured_accuracy": clf.score(X_test, y_test),
"start_time": start_time,
"training_time": end_time - start_time.timestamp()
}
|
8430edf945d03e6c68ca1fe5944ed6957d4e3857
| 34,197 |
def list_joysticks():
"""return list of all joystick names"""
joysticks = get_all_joysticks()
return [joy.get_name() for joy in joysticks]
|
a04e584fe5d35b21cde1b44274bb725ea95260bc
| 34,198 |
def kurtosis(inlist):
"""
Returns the kurtosis of a distribution, as defined in Numerical
Recipies (alternate defn in CRC Standard Probability and Statistics, p.6.)
Usage: lkurtosis(inlist)
"""
return moment(inlist, 4) / pow(moment(inlist, 2), 2.0)
|
e5df631d9d5d81ca9e2df8d7b7723eb723c696db
| 34,199 |
def compute_iou(box, boxes):
"""Calculates IoU of the given box with the array of the given boxes.
box: a polygon
boxes: a vector of polygons
Note: the areas are passed in rather than calculated here for
efficiency. Calculate once in the caller to avoid duplicate work.
"""
# Calculate intersection areas
iou = [box.intersection(b).area / box.union(b).area for b in boxes]
return np.array(iou, dtype=np.float32)
|
169cb66f025c7a3f6161a406bd6b0636a35816d3
| 34,200 |
def far(scores, labels, frr_op):
"""
Calculates FAR from FRR operating point.
Parameters
----------
scores: np array
It holds the score information for all samples (genuine and impostor).
It is expected that impostor (negative) scores are, at least by design, greater than genuine (positive) scores.
labels: np array
It holds the labels (int). It is assumed that impostor_labels != 0 and genuine labels == 0
frr_op: float
Closest FRR value to look for.
Returns
-------
"""
if not isinstance(scores, np.ndarray) or not isinstance(scores, np.ndarray):
raise TypeError(
"Scores [{}] and labels [{}] must be numpy arrays.".format(
type(scores), type(labels)
)
)
scores = scores.ravel()
labels = labels.ravel()
inlabels = np.zeros_like(labels)
inlabels[labels != 0] = 1
assert len(scores) == len(inlabels)
inv_scores = -1.0 * scores
fars, tprs, ths = metrics.roc_curve(inlabels, inv_scores, pos_label=0)
ths = -1.0 * ths
ths = np.clip(ths, scores.min(), scores.max())
far, th = _far_from_frr_value(fars, tprs, ths, frr_op)
return far, th
|
9873f854887982e6aa393eb4fa0b915f31dbd15f
| 34,201 |
def iso_to_plotly_time_string(iso_string):
"""Remove timezone info and replace 'T' delimeter with ' ' (ws)."""
# make sure we don't send timezone info to plotly
if (iso_string.split("-")[:3] == "00:00") or (iso_string.split("+")[0] == "00:00"):
raise Exception(
"Plotly won't accept timestrings with timezone info.\n"
"All timestrings are assumed to be in UTC."
)
iso_string = iso_string.replace("-00:00", "").replace("+00:00", "")
if iso_string.endswith("T00:00:00"):
return iso_string.replace("T00:00:00", "")
else:
return iso_string.replace("T", " ")
|
2a8f8dede7a50d07e283897bf6028fbfdcaa90d6
| 34,202 |
def mk_vis_txt_pair_datalist(anno_path, data_ratio=1.0,
vis_id_key="coco_id", txt_key="caption"):
"""
Args:
anno_path: str, path to .jsonl file, each line is a dict
data_ratio: float, (0, 1], when < 1, use part of the data.
vis_id_key: str, image/video file id access key in the input dict.
txt_key: str, txt access key in the input dict.
Returns:
"""
raw_datalist = load_datalist_with_ratio(anno_path, data_ratio)
datalist = []
for raw_d in raw_datalist:
d = dict(
txt=raw_d[txt_key],
vis_id=raw_d[vis_id_key]
)
datalist.append(d)
grouped = defaultdict(list) # examples grouped by image/video id
for d in datalist:
grouped[d["vis_id"]].append(d)
return grouped
|
3c36ff18f447e0ce5977d39c0bdc14bda94e3a64
| 34,203 |
def index_greater(array, prec=1e-8):
"""
Purpose:
Function for finding first item in an array that has a value greater than the first element in that array
If no element is found, returns None
Precision:
1e-8
Return:
int or None
"""
item=array[0]
for idx, val in np.ndenumerate(array): # slow ! : could be cythonized
if val > (item + prec):
return idx[0]
|
43f9401dc37426b1514ff1eb9dda79c39e347a7a
| 34,204 |
import torch
def get_ssl_sampler(labels, valid_num_per_class, annotated_num_per_class, num_classes):
"""
:param labels: torch.array(int tensor)
:param valid_num_per_class: the number of validation for each class
:param annotated_num_per_class: the number of annotation we use for each classes
:param num_classes: the total number of classes
:return: sampler_l,sampler_u
"""
sampler_valid = []
sampler_train_l = []
sampler_train_u = []
for i in range(num_classes):
loc = torch.nonzero(labels == i)
loc = loc.view(-1)
# do random perm to make sure uniform sample
loc = loc[torch.randperm(loc.size(0))]
sampler_valid.extend(loc[:valid_num_per_class].tolist())
sampler_train_l.extend(loc[valid_num_per_class:valid_num_per_class + annotated_num_per_class].tolist())
# sampler_train_u.extend(loc[num_valid + annotated_num_per_class:].tolist())
# here the unsampled part also include the train_l part
sampler_train_u.extend(loc[valid_num_per_class:].tolist())
sampler_valid = SubsetRandomSampler(sampler_valid)
sampler_train_l = SubsetRandomSampler(sampler_train_l)
sampler_train_u = SubsetRandomSampler(sampler_train_u)
return sampler_valid, sampler_train_l, sampler_train_u
|
05d7aa1700c096bc7a8250251cc73969c46ddabf
| 34,205 |
import copy
def load_parse_dict():
"""Dicts for parsing Arc line lists from NIST
Rejected lines are in the rejected_lines.yaml file
"""
dict_parse = dict(min_intensity=0., min_Aki=0., min_wave=0.)
arcline_parse = {}
# ArI
arcline_parse['ArI'] = copy.deepcopy(dict_parse)
arcline_parse['ArI']['min_intensity'] = 1000. # NOT PICKING UP REDDEST LINES
# HgI
arcline_parse['HgI'] = copy.deepcopy(dict_parse)
arcline_parse['HgI']['min_intensity'] = 800.
# HeI
arcline_parse['HeI'] = copy.deepcopy(dict_parse)
arcline_parse['HeI']['min_intensity'] = 20.
# NeI
arcline_parse['NeI'] = copy.deepcopy(dict_parse)
arcline_parse['NeI']['min_intensity'] = 999.
#arcline_parse['NeI']['min_Aki'] = 1. # NOT GOOD FOR DEIMOS, DESI
#arcline_parse['NeI']['min_wave'] = 5700.
arcline_parse['NeI']['min_wave'] = 5850. # NOT GOOD FOR DEIMOS?
# ZnI
arcline_parse['ZnI'] = copy.deepcopy(dict_parse)
arcline_parse['ZnI']['min_intensity'] = 50.
# KrI
arcline_parse['KrI'] = copy.deepcopy(dict_parse)
arcline_parse['KrI']['min_intensity'] = 50.
return arcline_parse
|
b02ae8446b9cc198ac1908dbbbe2bec78088178b
| 34,206 |
def is_test(method) -> bool:
"""
Checks if the given method is a test method.
:param method: The method to check.
:return: True if the method is a test method,
False if not.
"""
return getattr(method, _constants.IS_TEST_ATTRIBUTE, False)
|
23b5dc04b29b029ca5c44dc57df59f63087d61a6
| 34,207 |
def data_transform(array, array2=np.asarray((None)),type='z_score_norm', means=None, stds=None):
"""
Transforms data in the given array according to the type
array :an nd numpy array.
array2 :an nd numpy array(optional-for multidimensional datasets)
type :'z_score_norm' = implements z score normalisation using mean and standard deviation on each column (datasets of each variable) of the given array.
'min_max_norm' = implements min max scaling on each column (datasets of each variable) of the given array.
'back_transform_z_score_norm' = returns the original data without z_score transformations.
'back_transform_min_max_norm' = returns the original data without min_max transformations.
means :mean values(or min values) of each variable datasets - used for reverse transformation of data
stds :standard deviation values(or max values) of each variable datasets - used for reverse transformation of data
"""
if array.ndim == 1:
array = np.reshape(array,(len(array),1))
if array2.all() != None:
if array2.ndim == 1:
array2 = np.reshape(array2,(len(array2),1))
assert(np.shape(array)[1]) == np.shape(array2)[1]
if type== "z_score_norm":
means =[]
stds = []
for i in range(np.shape(array)[1]):
mean = np.mean(array[:,i])
std = np.std(array[:,i])
means.append(mean)
stds.append(std)
if mean == 0 and std == 0:
continue
for j in range(np.shape(array)[0]):
array[j,i]= (array[j,i] - mean)/std
if array2.all() != None:
for j in range(np.shape(array2)[0]):
array2[j,i]= (array2[j,i] - mean)/std
elif type == "min_max_norm":
for i in range(np.shape(array)[1]):
min_ = min(array[:,i])
max_ = max(array[:,i])
#print(min_, max_)
if min_ == 0 and max_ == 0:
continue
for j in range(np.shape(array)[0]):
array[j,i]= (array[j,i] - min_)/(max_ - min_)
if array2.all() != None:
for j in range(np.shape(array2)[0]):
array2[j,i]= (array2[j,i] - min_)/(max_ - min_)
elif type == "back_transform_z_score_norm":
assert(means) != None
assert(stds) != None
for i in range(np.shape(array)[1]):
mean = means[i]
std = stds[i]
if mean == 0 and std == 0:
continue
for j in range(np.shape(array)[0]):
array[j,i] = array[j,i] *std + mean
if array2.all() != None:
for j in range(np.shape(array2)[0]):
array2[j,i] = array2[j,i] *std + mean
else:
raise ValueError("undefined method")
if array2.all() != None:
return array, array2, means, stds
else:
return array, means, stds
|
f851bce2f0a88717873544506361bd6ef7c73813
| 34,208 |
import re
def load_items(reader):
"""Load items from HDF5 file:
* reader: :py:class:`guidata.hdf5io.HDF5Reader` object"""
with reader.group("plot_items"):
names = reader.read_sequence()
items = []
for name in names:
klass_name = re.match(
r"([A-Z]+[A-Za-z0-9\_]*)\_([0-9]*)", name.decode()
).groups()[0]
klass = item_class_from_name(klass_name)
item = klass()
with reader.group(name):
item.deserialize(reader)
items.append(item)
return items
|
ba473b9aa8c5af2beba8e22c68646a3204179c3d
| 34,209 |
def zmatrix(file_prefix):
""" generate zmatrix JSONObject
:param file_prefix: path to file
:type file_prefix: str
:param json_prefix: top level keys
ex: ('energy', ['gaussian', 'b3lyp', 'cc-pvdz', 'RR'])
:type json_prefix: tuple
:return: instance of JSONObject class
:rtype: JSONObject
"""
name = autofile.data_types.name.zmatrix(file_prefix)
return model.JSONObject(name=name)
|
9f22e8f4480fe21b853101a4cfb58c641207a0c1
| 34,210 |
def sequence_nd(
seq,
maxlen=None,
padding: str = 'post',
pad_val=0.0,
dim: int = 1,
return_len=False,
):
"""
padding sequence of nd to become (n+1)d array.
Parameters
----------
seq: list of nd array
maxlen: int, optional (default=None)
If None, will calculate max length in the function.
padding: str, optional (default='post')
If `pre`, will add 0 on the starting side, else add 0 on the end side.
pad_val, float, optional (default=0.0)
padding value.
dim: int, optional (default=1)
Returns
--------
result: np.array
"""
if padding not in ['post', 'pre']:
raise ValueError('padding only supported [`post`, `pre`]')
if not maxlen:
maxlen = max([np.shape(s)[dim] for s in seq])
padded_seqs, length = [], []
for s in seq:
npad = [[0, 0] for _ in range(len(s.shape))]
if padding == 'pre':
padding = 0
if padding == 'post':
padding = 1
npad[dim][padding] = maxlen - s.shape[dim]
padded_seqs.append(
np.pad(
s,
pad_width=npad,
mode='constant',
constant_values=pad_val,
)
)
length.append(s.shape[dim])
if return_len:
return np.array(padded_seqs), length
return np.array(padded_seqs)
|
83ec761d679b2c91592e000e1ee832341645a8e9
| 34,211 |
def random_dists(filename):
"""
Given a Excel filename with a row for each variable and columns for the
minimum and maximum, create a dictionary of Uniform distributions for
each variable.
Parameters
----------
filename : string
Number of parameter settings to generate
Returns
-------
dictionary (keys = variables, values = Uniform distributions)
Random distributions for each variable
"""
df = pd.read_excel(filename,index_col=0)
return {var[0]: (var[1]["minimum"], var[1]["maximum"], var[1]["step"]) \
for var in df.iterrows()}
|
d49229064979deb671fcade3518d260450718130
| 34,212 |
import re
def is_changed(event, old_event):
"""
Compares two events and discerns if it has changes that should trigger a push
:param event:
:param old_event:
:return: bool
"""
# Simple changes
if any(
event.get(field) != old_event.get(field) for field in ["severity", "certainty"]
):
return True
# Notify about big hail sizes
if "Hagel" not in event["parameters"]:
if event["event"].replace(" und HAGEL", "") != old_event["event"].replace(
" und HAGEL", ""
):
return True
else:
hail_re = r"^.*?(\d+).*?cm"
hail_size_now = int(re.match(hail_re, event["parameters"]["Hagel"]).group(1))
hail_size_before = int(
re.match(hail_re, old_event["parameters"].get("Hagel", "0 cm")).group(1)
)
if hail_size_now >= 3 > hail_size_before:
return True
elif event["event"].replace(" und HAGEL", "") != old_event["event"].replace(
" und HAGEL", ""
):
return True
# Changes in time
if (
abs(event["onset"] - event["sent"]) > timedelta(minutes=2)
and event["sent"] - event["onset"] < timedelta(minutes=2)
and old_event["onset"] != event["onset"]
):
return True
elif old_event["expires"] != event["expires"]:
return True
# New regions
if (
len(
set(r[0] for r in event["regions"])
- set(r[0] for r in old_event["regions"])
)
> 0
):
return True
# New districts
districts_now = {
district["name"]
for district in event["districts"]
if state_for_cell_id(district["warn_cell_id"]) in config.STATES_FILTER
}
districts_before = {
district["name"]
for district in old_event["districts"]
if state_for_cell_id(district["warn_cell_id"]) in config.STATES_FILTER
}
added = districts_now - districts_before
if len(districts_before) <= 3 and added:
return True
return False
|
a0c403caf71fb5547a4b4c7a52d3fcdcef4c4b34
| 34,213 |
def view(self, view_id):
"""Get a particular view belonging to a case group by providing view id
Arguments:
id(int): view id
Returns:
List of :class:`rips.generated.generated_classes.EclipseView`
"""
views = self.views()
for view_object in views:
if view_object.id == view_id:
return view_object
return None
|
0dadbe53c326d2d324e11222b2a751a09750bc82
| 34,214 |
from typing import Tuple
def enu2geodetic(
e: ndarray,
n: ndarray,
u: ndarray,
lat0: ndarray,
lon0: ndarray,
h0: ndarray,
ell: Ellipsoid = None,
deg: bool = True,
) -> Tuple[ndarray, ndarray, ndarray]:
"""
East, North, Up to target to geodetic coordinates
Parameters
----------
e : float
East ENU coordinate (meters)
n : float
North ENU coordinate (meters)
u : float
Up ENU coordinate (meters)
lat0 : float
Observer geodetic latitude
lon0 : float
Observer geodetic longitude
h0 : float
observer altitude above geodetic ellipsoid (meters)
ell : Ellipsoid, optional
reference ellipsoid
deg : bool, optional
degrees input/output (False: radians in/out)
Results
-------
lat : float
geodetic latitude
lon : float
geodetic longitude
alt : float
altitude above ellipsoid (meters)
"""
x, y, z = enu2ecef(e, n, u, lat0, lon0, h0, ell, deg=deg)
return ecef2geodetic(x, y, z, ell, deg=deg)
|
d552b072a428042435703f453a0f90bb9a1fded5
| 34,215 |
def Standard_GUID_HashCode(*args):
"""
* H method used by collections.
:param aguid:
:type aguid: Standard_GUID &
:param Upper:
:type Upper: int
:rtype: int
"""
return _Standard.Standard_GUID_HashCode(*args)
|
951ed1db9f0bc7c33345969e0b234bf31aaf463b
| 34,216 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.