content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def get_worksheet_data_block(sheet, coords, expand=None):
"""Get a data block.
Args:
sheet (Sheet): The worksheet containing the data block.
coords (str): The inclusive coordinates of the data block.
expand (str): Optionally expand the range of values.
Returns
(dict): A dicti... | bc6aed4c9bc300b4120cad3b9e47ac892d996579 | 3,606,000 |
def merge_adjustment_factor(*dataframes, with_self=True):
"""Returns a data frame with student id as the index and the peer
evaluation instances as the columns. The entry is the adjustment factor
value. A numerical value is also computed in the column 'Improvement' that
shows whether they were ranked hi... | 0b8267e6892ebdc2442dc06bbacbae97184613f6 | 3,606,001 |
def find_footer(messages, number=1):
"""
Returns the footer of a DataFrame of emails.
A footer is a string occurring at the tail of most messages.
Messages can be a DataFrame or a Series
"""
if isinstance(messages, pd.DataFrame):
messages = messages["Body"]
# sort in lexical order ... | c885f871c04a308bf0be0a549ddbe510055e57b0 | 3,606,002 |
def complexity_tolerance(
signal, method="maxApEn", r_range=None, delay=None, dimension=None, show=False
):
"""**Automated selection of tolerance (r)**
Estimate and select the optimal tolerance (*r*) parameter used by other entropy and other
complexity algorithms.
Many complexity algorithms are bu... | cfba5d97ab4eb91883a4cb4d4d57b7d480f5e99a | 3,606,003 |
def min(X, s):
"""
Compute element-wise min(x,s) assignment for sparse or dense matrix.
:param X: The input matrix.
:type X: :class:`scipy.sparse` of format csr, csc, coo, bsr, dok, lil, dia
or :class:`numpy.matrix`
:param s: the input scalar.
:type s: `float`
"""
if sp.isspmatrix(X... | 3f7a7a71435bacb18b70fd4aaaa64eb231b81fd3 | 3,606,004 |
import re
def empty_template(pattern, template):
"""F() to extract all {words} from the template using pattern"""
template = re.sub(pattern, "{}", template)
return template | b62592a449ce38971cc81083928cfd034be1984b | 3,606,005 |
from urllib import urlretrieve
from Queue import Queue
import socket
def dlmany(urls, fnames, nprocs=10, callback=None, validfunc=os.path.exists, checkexists=0, timeout=None):
"""Downloads many images simultaneously, `nprocs` at a time.
Handles many error cases, eg, downloads to a tempfname and atomically
... | aa31bec1c2104803e112f0f733799800eb36275b | 3,606,006 |
def generate_public_authfile(vo_data, legacy=True):
"""
Generate the Xrootd authfile needed for public caches
"""
if legacy:
authfile = "u * /user/ligo -rl \\\n"
else:
authfile = "u * \\\n"
id_to_dir = defaultdict(list)
public_dirs = []
for vo_name, vo_data in vo_data.v... | 3e9900c6fdcb4a5781019839ceb51b8041ec2b8c | 3,606,007 |
def unpack_params(handler):
"""Unpacks the queries from the body of the header
Parameters
----------
handler: tornado.web.RequestHandler
Handler for incoming request to collection
Returns dict
-------
Unpacked query in dict format.
"""
if isinstance(handler, tornado.web.... | 965a7b6568e30e9ab7b1dc4adb4d2c253910a917 | 3,606,008 |
import torch
def aug(image, preprocess):
"""Perform AugMix augmentations and compute mixture.
Args:
image: PIL.Image input image
preprocess: Preprocessing function which should return a torch tensor.
Returns:
mixed: Augmented and mixed image.
"""
ws = np.float32(
np.random.dirichlet([arg... | 988a3aa08df883f32ed9227be8bc430f61dc71e6 | 3,606,009 |
import shlex
def _cropped_pdf_page(pdf_path, page):
"""Extract a page of the specified PDF as an _SVG."""
lines = _run_command(
[
"inkscape",
"--pdf-poppler",
f"--pdf-page={page}",
"--query-width",
"--query-height",
"--export-pla... | 18bd92a24abfd95c840d720ddd2356ba997dcec1 | 3,606,010 |
def _get_auth_token(request: Request, auth_type):
"""Extract the Bearer token from the 'Authentication' header"""
header = get_authorization_header(request)
split = header.split()
if len(split) == 0:
return None
elif len(split) != 2 or split[0].lower() != auth_type:
raise exceptions.... | 0f239cd4f19dfb8e88d4108f2434ab10257e571d | 3,606,011 |
import pickle
def read_pickle(file_name):
"""Reload the dataset"""
with open (file_name,'rb') as file:
return pickle.load(file) | 404d578de68db726e14f6214aed3e512a9abf947 | 3,606,012 |
import re
def duration_to_seconds(duration):
"""
Convert duration string to seconds
:param duration: as string (either 00:00 or 00:00:00)
:return: duration in seconds :class:`int` or None if it's in the wrong format
"""
if not re.match("^\\d\\d:\\d\\d(:\\d\\d)?$", duration):
return Non... | 25340e85fdc2db03eaa65aba60a158f951da389a | 3,606,013 |
def returnTF():
"""Load the image transformer."""
tf = trn.Compose(
[
trn.Resize((224, 224)),
trn.ToTensor(),
trn.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]),
]
)
return tf | a4f4bcda309d5b65bc622ef87ee10cf1292187de | 3,606,014 |
def get_list_items(name, index, index_end='', to_num=False, to_str=False):
""" Get one or any of list items
Args:
name (`list`): list data
index (`int`): number of index for list to get
index_end (`int`): end number of index for list to get
to_num (`bool`): fl... | f96acb0f1cc661fb66774eaeeb4842cb96ff77c2 | 3,606,015 |
import torch
def h_normal_gpytorch(s):
""" Entropy of a normal distribution """
return torch.log(s * (2 * np.e * np.pi) ** 0.5) | bd43d55cfeb92d1e908f9c23fcc6bc2bf29ed7e0 | 3,606,016 |
def get_task(task_id):
""" Get one task
:param task_id:
:return: task
"""
global tasks
try:
task_id = int(task_id)
except ValueError:
return None
return tasks[task_id] if task_id in tasks else None | e011db4998083f148ab2aaa4ca10ebc7dd3b0298 | 3,606,017 |
def zscore(col: Series) -> Series:
"""Calculates zscore for column"""
zscore_col = (col - col.mean()) / (col.std(ddof=0))
return np.trunc(zscore_col * 100) / 100 | cd98e76c6012bac45ed65e45c4f37df7ef946c5a | 3,606,018 |
from sys import path
def setup_dir_is_not_exists(filename):
"""
:param filename:
:return:
"""
directory = path.abspath(path.normpath(path.dirname(filename) + sep + 'report'))
if not path.exists(directory):
makedirs(directory)
return directory | 89f0ca11c355154edc2a091a13f3e4b237dbb323 | 3,606,019 |
from typing import Set
from typing import Tuple
import socket
import time
def ping(addresses: Set[str]) -> Set[Tuple[str, float, headers.ip]]:
"""
Send an ICMP ECHO REQUEST to each address
in the set addresses. Then return a set which
contains all the addresses which replied and
which have the cor... | 721b7c79a22d101d2bed19b2f559b3b4a19e443e | 3,606,020 |
def flatten_tests(test_classes):
"""
>>> test_classes = {x: [x] for x in range(5)}
>>> flatten_tests(test_classes)
[(0, 0), (1, 1), (2, 2), (3, 3), (4, 4)]
>>> test_classes = {x: [x + 1, x + 2] for x in range(2)}
>>> flatten_tests(test_classes)
[(0, 1), (0, 2), (1, 2), (1, 3)]
"""
te... | 332b98ab499ff53ba974d51ac862e7015f616e64 | 3,606,021 |
def count_wallpapers(arg):
"""
Counts all the wallpaper associated with given category
creates list of all the links in the pagination of given wallpaper category
:param arg: search query from user
:return: wallpaper count and list of links
"""
try:
main_html = send_request(arg)
... | cc78ebe2060f59c68994fb709ade6104954e0d43 | 3,606,022 |
def clues_too_many(text: str) -> bool:
""" Check for any "too many connections" clues in the response code """
text = text.lower()
for clue in ("exceed", "connections", "too many", "threads", "limit"):
# Not 'download limit exceeded' error
if (clue in text) and ("download" not in text) and (... | 0d105985d7eb032668ad8b08704658846da725b7 | 3,606,023 |
def get_maestral_pid(config_name: str) -> int | None:
"""
Returns the PID of the daemon if it is running, ``None`` otherwise.
:param config_name: The name of the Maestral configuration.
:returns: The daemon's PID.
"""
return maestral_lock(config_name).locking_pid() | 0ab25f7a6f99bbd037eacfcb91c4f944208ab55a | 3,606,024 |
def FZStaeckel(u,v,pot,delta): #pragma: no cover because unused
"""
NAME:
FZStaeckel
PURPOSE:
return the vertical force
INPUT:
u - confocal u
v - confocal v
pot - potential
delta - focus
OUTPUT:
FZ(u,v)
HISTORY:
2012-11-30 - Written - Bovy ... | 898214f2255ae94ae3f0691b8d85984ff9993dfb | 3,606,025 |
import re
def sent_from_wordlist(elements):
""" Convert a list of word_texts to a spacy sentence """
text = " ".join(elements)
text = re.sub(r"[\n\s]+", " ", text)
text = re.sub(r"\s+([,\.\!\?])", r"\1", text)
sent = next(islice(nlp(text).sents, 0, None))
return (None, None, sent.root.lemma... | 0633cf9462744af612873f719a4a80a337f99d2d | 3,606,026 |
import pathlib
def create_feed_data(directory, height, width):
"""
Create batchs of feeding data by going directly
to the images. Labels are generated by the file
structure.
INPUT: Directory of images. The directory should
be structured as below:
Parent
|- Training
| |- Label
... | d0620a3a1947460df27df9744494d080977d0dfa | 3,606,027 |
def pyUtils():
"""
Exposing Spark PythonUtils
spark/core/src/main/scala/org/apache/spark/api/python/PythonUtils.scala
"""
return _curr_jvm().PythonUtils | 2456401a9a4c25670e74e1df72c346ccdccb6be7 | 3,606,028 |
import warnings
def flops(show=True):
"""
Decorator function which measures the FLOPs used by the decorated function and prints it to
stdout. The function relies on the availability of the PAPI_DP_OPS event. If the kernel does
not support this event, a warning is printed and the function is simply exe... | 22fd158e163232851eadbbce03a3a486c359c260 | 3,606,029 |
def lime_predictor(explainer, dict_mapping, feature_names, data_point, predictor):
"""
Creates an Explanation on given datapoint
Arguments:
explainer: lime object, A Lime explainer created while training
dict_mapping: dict, mapping dictionary of categorical columns
feature_names: lis... | 7ffcc38dd40c769d1e232ccdc888029683e02943 | 3,606,030 |
def _Candlestick(kwargs):
"""股价蜡烛图"""
df = kwargs.get('df')
limit_start = kwargs.get('limit_start')
limit_end = kwargs.get('limit_end')
data = df.loc[limit_start:limit_end, :]
hovertext = _get_date_hovertext(data)
trace = go.Candlestick(
x=np.arange(data.shape[0]),
open=data.... | 1116616a8332e4d28a4c6ecb7931451fbda7f805 | 3,606,031 |
def k_boltzmann(dlstr):
"""Return value of Boltzmann constant in current DL units
Args:
dlstr (string): "ev" | 'kJ" | "kcal" | "k" | "internal"
Returns:
Boltzmann constant in the relevant units
"""
key = dlstr.lower()
label = Label("k_b", "Boltzmann Constant", None)
if key == "... | 85dfbdc12d6b2d5d6e5dfd8e7efb871736f13a6e | 3,606,032 |
def get_srr(text, all=False, sep=None):
"""
Returns a list of SRR data.
"""
logger.info(f"searching ENA for {text}")
url = ENA_REPORT
if all:
fields = get_ena_fields()
else:
fields = [
'run_accession',
"sample_accession",
'first_public',
... | 0f8c5e54aee5e2f1cea2bbfeff61a94f36fbfdc5 | 3,606,033 |
import functools
def rgetattr(obj, attr, *args):
"""Get attribute recursively.
Nested attribute is specified as `a.b`.
"""
def _getattr(obj, attr):
return getattr(obj, attr, *args)
return functools.reduce(_getattr, [obj] + attr.split('.')) | 6e69a6730f6f3a5e305d90c77a7895379244d43c | 3,606,034 |
def prepare_job_links(soup):
"""Prepare list of job links from header titles"""
job_links = []
results = soup.select('div[class*="jobsearch-SerpJobCard unifiedRow"]')
for i in range(len(results)):
job_link = f"{URL_PREFIX}{results[i].h2.a['href']}"
job_links.append(job_link)
return j... | a0da2618ba91734855268bab8ff435f384613ed7 | 3,606,035 |
def load_vocab(filename: str):
"""
load vocabulary from given dataset file
"""
with open(filename, 'r', encoding='utf-8') as f:
text = f.read().strip().split('\n')
text = [word.split(' ') for word in text]
vocab_dict = {word[0]: word[1:] for word in text}
vocab_dict = {k: [float(d) f... | fe11e129439173ba13ca276c788c0f27053f5e6a | 3,606,036 |
def make_surrogate(data, method="rp"):
"""
Args:
data (ndarray): A one-dimensional time series
method (str): "rs" or rp"
Returns:
surr_data (ndarray): A single random surrogate time series
Todo:
Add ensemble function
"""
if method == "r... | 605f5094856f09bcecc60d1f7a007fd30cc4fcdc | 3,606,037 |
def HomeHandler():
"""
"""
return render_template('index.html') | 2b77c1ab00c67792512789db3f55788a0589d31d | 3,606,038 |
def BinomialBinArray(pvalues, x_ar, bin_num, use_zeros = True):
"""
Inputs:
Outputs:
"""
pmax = np.amax(pvalues)
pmin = np.amin(pvalues)
bin_width = (pmax-pmin)/float(bin_num)
bin_n = np.zeros(bin_num, dtype=float)
bin_mean = np.zeros(bin_num)
bin_error = np.zeros(bin_... | eba52ed5922f801da1a3e2567ad7741a9ed7fe2b | 3,606,039 |
import argparse
import os
def define_and_process_args():
""" Define and process command-line arguments.
Returns:
A Namespace with arguments as attributes.
"""
description = main.__doc__
formatter_class = argparse.ArgumentDefaultsHelpFormatter
parser = argparse.ArgumentParser(descript... | e15a3e62aad7eb10da6839bb12e929cb0444d910 | 3,606,040 |
import re
def normalize_whitespace(s: str) -> str:
"""Convert all whitespace (tabs, newlines, etc) into spaces."""
return re.sub(r"\s+", " ", s, flags=re.MULTILINE) | 6d8b65bcdca9838aa0f4d16d158db5d2218cbf24 | 3,606,041 |
from typing import Counter
def joint_refine_all(hpo_data, final_loci, cs_val=0.95, cnv_cov=None,
jac_cutoff=0.8, ncase_dict={}, cs_merge_buffer=200000):
"""
Wrapper to call joint_refinement() on all multi-HPO clusters
"""
for members in final_loci.values():
n_members = l... | ea88c99bae1e169fd5bfe4983f6b64be8f4cfe95 | 3,606,042 |
import os
import glob
def find_granule_metafiles_in_SAFE(inSAFE, tile_glob_pattern='*', tile_name=None):
"""Find granule metadata files in SAFE
Paramters
---------
inSAFE : str
path to .SAFE folder
tile_glob_pattern : str, optional
granule glob search pattern
e.g. '32???'
... | 8aed455fd01e9b74ec870ad6e4646521bc4cbe40 | 3,606,043 |
import errno
def net_if_stats():
"""Get NIC stats (isup, duplex, speed, mtu)."""
names = net_io_counters().keys()
ret = {}
for name in names:
try:
mtu = cext_posix.net_if_mtu(name)
isup = cext_posix.net_if_flags(name)
duplex, speed = cext_posix.net_if_duplex... | a8f599d75aff1baca753e11498a48bd6f5bcc50a | 3,606,044 |
def ode(Y,T,K):
"""
Ordinary differential equation system for a pendulum.
"""
th, om = Y
DYDT = [om, -g/l*np.sin(th)-K*(om)]
return DYDT | b80d60892f486778c341628dd8060ecfac351392 | 3,606,045 |
def tmp_notebook(tmp_path):
""" make an empty python notebook on disk
"""
notebook = nbformat.v4.new_notebook()
notebook.metadata["kernelspec"] = {"name": "python3"}
nb_path = tmp_path / "Untitled.ipynb"
nb_path.write_text(nbformat.writes(notebook))
return nb_path | 4837235eb77b7fe6a5bd00301994f28a06b88da8 | 3,606,046 |
def CTW_cc_nubar():
"""Fixture for forming a neutrino with charged-current CTWInteraction"""
return Particle(particle_id=Particle.Type.antielectron_neutrino,
vertex=[100, 200, -500], direction=[0, 0, 1], energy=1e9,
interaction_model=CTWInteraction,
in... | 140fd50cbe83d3999741992eb437d9d0ceeb52e7 | 3,606,047 |
def job_delete(jobId):
"""
Delete a saved job
RouteParams:
jobId: the id of a job
GetParams:
account: an account
user: a user
code: the new code for the job
Returns:
a json representation of a job
"""
account = request.form['account']
user = requ... | 682911a05622b0d7b2e8d4cd810ed5854dc8512b | 3,606,048 |
def set_dist_names(spc_dct_i, saddle):
""" Set various things needed for TSs
"""
dist_names = []
if saddle:
dist_names = []
mig = 'migration' in spc_dct_i['class']
elm = 'elimination' in spc_dct_i['class']
if mig or elm:
dist_names.append(spc_dct_i['dist_info... | cb5f72b3d00efb8272f7b5012f776bbd63e38634 | 3,606,049 |
def sort_and_save(summary_dfs):
"""
Takes the summary dfs that merely need sorted. Uses info from the sort_no_further_analysis var to know which dfs to
process
:param summary_dfs: dict of dfs holding summaries on the answers to each question
:return: a better ordered dict of dfs holding summaries on... | bfaec2f793e86904c0cf85cb60cbc07a7eff0416 | 3,606,050 |
import scipy
def applyMedianFilter(obj):
"""Performs a median filter on the array with the specified diameter"""
diameter, array = obj
return scipy.signal.medfilt2d(array, diameter) | 9e3b4c1c4750e3f054e512f2fe93580280614abd | 3,606,051 |
def get_session(autocommit=True, expire_on_commit=False):
"""Helper method to grab session"""
global _ENGINE
global _MAKER
if not _MAKER:
if not _ENGINE:
_ENGINE = create_engine(FLAGS.sql_connection,
pool_recycle=FLAGS.sql_idle_timeout,
... | 4e621924d1325e2c152bec158cc3caa92c8e5c9e | 3,606,052 |
import torch
def Quantizer_train(x, basis, level_codes, thrs_multiplier, nbit=2, training=False):
"""
Quantize weight.
Args:
x (torch.Tensor): a 4D tensor. [K x K x iC x oC] -> [oC x iC x K x K]
Must have known number of channels, but can have other unknown dimensions.
basis (t... | c427fab45cc7f2e5e8ae22ed14808b98b53068f6 | 3,606,053 |
def _mom_cyclic(g_step_op, base_mom=None, max_mom=None, step_size=None, gamma=0.99994, mode='triangular',
one_cycle=False, op_name=None):
"""Computes a cyclic momentum as in https://arxiv.org/abs/1803.09820. Notice we leave triangular2 and exponential ena-
bled but we do not know if this types o... | bc4bc380cb4d167ab73862e7e2d76cfd849535e6 | 3,606,054 |
def balance_error(request, pk):
""" Muestra la plantilla balance_error.html, con opciones para la corrección
de un saldo erróneo."""
cta = Account.objects.get(pk=pk)
return render(
request,
'finper/balance_error.html',
{
'request': request,
'cta': cta,... | 7a76041931f738ad9d0e47cafa3ea53d2635feaa | 3,606,055 |
import hashlib
def generate_edge_tablename(src_label, label, dst_label):
"""Generate a name for the edge table.
Because of the limit on table name length on PostgreSQL, we have
to truncate some of the longer names. To do this we concatenate
the first 2 characters of each word in each of the input arg... | 4c0d81ae53932e632649620e8f6a575e27ff072c | 3,606,056 |
from typing import Tuple
def timedelta_to_human_range(s: pd.Series) -> Tuple[pd.Series, str]:
"""Convert a pandas Series of timedeltas to a pandas Series of floats,
and derive a time unit (a string such as "years" or "minutes") that gives a nice human readable range of floats.
For example:
>>> import... | c9ebcb57a3495d7416abee08c8fd4a63429673b2 | 3,606,057 |
async def async_subscribe_to_server_originated_rpc_notification(
connection,
callback,
name,
arguments=[],
timeout_seconds=5,
defaults={},
role=RPC_ROLE_GENERIC,
session_title_display_name=None,
session_title_unique_id=None,
status_bar_comp... | 628c0fc5a419c3c89c64b5b3fb8ea9dfcb50e27b | 3,606,058 |
import time
def WaitForSigStr(serialPort, MinSigStr, Timeout):
""" Checks receive signal strength for specified time returning true when above min level or false when timeout."""
signalStr = 0
timeout = time.time() + Timeout # Set the timeout time
while time.time... | 0b30e1b3da91caadae06933b73c99ba628ba3824 | 3,606,059 |
def layer_norm(layer_inputs, hidden_size):
"""Implements layer norm from [Ba et al. 2016] Layer Normalization.
See eqn. 4 in (https://arxiv.org/pdf/1607.06450.pdf).
Args:
layer_inputs (tensor): The inputs to the layer.
shape <float32>[batch_size, hidden_size]
hidden_size (int): Dimensionality of t... | 2bc3bb741e5828c9478bfb8151292b3d0a8a6e02 | 3,606,060 |
def fit_loss(ac, fit):
"""Loss of the fit """
r = ac - fit
error = sum(r ** 2) / sum(ac ** 2)
return error | 00d41891dea7d914299d87d971fb2a41df2109ed | 3,606,061 |
from openeye import oechem, oedocking
from openeye import oequacpac
from openeye import oeomega
def dock_molecule_to_receptor(molecule, receptor_filename, covalent=False):
"""
Dock the specified molecules, writing out to specified file
Parameters
----------
molecule : oechem.OEMol
The mol... | 0848e7755a1e1a2a9153b62c11080920482d11af | 3,606,062 |
def dbus_variant_dict(dct):
"""
Build a dictionary with :class:`gi.repository.GLib.Variant` values, so it
can be used to create DBus types a{sv} objects.
"""
return {k: dbus_variant(v) for k, v in dct.items()} | e188728cf1d35db79c7597ea246a31a20fcbfffc | 3,606,063 |
def parse_condition_expression_to_tree(condition_expression: str) -> Tree:
"""
Parse a given condition expression with the help of the here defined grammar to a lark tree.
The grammar starts with condition keys, e.g. [45] and combines them with
and _/or_compositions corresponding to U/O operators or wit... | f9788fa63a803c94be483f6067a73f0572106841 | 3,606,064 |
def growth_pos_check(clods, pos):
"""for checking the position of a growing seed tip
Like position_calc but amended for growing seed
each time the seed grows there is a cheek for clod collisions
:param clods: All the clod objects in the bed
:param pos: The proposed position of the seed tip
:retu... | 743455907cc81dc3950db202b4f23a79c1eafd33 | 3,606,065 |
def comp_height_wind(self):
"""Compute the height of the winding area
Parameters
----------
self : SlotW14
A SlotW14 object
Returns
-------
Hwind: float
Height of the winding area [m]
"""
Rbo = self.get_Rbo()
# alpha is the angle to rotate P0 so ||P1,P10|| = ... | 1d7f8e87c90c7fea8eef4d4688e9f7a071643544 | 3,606,066 |
from typing import MutableSequence
def aslist(l): # type: (Any) -> MutableSequence[Any]
"""
Convenience function to wrap single items and lists.
Return lists unchanged.
"""
if isinstance(l, MutableSequence):
return l
else:
return [l] | edc375644b1e33bb6d7cc0499bba1b89dbbcfb62 | 3,606,067 |
import os
def dwritef(d, dirname=None, basename=None):
"""The dwritef() function pickles the dictionary pointed to by @p d
to the file whose directory and filename portions are pointed to by
@p dirname and @p basename, respectively. The directory at @p
dirname, as well as any intermediate directories, are re... | 365d5ef40db2649d42a91e1b757313d539f50e9a | 3,606,068 |
def determine_letter(current_score):
"""
Calculates the letter grade for a given score
:param current_score: the score to be evaluated
:return: the letter grade that score falls within
"""
if current_score >= 90:
return "A"
elif current_score >= 80:
return "B"
elif curren... | 324aaa8e28a0cbc298410ecd83ea4eee6d39a970 | 3,606,069 |
from typing import Tuple
from typing import Dict
def parse_icf(icf_file: str) -> Tuple[Dict, Dict]:
"""Parse ICF linker file.
ST only provides .icf linker files for many products, so there is a need
to generate basic GCC compatible .ld files for all products.
This parses the basic features from the .... | ddc1288603d0697bf915eb82a712f210f54efacd | 3,606,070 |
import os
def combine(params, recipe, infiles, math='average', same_type=True):
"""
Takes a list of infiles and combines them (infiles must be DrsFitsFiles)
combines using the math given.
Allowed math:
'sum', 'add', '+'
'average', 'mean'
'subtract', '-'
'divide', '/'
... | 49bf2dd467b0e7bd211174c9de066b0d90553c6d | 3,606,071 |
def scatter_figure(
coords: pd.DataFrame, title: str, img: str, img_x: float, img_y: float, img_sizex: float, img_sizey: float
) -> Figure:
"""Extracts the three coordinates from the dataframe and create a 2D scatter plot, which is overlayed on the top of
the top-down view of the game scene with the image p... | 2d8c4342d3959ca7646fedfc810cdceff2cc4d77 | 3,606,072 |
from typing import Iterator
def variables(value: SupportsVariables) -> Iterator[Variable]:
"""Return an iterator of the variables in this object.
The same variable may be yielded in any order and may appear multiple
times. If uniqueness is desired, store the results in a set::
vars = set(variabl... | ed2f3ec6c52e01a8cc66a24ee0aa98b8fe46e844 | 3,606,073 |
def get_vars(host):
"""
parse ansible variables
- defaults/main.yml
- vars/main.yml
- vars/${DISTRIBUTION}.yaml
- molecule/${MOLECULE_SCENARIO_NAME}/group_vars/all/vars.yml
"""
base_dir, molecule_dir = base_directory()
distribution = host.system_info.distribution
... | ddedabc49841354809c1e4a64695ae757ca8f710 | 3,606,074 |
def jit_attr_none(func, kls=_internal_jit_attr):
"""
Version of :py:func:`jit_attr` decorator that forces the uncached_val
to None.
This is mainly useful so that if any out of band forced regeneration of
the value, they know they just have to write None to the attribute to
force regeneration.
... | dceeb78b381486f2ae43cca71f3a81bd51dbceff | 3,606,075 |
import collections
def _separateByFormType(d):
""" Organize form elements into a manageable collection
Turn empty dicts into None so that forms render properly
Nonrepeating fields (fields that can't be repeated into multiple forms) are:
identifier, identifier-identifierType, language, publ... | 7676aee613ce0f3f257b2f06694a62718dab47ca | 3,606,076 |
def translate(word):
"""
translates third person words into first person words
"""
forms = {"is" : "am", 'she' : 'I', 'he' : 'I', 'her' : 'my', 'him' : 'me', 'hers' : 'mine', 'your' : 'my', 'has' : 'have'}
if word.lower() in forms:
return forms[word.lower()]
return word | ac433a4db5154c065e2cec1263976dba72863ad8 | 3,606,077 |
def advance_flatten(cursors: list[Cursor], pat: Pat) -> list[Cursor]:
"""Convenience function to advance a list of cursors."""
ret = []
for c in cursors:
ret.extend(c.advance(pat))
return ret | fb3fa007c460652d60ff57e25dbbc15bd168468e | 3,606,078 |
def pca_embedded_data_frame(df: pd.DataFrame, n_components=0.9, verbose: bool = False):
"""
Embed all observations of a bearing time series using PCA.
:param df: Data frame which contains computed features or raw features.
:param n_components: Number of components to be learned from PCA
:return: PCA... | c6d79e9bd49e330bdfcbba3240011a8c02bacd6d | 3,606,079 |
from typing import Union
from typing import List
def loot(loot_id=0) -> Union[Loot, List[Loot], bool]:
"""Returns information about the loot.
Endpoint
--------
https://www.nitrotype.com/index/624/bootstrap.js
Parameters
----------
loot_id : int
The loot to access from the boo... | 8da618a0166b305a3398cacbb73dbe507c067d58 | 3,606,080 |
import math
def cal_summary_and_weight(comments):
"""
计算评论内容的摘要及其对应权重
:param comments: 需要分析的评论列表
:return: 返回列表,列表元素为元组,元组中包含摘要和其对应的权重
"""
d = {}
ret = []
for c in comments:
nlp = SnowNLP(c.content)
# 评论获赞数越多,权重越高,取对数来平滑极差
w = int(math.log(c.votes + 1) + 1) ** 2... | f58b8bef624f0ad2d670747be6042baf7505a4b7 | 3,606,081 |
def dateToEvent(date, schemakey):
"""
return birthDate and deathDate schema.org attributes
don't return deathDate if the person is still alive (determined if e.g. the date looks like "1979-")
"""
if '-' in date:
dates = date.split('-')
if date[0] == '[' and date[-1] == ']': # oh..
... | c1e0d11de3e8b2b4240cc34006de1fc3b3b40581 | 3,606,082 |
def weekly_stats(
contours: gpd.GeoDataFrame, start: date, end: date, chirps_dir: str
) -> pd.DataFrame:
"""Compute weekly precipitation aggregation statistics.
Parameters
----------
contours : GeoDataFrame
Contours geodataframe with a geometry column (EPSG:4326).
start : date
S... | 99c21657a5992c4ecc18e2533fc5bc4dcd036b79 | 3,606,083 |
def sample_feature(df_row, id_column, df_columns, crs, res, all_touched, meta, frac, min_frac_area, feature_array=None):
"""
Samples polygon features
Args:
df_row (pandas.Series)
id_column (str)
df_columns (list)
crs (object)
res (tuple)
all_touched (bool)
... | 6552a713f298a1b076822c6ac5311b7fffcc4fe1 | 3,606,084 |
def normalize_attribute(attr):
"""
Normalizes the name of an attribute which is spelled in slightly different
ways in paizo HTMLs
"""
attr = attr.strip()
if attr.endswith(':'):
attr = attr[:-1] # Remove trailing ':' if any
if attr == 'Prerequisites':
attr = 'Prerequisite' # N... | 2cb66878547ee8a98c14bf08261f2610def57a37 | 3,606,085 |
import nipype.interfaces.fsl as fsl
import nipype.interfaces.utility as niu
import nipype.pipeline.engine as pe
from nipype.workflows.data import get_flirt_schedule
from nipype.workflows.dmri.fsl.artifacts import _xfm_jacobian
from nipype.workflows.dmri.fsl.utils import (
extract_bval,
recompose_dwi... | c0c24e6be62aa65735de3068824a48f9ccb75d8c | 3,606,086 |
from mxnet.contrib import onnx as onnx_mxnet
import onnx
import os
import json
def convert_onnx_model(model_path, onnx_file):
"""
Util to convert onnx model to MXNet model
:param model_path:
:param onnx_file:
:return:
"""
model_name = os.path.splitext(os.path.basename(onnx_file))[0]
sy... | 4400280314b0e471e36501d10c7538c24cc394ca | 3,606,087 |
def vector2cdl(vector):
"""Make a CDL string representation of a numeric 1D array."""
dtype = vector.dtype
def normalize(x):
"""Normalize a single value for CDL"""
if dtype == 'int16':
s = '{}s'.format(x)
elif dtype == 'int32':
s = str(x)
elif dtype =... | 3455670d27737eec9c9a5fc871d62b7ea4d2bb0e | 3,606,088 |
from typing import Optional
def _value_serde(serde, if_not_found=None):
""" inner function """
origin_serde = origin(serde)
if isinstance(origin_serde, list) or isinstance(origin_serde, tuple):
if len(origin_serde) == 2:
return Optional(of(origin_serde[1]))
else:
ra... | f15024c3f037156d0fe99fbb5435aacdd3c24216 | 3,606,089 |
def get_normal_vector(points: np.ndarray):
"""
Note: Direction of normal vector depends on right hand rule.
p0, p1, p2 = points
v01, v12 = p1 - p0, p2 - p1
"""
if points.shape != (3, 3):
logger.error(f"Received points matrix of size {points.shape}. Expected (3, 3).")
raise Except... | d561ad03c57efbee4a6dbeeccab22b3f9977ee25 | 3,606,090 |
def getPrefices(fileList, transferType, experiment):
""" Get the old/newPrefices as a dictionary needed for the SURL to TURL conversions """
# Format:
# prefix_dictionary[surl] = [oldPrefix, newPrefix]
# Note: this function returns oldPrefix, newPrefix, prefix_dictionary
# old/newPrefix are the fi... | a587a1e9b63a57684583b537d79a9529d8b1ee0c | 3,606,091 |
def is_lyrics_content_ok(title, text):
"""Compare lyrics text to expected lyrics for given title"""
setexpected = set(LYRICS_TEXTS[lyrics.slugify(title)].split())
settext = set(text.split())
setinter = setexpected.intersection(settext)
# consider lyrics ok if they share 50% or more with the referen... | e7e4e231081526cd560d8309d5cce429971a75dc | 3,606,092 |
def simdiag(ops, evals: bool = True, *,
tol: float = 1e-14, safe_mode: bool = True):
"""Simultaneous diagonalization of commuting Hermitian matrices.
Parameters
----------
ops : list/array
``list`` or ``array`` of qobjs representing commuting Hermitian
operators.
evals ... | d64be987216a9bd8d67c9a9b733fbba160c808f8 | 3,606,093 |
def black_clip_from_clip(clip, **blank_clip_args):
"""Creates a clip of black color in the same format as the passed in clip.
Unlike BlankClip, this takes the passed in clip's color range into account
by rendering the first frame.
"""
bit_depth = clip.format.bits_per_sample
is_integer = (clip.fo... | 9ed0ac06c2121bdeaad47c14f147afe8ed51071f | 3,606,094 |
import warnings
def vmap(map, v):
"""Transform coordinates while handling RuntimeWarning
that could be raised by NumPy when trying to transform
a zero in logarithmic scale for example"""
with warnings.catch_warnings():
warnings.simplefilter("ignore", category=RuntimeWarning)
output =... | 2d525e9de47aef7ccfb6cac120c886966d2be2ab | 3,606,095 |
def palindrome(data):
"""
:param data: image data as array
:return: score referring to what extent the structure of the two image halves is symmetrical
"""
# loop over both lists simultaneously and if the counts are equal, add True, else, add False
# lastly, divide the amount of Trues by the le... | fb086c94b821e39c10eb246c566e3db35b9328cb | 3,606,096 |
def bi_latest_parent_date_modified(vc_dir, parentname):
"""
given a path to a version control directory of build instructions and the
name of the parent model, return the parent model's revision date
"""
newest_bi = newest_file(vc_dir)
meta = read_meta_data(newest_bi)
# with open (newest_bi)... | 8ecda12c5c97f767b1b4da4d72d6bd6a6034a5e4 | 3,606,097 |
from typing import List
from sys import path
def save_images(images: List[np.ndarray], directory: str = 'new_img/') -> List[str]:
"""
Creates folder if there is none and saves all the images in the list
:param name: Name of person in image
:param images: List of images
:param directory: directory ... | 4d610a03aa17c940edec8672652f402875372774 | 3,606,098 |
def version(format_str='{short}'):
""" Returns current version number in specified format.
:param format_str: format string for the version
:type format_str: str
:return: version number in the specified format
:rtype: str
"""
major, minor, patch = version_numbers()
format_dict = ... | 15d2ea477460f7208863f673e64bf2f316054a43 | 3,606,099 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.