content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
from operator import add
def run(data_s: str) -> tuple[int, int]:
"""Solve the puzzles."""
trees = [parse(eval(line)) for line in data_s.splitlines()]
# Part 1
total = trees[0]
for other in trees[1:]:
total = add(total, other)
# Part 2
magnitudes = []
for tree1, tree2 in comb... | 034d31e8dfe6ef47e78ebf713ef0bbc11b4c098b | 67,021 |
def add_resource(request):
""" A view allowing admin to add a resource to the resources page """
if not request.user.is_superuser:
messages.error(request, 'Sorry, only admin can add resources.')
return redirect(reverse('home'))
if request.method == 'POST':
form = ResourceForm(reques... | 9f3798e34d3599b8c43501febdb80b088cab3b9a | 67,022 |
import array
def kernel_evaluate(pos, tree, tree_mcom, rmin, rmax, kvals):
"""
kvals - logarithmically spaced values between rmin and rmax
"""
lib = _initlib(null_log)
n_kernel = len(kvals)
res = lib.init_kernel(n_kernel, array(kvals, dtype=float32), rmin, rmax)
if res!=0:
ra... | c1f0b47a750f7510632c73aea9eb559672e44eb7 | 67,023 |
def graph_db(request) -> graph_tuple_database.Database:
"""A test fixture which returns a graph database with random graphs."""
graph_y_dimensionality, node_y_dimensionality = request.param
db = graph_tuple_database.Database(testing_databases.GetDatabaseUrls()[0])
random_graph_tuple_database_generator.PopulateD... | 71e873041f3ec7fa1c4550a3e7ea3e3ff66aacaf | 67,024 |
def qualified_name_to_object(qualified_name: str, default_module_name='builtins'):
"""
Convert a fully qualified name into a Python object.
It is true that ``qualified_name_to_object(object_to_qualified_name(obj)) is obj``.
>>> qualified_name_to_object('unittest.TestCase')
<class 'unittest.case.Tes... | f8758a80aaa4196aa559b18a5850840ba4bbd69b | 67,025 |
def aggregated_data_from_experiments(experiments, contains_err=False):
"""
experiments: Is a dict of score dicts with each key being the scores of an experiments
contains_err: If True, for each metric score a error is expected under the key metric_label + '_std'
Returns: a structured list that can be ... | 561f967e3777230484c2b355a3af109d7172350a | 67,026 |
def auc(actual, posterior): # pylint: disable=doc-string-with-all-args, doc-string-with-returns
"""
Computes the area under the receiver-operater characteristic (AUC)
This function computes the AUC error metric for binary classification.
Parameters
----------
actual : list of binary numbers, nu... | 1cf2098dd1d872092e7514ae7be9a09de72aa274 | 67,027 |
def integer_or_string(items: list[str]) -> tuple[list[str], list[str]]:
"""
given a list of strings return two lists, the first list will be the
strings that can be converted to integers. The second list will be
the list of strings that cannot be converted to a string.
"""
number_items = []
... | b543f820a474f9495cd1401423516191613d6715 | 67,028 |
def CheckForDoubles(String):
"""Prüft ob mehrere Personen gleichzeitig sprechen und teilt diese dann auf einzelne Einträge auf.
Rückgabe Liste der sprechenden Pers. : "#Anna #Berta" -> ["#Anna", "#Berta"]"""
stringList = []
y = len(String)
x = 0
for i in range(len(String) - 1, -1, -1):
i... | 5555d50e2bb1d6fedcf6e7d74c3c1c5c866cea3b | 67,030 |
from ..preprocessing import szFactor
def adata_processing_TF_link(adata, nt_layers, TF_list, gene_filter_rate=0.1, cell_filter_UMI=10000):
"""preprocess adata and get ready for TF-target gene analysis"""
n_obs, n_var = adata.n_obs, adata.n_vars
# filter genes
print(f"Original gene number: {n_var}")
... | 217855b77dbce9290f24162dbb81ea890e8dd9e2 | 67,033 |
def monitoredsystems():
"""this method returns the current list of monitored systems"""
# Replace this with sql logic to get monitored systems later
monitored = ['Arque', 'Zaonce', 'Teorge', 'Tianve', 'Tionisla', 'Neganhot', 'Orrere', 'Oguninksmii']
return monitored | 0590360d7a97e93ab6f00e5139dc94a7bb7c8c7c | 67,034 |
def preprocess_initial(train, image_size):
"""Initial preprocessing function for training on smaller resolution.
For training, do random_horizontal_flip -> random_crop.
For validation, just resize.
No color-jittering has been used.
"""
def _pp(image, label, train):
if train:
... | 8620fa7d56de80f093848f87d6af11f9e8fc8a68 | 67,035 |
import requests
from bs4 import BeautifulSoup
def forbes_rank(indicator: str = "2020福布斯美国富豪榜") -> pd.DataFrame:
"""
福布斯中国-榜单
https://www.forbeschina.com/lists
https://www.forbeschina.com/lists/1750
:param indicator: choice of {"2020福布斯美国富豪榜", "2020福布斯新加坡富豪榜", "2020福布斯中国名人榜", *}
:type indicator... | c543fb83220b091eaab6d3b114e22b54b56dde38 | 67,036 |
def sample(predictions, temperature):
""""Simulates creativity by sampling predicted probabilities of next character."""
predictions = np.asarray(predictions).astype('float64')
if temperature is None or temperature == 0.0:
return np.argmax(predictions)
predictions = np.log(predictions + K.ep... | 9e4cfc19305aea0417a7ab81b61ed7c9e8010fd0 | 67,037 |
import torch
def area_under_roc(pred, target):
"""
Area under receiver operating characteristic curve (ROC).
Parameters:
pred (Tensor): predictions of shape :math:`(n,)`
target (Tensor): binary targets of shape :math:`(n,)`
"""
if target.dtype != torch.long:
raise TypeErro... | 73fe771d46994cc0d72c726fc18e51a9d48f3c7d | 67,038 |
def vec_2d(v) -> np.ndarray:
"""Converts a higher order vector to a 2D vector."""
assert len(v) >= 2
return np.array(v[:2]) | 5e829483365cf000cfebf4f486a54c1a6136b9e8 | 67,039 |
def acceptable_drift(drMeasure, Tm, Thm, lowerBound, upperBound):
"""
Function that return true if drift is acceptable (based on lowerBound and upperBound), false otherwise
"""
mrMeasure = Tm/Thm
mrMeasure = preprocess_mr(mrMeasure)
drMean = np.mean(drMeasure)
drSTD = np.std(drMeasure)
m... | 63b8e59385548630083bf4661647140c9d40689b | 67,040 |
def get_crypto_layer(exr_file: OpenEXR.InputFile, layer_mapping: exr_info.CryptoLayerMapping) -> np.ndarray:
"""Extract one of the cryptomatte layers as a 4-channel numpy array.
Each cryptomatte layer has 4 channels for RGBA.
Note:
- By default, there are 3 crypto layers in an EXR, corresponding to... | 7c6e2fc0b48211d9008ec636cd852c7b1eaae708 | 67,041 |
def concatenate(matrices, out=None, dtype=None):
"""Concatenate matrix transformations.
Chain multiply matrices describing transform operations into a single matrix
product, that when applied, transforms points and vectors with each
operation in the order they're specified.
Parameters
--------... | 1d429d72f1094d599340a3afb4872e6b7b183ed8 | 67,042 |
def covidstats_df(data):
""" Dado un json de datos de un deparamento de covidstats devuelve un DataFrame con:
- indice la fecha
- casos_fa, casos_reporte
- CAMPO_acum el acumulado respectivo
- CAMPO_14acum acumulado en 14 dias
"""
day = pd.Series(pd.date_range(data['fecha_ini... | 3589ea71da4fc3df9f902d8b75a0068fabd744bf | 67,043 |
import yaml
def _write_and_build_prj(fp, d):
"""
Write project config file and build Project.
:param str fp: path to config file
:param dict d: project config data
:return looper.Project: newly built Project instance
"""
with open(fp, 'w') as f:
yaml.dump(d, f)
return Project(... | 860a563e9999cdf484d9280179d4406ed77573d5 | 67,044 |
import torch
def unnormalize_img(img, mean, std, in_gpu=True):
"""
img: [3, h, w]
"""
img = img.detach().cpu().clone()
# img = img / 255.
img *= torch.tensor(std).view(3, 1, 1)
img += torch.tensor(mean).view(3, 1, 1)
min_v = torch.min(img)
img = (img - min_v) / (torch.max(img) - mi... | 52698e7644e2d20e18e3ed44108af5b901d4f01b | 67,046 |
import math
def get_scalar_min_max_by_column(df, target_columns, column_to_properties):
"""Get a dictionary indexed by column name with minimum and maximum values.
(useful e.g., for normalized processing of subgroups).
If column to properties is set, for a column, the minimum and maximum are taken from t... | f35bdea2ac780610e95b3286e5ac2a21d870877e | 67,048 |
def get_options(optionset_label, current_only=True, as_stored=False):
"""
Return all options for this app_label as dictionary with the option name
being the key.
"""
#Hit the cache
cached = {}
if ls.ADMIN_CACHE_DB_OPTIONS:
cached = cache.get(get_option_cache_key(optionset_label), {}... | 65d635251cfae6054926bc12b2ce6082dbf7c522 | 67,049 |
def build_url(hub_base_url: str, org: str, workspace: str) -> str:
"""
Build the base URL of the Chaos Hub workspace where the experiment and
the journal will be stored and be made visible.
"""
return '/'.join([hub_base_url, 'api', org, workspace]) | 116b9b7f6211ca50b48550689b7e161cee0b4d9d | 67,050 |
def batched_nms_pattern(boxes, scores, idxs, iou_threshold, num_boxes, indices):
"""A pattern to detect batched_nms function in torchvision
The inputs to this function, boxes, scores, idxs, iou_threshold are wildcard
patterns which can be used later in the rewriting to extract matched Relay fragments.
... | e1e0f0bdf21b1cb466fff583c8f39871be3400f0 | 67,051 |
import types
import functools
def cmp_using(
eq=None,
lt=None,
le=None,
gt=None,
ge=None,
require_same_type=True,
class_name="Comparable",
):
"""
Create a class that can be passed into `attr.ib`'s ``eq``, ``order``, and
``cmp`` arguments to customize field comparison.
The ... | 0e463b4ca64b2f26e254e38c754cfe2ab4e9b918 | 67,052 |
def plot_single_sd(sd,
cmfs='CIE 1931 2 Degree Standard Observer',
out_of_gamut_clipping=True,
modulate_colours_with_sd_amplitude=False,
equalize_sd_amplitude=False,
**kwargs):
"""
Plots given spectral distribution.
... | 435a6ecf007ee0120806cf3feb02bea826a5be96 | 67,053 |
from datetime import datetime
def datetimes_equal(dt1, dt2):
"""Compare if datetimes are equal to the nearest second."""
diff = dt1 - dt2
return abs(diff) < datetime.timedelta(seconds=1) | de7c08c6360887b69e188f5cf638851195de03c7 | 67,054 |
def _repopulate_partitions(partition_string: str, partition_metadata: dict) -> tuple:
""" For each val in the partition string creates a list that can be added back into the dataframe
Args:
partition_string (str): S3 bucket to fetch from
partition_metadata (dict): A dictionary of all partitions... | b26c5e1c44b1158cfbfd6fd2c236f6de7593d35b | 67,056 |
def clean(key, value):
""""Clean the values"""
if key.startswith('WS'):
return QUANTITY(value, UREG.mph).to(UREG.knots).m
if key.startswith('RH') and value > 100:
return 100.
if pd.isnull(value):
return None
return value | e6f8f109a3222837690a2f84e4fd3aa481ceaf00 | 67,057 |
def _GetAddress(compute_client, address_ref):
"""Returns the address resource corresponding to the given reference.
Args:
compute_client: GCE API client,
address_ref: resource reference to reserved IP address
Returns:
GCE reserved IP address resource
"""
errors = []
messages = compute_client.m... | 544c7b30a8da5762ff50cb2cc563d3fc251121be | 67,058 |
def generate_active_htmls(conn: Connection) -> t.Iterable[str]:
"""Get HTML stored in the database for active sections."""
sql = "SELECT html FROM Notes WHERE html IS NOT NULL ORDER BY id ASC"
return (html.strip() for html, in conn.execute(sql)) | 6c61fb9d892518245d92e154e88b18eb1ff9c4f3 | 67,059 |
def parse_vcf_line(line):
"""
Parse a line in the VCF file.
:param line: a line from the VCF file
:type line: str
:return: :class:`.vcf.VCFRecord`
"""
if isinstance(line, str):
if line.startswith('#'):
return None
elem = line.strip().split('\t')
elif isinst... | a41e4efda445311c09ed97b079823d23867658f9 | 67,060 |
def fieldify(embed: discord.Embed, names: list, values: list, inline: bool = True, limit: int = None):
"""Easy embed fieldification
:returns embed:
"""
embed = embed
if not limit:
for name, val in zip(names, values):
embed.add_field(name=name, value=val, inline=inline)
... | c8a02d11abfd75921e988701a2e79112f0a0bf74 | 67,061 |
def init_floodfill(cpoint, opoints, xypoints, mincoord, xyreso):
"""
cpoint: center point
opoints: detected obstacles points (x,y)
xypoints: (x,y) point pairs
"""
centix, centiy = cpoint
prev_ix, prev_iy = centix - 1, centiy
ox, oy = opoints
xw, yw = xypoints
minx, miny = mincoo... | b5dc61459fac947161e611942b575d5ea9f65ff7 | 67,062 |
def naive_closest_pair(plane):
"""
Find the closest pair of points in the plane using the brute
force approach
Args:
plane: List of points [(p1_x, p1_y), (p2_x, p2_y), ...]
Returns:
Distance between closest pair of points and closest pair
of points: [dist_bw_p1_p2, (p1_x, p1... | 653fe7f35999a0c8827ee3108e720d323856c63a | 67,063 |
def _compute_factored_isogeny_prime_power(P, l, e):
"""
This method takes a point `P` of order `l^e` and returns
a sequence of degree-`l` isogenies whose composition has
the subgroup generated by `P` as its kernel.
EXAMPLES::
sage: from sage.schemes.elliptic_curves import hom_composite
... | cc5ec271b2bf0d39ee615d9eb21c96674c7b8748 | 67,064 |
def lanczosSubPixKernel( subPixShift, kernelShape=3, lobes=None ):
"""
Generate a kernel suitable for ni.convolve to subpixally shift an image.
"""
kernelShape = np.array( [kernelShape], dtype='int' )
if kernelShape.ndim == 1: # make it 2-D
kernelShape = np.array( [kernelShape[0], kernelSha... | 3208dd080ba737a1ab5d224b52352a86dd9769d3 | 67,066 |
def load_python_exec(text_data, builtins=None):
"""
Function to provide compatibility with python 3.7 for loading text formwatted in
python using exec buil-in method. Exec syntaxis in pyton 2.6 different
comared to python3.x and python3 spits "Invlaid Syntaxis error" while trying to
run code below... | 9f16866ec38138b8a7bfd359244bc10f7a2ac93c | 67,067 |
def one_hot_encoding(y):
"""creates one-hot vector for the target variables
for example,if a training set consists of multiple classes y=(0,1,2...n)
one-hot vector for y(0)=[1,0,0,..n],y(2)=[0,0,1,0,..n]"""
no_=y.shape[0]
class_set=set([_[0] for _ in y if isinstance(_,(list,np.ndarray))])
temp=np.full([no_,len(cl... | 16780d443fe83eb4473a1dfd66d5e860e122d43f | 67,069 |
def get_disassembler(disassembler=None):
"""
lazy import (so we can still change global path)
"""
if disassembler is None:
if ida_available:
disassembler = 'ida'
else:
disassembler = 'ghidra'
if disassembler == 'ida':
return IDA()
if disassembler ... | 2eb389278a5f1a70b6cf61ff325e195f62d2ba73 | 67,070 |
def icon_sys_title(icon_sys, encoding = None):
"""Extract the two lines of the title stored in an icon.sys tuple."""
offset = icon_sys[1]
title = icon_sys[14]
title2 = shift_jis_conv(title[offset:], encoding)
title1 = shift_jis_conv(title[:offset], encoding)
return (title1, title2) | ef66e05fcad94cdd558b1b1abe22300d9e8beb48 | 67,071 |
def get_old_color(request):
"""
Returns the old color of the label when edited
:param request: incomming request
:return: old color of the label (String)
"""
if('color' in request.json['changes']):
return request.json['changes']['color']['from'] | 8711c91e00ff5d5e550d4153f5eddbee56e710ea | 67,073 |
def unfold_tensor(tensor, dim, window_sz):
"""Unfold a tensor by applying a sliding window on a certain dimension with step 1 and padding of 0's. The window
dimension is added as the last dimension
:param tensor: the tensor to be unfolded, with shape [d_1, d_2, ..., T, ..., d_n]
:param dim: the dimensi... | 352b72ccb7a8e23d5c6e26d54f89bf6a6f8c1f72 | 67,074 |
def vectorized_lower_tri_to_mat(v, dim):
"""
:param v: a list of length (dim * (dim + 1) / 2)
:param dim: the number of rows (equivalently, columns) in the output array.
:return: Return the symmetric 2D array defined by taking "v" to
specify its lower triangular entries.
"""
rows, cols, va... | 38fb2a778806dc3cdad12217ceb387188d95e5a8 | 67,075 |
import random
def calc(metric: str, Y_mean: np.ndarray, Y_var: np.ndarray,
current_max: float, t: float,
beta: int, xi: float, stochastic: bool) -> np.ndarray:
"""Call corresponding metric function with the proper args"""
if metric == 'random':
return random(Y_mean)
if metric == ... | 588c7df0f25a24f22538d66934837abac4a6c685 | 67,076 |
def list_lookup(list_, select, default=0):
"""
Use `select` as an index into `list` (similar to a case statement)
`default` is used when `select` does not match any of the indices (e.g.
when the select width is longer than the list) and has a default value of
0.
"""
output = default
for... | b52c8e830999f01f6fe7f3ca43ddd1fabb04897a | 67,077 |
def unquote_unreserved(uri):
"""Un-escape any percent-escape sequences in a URI that are unreserved
characters. This leaves all reserved, illegal and non-ASCII bytes encoded."""
return ''.join(_gen_unquote(uri)) | 04f53539406a7561adf2d6553d7d5e483592c5c0 | 67,079 |
from operator import inv
def GLS(x, A, L):
"""
x: sample matrix, each column is a link flow vector sample; 24 * K
A: path-link incidence matrix
P: logit route choice probability matrix
L: dimension of xi
----------------
return: xi
----------------
"""
K = np.size(x, 1)
S =... | be0918ed4db96c07819f22d246c19df57bca654d | 67,080 |
def SelectDBSeveralFittest(n, db_list):
"""
Function: SelectDBSeveralFittest
=================================
Select n fittest individual
@param n: the number of fittest individuals
@param db_list: the ordered list of fitnesses with associated unique ids obtained from the database
... | b43709032f21e4854dd0cc7b00a1e7cae983d762 | 67,081 |
def get_image_resize_method(resize_method, batch_position=0):
"""Get tensorflow resize method.
If resize_method is 'round_robin', return different methods based on batch
position in a round-robin fashion. NOTE: If the batch size is not a multiple
of the number of methods, then the distribution of methods will ... | f54dd3a340a90f75fa9080fda561d231328a0797 | 67,082 |
import scipy
def abund_log_prob(genotype, abundance, refrabund=None, mean=30.0, sd=8.0,
error=0.001):
"""Calculate probability of k-mer abundance conditioned on genotype.
The `genotype` variable represents the number of assumed allele copies and
is one of {0, 1, 2} (corresponding to ge... | 59b6261cfe0759aaa084a5b6ddd8f56f9c6e38af | 67,084 |
import time
def train_model(model: Model, dataset: Dataset, epochs: int, batch_size: int, use_wandb: bool = False) -> Model:
"""Train model."""
callbacks = []
if EARLY_STOPPING:
early_stopping = EarlyStopping(monitor="val_loss", min_delta=0.01, patience=3, verbose=1, mode="auto")
callback... | 11034fc52a47485eeacdd6a2a1aadc58758eddc1 | 67,085 |
import xml
def ParseSVGFile(filename):
"""Parse an SVG file name and return an Art object for it.
Args:
filename: string - name of file to read and parse
Returns:
geom.Art
"""
dom = xml.dom.minidom.parse(filename)
return _SVGDomToArt(dom) | c657427fd599a1e89393a0b8a43c4810a4f281ee | 67,086 |
def writer_cache():
""" Singleton for WriterDriverCache
"""
# pylint: disable=protected-access
if not hasattr(writer_cache, '_instance'):
writer_cache._instance = WriterDriverCache('datacube.plugins.io.write')
return writer_cache._instance | e2a4f40a6544daa2293cece525ebabf4bef25784 | 67,087 |
def compute_rbf_encoding(input, rbf_center, rbf_sig=0.15):
"""
Compute the rbf encoding from trained rbf center to new input
m := n_frames * n_test_seq
n := n_neurons * n_train_seq
:param input: (n_feature, m)
:param rbf_center:(n_feature, n)
:param rbf_sig:
:return:
"""
# f_i... | b38865212e37e55e588289f78d3be9664eeacfa2 | 67,089 |
def longest_peak(relative_angles):
"""
Find the longest area < 0
:param relative_angles: list of angles
:return: coordinates of the area
"""
length = relative_angles.shape[0]
longest = (0, 0)
j = 0
for i in range(length):
if relative_angles[i] >= 0:
... | 742359ed60f4b6cebc9da8510cb801a08a40df99 | 67,090 |
def create_mesmer_input(membrane_files, nucleus_file):
"""Create membrane and nuclear images for input to Mesmer.
Parameter:
membrane_files : str list
paths to membrane marker (grayscale) images
nucleus_file : str
path to nuclear marker (grayscale) image
Returns:
... | b4fe0075a4f68a71daba1ce9b4ad6d96b93d5cc7 | 67,091 |
def add_event(event=None):
"""Add a data event.
Report a new data event to be retained in the archives.
:param event: Required inputs for creating a data archive.
:type event: dict | bytes
:rtype: None
"""
if connexion.request.is_json:
event = APIEvent.from_dict(connexion.request.... | 6d6eb77a7587d8ca09f7db3593e1fbc6010e64a5 | 67,092 |
def HtmlColorCode_to_floats(value):
"""
Convert a HTML color code
like '#FFCC00' or 'FFCC00'
to a list of floats [1.0, 0.8, 0.0]
"""
# return (float.fromhex('0x'+x)/255 for x in HtmlColorCode_to_strings(value)) # fromhex is python 2.6!
return [float(int(x, 16))/255 for x in HtmlColorCode_to... | 6ad60b806188524b15854c81482c9681721f931b | 67,093 |
from docker import client
def get_client():
"""Returns the client or initialize it"""
if 'client' not in __st__:
__st__['client'] = client.from_env()
return __st__['client'] | cf12d4e286e2a2813dfaab270da06f9442017e3f | 67,094 |
def uu_query_STK_EXCHANGE_LINK_CALENDAR():
"""
记录沪港通、深港通和港股通每天是否开市
:param :query(finance.STK_EXCHANGE_LINK_CALENDAR):表示从finance.STK_EXCHANGE_LINK_CALENDAR这张表中查询市场沪港通、深港通和港股通交易日历的信息,还可以指定所要查询的字段名,格式如下:query(库名.表名.字段名1,库名.表名.字段名2),多个字段用英文逗号进行分隔;query函数的更多用法详见:sqlalchemy.orm.query.Query对象
finance.S... | 454f6481fde72a1ba9d4449cda0f78d975b4bda2 | 67,095 |
from typing import Callable
from typing import Any
import functools
def agent_must_be_ready(f: Callable[..., Any]) -> Callable[..., Any]:
"""Any Agent method decorated with this will raise if the agent is not ready."""
@functools.wraps(f)
def decorated(self, *args: Any, **kwargs: Any) -> Any:
if ... | bec74702355d6aaa7796527a05d9510048513910 | 67,096 |
def min_sample_size(bcr, mde, power=0.8, sig_level=0.05):
"""Returns the minimum sample size to set up a split test
Arguments:
bcr (float): probability of success for control, sometimes
referred to as baseline conversion rate
mde (float): minimum change in measurement between control
... | a604255f40d8e150b575f346ffd9f826307c258a | 67,097 |
import math
def gcj02_to_bd09(lng, lat):
"""
火星坐标系(GCJ-02)转百度坐标系(BD-09)
谷歌、高德——>百度
:param lng:火星坐标经度
:param lat:火星坐标纬度
:return:
"""
z = math.sqrt(lng * lng + lat * lat) + 0.00002 * math.sin(lat * x_pi)
theta = math.atan2(lat, lng) + 0.000003 * math.cos(lng * x_pi)
bd_lng = z * ... | f2babb243037b2accc6d64d9fe7e06c78ceb785f | 67,098 |
def show_machine(machine_id):
"""Get machine."""
data = _get_request_args()
return utils.make_json_response(
200,
machine_api.get_machine(
machine_id, user=current_user, **data
)
) | ab85b3d6e626b4e349906d81617c575bc9913f88 | 67,099 |
import copy
def scsg_step(net, optimizer, train_loader, test_loader, loss_function, inner_iter_num, args):
"""
Function to updated weights with a SCSG backpropagation
args : net, optimizer, train_loader, test_loader, loss function, number of inner epochs, args
return : train_loss, test_loss, grad_norm... | 6e7f70c0642734bdc0d76e7fa7d9f1db718cde1b | 67,100 |
def to_pyvista_line(line_set: LineSet, as_tube=True, radius=None,
spline=False, n_interp_points=1000):
"""Create pyvista PolyData for 1D lines
Args:
line_set:
as_tube (bool):
radius (float): radius of the tube
spline: NotImplemented
n_interp_points: N... | 2b08a04cab5c604cd8889e9463a11a7b7ec42f73 | 67,101 |
def calc_exec_time(block):
"""
calculate the total time to execute all observing blocks by exp. time.
Excludes any read out time and overheads.
:param block: The observing Block document.
:type block: Dict
:rtype: int
"""
if "parameters" not in block:
return 0
exp1 = 0
... | deaf6649173de784a77601da4ef4df1b7c10cb93 | 67,102 |
def count_terms_v2_KEGG(ans_set, assoc_dict):
"""
count the number of terms in the study group
GOid2NumANs_dict: key=GOid, val=Num of occurrences
GOid2ANs_dict: key=GOid, val=ListOfANs
count_n: Integer(Number of ANs with a GO-term in assoc_dict and obo_dag
:return: Tuple(dict, dict, int)
"""... | 8716da136cd6752e55c5dc35110370af13a2b764 | 67,103 |
from typing import Dict
from typing import Any
def create_bot_utterance(message: Dict[Text, Any]) -> BotUttered:
"""Create BotUttered event from message."""
bot_message = BotUttered(
text=message.pop("text", None),
data={
"elements": message.pop("elements", None),
"qui... | f6d880edce11408493c616958cd874f9ac85b66a | 67,104 |
import pkg_resources
def get_example_data():
""" Get default path to experimental crystal ovelap populaiton data
Returns
-------
data_path : str
path to example lobster data
"""
data_path = pkg_resources.resource_filename(__name__, 'data/lobster')
return data_path | a04a47e3f70a9735c2badf32da13a6119c82c418 | 67,105 |
def get_page_content(code_lan, num_of_path, path):
"""
By passing the language code and path,
is return the page content object
"""
# Inside any page it saved the path with this format
url = "url_{}.{}".format(num_of_path, code_lan)
# Create a list of pages
list_pages = [ page for page... | 3d9a9148ef15f376a2a5ab3a1b50ded589531b4c | 67,106 |
from typing import Callable
import time
from typing import Any
def per_user_ratelimit(
max_requests: int,
period: float,
login_res: str = sign_in_page,
get_ratelimited_res: Callable[[float], str] = (
lambda left: f"Too many requests, wait {left} sec"
),
) -> Callable[[Callable], flask.Resp... | 2f3c1e6e15fcfca99ae66e92dd0af4614ba1e02a | 67,107 |
def _nondim_resist_braginskii(hall, Z, field_orientation):
"""
Dimensionless resistivity — Braginskii.
Braginskii, S. I. "Transport processes in a plasma." Reviews of plasma
physics 1 (1965): 205.
"""
allowed_Z = [1, 2, 3, 4, np.inf]
Z_idx = _check_Z(allowed_Z, Z)
# fixing overflow err... | 5ca98cce84907d056d29149c81167d09e8675a09 | 67,108 |
import signal
def smooth_data(df, window_length=21, polyorder=5):
"""
Apply a Savitzky-Golay filter spectrograms contained in DataFrame.
Column 'x' remains unchanged"""
x = df.x
smoothed = signal.savgol_filter(df, window_length=window_length, polyorder=polyorder, axis=0)
df_smoothed = pd.DataF... | 42b64263cc3604d7c9a23342b4dd75711fa686f2 | 67,109 |
def attributes(*args):
"""
a decorator to add an "attribute" to an action, which can be used
as a filtering mechanism to control what actions in given task are run.
If we have the following in tasks.init_data:
@attributes('test', 'dev')
def action_020_a_little_data()... | f03acfd500171f529f8ea0ec8e391dfd15cac092 | 67,110 |
import math
def ts_winp(a, b, env=None):
"""Win probability of player a over b given their trueskill ratings.
Formula found at https://github.com/sublee/trueskill/issues/1#issuecomment-244699989"""
if not env:
env = trueskill.global_env()
epsilon = trueskill.calc_draw_margin(env.draw_probabili... | 2a01c965db005f5f99e84e4583e5978dfac274b1 | 67,111 |
def _construct_sparse_tensors_for_sparse_features(features, tensor_dict):
"""Merges SparseTensors of indices and values of SparseFeatures.
Constructs new dict based on `tensor_dict`. For `SparseFeatures` in the values
of `features` expects their `index_key`s and `index_value`s to be present in
`tensor_dict` ma... | 07e8713a334a023f0c1ff43cc583337a69355416 | 67,112 |
def _check_limits(val, lb=None, ub=None, lb_ge=False, ub_le=False):
""" Returns True where lb < (or <=) val < (or <=) ub
"""
if lb_ge:
lb_op = np.greater_equal
else:
lb_op = np.greater
if ub_le:
ub_op = np.less_equal
else:
ub_op = np.less
if (lb is not None) ... | 3a3c54fb56a8b2ff06375c2276a5a011be11b9db | 67,113 |
def kml_response(kml_map):
"""
Args:
kml_map (KMLMap): KMLMap object
Returns:
Response: a Flask Response with proper MIME-type.
"""
return Response(kml_map.get_kml(), mimetype=kml_map.MIME_TYPE) | b101eb985873e75df6da07e69d5fc11928c95de3 | 67,114 |
def _parse_instructors(details):
"""
Extract instructor names from the course detail page
Args:
details(Tag): BeautifulSoup Tag for course details
Returns:
list of dict: List of first & last names of each instructor
"""
try:
instructors = details.findAll(
"... | 3dc4f4ddf62dc9dae894d218e249a279941eca5f | 67,115 |
def create_LeNet(img_dim, n_labels):
"""
Create CNN with LeNet Architecture
- Set 1: Conv2D - Actication - Pooling
- Set 2: Conv2D - Activation - Pooling
- Set 3: Flatten - Fully Connected - Activation
- Set 4: Output layer for classification
Input:
- img_dim: size of the inpu... | 7d6ebbc30da10fb50394bd96010cbbfa69faec29 | 67,116 |
import random
def convert_labels(read_dataset, write_dataset, percent, no_sentences_to_enable):
"""
Takes a file and randomly enables no_sentences_to_enable of them.
:param read_dataset: file to read from
:param write_dataset: file to write to
:param percent: percent to enable (used to calculate t... | 31acbb1a4146bcf4f09a15ed3d89794f90654a44 | 67,117 |
def subject_member_find(context, subject_id=None, member=None,
status=None, include_deleted=False):
"""Find all members that meet the given criteria.
Note, currently include_deleted should be true only when create a new
subject membership, as there may be a deleted subject membershi... | 07b2a431392c3d54560943e87d2226ef3e9c3b1f | 67,119 |
def reporthook(t):
"""https://github.com/tqdm/tqdm"""
last_b = [0]
def inner(b=1, bsize=1, tsize=None):
"""
b: int, optionala
Number of blocks just transferred [default: 1].
bsize: int, optional
Size of each block (in tqdm units) [default: 1].
tsize: int, opt... | 35ea69d974de5fa31c2ca910d1db09659b5bda23 | 67,120 |
def psse_to_df(file):
"""
Convert a PSS/E xlsx export to DataFrame.
"""
return excel_to_df(file, offset_row=1, offset_col=0, ) | fc3257594a55d7aba45d08fa6cae0794fb403162 | 67,122 |
def transform_point(point: (int, int), transform_metadata: TransformMetadata):
"""
:param point: point in original plane
:param M: transformation matrix
:return: prints point that point is transformed to in new plane
"""
a = np.array([np.array([point], dtype='float32')])
cur = cv2.perspectiv... | dffd0367c6af5b948612018ba6aee7c9b9593e2a | 67,123 |
def compute_possible_positions(start, grid):
"""
Get all possible position that are in the grid and are not walls
"""
possible = []
for direct in DIRECTIONS:
px, py = start[0] + direct[0], start[1] + direct[1]
if 0 <= px < len(grid[0]) and 0 <= py < len(grid):
if grid[py... | f855032fb31edd81d3293a645fd7ee7a785daabb | 67,124 |
def get_changed_docs():
""" Function to fetch docs which very whose notificatons have not been sen to the users. """
try:
client = MongoClient(host,port)
db=client[changes_db]
col=db[changes_collection]
docs=col.find({"status": "unnotified"})
client.close()
return docs
except Exception as e:
print "Fa... | aa1a51cc580455e4dd7e31781bb20bdf40a46615 | 67,125 |
def isCSERelative(uri:str) -> bool:
""" Check whether a URI is CSE-Relative. """
return uri is not None and uri[0] != '/' | 70384d58d9f00c20233ccb46ab9d8e8ec7dcf22c | 67,126 |
def sqrt(number):
"""
Calculate the floored square root of a number
Args:
number(int): Number to find the floored squared root
Returns:
int: Floored Square Root
"""
#Returning the number when it is less or equal to 1
if number <= 1:
return number
my_divsor = 2
my... | 541d7f2460532ba86c7a960b15c3b5629c2f4e94 | 67,127 |
def xml_pretty(elem):
"""Return a pretty-printed XML string for the Element.
"""
rough_string = ElementTree.tostring(elem, 'utf-8')
reparsed = minidom.parseString(rough_string)
return reparsed.toprettyxml(indent=" ") | 9c2e65d107ec5ba89ba2f4b5f929fbc06bb5da70 | 67,128 |
def be_in(a, b, msg=None):
"""
Asserts **ARG1 in ARG2**
"""
return contain(b, a, msg) | 99ebf628f12af52ded3c4629832ce6f83db306e2 | 67,129 |
import functools
def needs(*things):
"""An injector that injects the requested dependences into a function's
arguments.
If the dependency has "."s in the name, only the last segment will be used,
and "-" will be replaced with "_".
"""
things_parameter_names = {
requirement.rsplit("."... | ab0852b530d153cb07104c5fe8bf9e1a772e47fe | 67,130 |
def reverse_translate(protein_sequence, randomize_codons=False, table="Standard"):
"""Return a DNA sequence which translates to the provided protein sequence.
Parameters
----------
protein_sequence
A sequence string of aminoacids, e.g. "MVKK..."
table
Genetic code table to use (e.g. '... | 123848bb83111e774013900f3d3b9a4ab0572735 | 67,131 |
def unindent(line, from_row, to_row, count=1):
"""
Unindent text of the `Line` object.
"""
current_row = line.document.cursor_position_row
line_range = range(from_row, to_row)
def transform(text):
remove = ' ' * count
if text.startswith(remove):
return text[len(re... | 3befe045bd7b1a78ee2f675a66410a745046c346 | 67,132 |
def get_image(mol, atomset, name):
"""Save image of the SMILES for vis purposes"""
hcolor = colors.to_rgb('green')
if atomset is not None:
# highlight the atoms set while drawing the whole molecule.
img = MolToImage(mol, size=(600, 600), fitImage=True, highlightAtoms=atomset, highlightColor=... | 6baa202b2ce78f7db60dc8ff44fdd0a5625a9f26 | 67,133 |
from bs4 import BeautifulSoup
def parse_page_deb(page, source, version, prefix):
"""Parses a Debian deb HTML page and return URLs.
"""
html = BeautifulSoup(page, 'html.parser')
elements = [x.select('a')[0].get_text() for x in html.select('tr')[3:-1]]
elements = list(filter(lambda x: not x.endswith... | 45f93c811172bfdb308dcd59dc16cc5e1f3ed87f | 67,134 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.