content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def add_counter_text(img, box_shape, people_in):
"""
Add person counter text on the image
Args:
img (np.array): Image
box_shape (tuple): (width, height) of the counter box
people_in (int): Number representing the amount of
people inside the space
Returns:
(n... | ca182338a7dc11596b8375d788036d5de50381e2 | 3,837 |
def create_override(override):
"""Takes override arguments as dictionary and applies them to copy of current context"""
override_context = bpy.context.copy()
for key, value in override.items():
override_context[key] = value
return override_context | 25ecb761d8e9225081752fef10d2a6a885ba14d2 | 3,838 |
import json
def load_or_make_json(file, *, default=None):
"""Loads a JSON file, or makes it if it does not exist."""
if default is None:
default = {}
return __load_or_make(file, default, json.load, json.dump) | 3045cf141d26313fe8ffe60d6e74ff7af18ddce2 | 3,840 |
import warnings
def plot_predictions(image, df, color=None, thickness=1):
"""Plot a set of boxes on an image
By default this function does not show, but only plots an axis
Label column must be numeric!
Image must be BGR color order!
Args:
image: a numpy array in *BGR* color order! Channel ... | c666b1a92eefbc04abc7da1c3a4bc6cccde93769 | 3,841 |
from sympy import solveset, diff
from re import S
def stationary_points(f, symbol, domain=S.Reals):
"""
Returns the stationary points of a function (where derivative of the
function is 0) in the given domain.
Parameters
==========
f : Expr
The concerned function.
symbol : Symbol
... | 21011d7925c136de43f962a56edd5ffcc09c144f | 3,842 |
def _create_table(data_list, headers):
""" Create a table for given data list and headers.
Args:
data_list(list): list of dicts, which keys have to cover headers
headers(list): list of headers for the table
Returns:
new_table(tabulate): created table, ready to p... | d072857776c16128808b7e2b4b64075cc4894199 | 3,843 |
def _validate_attribute_id(this_attributes, this_id, xml_ids, enforce_consistency, name):
""" Validate attribute id.
"""
# the given id is None and we don't have setup attributes
# -> increase current max id for the attribute by 1
if this_id is None and this_attributes is None:
this_id = ma... | e85201c85b790576f7c63f57fcf282a985c22347 | 3,844 |
def Arrows2D(startPoints, endPoints=None,
shaftLength=0.8,
shaftWidth=0.09,
headLength=None,
headWidth=0.2,
fill=True,
c=None,
cmap=None,
alpha=1):
"""
Build 2D arrows between two lists of points `startPoints... | d2276def355c56c6fe494c29bab04cd6f1e28221 | 3,845 |
def filter_characters(results: list) -> str:
"""Filters unwanted and duplicate characters.
Args:
results: List of top 1 results from inference.
Returns:
Final output string to present to user.
"""
text = ""
for i in range(len(results)):
if results[i] == "$":
... | 6b2ca1446450751258e37b70f2c9cbe5110a4ddd | 3,846 |
def seq_alignment_files(file1, file2, outputfile=""):
"""This command takes 2 fasta files as input, each file contains a single sequence. It reads the 2 sequences from
files and get all their alignments along with the score. The -o is an optional parameter if we need the output to
be written on a file inste... | b225d97e29040040755cc3f2260b60f90c390bce | 3,847 |
def main(Block: type[_Block], n: int, difficulty: int) -> list[tuple[float, int]]:
"""Test can hash a block"""
times_and_tries = []
for i in range(n):
block = Block(rand_block_hash(), [t], difficulty=difficulty)
# print(f"starting {i}... ", end="", flush=True)
with time_it() as timer... | 27c729604b3f3441e1ceb5f6d6d28f47d64fdb13 | 3,848 |
from typing import Union
from typing import SupportsFloat
def is_castable_to_float(value: Union[SupportsFloat, str, bytes, bytearray]) -> bool:
"""
prüft ob das objekt in float umgewandelt werden kann
Argumente : o_object : der Wert der zu prüfen ist
Returns : True|False
Exceptions : keine... | e3882c0e64da79dc9a0b74b4c2414c7bf29dd6c9 | 3,849 |
from operator import itemgetter
def list_unique(hasDupes):
"""Return the sorted unique values from a list"""
# order preserving
d = dict((x, i) for i, x in enumerate(hasDupes))
return [k for k, _ in sorted(d.items(), key=itemgetter(1))] | 0ba0fcb216400806aca4a11d5397531dc19482f6 | 3,850 |
def filter_by_networks(object_list, networks):
"""Returns a copy of object_list with all objects that are not in the
network removed.
Parameters
----------
object_list: list
List of datamodel objects.
networks: string or list
Network or list of networks to check for.
Return... | 9ffb2cedd1508e5924f3a2894a2f842bc5673440 | 3,851 |
def score_per_year_by_country(country):
"""Returns the Global Terrorism Index (GTI) per year of the given country."""
cur = get_db().execute('''SELECT iyear, (
1*COUNT(*)
+ 3*SUM(nkill)
+ 0.5*SUM(nwound)
+ 2*SUM(case propextent when 1.0 then 1 else 0 end)
+ 2*SUM(case propextent when 2.0 the... | ac8992a0bd2227b7b9f5622b9395e4c7933af35a | 3,853 |
def build(options, is_training):
"""Builds a model based on the options.
Args:
options: A model_pb2.Model instance.
Returns:
A model instance.
Raises:
ValueError: If the model proto is invalid or cannot find a registered entry.
"""
if not isinstance(options, model_pb2.Model):
raise ValueE... | 99fc2f283075091254743a9d70ecab3d7a65066d | 3,854 |
def string_to_rdkit(frmt: str, string: str, **kwargs) -> RDKitMol:
"""
Convert string representation of molecule to RDKitMol.
Args:
frmt: Format of string.
string: String representation of molecule.
**kwargs: Other keyword arguments for conversion function.
Returns:
RDK... | 34803a46d5228644bb3db614aca5580bcb286655 | 3,855 |
from datetime import datetime
def clean_datetime_remove_ms(atime):
"""
将时间对象的 毫秒 全部清零
:param atime:
:return:
"""
return datetime(atime.year, atime.month, atime.day, atime.hour, atime.minute, atime.second) | 94a47ad8802b3eb4d58d332d71bb3d3e0c67d947 | 3,856 |
def perDay(modified):
"""Auxiliary in provenance filtering: chunk the trails into daily bits."""
chunks = {}
for m in modified:
chunks.setdefault(dt.date(m[1]), []).append(m)
return [chunks[date] for date in sorted(chunks)] | ce9fe31c39c9c6c5e0753aa2dc6dc5113fb199e4 | 3,857 |
def login():
"""The screen to log the user into the system."""
# call create_all to create database tables if this is the first run
db.create_all()
# If there are no users, create a default admin and non-admin
if len(User.query.all()) == 0:
create_default_users()
# Redirect the user if a... | 0912dca53b40677da9a9443c4500badf05fff8a8 | 3,859 |
def freight_sep_2014():
"""Find the number of freight of the month"""
for i in fetch_data_2014():
if i[1] == "Freight" and i[4] == "September":
num_0 = i[6]
return int(num_0) | b7f770362f7a85ffc92591a48660d01d7f784dc1 | 3,860 |
def piotroski_f(df_cy,df_py,df_py2):
"""function to calculate f score of each stock and output information as dataframe"""
f_score = {}
tickers = df_cy.columns
for ticker in tickers:
ROA_FS = int(df_cy.loc["NetIncome",ticker]/((df_cy.loc["TotAssets",ticker]+df_py.loc["TotAssets",ticker])/2) > 0)... | 119a3dd426fbe5e8b5106cbebebf4b000799a839 | 3,862 |
from typing import Dict
def evaluate_circuit(
instances: Dict[str, SType],
connections: Dict[str, str],
ports: Dict[str, str],
) -> SDict:
"""evaluate a circuit for the given sdicts."""
# it's actually easier working w reverse:
reversed_ports = {v: k for k, v in ports.items()}
block_diag... | 7dd6d019845dbf7f69c6324143d88d4d48af9dea | 3,863 |
def canonical_smiles_from_smiles(smiles, sanitize = True):
"""
Apply canonicalisation with rdkit
Parameters
------------
smiles : str
sanitize : bool
Wether to apply rdkit sanitisation, default yes.
Returns
---------
canonical_smiles : str
Returns None if canonicali... | 0c4dc4583d9a12439b915412cab8458e380a4e6c | 3,864 |
def get_ref(struct, ref, leaf=False):
"""
Figure out if a reference (e.g., "#/foo/bar") exists within a
given structure and return it.
"""
if not isinstance(struct, dict):
return None
parts = ref_parts(ref)
result = {}
result_current = result
struct_current = struct
... | 61ebb2561c2c79c58c297c91ac266e9e786a5b7f | 3,865 |
def edit_maker_app(
operator,
app_maker_code,
app_name="",
app_url="",
developer="",
app_tag="",
introduction="",
add_user="",
company_code="",
):
"""
@summary: 修改 maker app
@param operator:操作者英文id
@param app_maker_code: maker app编码
@param app_name:app名称,可选参数,为空则不... | abb2d57235e6c231b96182f989606060f8ebb4ab | 3,867 |
def fifo():
"""
Returns a callable instance of the first-in-first-out (FIFO) prioritization
algorithm that sorts ASDPs by timestamp
Returns
-------
prioritize: callable
a function that takes an ASDP type name and a dict of per-type ASDPDB
metadata, as returned by `asdpdb.load_as... | 8f0d24c43a15467c9e6b9f195d12978664867bd3 | 3,868 |
def super(d, t):
"""Pressure p and internal energy u of supercritical water/steam
as a function of density d and temperature t (deg C)."""
tk = t + tc_k
tau = tstar3 / tk
delta = d / dstar3
taupow = power_array(tau, tc3)
delpow = power_array(delta, dc3)
phidelta = nr3[0] * delpow[-1] +... | 937d58264b94b041aafa63b88d5fd4498d4acb8e | 3,869 |
import tty
import logging
import json
def ls(query=None, quiet=False):
"""List and count files matching the query and compute total file size.
Parameters
----------
query : dict, optional
(default: None)
quiet : bool, optional
Whether to suppress console output.
"""
tty.sc... | acbf576170f34cfc09e4a3a8d64c1c313a7d3b51 | 3,870 |
def _create_full_gp_model():
"""
GP Regression
"""
full_gp_model = gpflow.models.GPR(
(Datum.X, Datum.Y),
kernel=gpflow.kernels.SquaredExponential(),
mean_function=gpflow.mean_functions.Constant(),
)
opt = gpflow.optimizers.Scipy()
opt.minimize(
full_gp_model... | bebe02e89e4ad17c5832cfced8f7cd1dce9a3b11 | 3,871 |
def read_file_header(fd, endian):
"""Read mat 5 file header of the file fd.
Returns a dict with header values.
"""
fields = [
('description', 's', 116),
('subsystem_offset', 's', 8),
('version', 'H', 2),
('endian_test', 's', 2)
]
hdict = {}
for name, fmt, num_... | d994f74a889cedd7e1524102ffd1c62bb3764a0f | 3,872 |
def shape_padleft(t, n_ones=1):
"""Reshape `t` by left-padding the shape with `n_ones` 1s.
See Also
--------
shape_padaxis
shape_padright
Dimshuffle
"""
_t = aet.as_tensor_variable(t)
pattern = ["x"] * n_ones + [i for i in range(_t.type.ndim)]
return _t.dimshuffle(pattern) | 44e68fed0ea7497ba244ad83fbd4ff53cec22f24 | 3,873 |
def zad1(x):
"""
Функция выбирает все элементы, идущие за нулём.
Если таких нет, возвращает None.
Если такие есть, то возвращает их максимум.
"""
zeros = (x[:-1] == 0)
if np.sum(zeros):
elements_to_compare = x[1:][zeros]
return np.max(elements_to_compare)
return None | e54f99949432998bf852afb8f7591af0af0b8b59 | 3,874 |
def skopt_space(hyper_to_opt):
"""Create space of hyperparameters for the gaussian processes optimizer.
This function creates the space of hyperparameter following skopt syntax.
Parameters:
hyper_to_opt (dict): dictionary containing the configuration of the
hyperparameters to optimize.... | bdfbc685b5fd51f8f28cb9b308d3962179d15c7e | 3,875 |
import torch
def process_text_embedding(text_match, text_diff):
"""
Process text embedding based on embedding type during training and evaluation
Args:
text_match (List[str]/Tensor): For matching caption, list of captions for USE embedding and Tensor for glove/fasttext embeddings
... | 6f052cc29186f8bcc1598780bf7f437098774498 | 3,877 |
import requests
import json
import base64
def x5u_vulnerability(jwt=None, url=None, crt=None, pem=None, file=None):
"""
Check jku Vulnerability.
Parameters
----------
jwt: str
your jwt.
url: str
your url.
crt: str
crt path file
pem: str
pem file name
... | 0424072951e99d0281a696b94889538c1d17ed81 | 3,878 |
def get_all_interactions(L, index_1=False):
"""
Returns a list of all epistatic interactions for a given sequence length.
This sets of the order used for beta coefficients throughout the code.
If index_1=True, then returns epistatic interactions corresponding to
1-indexing.
"""
if index_1:
... | f8a151e5d44f2e139820b3d06af3995f60945dd2 | 3,880 |
import xml
import math
def convertSVG(streamOrPath, name, defaultFont):
"""
Loads an SVG and converts it to a DeepSea vector image FlatBuffer format.
streamOrPath: the stream or path for the SVG file.
name: the name of the vector image used to decorate material names.
defaultFont: the default font to use.
The ... | f71b22af076a466f951815e73f83ea989f920cdf | 3,881 |
def to_accumulo(df, config: dict, meta: dict, compute=True, scheduler=None):
"""
Paralell write of Dask DataFrame to Accumulo Table
Parameters
----------
df : Dataframe
The dask.Dataframe to write to Accumulo
config : dict
Accumulo configuration to use to connect to accumulo
... | 016ee1cc516b8fd6c055902002a196b30ceb0e07 | 3,882 |
def compute_euclidean_distance(x, y):
"""
Computes the euclidean distance between two tensorflow variables
"""
d = tf.reduce_sum(tf.square(x-y),axis=1,keep_dims=True)
return d | 26171d3a0c719d0744ab163b33590f4bb1f92480 | 3,883 |
def vpn_ping(address, port, timeout=0.05, session_id=None):
"""Sends a vpn negotiation packet and returns the server session.
Returns False on a failure. Basic packet structure is below.
Client packet (14 bytes)::
0 1 8 9 13
+-+--------+-----+
|x| cli_id |?????|
+-+--------+-----+
... | dcc4d8cf347486b0f10f1dd51d230bd6fb625551 | 3,884 |
def is_admin():
"""Checks if author is a server administrator, or has the correct permission tags."""
async def predicate(ctx):
return (
# User is a server administrator.
ctx.message.channel.permissions_for(ctx.message.author).administrator
# User is a developer.
... | 70a87d8ae4970b05aa39339fec2aa1ade43d238a | 3,885 |
def send_message(chat_id):
"""Send a message to a chat
If a media file is found, send_media is called, else a simple text message
is sent
"""
files = request.files
if files:
res = send_media(chat_id, request)
else:
message = request.form.get("message", default="Empty Message"... | df77e115497cfc975b9fad6f9a3b43648349133e | 3,886 |
def get_neighbours(sudoku, row, col):
"""Funkcja zwraca 3 listy sasiadow danego pola, czyli np. wiersz tego pola, ale bez samego pola"""
row_neighbours = [sudoku[row][y] for y in range(9) if y != col]
col_neighbours = [sudoku[x][col] for x in range(9) if x != row]
sqr_neighbours = [sudoku[x][y] for x in... | b10766fc8925b54d887925e1a684e368c0f3b550 | 3,887 |
import torch
import PIL
def to_ndarray(image):
"""
Convert torch.Tensor or PIL.Image.Image to ndarray.
:param image: (torch.Tensor or PIL.Image.Image) image to convert to ndarray
:rtype (ndarray): image as ndarray
"""
if isinstance(image, torch.Tensor):
return image.numpy()
if is... | f12444779e2d2eb78e3823821c8c6acec7c601a6 | 3,888 |
def calc_random_piv_error(particle_image_diameter):
"""
Caclulate the random error amplitude which is proportional to the diameter of the displacement correlation peak.
(Westerweel et al., 2009)
"""
c = 0.1
error = c*np.sqrt(2)*particle_image_diameter/np.sqrt(2)
return error | 91b02b658c0c6476739695017925c44c92bf67c8 | 3,890 |
def resolve(name, module=None):
"""Resolve ``name`` to a Python object via imports / attribute lookups.
If ``module`` is None, ``name`` must be "absolute" (no leading dots).
If ``module`` is not None, and ``name`` is "relative" (has leading dots),
the object will be found by navigating relative to ``mod... | d778ff9e4ea821be6795cc9007552e6c0afeb565 | 3,891 |
def fibonacci(n:int) -> int:
"""Return the `n` th Fibonacci number, for positive `n`."""
if 0 <= n <= 1:
return n
n_minus1, n_minus2 = 1,0
result = None
for f in range(n - 1):
result = n_minus2 + n_minus1
n_minus2 = n_minus1
n_minus1 = result
return result | 4be929f69dc9c35679af580767bfe047fc1963e9 | 3,892 |
import select
def get_budget(product_name, sdate):
"""
Budget for a product, limited to data available at the database
:param product_name:
:param sdate: starting date
:return: pandas series
"""
db = DB('forecast')
table = db.table('budget')
sql = select([table.c.budget]).where(ta... | a17ae7db2734c2c877a41eb0986016a4f0241f07 | 3,893 |
def _residual_block_basic(filters, kernel_size=3, strides=1, use_bias=False, name='res_basic',
kernel_initializer='he_normal', kernel_regularizer=regulizers.l2(1e-4)):
"""
Return a basic residual layer block.
:param filters: Number of filters.
:param kernel_size... | 87c041f58de71d7bd2d3fcbe97ec35b8fa057468 | 3,894 |
def console_script(tmpdir):
"""Python script to use in tests."""
script = tmpdir.join('script.py')
script.write('#!/usr/bin/env python\nprint("foo")')
return script | be6a38bec8bb4f53de83b3c632ff3d26d88ef1c7 | 3,895 |
def parse_tpl_file(tpl_file):
""" parse a PEST-style template file to get the parameter names
Args:
tpl_file (`str`): path and name of a template file
Returns:
[`str`] : list of parameter names found in `tpl_file`
Example::
par_names = pyemu.pst_utils.parse_tpl_file("my.tpl")
... | 01ed281f4ee9f1c51032d4f3655bd3e17b73bbb2 | 3,896 |
def get_single_image_results(pred_boxes, gt_boxes, iou_thr):
"""Calculates number of true_pos, false_pos, false_neg from single batch of boxes.
Args:
gt_boxes (list of list of floats): list of locations of ground truth
objects as [xmin, ymin, xmax, ymax]
pred_boxes (d... | 3f3bc93641e2f7d04a21fed9a8d0c40fcbc9eacc | 3,898 |
def get_list(caller_id):
"""
@cmview_user
@response{list(dict)} PublicIP.dict property for each caller's PublicIP
"""
user = User.get(caller_id)
ips = PublicIP.objects.filter(user=user).all()
return [ip.dict for ip in ips] | 41f7855eb258df444b29dc85860e5e85ae6de441 | 3,899 |
def matrix_zeros(m, n, **options):
""""Get a zeros matrix for a given format."""
format = options.get('format', 'sympy')
dtype = options.get('dtype', 'float64')
spmatrix = options.get('spmatrix', 'csr')
if format == 'sympy':
return zeros(m, n)
elif format == 'numpy':
return _nump... | e4c87a85dd6a37868704205b21732d82a4ffb2df | 3,900 |
def make_password(password, salt=None):
"""
Turn a plain-text password into a hash for database storage
Same as encode() but generate a new random salt. If password is None then
return a concatenation of UNUSABLE_PASSWORD_PREFIX and a random string,
which disallows logins. Additional random string ... | 6c39486c2eb88af278580cdf4b86b7b45489eef0 | 3,901 |
from typing import Union
from pathlib import Path
from typing import Tuple
import torch
from typing import Optional
from typing import Callable
from re import T
def compute_spectrogram(
audio: Union[Path, Tuple[torch.Tensor, int]],
n_fft: int,
win_length: Optional[int],
hop_length: int,
n_mels: in... | 918fc0c9273b2085ded2ca8d6dd5d4db758538f0 | 3,904 |
def decode_html_dir(new):
""" konvertiert bestimmte Spalte in HTML-Entities """
def decode(key):
return decode_html(unicode(new[key]))
if new.has_key('title') and new['title'].find('&') >= 0:
new['title'] = decode('title')
if new.has_key('sub_title') and new['sub_title'].find('&') >= 0:
new['sub_t... | 029483974a26befc2df8d92babf53f5a32be31f5 | 3,905 |
def dmsp_enz_deg(
c,
t,
alpha,
vmax,
vmax_32,
kappa_32,
k
):
"""
Function that computes dD32_dt and dD34_dt of DMSP
Parameters
----------
c: float.
Concentration of DMSP in nM.
t: int
Integration time in min.
alpha: float.
Alpha for cleavage by Ddd... | d5e4b77523ab469b61eec106a28e1e3143644bf7 | 3,907 |
def plot_holdings(returns, positions, legend_loc='best', ax=None, **kwargs):
"""Plots total amount of stocks with an active position, either short
or long.
Displays daily total, daily average per month, and all-time daily
average.
Parameters
----------
returns : pd.Series
Daily ret... | 5e375729aa48d0d3f8aada17268048a68a662421 | 3,908 |
def concatenation_sum(n: int) -> int:
"""
Algo:
1. Find length of num (n), i.e. number of digits 'd'.
2. Determine largest number with 'd - 1' digits => L = 10^(d - 1) - 1
3. Find diff => f = n - L
4. Now, the sum => s1 = f * d, gives us the number of digits in the string formed ... | 644c994ee9b5af280feb233a40df51b519c4b9c6 | 3,910 |
def make_join_conditional(key_columns: KeyColumns, left_alias: str, right_alias: str) -> Composed:
"""
Turn a pair of aliases and a list of key columns into a SQL safe string containing
join conditionals ANDed together.
s.id1 is not distinct from d.id1 and s.id2 is not distinct from d.id2
"""
... | c0b239598f606f35d3af0cbf8c34168137e05b9c | 3,911 |
def home():
""" Home interface """
return '''<!doctype html>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<body style="margin:0;font-family:sans-serif;color:white">
<form method="POST" action="analyse" enctype="multipart/form-data">
<label style="text-align:center;position:fixe... | d8a9c3449ac56b04ee1514729342ce29469c5c2f | 3,912 |
def _enable_mixed_precision_graph_rewrite_base(opt, loss_scale,
use_v1_behavior):
"""Enables mixed precision. See `enable_mixed_precision_graph_rewrite`."""
opt = _wrap_optimizer(opt, loss_scale, use_v1_behavior=use_v1_behavior)
config.set_optimizer_experimental_opti... | 8601ae6d24575e2bf5a7057bc06992088d473179 | 3,913 |
def selection_criteria_1(users, label_of_interest):
"""
Formula for Retirement/Selection score:
x = sum_i=1_to_n (r_i) — sum_j=1_to_m (r_j).
Where first summation contains reliability scores of users who have labeled it as the same
as the label of interest, second summation contains reliability scor... | 8255fd3645d5b50c43006d2124d06577e3ac8f2d | 3,915 |
import requests
from typing import cast
def get_default_product_not_found(product_category_id: str) -> str:
"""Get default product.
When invalid options are provided, the defualt product is returned. Which happens to be unflavoured whey at 2.2 lbs.
This is PRODUCT_INFORMATION.
"""
response = requ... | 4464a56de2ff514a71d5d06b1684f04a9ed8e564 | 3,916 |
import re
def book_number_from_path(book_path: str) -> float:
"""
Parses the book number from a directory string.
Novellas will have a floating point value like "1.1" which indicates that it was the first novella
to be published between book 1 and book 2.
:param book_path: path of the currently ... | 087cb0b8cd0c48c003175a05ed0d7bb14ad99ac3 | 3,917 |
def intervals_split_merge(list_lab_intervals):
"""
对界限列表进行融合
e.g.
如['(2,5]', '(5,7]'], 融合后输出为 '(2,7]'
Parameters:
----------
list_lab_intervals: list, 界限区间字符串列表
Returns:
-------
label_merge: 合并后的区间
"""
list_labels = []
# 遍历每个区间, 取得左值右值字符串组成列表
for lab in list_la... | a9e99ec6fc51efb78a4884206a72f7f4ad129dd4 | 3,918 |
def antique(bins, bin_method=BinMethod.category):
"""CARTOColors Antique qualitative scheme"""
return scheme('Antique', bins, bin_method) | 718ca4c2b9efede292bb5e8e1eb5128e6200a454 | 3,919 |
import json
def do_request(batch_no, req):
"""execute one request. tail the logs. wait for completion"""
tmp_src = _s3_split_url(req['input'])
cpy_dst = _s3_split_url(req['output'])
new_req = {
"src_bucket": tmp_src[0],
"src_key": tmp_src[1],
"dst_bucket": cpy_dst[0],
... | 6e4b8591abfe8a1c106a0ede1e6aa3f6712afd4a | 3,920 |
def _robot_barcode(event: Message) -> str:
"""Extracts a robot barcode from an event message.
Args:
event (Message): The event
Returns:
str: robot barcode
"""
return str(
next(
subject["friendly_name"] # type: ignore
for subject in event.message["ev... | 5ffb6567ebb103fc534390d13876d9c1fa956169 | 3,922 |
from typing import List
from typing import Union
def check_thirteen_fd(fds: List[Union[BI, FakeBI]]) -> str:
"""识别十三段形态
:param fds: list
由远及近的十三段形态
:return: str
"""
v = Signals.Other.value
if len(fds) != 13:
return v
direction = fds[-1].direction
fd1, fd2, fd3, fd4, f... | 95c308c2560cc7a337e4a1719836c3df74ab1bbe | 3,924 |
from typing import List
def set_process_tracking(template: str, channels: List[str]) -> str:
"""This function replaces the template placeholder for the process tracking with the correct process tracking.
Args:
template: The template to be modified.
channels: The list of channels to be used.
... | 0cf720bd56a63939541a06e60492472f92c4e589 | 3,925 |
def solve(instance: Instance) -> InstanceSolution:
"""Solves the P||Cmax problem by using a genetic algorithm.
:param instance: valid problem instance
:return: generated solution of a given problem instance
"""
generations = 512
population_size = 128
best_specimens_number = 32
generator ... | f8a82a066de29e0c149c3c5f01821af080619764 | 3,926 |
def payee_transaction():
"""Last transaction for the given payee."""
entry = g.ledger.attributes.payee_transaction(request.args.get("payee"))
return serialise(entry) | 47a21c7921cae4be30b6eefbbde43bfdf5a38013 | 3,927 |
def represent(element: Element) -> str:
"""Represent the regular expression as a string pattern."""
return _Representer().visit(element) | dfd44499aa1f63248c1a6632131974b242fedf95 | 3,928 |
def read_dynamo_table(gc, name, read_throughput=None, splits=None):
"""
Reads a Dynamo table as a Glue DynamicFrame.
:param awsglue.context.GlueContext gc: The GlueContext
:param str name: The name of the Dynamo table
:param str read_throughput: Optional read throughput - supports values from "0.1"... | 5f789626cb3fc8004532cc59bdae128b744b111e | 3,929 |
import six
def convert_to_bytes(text):
"""
Converts `text` to bytes (if it's not already).
Used when generating tfrecords. More specifically, in function call `tf.train.BytesList(value=[<bytes1>, <bytes2>, ...])`
"""
if six.PY2:
return convert_to_str(text) # In python2, str is byte
el... | da10be9cb88a80f66becead41400b3a4eb6152a2 | 3,930 |
from typing import OrderedDict
def xreplace_constrained(exprs, make, rule=None, costmodel=lambda e: True, repeat=False):
"""
Unlike ``xreplace``, which replaces all objects specified in a mapper,
this function replaces all objects satisfying two criteria: ::
* The "matching rule" -- a function re... | f24f0bb1356c5613c012fe405691b1b493ffc6a2 | 3,931 |
import re
def get_comp_rules() -> str:
"""
Download the comp rules from Wizards site and return it
:return: Comp rules text
"""
response = download_from_wizards(COMP_RULES)
# Get the comp rules from the website (as it changes often)
# Also split up the regex find so we only have the URL
... | dbb48b391305199182a2bf66bed62dcd91dc0071 | 3,932 |
def delete_vpc(vpc_id):
"""Delete a VPC."""
client = get_client("ec2")
params = {}
params["VpcId"] = vpc_id
return client.delete_vpc(**params) | 5c1a043d837ff1bc0cab41ccdbe784688966a275 | 3,933 |
def test_network_xor(alpha = 0.1, iterations = 1000):
"""Creates and trains a network against the XOR/XNOR data"""
n, W, B = network_random_gaussian([2, 2, 2])
X, Y = xor_data()
return n.iterate_network(X, Y, alpha, iterations) | cb05f01f589d7e224d1a0a87f594a075228741fc | 3,934 |
from pathlib import Path
import shutil
def assemble_book(draft__dir: Path, work_dir: Path, text_dir: Path) -> Path:
"""Merge contents of draft book skeleton with test-specific files for
the book contents.
"""
book_dir = work_dir / "test-book"
# Copy skeleton from draft__dir
shutil.copytree(draft__dir, book_dir)... | 51ec6ed21760feeff3eeee6ee6fa802383b5afa3 | 3,935 |
def merid_advec_spharm(arr, v, radius):
"""Meridional advection using spherical harmonics."""
_, d_dy = horiz_gradient_spharm(arr, radius)
return v * d_dy | 7973f99b60ad9d94b6858d28d8877f5c814160c2 | 3,936 |
def run_win_pct(team_name, df):
"""
Function that calculates a teams winning percentage Year over Year (YoY)
Calculation:
Number of wins by the total number of competitions.
Then multiply by 100 = win percentage.
Number of loses by the total number of competitions.
Then multi... | 3fc071cd7e89f68216286b0b6422a95ce8f690f6 | 3,937 |
def get_container_info(pi_status):
"""
Expects a dictionary data structure that include keys and values of the
parameters that describe the containers running in a Raspberry Pi computer.
Returns the input dictionary populated with values measured from the current
status of one or more containers... | a488e7afa9c2e003edb3138c1d78e434921dbf3e | 3,938 |
import math
def formatSI(n: float) -> str:
"""Format the integer or float n to 3 significant digits + SI prefix."""
s = ''
if n < 0:
n = -n
s += '-'
if type(n) is int and n < 1000:
s = str(n) + ' '
elif n < 1e-22:
s = '0.00 '
else:
assert n < 9.99e26
... | ddbbb70e66d368253d29c3223eee7a5926518efd | 3,939 |
import scipy
def pemp(stat, stat0):
""" Computes empirical values identically to bioconductor/qvalue empPvals """
assert len(stat0) > 0
assert len(stat) > 0
stat = np.array(stat)
stat0 = np.array(stat0)
m = len(stat)
m0 = len(stat0)
statc = np.concatenate((stat, stat0))
v = np.... | 7d046666687ede0b671c00d5c691ac520179e11f | 3,940 |
def help_message() -> str:
"""
Return help message.
Returns
-------
str
Help message.
"""
msg = f"""neocities-sync
Sync local directories with neocities.org sites.
Usage:
neocities-sync options] [--dry-run] [-c CONFIG] [-s SITE1] [-s SITE2] ...
Options:
-C CONFIG_FIL... | 8c2d0c31513e36c1ef1c9f0b096d264449dafdee | 3,941 |
def fuzzyCompareDouble(p1, p2):
"""
compares 2 double as points
"""
return abs(p1 - p2) * 100000. <= min(abs(p1), abs(p2)) | e2a93a993147e8523da0717d08587250003f9269 | 3,942 |
def filter_date_df(date_time, df, var="date"):
"""Filtrar dataframe para uma dada lista de datas.
Parameters
----------
date_time: list
list with dates.
df: pandas.Dataframe
var: str
column to filter, default value is "date" but can be adaptable for other ones.
Returns
... | 6d3002917ef0786e8b128a2a02df3fabb9997aab | 3,943 |
import urllib
def pproxy_desired_access_log_line(url):
"""Return a desired pproxy log entry given a url."""
qe_url_parts = urllib.parse.urlparse(url)
protocol_port = '443' if qe_url_parts.scheme == 'https' else '80'
return 'http {}:{}'.format(qe_url_parts.hostname, protocol_port) | 4c056b1d2cc11a72cf63400734807b9b074f147c | 3,944 |
import socket
def unused_port() -> int:
"""Return a port that is unused on the current host."""
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.bind(("127.0.0.1", 0))
return s.getsockname()[1] | 26d72e1a529edd37b14ac746bcb4082c1d1b9061 | 3,945 |
def get_axioma_risk_free_rate(conn) :
"""
Get the USD risk free rate provided by Axioma and converted it into
a daily risk free rate assuming a 252 trading data calendar.
"""
query = """
select
data_date,
Risk_Free_Rate
from
axioma_... | 2c6c680ef36c247b67c481ff4dde685afc4bad4d | 3,946 |
import numbers
import time
import warnings
def _fit_and_score(estimator, X, y, scorer, train, test, verbose,
parameters, fit_params, return_train_score=False,
return_parameters=False, return_n_test_samples=False,
return_times=False, return_estimator=False,
... | 6330fb95709e74471b72b58297b3ce3c7d483449 | 3,948 |
from typing import Dict
from typing import List
def prettify_eval(set_: str, accuracy: float, correct: int, avg_loss: float, n_instances: int,
stats: Dict[str, List[int]]):
"""Returns string with prettified classification results"""
table = 'problem_type accuracy\n'
for k in sorted(stats... | 5e5ba8ffa62668e245daa2ada9fc09747b5b6dd2 | 3,949 |
def load_location(doc_name):
"""Load a location from db by name."""
doc_ref = get_db().collection("locations").document(doc_name)
doc = doc_ref.get()
if not doc.exists:
return None
else:
return doc.to_dict() | 900450ec3a1c033a9c11baed611170457660754f | 3,951 |
def plotMultiROC(y_true, # list of true labels
y_scores, # array of scores for each class of shape [n_samples, n_classes]
title = 'Multiclass ROC Plot',
n_points=100, # reinterpolates to have exactly N points
labels = None, # list... | a8ca19b92f7f3539d8550cf63121a46d36e59cbf | 3,952 |
def fasta_to_dict(fasta_file):
"""Consolidate deflines and sequences from FASTA as dictionary"""
deflines = []
sequences = []
sequence = ""
with open(fasta_file, "r") as file:
for line in file:
if line.startswith(">"):
deflines.append(line.rstrip().lst... | e1740ad29672e5239d575df963e21a0bf5caee08 | 3,953 |
def find_roots(graph):
"""
return nodes which you can't traverse down any further
"""
return [n for n in graph.nodes() if len(list(graph.predecessors(n))) == 0] | 7dbf755d2b76f066370d149638433c6693e8e7b9 | 3,954 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.