content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def trunc_artist(df: pd.DataFrame, artist: str, keep: float = 0.5, random_state: int = None):
"""
Keeps only the requested portion of songs by the artist
(this method is not in use anymore)
"""
data = df.copy()
df_artist = data[data.artist == artist]
data = data[data.artist != artist]
... | 7157e223bdf87d0463820565e40eade3e1725ae5 | 3,658,400 |
async def test_postprocess_results(original, expected):
"""Test Application._postprocess_results."""
callback1_called = False
callback2_called = False
app = Application("testing")
@app.result_postprocessor
async def callback1(app, message):
nonlocal callback1_called
callback1_c... | 9c2a6bdfcb281d62959135be01693baaaf266780 | 3,658,401 |
def toContinuousCategory(
oX: pd.DataFrame,
features: list = [],
drop: bool = True,
int_: bool = True,
float_: bool = True,
quantile: bool = True,
nbin: int = 10,
inplace: bool = True,
verbose: bool = True,
) -> pd.DataFrame:
"""
Transforms any float, continuous integer value... | bc8bc9c339d998e4e3c337a039421ec835a6f16f | 3,658,402 |
def task_migrate():
"""Create django databases"""
return {
'actions': ['''cd CCwebsite && python3 manage.py migrate''']
} | d0d146c2e628abbe33714ae0ff6a546aab9842cc | 3,658,403 |
import numpy
def distance_to_arc(alon, alat, aazimuth, plons, plats):
"""
Calculate a closest distance between a great circle arc and a point
(or a collection of points).
:param float alon, alat:
Arc reference point longitude and latitude, in decimal degrees.
:param azimuth:
Arc a... | e8868a2ce9125cc75e587a8a408f5b479b6a198a | 3,658,404 |
def model_predict(test_data: FeatureVector):
"""
Endpoint to make a prediction with the model. The endpoint `model/train` should have been used before this one.
Args:
test_data (FeatureVector): A unit vector of feature
"""
try:
y_predicted = api.ml_model.predict_proba(test_data.to_... | c8b473d09092e03be85e986287350dd3115cf88d | 3,658,405 |
import os
def print_header(args, argv, preamble='CIFAR10', printfn=print,
log=open(os.devnull, 'w'),
first=('model','dataset','epoch','batchsize','resume','out')):
""" Prints the arguments and header, and returns a logging print function """
def logprint(*args, file... | c1213f441696dbabedafe9888a681cf64bab4249 | 3,658,406 |
def search_folders(project, folder_name=None, return_metadata=False):
"""Folder name based case-insensitive search for folders in project.
:param project: project name
:type project: str
:param folder_name: the new folder's name
:type folder_name: str. If None, all the folders in the project will ... | cf8a9d95efcdb90d0891ef4ca588edf6375ed2af | 3,658,407 |
def tempo_para_percorrer_uma_distancia(distancia, velocidade):
""" Recebe uma distância e a velocidade de movimentação, e retorna
as horas que seriam gastas para percorrer em linha reta"""
horas = distancia / velocidade
return round(horas,2) | e7754e87e010988284a6f89497bb1c5582ea0e85 | 3,658,408 |
import math
def getCorrection(start, end, pos):
"""Correct the angle for the trajectory adjustment
Function to get the correct angle correction when the robot deviates from
it's estimated trajectory.
Args:
start: The starting position of the robot.
end: The position the robot is suppos... | 9f1073cb4c071abfecac20c85c56e5fb1638de6e | 3,658,409 |
import logging
def main(input_filepath, output_filepath):
""" Runs data processing scripts to turn raw data from (../raw) into
cleaned data ready to be analyzed (saved in ../processed).
"""
logger = logging.getLogger(__name__)
logger.info('making final data set from raw data...')
df = loa... | fe799a34f9cb5811228853469dbff92592a87e69 | 3,658,410 |
def string2symbols(s):
"""
Convert string to list of chemical symbols.
Args:
s:
Returns:
"""
i = None
n = len(s)
if n == 0:
return []
c = s[0]
if c.isdigit():
i = 1
while i < n and s[i].isdigit():
i += 1
return int(s[:i]) * s... | 1f08ba5c02536f4b67c9bd573c0dde8fbe46dc74 | 3,658,411 |
def coe2rv(a, e, i, node, w, v, MU=Earth.mu, degrees=True):
"""Given the classical orbital elements (a, e, i, node, w, v), this
returns the position (R) and the velocity (V) in an ECI frame
- Semimajor-axis (a)[km]: orbit size
- Eccentricity (e): orbit shape (0=circle, 1=line)
- Inclination (i)[deg... | 489ba6c1e484fa054063dddbeff5b686b35c0458 | 3,658,412 |
import csv
from typing import Counter
def get_dictionary(filename, dict_size=2000):
"""
Read the tweets and return a list of the 'max_words' most common words.
"""
all_words = []
with open(filename, 'r') as csv_file:
r = csv.reader(csv_file, delimiter=',', quotechar='"')
for row in... | 20917b0c9cda18d5436b438e0cdcf0c83d464899 | 3,658,413 |
def find_last_index(l, x):
"""Returns the last index of element x within the list l"""
for idx in reversed(range(len(l))):
if l[idx] == x:
return idx
raise ValueError("'{}' is not in list".format(x)) | f787b26dd6c06507380bf2e336a58887d1f1f7ea | 3,658,414 |
import requests
import zipfile
import io
def download_query_alternative(user, password, queryid, batch_size=500):
"""
This is an alternative implementation of the query downloader.
The original implementation only used a batch size of 20 as this allowed for using
plain LOC files. Unfortunately this i... | 2de7c3b453809c86093d1884438613985f7041b3 | 3,658,415 |
def parse_template(templ_str, event):
"""
Parses a template string and find the corresponding element in an event data structure.
This is a highly simplified version of the templating that is supported by
the Golang template code - it supports only a single reference to a sub
element of the event s... | ec5c3822c390cbb4beff6428b91cd8b12157f2e3 | 3,658,416 |
import time
def current_time_hhmm() -> str:
"""
Uses the time library to get the current time in hours and minutes
Args:
None
Returns:
str(time.gmtime().tm_hour) + ":" + str(time.gmtime().tm_min) (str):
Current time formatted as hour:minutes
"... | c7902ac8a8fb2528bacf6a5bc8459865604dd204 | 3,658,417 |
import torch
def mae_loss(output, target):
"""Creates a criterion that measures the mean absolute error (l1 loss)
between each element in the input :math:`output` and target :math:`target`.
The loss can be described as:
.. math::
\\ell(x, y) = L = \\operatorname{mean}(\\{l_1,\\dots,l_N\\... | 159c50cf673750c1d27b8ad8b2a5bbde3bb76111 | 3,658,418 |
import json
def aistracker_from_json(filepath, debug=True):
"""
get an aistracker object from a debug messages JSON that was previously
exported from pyaisnmea
Args:
filepath(str): full path to json file
debug(bool): save all message payloads and decoded attributes into
... | 99426c11d33fc8bb00cdb4cfec51b60e8d8f481d | 3,658,419 |
def configure(node):
""" Generates the script to set the hostname in a node """
script = []
script.append(Statements.exec("hostname %s" % node.getName()))
script.append(Statements.createOrOverwriteFile(
"/etc/hostname", [node.getName()]))
script.append(Statements.exec(
"sed -i 's/127... | b0acf0f6a1363f1c7ad5a8e6dce6cb5d45586135 | 3,658,420 |
import random
def processOptional(opt):
"""
Processes the optional element 50% of the time, skips it the other 50% of the time
"""
rand = random.random()
if rand <= 0.5:
return ''
else:
return processRHS(opt.option) | bda8130952f11f4df9342764d749dd6c93109d8e | 3,658,421 |
def remove_non_paired_trials(df):
"""Remove non-paired trials from a dataset.
This function will remove any trials from the input dataset df that do not
have a matching pair. A matching pair are trial conditions A->B and B->A.
"""
# Define target combinations
start_pos = np.concatenate(df['sta... | 30b5b86d9354c55dd2514114dc1180f397f2e56c | 3,658,422 |
def compute_weighted_means_ds(ds,
shp,
ds_name='dataset',
time_range=None,
column_names=[],
averager=False,
df_output=pd.DataFrame(),
... | e575d17eefe8de66c0b6fd63abcf5d3bd6cac6ae | 3,658,423 |
def action_remove(indicator_id, date, analyst):
"""
Remove an action from an indicator.
:param indicator_id: The ObjectId of the indicator to update.
:type indicator_id: str
:param date: The date of the action to remove.
:type date: datetime.datetime
:param analyst: The user removing the ac... | 806c818cd4c18624d9713a02d5c1826cab43a631 | 3,658,424 |
def repack_orb_to_dalton(A, norb, nclosed, nact, nvirt):
"""Repack a [norb, norb] matrix into a [(nclosed*nact) +
(nclosed*nvirt) + (nact*nvirt)] vector for contraction with the CI
Hamiltonian.
"""
assert norb == nclosed + nact + nvirt
assert A.shape == (norb, norb)
# These might be availa... | 05b356e9ded74c180d2a220f147cd69e91a5b597 | 3,658,425 |
def get_config(section="MAIN", filename="config.ini"):
"""
Function to retrieve all information from token file.
Usually retrieves from config.ini
"""
try:
config = ConfigParser()
with open(filename) as config_file:
config.read_file(config_file)
return config[sect... | 32d6c579b0ce002a601ea9041b54e9ce03858eb4 | 3,658,426 |
def _worst_xt_by_core(cores) -> float:
"""
Assigns a default worst crosstalk value based on the number of cores
"""
worst_crosstalks_by_core = {7: -84.7, 12: -61.9, 19: -54.8} # Cores: Crosstalk in dB
worst_xt = worst_crosstalks_by_core.get(cores) # Worst aggregate intercore XT
return worst_xt | 331fdd7dc20db6909a6952483cfa9699f983a721 | 3,658,427 |
def _CheckUploadStatus(status_code):
"""Validates that HTTP status for upload is 2xx."""
return status_code / 100 == 2 | d799797af012e46945cf413ff54d2ee946d364ba | 3,658,428 |
def load(path: str, **kwargs) -> BELGraph:
"""Read a BEL graph.
:param path: The path to a BEL graph in any of the formats
with extensions described below
:param kwargs: The keyword arguments are passed to the importer
function
:return: A BEL graph.
This is the universal loader, which me... | 871c7e3becac089758c94f7416def0020e63f9c1 | 3,658,429 |
from typing import Optional
def smooth_l1_loss(
prediction: oneflow._oneflow_internal.BlobDesc,
label: oneflow._oneflow_internal.BlobDesc,
beta: float = 1.0,
name: Optional[str] = None,
) -> oneflow._oneflow_internal.BlobDesc:
"""This operator computes the smooth l1 loss.
The equation is:
... | ddebf5ba77ca8e4d2a964e5c86e05a0b61db9ded | 3,658,430 |
def get_model_fields(model, concrete=False): # type: (Type[Model], Optional[bool]) -> List[Field]
"""
Gets model field
:param model: Model to get fields for
:param concrete: If set, returns only fields with column in model's table
:return: A list of fields
"""
if not hasattr(model._meta, 'g... | 9e9172b2e606041c6f9dbf3a991e79d73518227f | 3,658,431 |
def loss_fun(para):
"""
This is the loss function
"""
return -data_processing(my_cir(para)) | 5703755e3f5547be933f85224c103c58acbeaabb | 3,658,432 |
def GetDynTypeMgr():
"""Get the dynamic type manager"""
return _gDynTypeMgr | 7acf02dd2072ea819c847f53fbf11e68146b2400 | 3,658,433 |
def identifyEntity(tweet, entities):
"""
Identify the target entity of the tweet from the list of entities
:param tweet:
:param entities:
:return:
"""
best_score = 0 # best score over all entities
targetEntity = "" # the entity corresponding to the best score
for word in tweet:
... | d6825dfddf01706ee266e0f1c82128a42bcb8554 | 3,658,434 |
def angle_between(a, b):
"""
compute angle in radian between a and b. Throws an exception if a or b has zero magnitude.
:param a:
:param b:
:return:
"""
# TODO: check if extreme value that can make the function crash-- use "try"
# from numpy.linalg import norm
# from numpy import dot... | c739915a75c36c26b7b3f002239de931653e4d09 | 3,658,435 |
def _apply_D_loss(scores_fake, scores_real, loss_func):
"""Compute Discriminator losses and normalize loss values
Arguments
---------
scores_fake : list
discriminator scores of generated waveforms
scores_real : list
discriminator scores of groundtruth waveforms
loss_func : objec... | 9432962af57193c07a268d00a3f1f01d372cb6a0 | 3,658,436 |
import tempfile
def get_temp_dir():
"""
Get path to the temp directory.
Returns:
str: The path to the temp directory.
"""
return fix_slashes( tempfile.gettempdir() ) | 3d0dd90c8187ac7b13913e7d4cd2b481c712fa6b | 3,658,437 |
import random
def pick_op(r, maxr, w, maxw):
"""Choose a read or a write operation"""
if r == maxr or random.random() >= float(w) / maxw:
return "write"
else:
return "read" | a45f53bf12538412b46f78e2c076966c26cf61ac | 3,658,438 |
def sim_nochange(request):
""" Return a dummy YATSM model container with a no-change dataset
"No-change" dataset is simply a timeseries drawn from samples of one
standard normal.
"""
X, Y, dates = _sim_no_change_data()
return setup_dummy_YATSM(X, Y, dates, [0]) | a39ba5824644764ae2aaf4e4d95c68d1c26bd132 | 3,658,439 |
import os
def internalpatch(patchobj, ui, strip, cwd, files=None, eolmode='strict'):
"""use builtin patch to apply <patchobj> to the working directory.
returns whether patch was applied with fuzz factor."""
if files is None:
files = {}
if eolmode is None:
eolmode = ui.config('patch', ... | 64060526a6ed028dc48ebfbf447751a69590fb65 | 3,658,440 |
from functools import reduce
import operator
def get_queryset_descendants(nodes, include_self=False, add_to_result=None):
"""
RUS: Запрос к базе данных потомков. Если нет узлов,
то возвращается пустой запрос.
:param nodes: список узлов дерева, по которым необходимо отыскать потомков
:param include... | 7de9fe6c146c9569bc78b714b75238b770f9157e | 3,658,441 |
from operator import mul
def op_mul(lin_op, args):
"""Applies the linear operator to the arguments.
Parameters
----------
lin_op : LinOp
A linear operator.
args : list
The arguments to the operator.
Returns
-------
NumPy matrix or SciPy sparse matrix.
The resu... | a1f770d2132fc9c3a60d4de3c3d87f59a03241eb | 3,658,442 |
def comparator(x, y):
"""
default comparator
:param x:
:param y:
:return:
"""
if x < y:
return -1
elif x > y:
return 1
return 0 | 53fc36f1afc3347689a1230c5ee3ba25d90f1239 | 3,658,443 |
def set_trait(age, age_risk_map, sex, sex_risk_map, race, race_risk_map):
""" A trait occurs based on some mix of """
if age in age_risk_map:
risk_from_age = age_risk_map[age]
else:
risk_from_age = 0
if sex in sex_risk_map:
risk_from_sex = sex_risk_map[sex]
else:
ri... | fe9f6c75ae4d7f80c2da86af4315b35fe29df482 | 3,658,444 |
import os
def isvalid(save_path, file):
""" Returns true if the file described by the parameters is a file with
the appropriate file extension. """
return os.path.isfile(os.path.join(save_path, file)) and \
str(file).endswith('.meta') | 55f76212eaaae3be6706a01f3f28d24005d28f75 | 3,658,445 |
def tidy_expression(expr, design=None):
"""Converts expression matrix into a tidy 'long' format."""
df_long = pd.melt(
_reset_index(
expr, name='gene'), id_vars=['gene'], var_name='sample')
if design is not None:
df_long = pd.merge(
df_long,
_reset_index... | 7c904e13a55f38cc05309b5927f2fdbb23c3f8c9 | 3,658,446 |
def model_remote_to_local(remote_timestamps, local_timestamps, debug=False):
"""for timestamps"""
a1=remote_timestamps[:,np.newaxis]
a2=np.ones( (len(remote_timestamps),1))
A = np.hstack(( a1,a2))
b = local_timestamps[:,np.newaxis]
x,resids,rank,s = np.linalg.lstsq(A,b)
if debug:
pri... | 74e9a6e367be1e77be715c8f17818abaa268923e | 3,658,447 |
def get_optimizer(name):
"""Get an optimizer generator that returns an optimizer according to lr."""
if name == 'adam':
def adam_opt_(lr):
return tf.keras.optimizers.Adam(lr=lr)
return adam_opt_
else:
raise ValueError('Unknown optimizer %s.' % name) | 8c97ee9f4b77d0fc80914ac7cbb49a448d48644a | 3,658,448 |
from typing import List
def get_multi(response: Response, common: dict = Depends(common_parameters)) -> List[ShopToPriceSchema]:
"""List prices for a shop"""
query_result, content_range = shop_to_price_crud.get_multi(
skip=common["skip"],
limit=common["limit"],
filter_parameters=common... | f97868e66c7743127d2d2951b732ff4c62708ae5 | 3,658,449 |
from datetime import datetime
def send_crash(request, machine_config_info, crashlog):
"""
Save houdini crashes
"""
machine_config = get_or_save_machine_config(
machine_config_info, get_ip_address(request),
datetime.datetime.now())
save_crash(machine_config, crashlog, datetime.datet... | 43e44950bdb4b6dc305bb1f36651daa31b4f813e | 3,658,450 |
import sys
import csv
def read_csv_file(filename):
"""Read csv file into a numpy array
"""
header_info = {}
# Make this Py2.x and Py3.x compatible
if sys.version_info[0] < 3:
infile = open(filename, 'rb')
else:
infile = open(filename, 'r', newline='', encoding='utf8')
with... | 8aa8c7bb1aeda1b85c99e09ee7033753ffd6d9a2 | 3,658,451 |
def apply_HAc_dense(A_C, A_L, A_R, Hlist):
"""
Construct the dense effective Hamiltonian HAc and apply it to A_C.
For testing.
"""
d, chi, _ = A_C.shape
HAc = HAc_dense(A_L, A_R, Hlist)
HAc_mat = HAc.reshape((d*chi*chi, d*chi*chi))
A_Cvec = A_C.flatten()
A_C_p = np.dot(HAc_mat, A_Cv... | b13f9db7287fcdf275e8f7c9a7fb542e7b79323c | 3,658,452 |
def min_index(array, i, j):
"""Pomocna funkce pro razeni vyberem. Vrati index nejmensiho prvku
v poli 'array' mezi 'i' a 'j'-1.
"""
index = i
for k in range(i, j):
if array[k] < array[index]:
index = k
return index | 4c59362fac2e918ba5a0dfe9f6f1670b3e95d68c | 3,658,453 |
def filterControlChars(value, replacement=' '):
"""
Returns string value with control chars being supstituted with replacement character
>>> filterControlChars(u'AND 1>(2+3)\\n--')
u'AND 1>(2+3) --'
"""
return filterStringValue(value, PRINTABLE_CHAR_REGEX, replacement) | a0f508d281f0c12311a5c2aa2f898def5eb38913 | 3,658,454 |
def get_deobfuscator(var_names) -> str:
"""Creates a deobfuscator for the given set of var names.
Args:
var_names (list): List of variable names from the `obfuscate` function.
Returns:
str: Deobfuscator
"""
return f'\n\ngetattr(getattr(__main__, [x for x in dir(__main__) if x.start... | 0ad26818cd8a802aabb666631f096d5b2f6c47a0 | 3,658,455 |
import csv
def write_trt_rpc(cell_ID, cell_time, lon, lat, area, rank, hmin, hmax, freq,
fname, timeformat='%Y%m%d%H%M'):
"""
writes the rimed particles column data for a TRT cell
Parameters
----------
cell_ID : array of ints
the cell ID
cell_time : array of datetime... | fd634914a8c3d96d10d4dcc81514d492d6be899c | 3,658,456 |
def get_tag(string: str) -> Tag:
"""Получить тему."""
return Tag.objects.get(tag=string) | 816bbaecc4cf45e2fc75b1e428842b5502a353bc | 3,658,457 |
def average_precision(gt, pred):
"""
Computes the average precision.
This function computes the average prescision at k between two lists of
items.
Parameters
----------
gt: set
A set of ground-truth elements (order doesn't matter)
pred: list
A list of predicted elements (order does mat... | ca265471d073b6a0c7543e24ef0ba4f872737997 | 3,658,458 |
import math
def rotate_coo(x, y, phi):
"""Rotate the coordinates in the *.coo files for data sets
containing images at different PAs.
"""
# Rotate around center of image, and keep origin at center
xin = 512.
yin = 512.
xout = 512.
yout = 512.
cos = math.cos(math.radians(phi))
... | a57a4c36119e96d757bd23f28a0790f6d68661fc | 3,658,459 |
def ip_block_array():
"""
Return an ipBlock array instance fixture
"""
return ['10.0.0.1', '10.0.0.2', '10.0.0.3'] | c74756f34b97d2550cb238bd63e0c9505f3935d3 | 3,658,460 |
from pathlib import Path
import joblib
def load_model(model_name, dir_loc=None, alive_bar_on=True):
"""Load local model_name=model_s if present, else fetch from hf.co."""
if dir_loc is None:
dir_loc = ""
dir_loc = Path(dir_loc).absolute().as_posix()
file_loc = f"{dir_loc}/{model_name}"
if... | 1847e061c6980fd4fd185f79d48682cbf7cb14ff | 3,658,461 |
from typing import Generator
def get_dev_requirements() -> Generator:
"""Yield package name and version for Python developer requirements."""
return get_versions("DEVELOPMENT") | 728658648d6bce6fecbf4c1bc6b6de42c315b3c0 | 3,658,462 |
def _ndb_key_to_cloud_key(ndb_key):
"""Convert a ndb.Key to a cloud entity Key."""
return datastore.Key(
ndb_key.kind(), ndb_key.id(), project=utils.get_application_id()) | ce71b0d13f2e37ded12bf87ad133492a9b68d0c7 | 3,658,463 |
def inference(H, images, train=True):
"""Build the MNIST model up to where it may be used for inference.
Parameters
----------
images: Images placeholder, from inputs().
train: whether the network is used for train of inference
Returns
-------
softmax_linear: Output tensor with the com... | bf7e0f60bdc85d52fb6778cc40eedaa63c0387e3 | 3,658,464 |
import os
def _find_modules_and_directories(top_level_directory):
"""
Recursive helper function to find all python files included in top level
package. This will recurse down the directory paths of any package to find
all modules and subpackages in order to create an exhaustive list of all
python ... | 2aecb5974f83ce01b2a8e4a6fb8313399756c1d4 | 3,658,465 |
def UniqueLattice(lattice_vectors,ind):
"""
Takes a list with two tuples, each representing a lattice vector and a list with the genes of an individual.
Returns a list with two tuples, representing the equivalent lattice vectors with the smallest cell circunference.
"""
x_1 = lattice_vectors(0,ind)
... | e2474a54cf3351ff112ecb6d139eec8eac2ef1fa | 3,658,466 |
def register_errors(app: Flask):
"""注册需要的错误处理程序包到 Flask 程序实例 app 中"""
@app.errorhandler(400) # Bad Request 客户端请求的语法错误,服务器无法理解
def bad_request(e):
return render_template('error.html', description=e.description, code=e.code), 400
@app.errorhandler(404) # Not Found 服务器无法根据客户端的请求找到资源(网页)
def... | 27634a139aab88215b77e53a25758d6096571a09 | 3,658,467 |
def websafe_encode(data):
"""Encodes a byte string into websafe-base64 encoding.
:param data: The input to encode.
:return: The encoded string.
"""
return urlsafe_b64encode(data).replace(b'=', b'').decode('ascii') | ed5b06d2fab3dcc64275cb0046cabd88f63894ec | 3,658,468 |
from typing import Union
def gravatar(email: Union[str, list]) -> str:
"""Converts the e-mail address provided into a gravatar URL.
If the provided string is not a valid e-mail address, this
function just returns the original string.
Args:
email: e-mail address to convert.
Returns:
... | 8807eefd40472068310455c1c477933dbaa67be0 | 3,658,469 |
def bar_2_MPa(value):
"""
converts pressure in bar to Pa
:param value: pressure value in bar
:return: pressure value in Pa
"""
return value * const.bar / const.mega | d6c8084a6603f74bd1fb11739e4f4d9100cf14de | 3,658,470 |
def walk(x, y, model, theta, conditions=None, var2=0.01, mov=100,
d=1, tol=1e-3, mode=True):
"""Executes the walker implementation.
Parameters
----------
x : np.ndarray
An $(m, n)$ dimensional array for (cols, rows).
y : np.ndarray
An $n$ dimensional array that will be ... | ef7386f4c7141edfcdeb041b47d741e186f207e2 | 3,658,471 |
def izbor_letov():
"""Glavna stran."""
# Iz cookieja dobimo uporabnika in morebitno sporočilo
(username, ime, priimek) = get_potnik()
c.execute("SELECT distinct drzava FROM lokacija ORDER BY drzava")
drzave=c.fetchall()
drzava_kje = bottle.request.forms.drzava_kje
mesto_kje = bottle.request.forms.mesto_kje
l... | 664de2c3cf2507ac43efa22105a51b1e14ad441a | 3,658,472 |
def generate_data_from_cvs(csv_file_paths):
"""Generate data from list of csv_file_paths. csv_file_paths contains path to CSV file, column_name, and its label
`csv_file_paths`: A list of CSV file path, column_name, and label
"""
data = []
for item in csv_file_paths:
values = read_csv(item[0]... | 1c9f393a18edc9c2fcc3f28cdbeb71fb9c006731 | 3,658,473 |
import math
import torch
def log_density_gaussian(x, mu, logvar):
"""Calculates log density of a gaussian.
Parameters
----------
mu: torch.Tensor or np.ndarray or float
Mean.
logvar: torch.Tensor or np.ndarray or float
Log variance.
"""
normalization = - 0.5 * (math.log(2... | 3fdc751aa58b3ec82e1aa454f593879d5da4c310 | 3,658,474 |
def invalid_hexadecimal(statement):
"""Identifies problem caused by invalid character in an hexadecimal number."""
if statement.highlighted_tokens: # Python 3.10
prev = statement.bad_token
wrong = statement.next_token
else:
prev = statement.prev_token
wrong = statement.bad_t... | a0b252001dd1f0f466302a131c2a460743a8c197 | 3,658,475 |
def get_pool_name(pool_id):
"""Returns AS3 object name for TLS profiles related to pools
:param pool_id: octavia pool id
:return: AS3 object name
"""
return "{}{}".format(constants.PREFIX_TLS_POOL, pool_id) | 2a850d48f52d822712cdfc3543532c9b0dd80fd6 | 3,658,476 |
def search_sliceable_by_yielded_chunks_for_str(sliceable, search_string, starting_index, down, case_insensitive):
"""This is the main entry point for everything in this module."""
for chunk, chunk_start_idx in search_chunk_yielder(sliceable, starting_index, down):
found_at_chunk_idx = search_list_for_st... | 7179179403098cd1d3993a35cf59c9162384ac4d | 3,658,477 |
def split_page(array, limit, index):
"""
按限制要求分割数组,返回下标所指向的页面
:param array: 需要分割的数组
:param limit: 每个数组的大小
:param index: 需要返回的分割后的数组
:return: 数组
"""
end = index * limit
start = end - limit
return array[start:end] | ecce83d6e2e09d47e124536f294ece1e1631e6b6 | 3,658,478 |
def creatKdpCols(mcTable, wls):
"""
Create the KDP column
Parameters
----------
mcTable: output from getMcSnowTable()
wls: wavelenght (iterable) [mm]
Returns
-------
mcTable with an empty column 'sKDP_*' for
storing the calculated KDP of a given wavelength.
"""
... | 9adc20c1ff94778bec4551156b5774863eb2203f | 3,658,479 |
def get_products_by_user(user_openid, allowed_keys=None, filters=None):
"""Get all products that user can manage."""
return IMPL.get_products_by_user(user_openid, allowed_keys=allowed_keys,
filters=filters) | 458664aa75c5b423ccfb2a80287c565cae51e0d0 | 3,658,480 |
def sample_from_ensemble(models, params, weights=None, fallback=False, default=None):
"""Sample models in proportion to weights and execute with
model_params. If fallback is true then call different model from
ensemble if the selected model throws an error. If Default is not
None then return default if ... | c771108cb36cff2cb48af22a9efaad749d267ce0 | 3,658,481 |
def Flatten(matrix):
"""Flattens a 2d array 'matrix' to an array."""
array = []
for a in matrix:
array += a
return array | 00389b4dd295274d8081331d6ae78f233f0b5b59 | 3,658,482 |
def create_verification_token(
data: dict
) -> VerificationTokenModel:
"""
Save a Verification Token instance to database.
Args:
data (dictionary):
Returns:
VerificationToken:
Verification Token entity of VerificationTokenModel object
Raises:
None
"""
... | 9008bc298c8e8075031f7e14e8cb0f288e894869 | 3,658,483 |
from typing import Union
from typing import Sequence
from typing import Tuple
def _find_highest_cardinality(arrays: Union[int, Sequence, np.ndarray, Tuple]) -> int:
"""Find the highest cardinality of the given array.
Args:
arrays: a list of arrays or a single array
Returns:
The highest ... | abe9ad85ffabb88f9097b9c2de97319f1342f586 | 3,658,484 |
import logging
from datetime import datetime
import pytz
def get_yesterday() -> tuple:
"""Get yesterday`s date and split it to year,month and day strings"""
logging.debug("Starting get_yesterday function.")
today = datetime.now(pytz.timezone("America/New_York"))
yesterday = (today - timedelta(days=1))... | 1ccf514f0f121489d2e467c2f8bc3f8cc7715324 | 3,658,485 |
def rowmap(table, rowmapper, header, failonerror=False):
"""
Transform rows via an arbitrary function. E.g.::
>>> import petl as etl
>>> table1 = [['id', 'sex', 'age', 'height', 'weight'],
... [1, 'male', 16, 1.45, 62.0],
... [2, 'female', 19, 1.34, 55.4],
... | dabceae8171330d3f8c4cdba7b50be2106ad1438 | 3,658,486 |
def squeeze(dataset, how: str = 'day'):
"""
Squeezes the data in dataset by close timestamps
Args:
dataset (DataFrame) - the data to squeeze
how (str) - one of 'second', 'minute', 'hour', 'day', 'month' (default day)
Returns:
dataset (DataFrame) - a dataframe where the indexes are squeez... | e41cbc4e054218b1f88ed0745fcc980df29ac8d4 | 3,658,487 |
def callback():
"""
Process response for "Login" try from Dropbox API.
If all OK - redirects to ``DROPBOX_LOGIN_REDIRECT`` url.
Could render template with error message on:
* oAuth token is not provided
* oAuth token is not equal to request token
* Error response from Dropbox API
Def... | 8b35d67d065a5ec65606b6e505cfccc51460fe1c | 3,658,488 |
def get_ws_param(args, attr):
"""get the corresponding warm start parameter, if it is not exists, use the value of the general parameter"""
assert hasattr(args, attr), 'Invalid warm start parameter!'
val = getattr(args, attr)
if hasattr(args, 'ws_' + attr):
ws_val = getattr(args, 'ws_' + attr)
... | ea1d762654153602f8ad54048e54995c26304e40 | 3,658,489 |
def _redundant_relation(lex: lmf.Lexicon, ids: _Ids) -> _Result:
"""redundant relation between source and target"""
redundant = _multiples(chain(
((s['id'], r['relType'], r['target']) for s, r in _sense_relations(lex)),
((ss['id'], r['relType'], r['target']) for ss, r in _synset_relations(lex)),... | cc32c55a35cd7056a249ad05bd0b483af18fcd3a | 3,658,490 |
def get_ph_bs_symm_line(bands_path, has_nac=False, labels_dict=None):
"""
Creates a pymatgen PhononBandStructure from a band.yaml file.
The labels will be extracted from the dictionary, if present.
If the 'eigenvector' key is found the eigendisplacements will be
calculated according to the formula:... | 40b135c09c829348d0693574b745ad5c114ec037 | 3,658,491 |
import subprocess
import logging
import ipaddress
def get_peer_ip(result_host_dic: dict):
"""
find peer multi address based on peerID
:param result_host_dic: [provider_peerID : who provides (peerID)]
:return: dic {provider_peerID : Address[]}
"""
provider_ip = {}
for peer in result_host_di... | 2bed8cf2be996d0d71516eb9c000ea7b2f0212b8 | 3,658,492 |
def LinterPath():
"""Ascertain the dxl.exe path from this .py files path because sublime.packages_path is unavailable at startup."""
ThisPath = abspath(dirname(__file__))
if isfile(ThisPath):
# We are in a .sublime-package file in the 'Installed Package' folder
return abspath(join(ThisPath, ... | 5e7e8e5761b69ba3383b10af92f4d9a442bab69e | 3,658,493 |
import base64
def encrypt_and_encode(data, key):
""" Encrypts and encodes `data` using `key' """
return base64.urlsafe_b64encode(aes_encrypt(data, key)) | b318e5e17c7a5b8f74036157ce547a3c0d68129c | 3,658,494 |
def _get_undelimited_identifier(identifier):
"""
Removes delimiters from the identifier if it is delimited.
"""
if pd.notna(identifier):
identifier = str(identifier)
if _is_delimited_identifier(identifier):
return identifier[1:-1]
return identifier | cd31b5cd2aea8f6c115fa117da30960f5f6dd8d8 | 3,658,495 |
def build_movie_json(mongodb_result, hug_timer):
"""
For reducing the duplicate lines in the 'get_goat_movies' function.
TODO: Modify nodejs code if integrating this info!
"""
combined_json_list = []
movie_vote_quantities = []
for result in mongodb_result:
#print(result)
total_votes = int(result['goat_upvot... | 27eeac479911c24e46f7df2b34aa7d4897e4b94b | 3,658,496 |
def has_product_been_used(uuid):
"""Check if this product has been used previously."""
existing = existing_processed_products()
if not isinstance(existing, pd.DataFrame):
return False
has_uuid = not existing.query("uuid == @uuid").empty
return has_uuid | f361c5177c0152179300d6c1356139ba8f7face9 | 3,658,497 |
def _FilterMemberData(
mr, owner_ids, committer_ids, contributor_ids, indirect_member_ids,
project):
"""Return a filtered list of members that the user can view.
In most projects, everyone can view the entire member list. But,
some projects are configured to only allow project owners to see
all member... | be258b2d0559423a70fb5722734144f6a946b70e | 3,658,498 |
def escape_name(name):
"""Escape sensor and request names to be valid Python identifiers."""
return name.replace('.', '_').replace('-', '_') | 856b8fe709e216e027f5ab085dcab91604c93c2e | 3,658,499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.