content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def norm_potential(latitude, longitude, h, refell, lmax):
"""
Calculates the normal potential at a given latitude and height
Arguments
---------
latitude: latitude in degrees
longitude: longitude in degrees
height: height above reference ellipsoid in meters
refell: reference ellipsoid n... | 5fc9f26a206c4fced5ebd434c84dda26621c08dc | 3,659,069 |
def get_pp_gene_chains(chain_class_file, v=False):
"""Get gene: pp chains dict."""
gene_to_pp_chains = defaultdict(list) # init the dict
f = open(chain_class_file, "r") # open file with classifications
f.__next__() # skip header
for line in f:
line_data = line.rstrip().split("\t")
... | d09fe5f7e8aaed0b8aa46593931b3cda655f56e3 | 3,659,071 |
def skip_object(change_mode, change):
"""
If `Mode` is `change`: we do not care about the `Conditions`
Else:
If `cfn` objects:
- We can omit the `Conditions`, objects will be involed when `Mode` is `provision` or `destroy`. (Original design. Backward compatibility.)
- In case... | a80365acc6f3390818f4c56a44ad4923f771fcee | 3,659,073 |
def rootfinder(*args):
"""
rootfinder(str name, str solver, dict:SX rfp, dict opts) -> Function
Create a solver for rootfinding problems Takes a function where one of the
rootfinder(str name, str solver, dict:MX rfp, dict opts) -> Function
rootfinder(str name, str solver, Function f, dic... | 13ac40736849b6b4240dc5d22ad36aa472583bcb | 3,659,074 |
def f18(x, rotation=None, shift=None, shuffle=None):
"""
Hybrid Function 8 (N=5)
Args:
x (array): Input vector of dimension 2, 10, 20, 30, 50 or 100.
rotation (matrix): Optional rotation matrix. If None (default), the
official matrix from the benchmark suite will be used.
... | d76b4aef256bdc72bc077adefda5e7a93f8ea500 | 3,659,075 |
def shake_256_len(data: bytes, length: int) -> hashes.MessageDigest:
"""
Convenience function to hash a message.
"""
return HashlibHash.hash(hashes.shake_256_len(length), data) | c59f1a224264649573d53b67f170c7238b5a9840 | 3,659,076 |
def rgb_to_cmyk(color_values: tp.List[float]) -> tp.List[float]:
"""Converts list of RGB values to CMYK.
:param color_values: (list) 3-member RGB color value list
:return: (list) 4-member CMYK color value list
"""
if color_values == [0.0, 0.0, 0.0]:
return [0.0, 0.0, 0.0, 1.0]
r, g, b =... | f0054c92e862c5f0a8b09f94c115c03150b3363b | 3,659,077 |
import re
def parse_pgt_programmearray(url):
"""
Parse filter.js programmearray for pgt information
:param url: base url for timetabling system
:return: pgt programme name to id dict
"""
# get filter.js file
source = get_filterjs(url)
name_to_id = {}
# e.g. programmearray[340] [... | b7901c37cdb931dce75a77422394f98b5e3898d1 | 3,659,079 |
def distance_calc(x1, y1, x2, y2):
"""Calculates distance between two points"""
return ((x2 - x1) ** 2 + (y2 - y1) ** 2) ** 0.5 | 4c0001d90d38371a5336e8163fbf63b3d6e95834 | 3,659,080 |
import requests
def LoadNasaData(lat, lon, show= False, selectparms= None):
""" Execute a request from NASA API for 10 years of atmospheric data
required to prepare daily statistical data used in Solar Insolation
calculations """
cmd = formulateRequest(-0.2739, 36.3765, selectparms)
jdi ... | a2f61d20f46feee5d86bad2525c3bc20c3e00e14 | 3,659,081 |
from datetime import datetime
def mmyy_date_slicer(date_str):
"""Return start and end point for given date in mm-yy format.
:param date_str: date in mmyy format, i.e. "1222" or "0108".
:return: start and end date string for a given mmyy formatted date string
"""
# Initialize output
start... | f1c7f74f1824d5b4c410f3d8cc6ade15571fe3ca | 3,659,082 |
import typing
def constant_arg(name: str):
"""
Promises that the given arg will not be modified
Only affects mutable data types
Removes the need to copy the data during inlining
"""
def annotation(target: typing.Callable):
optimiser = _schedule_optimisation(target)
optimiser.c... | fdd132d3beea900b81bfe645616b0c20933e22e3 | 3,659,083 |
def place_connection(body): # noqa: E501
"""Place an connection request from the SDX-Controller
# noqa: E501
:param body: order placed for creating a connection
:type body: dict | bytes
:rtype: Connection
"""
if connexion.request.is_json:
body = Connection.from_dict(connexion.re... | c69520f428f257a9eb3df97e060ad2e5cde45c94 | 3,659,084 |
def tag_list(request):
"""展示所有标签"""
return render(request, 'admin/tags_list.html') | 44b33197b3f8cb3467c8e7d32d4538f4dc2833b1 | 3,659,085 |
import requests
def scan_url(urls):
"""
Scan the url using the API
Args:
urls:
the list of urls
Returns:
A tuple of a bool indicating if all the urls are safe and a list indicating
the safeness of individual urls
"""
is_safe = True
safe_list = [True] * l... | 9d3217a4c69a6a521d372b5692f93387ae7d61ad | 3,659,086 |
def head_to_tree(head, len_, prune, subj_pos, obj_pos):
"""
Convert a sequence of head indexes into a tree object.
"""
head = head[:len_].tolist()
root = None
if prune < 0:
nodes = [Tree() for _ in head]
for i in range(len(nodes)):
h = head[i]
nodes[i].i... | 0459e6ebb0c64a8170970d44e5c6bcde5bb6221c | 3,659,087 |
def capped_subtraction(x, y):
"""Saturated arithmetics. Returns x - y truncated to the int64_t range."""
assert_is_int64(x)
assert_is_int64(y)
if y == 0:
return x
if x == y:
if x == INT_MAX or x == INT_MIN:
raise OverflowError(
'Integer NaN: subtracting IN... | c4a171497ff351c22df3fc831a1e840366a90c5b | 3,659,088 |
def evaluate_points(func, begin, total_samps, var_list, attr):
"""
Inputs: func- the lambda function used to generate the data from the
evaluation vector
begin- the index to start at in the `attr` array
total_samps- the total number of samples to generate
var_lis... | 68ba7eb95e8d26becbef58f14e3073f7ed184a5b | 3,659,089 |
def corresponding_chromaticities_prediction_CIE1994(experiment=1):
"""
Returns the corresponding chromaticities prediction for *CIE 1994*
chromatic adaptation model.
Parameters
----------
experiment : integer or CorrespondingColourDataset, optional
{1, 2, 3, 4, 6, 8, 9, 11, 12}
... | f138ec844b2712d0d09be630f912f156aa50acbd | 3,659,091 |
def interpExtrap(x, xp, yp):
"""numpy.interp interpolation function extended by linear extrapolation."""
y = np.interp(x, xp, yp)
y = np.where(x < xp[0], yp[0]+(x-xp[0])*(yp[0]-yp[1])/(xp[0]-xp[1]), y)
return np.where(x > xp[-1], yp[-1]+(x-xp[-1])*(yp[-1]-yp[-2]) /
(xp[-1]-xp[-2]), y... | 8a0acc55e146a29171ef6648897cd5eba7e23c12 | 3,659,092 |
import json
def get_nome_socio(id):
"""pega o nome de um livro pelo id."""
if request.method == 'GET':
try:
socio = db.query_bd('select * from socio where id = "%s"' % id)
if socio:
print(socio)
socio = socio[0]
print(soc... | 8945ef5bbc46cd8b6c79903f1dd0d3d226860792 | 3,659,094 |
def processDeps(element: etree.Element, params: dict = {}) -> None:
"""Function to NAF deps layer to RDF
Args:
element: element containing the deps layer
params: dict of params to store results
Returns:
None
"""
output = params["out"]
for dep in element:
if dep... | a096e42a3a036048daf97079f9e5bb78f5f068d9 | 3,659,095 |
def fit_solution_matrix(weights, design_matrix, cache=None, hash_decimal=10, fit_mat_key=None):
"""
Calculate the linear least squares solution matrix
from a design matrix, A and a weights matrix W
S = [A^T W A]^{-1} A^T W
Parameters
----------
weights: array-like
ndata x ndata matr... | 3b237600ab2ae266cec1cdc3f1fc650cc02b82d8 | 3,659,096 |
def nessus_vuln_check(request):
"""
Get the detailed vulnerability information.
:param request:
:return:
"""
if request.method == 'GET':
id_vul = request.GET['vuln_id']
else:
id_vul = ''
vul_dat = nessus_report_db.objects.filter(vul_id=id_vul)
return render(request, ... | b1b9e2cce8b00f4a837f2712abd2dc4e2f5edb3d | 3,659,098 |
def delete_data(data, object_name, **kwargs):
"""
Delete data
"""
data.delete()
is_queryset = isinstance(data, QuerySet)
return {
"is_queryset": is_queryset,
"data": data,
"object_name": object_name,
} | 28405ae426e53fc3637a4b281775cba99e112a0a | 3,659,100 |
def get_g(source):
""" Read the Graph from a textfile """
G = {}
Grev = {}
for i in range(1, N+1):
G[i] = []
Grev[i] = []
fin = open(source)
for line in fin:
v1 = int(line.split()[0])
v2 = int(line.split()[1])
G[v1].append(v2)
Grev[v2].append(v1)
... | f2771c28d6c86a0af035cc38cd5cdad2774b0dba | 3,659,101 |
def _mercator(lat_long):
"""
Calculate the 2D X and Y coordinates from a set of coordinates based on radius, latitude and longitude using the
Mercator projection.
:param lat_long: The coordinates of the points to be projected expressed as radius, latitude and longitude.
:type lat_long: list[tuple]
... | cc1f4eb97f4c5a1505b88ab5aa8fa6992744dccf | 3,659,102 |
def subjectForm(request, experiment_id):
"""
Generates the fourth page, the demographic/participant data form of an experiment.
"""
experiment = get_object_or_404(Experiment, pk=experiment_id)
form = SubjectDataForm(experiment=experiment)
t = Template(experiment.demographic_data_page_tpl)
... | 48273e891c87b30157c13c726376a9d3052eebe6 | 3,659,103 |
def sigma_0(x):
"""First rotational + shifting mixing function
σ_256_0(x) = ROTR_7(x) ⊕ ROTR_18(x) ⊕ SHR_3(x)
"""
return ROTR(x, 7) ^ ROTR(x, 18) ^ SHR(x, 3) | 9090dc6652944189765657ad9b3650f54b10e70a | 3,659,104 |
from datetime import datetime
def edit_entry(edit_result):
"""Edit entry"""
new_entry = edit_result.copy()
edit_key = None
edit_value = None
date_keys = ["Date"]
int_keys = ["Time Spent"]
while edit_key not in edit_result:
reset_screen("key", "Please type the key you want to edit."... | e63b9d94f192fdc2175457ebc1ce7f9562e1cf41 | 3,659,105 |
def srpd(mvec, k, ra, Nmax, w, V):
"""
Calculate the Steered Response Power Density (SRPD)
:param mvec: SHD coefficients for the TF bin to be analysed
:param k: Wave number (2*pi*f/c)
:param ra: Radius of the microphone array
:param Nmax: Maximum SHD order to be used
:param w: Diagonal eig... | 0506c76812bfdff447f09e4dae8380635e894040 | 3,659,107 |
import torch
def batch_inverse(tensor):
"""
Compute the matrix inverse of a batch of square matrices. This routine is used for removing rotational motion
during the molecular dynamics simulation. Taken from https://stackoverflow.com/questions/46595157
Args:
tensor (torch.Tensor): Tensor of s... | b8defb26561e38d5e16e2483f27287a334b2cd61 | 3,659,108 |
def create(**kwds):
"""
Add data.
"""
status_code = 200
message = "Successfully added data."
articles = []
for a in kwds.get("articles", []):
a = Article.query.filter_by(id=a).first()
if a:
articles.append(a)
cols = {"user_id": current_user.id, "name": kwds[... | a8add828427b285700f23a041bd2c592346775f2 | 3,659,109 |
def _center_size_bbox_to_corners_bbox(centers, sizes):
"""Converts bbox center-size representation to corners representation.
Args:
centers: a tensor with shape [N, 2] representing bounding box centers
sizes: a tensor with shape [N, 2] representing bounding boxes
Returns:
corners: tensor with shap... | 885bbbe2760a464c6fd3bad0811e91a70610eb8c | 3,659,110 |
from datetime import datetime
def get_starting_month(number_of_months_to_get,
include_actual_month=True,
actual_date=datetime.datetime.now()):
"""
Get starting month based on parameters
:param number_of_months_to_get: Numbers of months to get - e.g: 2
:par... | c075ef074b644749ca72955598c098cf76845608 | 3,659,111 |
def user_in_user_groups(user_id, **options):
"""
Get all user groups a user belongs to
:param user_id: The id of user
:param user_id: str
:param options: Generic advanced options dict, see online documentation
:type options: dict, optional
:re... | 70b83b81ee4d03e7ab5fff68be710c02c01aaa0d | 3,659,113 |
def read_book(title_path):
"""Read a book and return it as a string"""
with open(title_path, "r", encoding = "utf8") as current_file: #encoding = "utf8" causes a problem when running the code in Python 2.7. However, it runs normally when using Python 3.5.
text = current_file.read()
text = text.r... | e5273c6b0b71638b47ce5ee5beb33c715c914a1b | 3,659,114 |
from datetime import datetime
def eval_whole_scene_one_epoch(sess, ops, test_writer):
""" ops: dict mapping from string to tf ops """
global EPOCH_CNT
is_training = False
test_idxs = np.arange(0, len(TEST_DATASET_WHOLE_SCENE))
num_batches = len(TEST_DATASET_WHOLE_SCENE)
total_correct = 0
... | 0c5fd39c8cb464a0b4883be15aa687882a20f94a | 3,659,115 |
def _create_save_name(save_path: str, case_date: date, field_names: list, fix: str = "") -> str:
"""Creates file name for saved images."""
date_string = case_date.strftime("%Y%m%d")
return f"{save_path}{date_string}_{'_'.join(field_names)}{fix}.png" | a731effa50ae291df31fcd4b282a924a057561dd | 3,659,116 |
def list_favorite_queries():
"""List of all favorite queries.
Returns (title, rows, headers, status)"""
headers = ["Name", "Query"]
rows = [(r, favoritequeries.get(r)) for r in favoritequeries.list()]
if not rows:
status = '\nNo favorite queries found.' + favoritequeries.usage
else:
... | e3b20d3d06a76d7f621fa830e2d22f0d3e6614ad | 3,659,117 |
def random_portfolio_weights(weights_count) -> np.array:
""" Random portfolio weights, of length weights_count. """
weights = np.random.random((weights_count, 1))
weights /= np.sum(weights)
return weights.reshape(-1, 1) | 47ba5ea84b24ede66fe4d1071fb82f721a550995 | 3,659,118 |
def matrix2list(mat):
"""Create list of lists from blender Matrix type."""
return list(map(list, list(mat))) | 9b4b598eb33e4d709e15fd826f23d06653659318 | 3,659,119 |
def convert_handle(handle):
"""
Takes string handle such as 1: or 10:1 and creates a binary number accepted
by the kernel Traffic Control.
"""
if isinstance(handle, str):
major, minor = handle.split(':') # "major:minor"
minor = minor if minor else '0'
return int(major, 16)... | ed4ef5107178bd809a421e0b66c621d9bdaceef1 | 3,659,120 |
def index(request):
"""Display start page"""
return HttpResponseRedirect(reverse('admin:index')) | c237e46affb7217bbcfc1146d98f84fb1cc20cc6 | 3,659,121 |
import traceback
from datetime import datetime
async def check_data(user_input, hass, own_id=None):
"""Check validity of the provided date."""
ret = {}
if(CONF_ICS_URL in user_input):
try:
cal_string = await async_load_data(hass, user_input[CONF_ICS_URL])
try:
Calendar.from_ical(cal_string)
except E... | a0b9302cb1f69c98585edb0bae918675ceab32cf | 3,659,122 |
def legendre(N, x):
"""
Returns the value of Legendre Polynomial P_N(x) at position x[-1, 1].
"""
P = np.zeros(2 * N)
if N == 0:
P[0] = 1
elif N == 1:
P[1] = x
else:
P[0] = 1
P[1] = x
for i in range(2, N + 1):
P[i] = (1.0 / float(i)) * ((2 * i - 1... | 0e02e19ef0a251aa4b30823d1598fc5fb8933288 | 3,659,127 |
def skip_any_whitespace(doc, idx):
"""Iterate through characters in ``doc`` starting from index ``idx`` until
a non-whitespace character is reached. This iteration will also attempt to
ignore comments.
Args:
doc (str): The JSPEC document.
idx (int): The starting index for the iterator.
... | 18038bce945fb35222254a0fedf5d3936bb83308 | 3,659,128 |
def normalized_cross_correlation(f, g):
""" Normalized cross-correlation of f and g.
Normalize the subimage of f and the template g at each step
before computing the weighted sum of the two.
Hint: you should look up useful numpy functions online for calculating
the mean and standard deviati... | fb6057d882b655a43a7d4a7d3c7ced00d32eeabf | 3,659,129 |
import numpy
def sphere_coordinates(sphere, inversion=False):
"""
Compute spherical coordinates (longitude, latitude) on a sphere.
Parameters
----------
sphere: (AimsTimeSurface_3_VOID)
a sphere mesh: vertices must be on a sphere with center 0.
inversion: bool
if True, the lon... | 82f9e9c0e969904414761ed2ebe70d30194277e5 | 3,659,130 |
def get_height(img):
"""
Returns the number of rows in the image
"""
return len(img) | 765babc9fbc1468ef5045fa925843934462a3d32 | 3,659,132 |
def wpt_ask_for_name_and_coords():
"""asks for name and coordinates of waypoint that should be created"""
name = input("Gib den Namen des Wegpunkts ein: ")
print("Gib die Koordinaten ein (Format: X XX°XX.XXX, X XXX°XX.XXX)")
coordstr = input(">> ")
return name, coordstr | d38a728c5a6ecd1fde9500175ea5895ade8c6880 | 3,659,133 |
def car_following_with_adp(distance_2_tan, radian_at_tan, distance_integral, K, estimated_dis, rec):
""" Control with `distance_2_tan`, `radian_at_tan` and `distance_integral`
with `K` trained from the ADP algorithm.
While following the car in front of it with a simple P controller and `distance_2_c... | 7a49b257e7361451deae10d37a8d8ec811f4890d | 3,659,134 |
def construct_full_available(cards, suits):
"""
Construct suit availability grid - a list of available suits for each
rank slot in each player's deck. Returns grid and array giving the the
total number of available suits for each slot.
"""
num_players, num_in_deck = cards.shape
num_availabl... | 0f4b2712a1346372d0782edfbc7c7b69a8e9e8e6 | 3,659,135 |
import io
def fit_gaussians(estimated_hapcov,
chromosomes=None, output_dir=None, cov_max=None, cov_min=None, level=0, cov_sample=None):
"""
Fits a 7-component Gaussian mixture model to the coverage distribution of the sample, using the appropriate attributes of the PloidyEstimation
obje... | 660952140f6ea8685488a108e11ea1ca6f4e7fc5 | 3,659,137 |
from natsort import natsorted
from sklearn.cluster import DBSCAN
def remove_outliers(cords, eps: int = 1, min_samples: int = 2):
"""
Remove outlying cells based on UMAP embeddings with DBScan (density based clustering)
Call as: sub.obs["d_cluster"] = remove_outliers(sub.obsm["X_umap"], min_samples = 10)
... | 0b4c581158bc3c074b60ad5d29b333418a4f52ce | 3,659,138 |
def sum_squares(n):
"""
Returns: sum of squares from 1 to n-1
Example: sum_squares(5) is 1+4+9+16 = 30
Parameter n: The number of steps
Precondition: n is an int > 0
"""
# Accumulator
total = 0
for x in range(n):
total = total + x*x
return total | 669a5aa03a9d9a9ffe74e48571250ffa38a7d319 | 3,659,139 |
def resolve_attribute(thing, name):
"""
A replacement resolver function for looking up symbols as members of
*thing*. This is effectively the same as ``thing.name``. The *thing* object
can be a :py:func:`~collections.namedtuple`, a custom Python class or any
other object. Each of the members of *thing* must be of ... | 76f7b4548a177168d98bb5cdf4c022bfe8e0d36e | 3,659,140 |
def moment_fluxes(indices, wts_left, wts_right, xi_left, xi_right):
"""
Computes moment fluxes
inputs:
-------
num_nodes: number of quadrature nodes, depends on inversion algorithm
indices: moment indices, size [ num_moments, num_internal_coords ]
wts_left: weights on the left side, ... | 24ed54b56afe127963e6cc7f9d74448e8415edb0 | 3,659,141 |
def froc_curve_per_side(df_gt, df_pred, thresholds, verbose, cases="all"):
"""
Compute FROC curve per side/breast. All lesions in a breast are considered TP if
any lesion in that breast is detected.
"""
assert cases in ["all", "cancer", "benign"]
if not cases == "all":
df_exclude = df_g... | 6a113856a920f775be3ce652fa09d9d79fb9be00 | 3,659,143 |
import itertools
def make_lists(*args, **kwargs):
"""
The make_lists function attaches auxiliary things to an input key_list
of (normally) AD objects. Each key gets exactly one auxiliary thing from
each other list -- these lists can be as long as the key_list, or have
only one item in (in which ca... | 5bdfd32ad317238e21f631655d01bf629722c959 | 3,659,144 |
def get_free_comment_url_ajax(content_object, parent=None, ajax_type='json'):
"""
Given an object and an optional parent, this tag gets the URL to POST to for the
creation of new ``FreeThreadedComment`` objects. It returns the latest created object
in the AJAX form of the user's choosing (json or xml).... | 7d22d2f2b0e012d462d0244d8154cd9ae00ee608 | 3,659,145 |
def cosine_score(vector1, vector2):
"""Calculate cosine cosine score between two spectral vectors."""
return np.dot(vector1, vector2)/np.sqrt(np.dot(np.dot(vector1, vector1), np.dot(vector2, vector2))) | 5b206abb179f1635eeda6267e8019901c480afad | 3,659,147 |
def fixture_times() -> Problem[int]:
"""Generate a problem which tests a times function."""
@test_case(4, 6)
@test_case(-2, 16)
@test_case(2, -3, aga_hidden=True, aga_output=-6)
@problem()
def times(x: int, y: int) -> int:
"""Compute x * y."""
return x * y
return times | a00286a5827ec0c4fe7cb390d0d420d11823eb15 | 3,659,148 |
def get_axis_bounds(ax=None):
"""Obtain bounds of axis in format compatible with ipyleaflet
Returns:
bounds np.array with lat and lon bounds.
bounds.tolist() gives [[s, w],[n, e]]
"""
if ax is None:
ax = plt.gca()
return np.array([ax.get_ylim(), ax.get_xlim()]).T | 32bc97cf6596775dbfdffea655f5346a1fd21764 | 3,659,149 |
def get_pymatgen_structure(cell:tuple) -> Structure:
"""
Get pymatgen structure from cell.
Args:
cell: Cell (lattice, scaled_positions, symbols).
"""
return Structure(lattice=cell[0],
coords=cell[1],
species=cell[2]) | c76e0e71da83737f079d36e56b4867e551affeff | 3,659,150 |
def conditional_samples(x_3, x_prime_3, MC_method, M):
"""Generate mixed sample sets of interest distributed accroding to a conditional PDF.
Parameters
----------
x_3 : np.ndarray
Array with shape (n_draws, 3).
x_prime : np.ndarray
Array with shape (n_draws, 3).
MC_method : stri... | e80d238f27a65271115fd3de2f574bfc3bbdb432 | 3,659,152 |
def recombine(geno_matrix, chr_index, no_loci): #, no_samples):
"""
Recombine at randomly generated breakpoints.
"""
recomb = {0: 0, 1: 2, 2: 1, 3: 3} # '0|1' <-> '1|0'
no_samples = geno_matrix.shape[0]
#print(no_samples)
masked, bp_list = designate_breakpoints(chr_index, no_loci, no_sample... | 455ee154763b31e4d5baa9653caa9f9a118f248e | 3,659,153 |
def update_record_files_async(object_version):
"""Get the bucket id and spawn a task to update record metadata."""
# convert to string to be able to serialize it when sending to the task
str_uuid = str(object_version.bucket_id)
return update_record_files_by_bucket.delay(bucket_id=str_uuid) | ba0ed0af4e6a604801344aa459b6279c5a79dfae | 3,659,154 |
import platform
def check_platform():
"""
str returned
"""
return platform.system() | 73e813c55807e7d84517cb7ce51ce9db34e42c23 | 3,659,155 |
def get_field_keys(table):
""" Field keys for a selected table
:param table:
:return: list op dictionaries
"""
cql = 'SHOW FIELD KEYS FROM \"{}\"'.format(table)
response = db_man.influx_qry(cql).get_points()
return [x for x in response] | ca7be2b79c1641d407fa52ea805e5d99bb2b5c42 | 3,659,156 |
def extract_text_from_spans(spans, join_with_space=True, remove_integer_superscripts=True):
"""
Convert a collection of page tokens/words/spans into a single text string.
"""
if join_with_space:
join_char = " "
else:
join_char = ""
spans_copy = spans[:]
if remove_intege... | ccb45164f695bdbbc53eac9c4cf6596e67c24fd0 | 3,659,157 |
def cf_resource_pool(cli_ctx, *_):
"""
Client factory for resourcepools.
"""
return cf_connectedvmware(cli_ctx).resource_pools | 6cc838a7ad23786b5d86f945da98410506f7e758 | 3,659,158 |
from typing import OrderedDict
def get_bcolz_col_names(cols):
"""整理适应于bcolz表中列名称规范,返回OrderedDict对象"""
trantab = str.maketrans(IN_TABLE, OUT_TABLE) # 制作翻译表
# col_names = OrderedDict(
# {col: get_acronym(col.translate(trantab)) for col in cols})
col_names = OrderedDict()
for col in cols:
... | 9f52cd5adba9ef5d45ff74ef9b35825b80e2c621 | 3,659,160 |
def classify_loss(logits, target, eps):
"""
"""
if eps > 0:
loss = cross_entropy_with_smoothing(logits, target, eps, None)
else:
loss = F.cross_entropy(logits, target.view(-1))
return loss | 549d2c1cbd3275153960ffde6f029c231b9e5703 | 3,659,161 |
def flip(position, adjacent):
"""finds the furthest position on grid up to which the player has captured enemy pieces"""
interval = (adjacent[0] - position[0], adjacent[1] - position[1])
if adjacent[0] < 0 or adjacent[0] > (8*tile_size):
return False
elif adjacent[1] < 0 or adjacent[1] > (8*til... | f6691ae4fe078668220c68c1df4706a0f5825faf | 3,659,162 |
def zeros_from_spec(nested_spec, batch_size):
"""Create nested zero Tensors or Distributions.
A zero tensor with shape[0]=`batch_size is created for each TensorSpec and
A distribution with all the parameters as zero Tensors is created for each
DistributionSpec.
Args:
nested_spec (nested Te... | 8c89a930a6fd81d793c95166b90f4621312e69a9 | 3,659,164 |
def type_to_str(t):
"""Return str of variable type."""
if not hasattr(t, "broadcastable"):
return str(t)
s = broadcastable_to_str(t.broadcastable)
if s == "":
s = str(t.dtype)
else:
s = dtype_to_char(t.dtype) + s
return s | a07982cbc6c8922c43620d23a3dcced24bafbef4 | 3,659,165 |
def save(self, fname="", ext="", slab="", **kwargs):
"""Saves all current database information.
APDL Command: SAVE
Parameters
----------
fname
File name and directory path (248 characters maximum,
including the characters needed for the directory path).
An unspecified direc... | ddc79dc0f54e32d6cd96e115ad9842c1689c17b1 | 3,659,166 |
def rollout(
env,
agent,
max_path_length=np.inf,
render=False,
render_kwargs=None,
fast_rgb=True
):
"""
The following value for the following keys will be a 2D array, with the
first dimension corresponding to the time dimension.
- observations
- acti... | a90c712155648773e72d5226b0f2be4c7fe72b2a | 3,659,167 |
def data_dir():
"""The data directory."""
return DATA | f7696b434ebdab7ec1619f42bed124ba562de64d | 3,659,169 |
def create_single_test(j):
"""Walk through the json cases and recursively write the test cases"""
si = []
for tnum, c in enumerate(j['cases']):
if 'cases' in c:
si.extend(create_single_test(c))
else:
si.extend(write_testcase(c, tnum))
return si | 4a37a95f59e90b5314ea225f58144fa112b9722e | 3,659,170 |
def _token_text(token):
"""Helper to get the text of a antlr token w/o the <EOF>"""
istream = token.getInputStream()
if istream is None:
return token.text
n = istream.size
if token.start >= n or token.stop >= n:
return []
return token.text | 0821c44eea9dfc229034bebc45211f8e6336c552 | 3,659,171 |
def show_interface(enode, dev, shell=None):
"""
Show the configured parameters and stats of an interface.
:param enode: Engine node to communicate with.
:type enode: topology.platforms.base.BaseNode
:param str dev: Unix network device name. Ex 1, 2, 3..
:rtype: dict
:return: A combined dict... | 54ae542cf5df747ad45e016b8296a7ae5408635e | 3,659,172 |
def get_params_for_category_api(category):
"""Method to get `GET` parameters for querying MediaWiki for category details.
:param category: category name to be passed in params.
:return: GET parameters `params`
"""
params = CATEGORY_API_PARAMS.copy()
params['cmtitle'] = 'Category:' + category
... | c97be0a2aae9b1d92e5a02d4376e0a186f669735 | 3,659,173 |
def get_dict_or_generate(dictionary, key, generator):
"""Get value from dict or generate one using a function on the key"""
if key in dictionary:
return dictionary[key]
value = generator(key)
dictionary[key] = value
return value | e31cd2b6661cf45e5345ce57d1e628174e6fd732 | 3,659,174 |
def createNotInConfSubGraph(graphSet, possibleSet):
"""
Return a subgraph by removing all incoming
edges to nodes in the possible set.
"""
subGraph = {}
for i in graphSet:
subGraph[i] = graphSet[i] - possibleSet
return subGraph | d3cbee9049416d7ff865306713e9a12f26717fae | 3,659,175 |
def _backprop_gradient_pure(dL, L):
"""
Given the derivative of an objective fn with respect to the cholesky L,
compute the derivate with respect to the original matrix K, defined as
K = LL^T
where L was obtained by Cholesky decomposition
"""
dL_dK = np.tril(dL).copy()
N = L.shape[... | 28ab304a375e20f952da341024a09477221d54c5 | 3,659,176 |
import random
def get_random_instance() -> random.Random:
"""
Returns the Random instance in the random module level.
"""
return random._inst | ee66055275153ce8c3eae67eade6e32e50fe1d79 | 3,659,177 |
import types
def to(cond, inclusive = True):
"""
Stream elements until the one that fits some condition.
Arguments:
cond -- Either a function or some other object. In the first case, the
function will be applied to each element; in the second case, the object
will be co... | bc7b4fec4b868e12f4e075256ada80c05dfd2c4d | 3,659,178 |
def model(X_train, Y_train, X_test, Y_test, num_iterations = 2000, learning_rate = 0.5, print_cost = False):
"""
Builds the logistic regression model by calling the function you've implemented previously
Arguments:
X_train -- training set represented by a numpy array of shape (num_px * num_px * 3, ... | 073f474ada5d43811564180026cb9d4b2b052cf4 | 3,659,179 |
def mixlogistic_invcdf(y, *, logits, means, logscales, mix_dim,
tol=1e-8, max_bisection_iters=60, init_bounds_scale=100.):
"""
inverse cumulative distribution function of a mixture of logistics, via bisection
"""
if _FORCE_ACCURATE_INV_CDF:
tol = min(tol, 1e-14)
ma... | ef25170fbaaa5eae55b22b09d2d2fb66d20d03fe | 3,659,180 |
import cgitb
def FormatException(exc_info):
"""Gets information from exception info tuple.
Args:
exc_info: exception info tuple (type, value, traceback)
Returns:
exception description in a list - wsgi application response format.
"""
return [cgitb.handler(exc_info)] | 733c2170a08f9880f8c191c1c6a52ee1ab455b7f | 3,659,181 |
def trackers_init(box, vid_path, image):
"""Initialize a single tracker"""
tracker = cv2.TrackerCSRT_create()
tracker.init(image, box)
return tracker, cv2.VideoCapture(vid_path) | 9b32501ad68dcc698fad2b734ff140be7a137903 | 3,659,182 |
from typing import Optional
def get_image(id: Optional[int] = None,
name: Optional[str] = None,
slug: Optional[str] = None,
source: Optional[str] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetImageResult:
"""
Get information on an i... | 180e133173ddb6e99d1743326ec5dcacbc7d5901 | 3,659,183 |
def _infer_added_params(kw_params):
"""
Infer values for proplot's "added" parameters from stylesheets.
"""
kw_proplot = {}
mpl_to_proplot = {
'font.size': ('tick.labelsize',),
'axes.titlesize': (
'abc.size', 'suptitle.size', 'title.size',
'leftlabel.size', 'r... | fec171caef3562344ee86684edc944b0d08af3f3 | 3,659,184 |
def create_table_description(config: ConfigLoader):
""" creates the description for the pytables table used for dataloading """
n_sample_values = int(config.SAMPLING_RATE * config.SAMPLE_DURATION)
table_description = {
COLUMN_MOUSE_ID: tables.Int16Col(),
COLUMN_LABEL: tables.StringCol(10)
... | bd26332586a87e66e14427adb3b0c1ddfd809ce9 | 3,659,185 |
def get_target_rank_list(daos_object):
"""Get a list of target ranks from a DAOS object.
Note:
The DaosObj function called is not part of the public API
Args:
daos_object (DaosObj): the object from which to get the list of targets
Raises:
DaosTestError: if there is an error ob... | 9ce003a4e21ed0fbbf58b57989273939613fff95 | 3,659,186 |
import copy
def find_global_best(particle_best=[]):
"""
Searches for the best particle best to make it the global best.
:param particle_best:
:return:
"""
best_found = None
for particle in particles_best:
if best_found is None:
best_found = copy(particle)
... | 15a6b0f970e385fdc83fcffe19808c61d2a14d7f | 3,659,187 |
def rename_to_monet_latlon(ds):
"""Short summary.
Parameters
----------
ds : type
Description of parameter `ds`.
Returns
-------
type
Description of returned object.
"""
if "lat" in ds.coords:
return ds.rename({"lat": "latitude", "lon": "longitude"})
el... | 18647e3bbf82bae9d02db3e965c0ddfd51ddd6dd | 3,659,188 |
def payments_reset():
""" Removes all payments from the database """
Payment.remove_all()
return make_response('', status.HTTP_204_NO_CONTENT) | c5132e8a1809a2b04ba4282d3f05aafbcf996209 | 3,659,189 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.