content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def get_post_count(user):
"""
Get number of posts published by the requst user.
Parameters
------------
user: The request user
Returns
-------
count: int
The number of posts published by the requst user.
"""
count = Post.objects.filter(publisher=user).count()
return... | 6000bcd43ef2b8edf3c1dd04df89dcef38f110d5 | 12,459 |
from config import employee_required_fields
def create_new_employee(employees):
"""
Create a new employee record with the employees dictionary
Use the employee_sections dictionary template to create a
new employee record.
"""
subsidiary = input('Employee Subsidiary (SK, CZ):')
emp... | aa5d0981c2b81ad65ed5ad0368fd1b3b79796a40 | 12,460 |
def gather_squares_triangles(p1,p2,depth):
""" Draw Square and Right Triangle given 2 points,
Recurse on new points
args:
p1,p2 (float,float) : absolute position on base vertices
depth (int) : decrementing counter that terminates recursion
return:
squares [(float,float,float,float)...] : absolut... | de4e720eb10cb378f00086a6e8e45886746055c0 | 12,461 |
def update_node(node_name, node_type, root=None):
"""
! Node is assumed to have only one input and one output port with a maximum
of one connection for each.
Returns:
NodegraphAPI.Node: newly created node
"""
new = NodegraphAPI.CreateNode(node_type, root or NodegraphAPI.GetRootNode())
... | 916beec7de527ee56d5326061aa2c367af17434f | 12,462 |
def dan_acf(x, axis=0, fast=False):
"""
Estimate the autocorrelation function of a time series using the FFT.
Args:
x (array): The time series. If multidimensional, set the time axis
using the ``axis`` keyword argument and the function will be
computed for every other axis.
... | 85273d95564f0e8c0afb9ff00ac23dc04539f291 | 12,463 |
from datetime import datetime
def schedule_decision():
"""最適化の実行と結果の表示を行う関数"""
# トップページを表示する(GETリクエストがきた場合)
if request.method == "GET":
return render_template("scheduler/schedule_decision.html", solution_html=None)
# POSTリクエストである「最適化を実行」ボタンが押された場合に実行
# データがアップロードされているかチェックする。適切でなければ元のページに... | 6f259961d027b6e4a3dc88289a5ba62b162705f6 | 12,464 |
def infection_rate_asymptomatic_30x40():
"""
Real Name: b'infection rate asymptomatic 30x40'
Original Eqn: b'contact infectivity asymptomatic 30x40*(social distancing policy SWITCH self 40*social distancing policy 40\\\\ +(1-social distancing policy SWITCH self 40))*Infected asymptomatic 30x40*Susceptible 4... | 16aebdca2259933dcdab1a00ed8d37b10d5b8714 | 12,465 |
def slug(hans, style=Style.NORMAL, heteronym=False, separator='-',
errors='default', strict=True):
"""将汉字转换为拼音,然后生成 slug 字符串.
:param hans: 汉字字符串( ``'你好吗'`` )或列表( ``['你好', '吗']`` ).
可以使用自己喜爱的分词模块对字符串进行分词处理,
只需将经过分词处理的字符串列表传进来就可以了。
:type hans: unicode 字符串或字符串列表
... | 124431e3ea8747dfdc024f93e88f692746797013 | 12,466 |
def A_weight(signal, fs):
"""
Return the given signal after passing through an A-weighting filter
signal : array_like
Input signal
fs : float
Sampling frequency
"""
b, a = A_weighting(fs)
return lfilter(b, a, signal) | 1c6abdd90b85762db4383972de7508d00b561065 | 12,467 |
from typing import Tuple
from typing import Union
import traceback
def send_task_to_executor(task_tuple: TaskInstanceInCelery) \
-> Tuple[TaskInstanceKey, CommandType, Union[AsyncResult, ExceptionWithTraceback]]:
"""Sends task to executor."""
key, _, command, queue, task_to_run = task_tuple
try:
... | cbc93ac3a3c146b748c0ec88eaa9cb2cd631ac85 | 12,470 |
def geometries_from_bbox(north, south, east, west, tags):
"""
Create a GeoDataFrame of OSM entities within a N, S, E, W bounding box.
Parameters
----------
north : float
northern latitude of bounding box
south : float
southern latitude of bounding box
east : float
ea... | 32aeebe7f644df00b613ef6e0d4f30baef1a5743 | 12,473 |
def dBzdtAnalCircT(a, t, sigma):
"""
Hz component of analytic solution for half-space (Circular-loop source)
Src and Rx are on the surface and receiver is located at the center of the loop.
Src waveform here is step-off.
.. math::
\\frac{\partial h_z}{\partial t} = -\\... | 18b9428528ed11a121ad01578d2bfc35faceae21 | 12,474 |
def count_increasing(ratings, n):
"""
Only considering the increasing case
"""
arr = [1] * n
cnt = 1
for i in range(1, n):
cnt = cnt + 1 if ratings[i - 1] < ratings[i] else 1
arr[i] = cnt
return arr | 9fe274527fbba505467a195bf555c77d2f3e6aed | 12,475 |
import copy
def load_train_data_frame(train_small, target, keras_options, model_options, verbose=0):
"""
### CAUTION: TF2.4 Still cannot load a DataFrame with Nulls in string or categoricals!
############################################################################
#### TF 2.4 still cannot load ten... | 85c496b485bbc26afbadf181a2231e3f5bd93706 | 12,476 |
def stat_float_times(space, newval=-1):
"""stat_float_times([newval]) -> oldval
Determine whether os.[lf]stat represents time stamps as float objects.
If newval is True, future calls to stat() return floats, if it is False,
future calls return ints.
If newval is omitted, return the current setting.
"""
state =... | e183f0cc2ce56bc7b4ac6ce95d8cb671a963422f | 12,477 |
def decorate(rvecs):
"""Output range vectors into some desired string format"""
return ', '.join(['{%s}' % ','.join([str(x) for x in rvec]) for rvec in rvecs]) | 31a3d4414b0b88ffd92a5ddd8eb09aaf90ef3742 | 12,478 |
def update_topic_collection_items(request_ctx, collection_item_id, topic_id, **request_kwargs):
"""
Accepts the same parameters as create
:param request_ctx: The request context
:type request_ctx: :class:RequestContext
:param collection_item_id: (required) ID
:type collection_it... | 06b0709f5fa4acf189baef8f2665bee81b3c4993 | 12,479 |
def upsample(inputs, factor=(2, 2), interpolation='nearest'):
"""
Upsampling layer by factor
Parameters
----------
inputs: Input tensor
factor: The upsampling factors for (height, width). One integer or tuple of
two integers
interpolation: A string, one of [`nearest`, `bilinear`, 'b... | dfbd42871e63cb685f9cfbf9185da38839a9ee4e | 12,480 |
def root_mean_squared_error(*args, **kwargs):
"""
Returns the square-root of ``scikit-learn``'s ``mean_squared_error`` metric.
All arguments are forwarded to that function.
"""
return np.sqrt(mean_squared_error(*args, **kwargs)) | 51084b2ec55d14657fa128f0df2bd3f438c2367b | 12,481 |
def idwt2(Wimg, level=4):
""" inverse 2d wavelet transform
:param Wimg: 2d array
wavelet coefficients
:param level: int
level of wavelet transform - image shape has to be multiples of 2**level
:return: 2d array
image
"""
coeffs = _from_img_to_coeffs(Wimg, levels=level)
... | 521ceca879b0961730b1efd6dac54772a2b41ca3 | 12,482 |
def get_color(card):
"""Returns the card's color
Args:
card (webelement): a visible card
Returns:
str: card's color
"""
color = card.find_element_by_xpath(".//div/*[name()='svg']/*[name()='use'][2]").get_attribute("stroke")
# both light and dark theme
if (color == "#ff0101... | 452266b81d70973149fed4ab2e6cbc9c93591180 | 12,483 |
from typing import Dict
from typing import Any
def is_valid_path(parameters: Dict[str, Any]) -> bool:
"""Single "." chars and empty strings "" are excluded from path by urllib3.
A path containing to "/" or "%2F" will lead to ambiguous path resolution in
many frameworks and libraries, such behaviour have ... | 5f80ff76c535b3913efc7ba83e04c4c049a9e50b | 12,484 |
import torch
def to_tensor(x):
"""
Arguments:
x: an instance of PIL image.
Returns:
a float tensor with shape [3, h, w],
it represents a RGB image with
pixel values in [0, 1] range.
"""
x = np.array(x)
x = torch.FloatTensor(x)
return x.permute(2, 0, 1).unsqu... | 6ff19bd7549a4fce455f03559420216020658c44 | 12,485 |
def fetch_data(fold_path):
"""Fetch data saving in fold path.
Convert data into suitable format, using csv files in fold path.
:param fold_path: String. The fold in which data files are saved.
:return:
training_data: Dataframe. Combined dataframe to create training data.
testing_data:... | 42ea9ea6d1d9d597acc4ed1a14099711642608f4 | 12,488 |
def add_chr_prefix(band):
"""
Return the band string with chr prefixed
"""
return ''.join(['chr', band]) | 08a99220023f10d79bdacdb062a27efcb51086ce | 12,489 |
def disable_text_recog_aug_test(cfg, set_types=None):
"""Remove aug_test from test pipeline of text recognition.
Args:
cfg (mmcv.Config): Input config.
set_types (list[str]): Type of dataset source. Should be
None or sublist of ['test', 'val']
Returns:
cfg (mmcv.Config):... | bda3a5420d32d55062b23a6af27cee3e203b878c | 12,490 |
def layer_svg(svg_bottom, svg_top, offset: list = [0.0, 0.0]):
"""
Adds one SVG over another. Modifies the bottom SVG in place.
:param svg_bottom: The bottom SVG, in in xml.etree.ElementTree form
:param svg_top: The top SVG, in in xml.etree.ElementTree form
:param offset: How far to offset the top S... | 6c6a8151d17f4aff9f1491d1ed71772d9434ae4c | 12,491 |
def utxo_cmd(ctx, dry_run):
"""Get the node's current UTxO with the option of filtering by address(es)"""
try:
CardanoCli.execute(cmd=["cardano-cli", "query", "utxo"], dry_run=dry_run, include_network=True)
except CardanoPyError as cpe:
ctx.fail(cpe.message)
return cpe.return_code | 52807294a445fc2f641c1b921807bba898ad8c34 | 12,493 |
def delta_in_ms(delta):
"""
Convert a timedelta object to milliseconds.
"""
return delta.seconds*1000.0+delta.microseconds/1000.0 | 4ed048155daf4a4891488e28c674e905e1bbe947 | 12,494 |
import slicer, collections, fnmatch
def getNodes(pattern="*", scene=None, useLists=False):
"""Return a dictionary of nodes where the name or id matches the ``pattern``.
By default, ``pattern`` is a wildcard and it returns all nodes associated
with ``slicer.mrmlScene``.
If multiple node share the same name, ... | 6d6c44987a800f361d45f4538167acb65e738418 | 12,495 |
from typing import Union
from typing import Type
from re import X
from typing import Mapping
from typing import Optional
def get_cls(
query: Union[None, str, Type[X]],
base: Type[X],
lookup_dict: Mapping[str, Type[X]],
lookup_dict_synonyms: Optional[Mapping[str, Type[X]]] = None,
default: Optional... | e5f805df5ef19de9939344beee21834e3f2556ab | 12,496 |
def selection_sort(data):
"""Sort a list of unique numbers in ascending order using selection sort. O(n^2).
The process includes repeatedly iterating through a list, finding the smallest element, and sorting that element.
Args:
data: data to sort (list of int)
Returns:
sorted l... | 8b745be41c857669aedecb25b3006bbdc1ef04eb | 12,497 |
def _conv(args, filter_size, num_features, bias, reuse, w_init=None, b_init=0.0, scope='_conv'):
"""convolution:
Args:
args: a Tensor or a list of Tensors of dimension 3D, 4D or 5D
batch x n, Tensors.
filter_size: int tuple of filter height and width.
reuse: None/True, whether to reuse vari... | 104d91623949e4506c4b72001c23b6ab7fb312ca | 12,498 |
def _feature_normalization(features, method, feature_type):
"""Normalize the given feature vector `y`, with the stated normalization `method`.
Args:
features (np.ndarray): The signal array
method (str): Normalization method.
'global': Uses global mean and standard deviation values ... | 0479363651a4bcf1622e7bdb0906b55e3adb1cce | 12,500 |
def get_constraint(name):
"""
Lookup table of default weight constraint functions.
Parameters
----------
name : Constraint, None, str
Constraint to look up. Must be one of:
- 'l1' : L1 weight-decay.
- 'l2' : L2 weight-decay.
- 'l1-l2' : Combined L1-L2 weight-decay.
- Constraint : A custom implementa... | 09927531f4c6770e86ad603063e4edb0b0c4ff48 | 12,501 |
def player_count(conn, team_id):
"""Returns the number of players associated with a particular team"""
c = conn.cursor()
c.execute("SELECT id FROM players WHERE team_id=?", (team_id,))
return len(c.fetchall()) | cfced6da6c8927db2ccf331dca7d23bba0ce67e5 | 12,502 |
def _RedisClient(address):
"""
Return a connection object connected to the socket given by `address`
"""
h1, h2 = get_handle_pair(conn_type=REDIS_LIST_CONN)
c = _RedisConnection(h1)
#redis_client = util.get_redis_client()
redis_client = util.get_cache_client()
ip, port = address
chan... | fc8bab786bb521fbd0715da3ab690575d1df865e | 12,503 |
import math
def format_timedelta(value,
time_format="{days} days, {hours2}:{minutes2}:{seconds2}"):
"""Format a datetie.timedelta. See """
if hasattr(value, 'seconds'):
seconds = value.seconds + value.days * 24 * 3600
else:
seconds = int(value)
seconds_total = seconds
minutes ... | 19dc2b175beb1d030f14ae7fe96cb16d66f6c219 | 12,504 |
def random_account_user(account):
"""Get a random user for an account."""
account_user = AccountUser.objects.filter(account=account).order_by("?").first()
return account_user.user if account_user else None | 5fe918af67710d0d1519f56eee15811430a0e139 | 12,505 |
def overwrite(main_config_obj, args):
"""
Overwrites parameters with input flags
Args:
main_config_obj (ConfigClass): config instance
args (dict): arguments used to overwrite
Returns:
ConfigClass: config instance
"""
# Sort on nested level to override shallow items first
args = dict(s... | 98ee9cf034a9b714ae18e737761b06bfd669bfa4 | 12,506 |
def max_delta(model, new_model):
"""Return the largest difference between any two corresponding
values in the models"""
return max( [(abs(model[i] - new_model[i])).max() for i in range(len(model))] ) | faf4a9fb2b24f7e7b4f357eef195e435950ea218 | 12,507 |
def wiener_khinchin_transform(power_spectrum, frequency, time):
"""
A function to transform the power spectrum to a correlation function by the Wiener Khinchin transformation
** Input:**
* **power_spectrum** (`list or numpy.array`):
The power spectrum of the signal.
* **frequency** (`lis... | 3cf8916c75632e3a0db52f907ce180eb766f9f2e | 12,508 |
def child_is_flat(children, level=1):
"""
Check if all children in section is in same level.
children - list of section children.
level - integer, current level of depth.
Returns True if all children in the same level, False otherwise.
"""
return all(
len(child) <= level + 1 or child... | e14f9210a90b40b419d21fffa1542212429d80be | 12,509 |
from pathlib import Path
def load_dataset(name, other_paths=[]):
"""Load a dataset with given (file) name."""
if isinstance(name, Dataset):
return name
path = Path(name)
# First, try if you have passed a fully formed dataset path
if path.is_file():
return _from_npy(name, classes=... | 3f3d2e7e7ec577098e1a1599c74638ced5d3c103 | 12,510 |
def isqrtcovresnet101b(**kwargs):
"""
iSQRT-COV-ResNet-101 model with stride at the second convolution in bottleneck block from 'Towards Faster Training
of Global Covariance Pooling Networks by Iterative Matrix Square Root Normalization,'
https://arxiv.org/abs/1712.01034.
Parameters:
----------... | fdf166fa3ce9e893e8e97d1057dac89d084d2217 | 12,511 |
def get_data(name: str, level: int, max_level: int) -> str:
"""從維基頁面爬取資料
參數:
name: 程式或節點名稱
level: 欲查詢的等級
回傳:
爬到的資料
"""
reply_msg = []
for dataframe in read_html(generate_url(name)):
if (max_level < dataframe.shape[0] < max_level + 3 and
dataframe... | 4e0f11a33c81993132d45f3fdad5f42c1288bbe5 | 12,512 |
def insert_data(context, data_dict):
"""
:raises InvalidDataError: if there is an invalid value in the given data
"""
data_dict['method'] = _INSERT
result = upsert_data(context, data_dict)
return result | c631016be36f1988bfa9c98cea42a7f63fddc276 | 12,514 |
import time
def timestamp():
"""Get the unix timestamp now and retuen it.
Attention: It's a floating point number."""
timestamp = time.time()
return timestamp | 8e56a61659da657da9d5dda364d4d9e8f3d58ed2 | 12,515 |
from datetime import datetime
def _n64_to_datetime(n64):
"""Convert Numpy 64 bit timestamps to datetime objects. Units in seconds"""
return datetime.utcfromtimestamp(n64.tolist() / 1e9) | a25327f2cd0093635f86f3145f5674cc1945d3f8 | 12,516 |
import itertools
def cycle(iterable):
"""Make an iterator returning elements from the iterable and saving a copy of each.
When the iterable is exhausted, return elements from the saved copy. Repeats indefinitely.
This function uses single dispatch.
.. seealso:: :func:`itertools.cycle`
"""
re... | 13f479fca709dffa77eeca3d32ff7265c81588bf | 12,517 |
def get_availability_zone(name=None,state=None,zone_id=None,opts=None):
"""
`.getAvailabilityZone` provides details about a specific availability zone (AZ)
in the current region.
This can be used both to validate an availability zone given in a variable
and to split the AZ name into its compone... | 6cb20524c1e0a2539e221711f1153949ab72f8e1 | 12,518 |
def _add_u_eq(blk, uex=0.8):
"""Add heat transfer coefficent adjustment for feed water flow rate.
This is based on knowing the heat transfer coefficent at a particular flow
and assuming the heat transfer coefficent is porportial to feed water
flow rate raised to certain power (typically 0.8)
Args:
... | f6b34a8e75367b43dbe759d273aa4be7dc371c12 | 12,519 |
def find_process_in_list( proclist, pid ):
"""
Searches for the given 'pid' in 'proclist' (which should be the output
from get_process_list(). If not found, None is returned. Otherwise a
list
[ user, pid, ppid ]
"""
for L in proclist:
if pid == L[1]:
return L
r... | 19eab54b4d04b40a54a39a44e50ae28fbff9457c | 12,520 |
def solution(s, start_pos, end_pos):
"""
Find the minimal nucleotide from a range of sequence DNA.
:param s: String consisting of the letters A, C, G and T,
which correspond to the types of successive nucleotides in the sequence
:param start_pos: array with the start indexes for the intervals to check
:p... | 25ef2f7e9b009de0534f8dde132c0eb44e3fe374 | 12,521 |
def validate_address(value: str, context: dict = {}) -> str:
"""
Default address validator function. Can be overriden by providing a
dotted path to a function in ``SALESMAN_ADDRESS_VALIDATOR`` setting.
Args:
value (str): Address text to be validated
context (dict, optional): Validator c... | 65e04a4780432608aa049687da98bd05a527fbad | 12,522 |
from pathlib import Path
def _get_hg_repo(path_dir):
"""Parse `hg paths` command to find remote path."""
if path_dir == "":
return ""
hgrc = Path(path_dir) / ".hg" / "hgrc"
if hgrc.exists():
config = ConfigParser()
config.read(str(hgrc))
if "paths" in config:
... | 773ab4b45ba6883446c8e4a7725b7ac9d707440f | 12,525 |
def array_to_string(array,
col_delim=' ',
row_delim='\n',
digits=8,
value_format='{}'):
"""
Convert a 1 or 2D array into a string with a specified number
of digits and delimiter. The reason this exists is that the
basic nump... | 9e7f189049b1ad3eff3679568a84e7151e2c643c | 12,526 |
def get_dp_logs(logs):
"""Get only the list of data point logs, filter out the rest."""
filtered = []
compute_bias_for_types = [
"mouseout",
"add_to_list_via_card_click",
"add_to_list_via_scatterplot_click",
"select_from_list",
"remove_from_list",
]
for log in... | e0a7c579fa9218edbf942afdbdb8e6cf940d1a0c | 12,527 |
from typing import List
from typing import Dict
def assign_reports_to_watchlist(cb: CbThreatHunterAPI, watchlist_id: str, reports: List[Dict]) -> Dict:
"""Set a watchlist report IDs attribute to the passed reports.
Args:
cb: Cb PSC object
watchlist_id: The Watchlist ID to update.
reports: T... | 92bb0369211c1720fa4d9baa7a4e3965851339f2 | 12,528 |
def visualize_filter(
image,
model,
layer,
filter_index,
optimization_parameters,
transformation=None,
regularization=None,
threshold=None,
):
"""Create a feature visualization for a filter in a layer of the model.
Args:
image (array): the image to be modified by the fea... | 09940c0484361240929f61f04c9a96771b440033 | 12,529 |
def subtraction(x, y):
"""
Subtraction x and y
>>> subtraction(-20, 80)
-100
"""
assert isinstance(x, (int, float)), "The x value must be an int or float"
assert isinstance(y, (int, float)), "The y value must be an int or float"
return x - y | 203233897d31cb5bc79fca0f8c911b03d7deb5ba | 12,530 |
import aiohttp
async def paste(text: str) -> str:
"""Return an online bin of given text."""
session = aiohttp.ClientSession()
async with session.post("https://hasteb.in/documents", data=text) as post:
if post.status == 200:
response = await post.text()
return f"https://has... | d204f6f1db3aa33c98c4ebeae9888acc438f7dc3 | 12,531 |
def lr_step(base_lr, curr_iter, decay_iters, warmup_iter=0):
"""Stepwise exponential-decay learning rate policy.
Args:
base_lr: A scalar indicates initial learning rate.
curr_iter: A scalar indicates current iteration.
decay_iter: A list of scalars indicates the numbers of
iteration when the lear... | b8cfe670aba0bed1f84ae09c6271e681fad42864 | 12,532 |
def apo(coalg):
"""
Extending an anamorphism with the ability to halt.
In this version, a boolean is paired with the value that indicates halting.
"""
def run(a):
stop, fa = coalg(a)
return fa if stop else fa.map(run)
return run | a1e64d9ed49a8641095c8a8c20ae08c1cc6e9c19 | 12,533 |
def cat_sample(ps):
"""
sample from categorical distribution
ps is a 2D array whose rows are vectors of probabilities
"""
r = nr.rand(len(ps))
out = np.zeros(len(ps),dtype='i4')
cumsums = np.cumsum(ps, axis=1)
for (irow,csrow) in enumerate(cumsums):
for (icol, csel) in enumer... | 30009b31dba0eff23010bfe6d531e8c55e46873c | 12,534 |
def extract_text(text):
""" """
l = []
res = []
i = 0
while i < len(text) - 2:
h, i, _ = next_token(text, i)
obj = text[h:i]
l.append(obj)
for j, tok in enumerate(l):
if tok == b'Tf':
font = l[j-2]
fsize = float(l[j-1])
elif tok ==... | 9b0746be6f6fa39548fd34f3bffda7e8baf4a6ef | 12,536 |
def add_pruning_arguments_to_parser(parser):
"""Add pruning arguments to existing argparse parser"""
parser.add_argument('--do_prune', action='store_true',
help="Perform pruning when training a model")
parser.add_argument('--pruning_config', type=str,
default=... | 2a94e0986564f4af8fe580ca3500f06c04598f14 | 12,537 |
def read_ult_meta(filebase):
"""Convenience fcn for output of targeted metadata."""
meta = _parse_ult_meta(filebase)
return (meta["NumVectors"],
meta["PixPerVector"],
meta["ZeroOffset"],
meta["Angle"],
meta["PixelsPerMm"],
meta["FramesPerSec"],
... | b2237a2dab9faf98179f69de9e9a5f1dc7289f78 | 12,539 |
from typing import Iterable
from typing import List
def safe_identifiers_iterable(val_list: Iterable[str]) -> List[str]:
"""
Returns new list, all with safe identifiers.
"""
return [safe_identifier(val) for val in val_list] | 6b80d90cfac2ea527ace38cc6550571b5f120a7f | 12,540 |
def encode_varint(value, write):
""" Encode an integer to a varint presentation. See
https://developers.google.com/protocol-buffers/docs/encoding?csw=1#varints
on how those can be produced.
Arguments:
value (int): Value to encode
write (function): Called per byte that needs ... | 075286208008a0b7507eafe19158eebdb2af66b7 | 12,541 |
def heap_sort(li):
""" [list of int] => [list of int]
Heap sort: divides its input into a sorted and an unsorted region,
and it iteratively shrinks the unsorted region by extracting the
largest element from it and inserting it into the sorted region.
It does not waste time with a linear-time scan of... | a72be31e5256c880c157636aa7a15df013ce651d | 12,542 |
def vector_field(v, t, inf_mat, state_meta):
"""vector_field returns the temporal derivative of a flatten state vector
:param v: array of shape (1,mmax+1+(nmax+1)**2) for the flatten state vector
:param t: float for time (unused)
:param inf_mat: array of shape (nmax+1,nmax+1) representing the infection... | 31c8023966fd3e5c35b734759a3747f0d2752390 | 12,543 |
def newton(start, loss_fn, *args, lower=0, upper=None, epsilon=1e-9):
"""
Newton's Method!
"""
theta, origin, destination = args[0], args[1], args[2]
if upper is None:
upper = 1
start = lower
while True:
if loss_fn(start, theta, origin, destination) > 0:
start ... | bbd04297639fbc964c55a8c964e5bd5fb24d6e22 | 12,544 |
import torch
def eval_det_cls(pred, gt, iou_thr=None):
"""Generic functions to compute precision/recall for object detection for a
single class.
Args:
pred (dict): Predictions mapping from image id to bounding boxes \
and scores.
gt (dict): Ground truths mapping from image id ... | 762f70d95261509778a1b015af30eab68f951b15 | 12,545 |
import pathlib
from typing import List
from typing import Dict
import tqdm
def parse_g2o(path: pathlib.Path, pose_count_limit: int = 100000) -> G2OData:
"""Parse a G2O file. Creates a list of factors and dictionary of initial poses."""
with open(path) as file:
lines = [line.strip() for line in file.r... | 6c766401220849e337279e8b465f9d67477a1599 | 12,546 |
def _som_actor(env):
"""
Construct the actor part of the model and return it.
"""
nactions = np.product(env.action_shape)
model = keras.models.Sequential()
model.add(keras.layers.Flatten(input_shape=(1,) + env.observation_space.shape))
model.add(keras.layers.Dense(400))
model.add(keras.... | e3bc1f675b16b2d728b1c070324139f0d99071a7 | 12,547 |
def sendEmail():
"""email sender"""
send_email('Registration ATS',
['[email protected]'],
'Thanks for registering ATS!',
'<h3>Thanks for registering with ATS!</h3>')
return "email sent to [email protected]... | e9125c32adac8267aaa550e59e27db4a10746ace | 12,548 |
import scipy
def Pvalue(chi2, df):
"""Returns the p-value of getting chi2 from a chi-squared distribution.
chi2: observed chi-squared statistic
df: degrees of freedom
"""
return 1 - scipy.stats.chi2.cdf(chi2, df) | 1a2198e5d47396fc785a627d96513ded1d6894e0 | 12,549 |
def template(template_lookup_key: str) -> str:
"""Return template as string."""
with open(template_path(template_lookup_key), "r") as filepath:
template = filepath.read()
return template | d03bbc2baa8cb18174a468579bdea1da906de09d | 12,550 |
def filter_rows(df, condition, reason):
"""
:param reason:
:param df:
:param condition: boolean, true for row to keep
:return: filter country_city_codes df
"""
n_dropped = (condition == False).sum()
print(
f"\nexcluding {n_dropped} locations ({n_dropped / df.shape[0]:.1%}) due to... | 7e5e6925bfb7d90bc90b42fda202d80e8ef5e3f6 | 12,551 |
def parse_projected_dos(f):
"""Parse `projected_dos.dat` output file."""
data = np.loadtxt(f)
projected_dos = {"frequency_points": data[:, 0], "projected_dos": data[:, 1:].T}
pdos = orm.XyData()
pdos_list = [pd for pd in projected_dos["projected_dos"]]
pdos.set_x(projected_dos["frequency_points"... | 89c280e92c7598e3947d8ccda20b921c601c9b10 | 12,552 |
def get_from_parameters(a, b, c, alpha, beta, gamma):
"""
Create a Lattice using unit cell lengths and angles (in degrees).
This code is modified from the pymatgen source code [1]_.
Parameters
----------
a : :class:`float`:
*a* lattice parameter.
b : :class:`float`:
*b* la... | 076763f30da86b12747ede930993d99fc3b742d8 | 12,553 |
import random
def random_chinese_name():
"""生成随机中文名字
包括的名字格式:2个字名字**,3个字名字***,4个字名字****
:return:
"""
name_len = random.choice([i for i in range(4)])
if name_len == 0:
name = random_two_name()
elif name_len == 1:
name = random_three_name()
elif name_len == 2:
n... | c86232cb81c492e2301837f5e330e6140ee503f3 | 12,554 |
def power_list(lists: [list]) -> list:
""" power set across the options of all lists """
if len(lists) == 1:
return [[v] for v in lists[0]]
grids = power_list(lists[:-1])
new_grids = []
for v in lists[-1]:
for g in grids:
new_grids.append(g + [v])
return new_grids | 135e3cde20388d999456e2e8a2fed4d98fac581d | 12,555 |
import time
def send_email(from_email, to, subject, message, html=True):
"""
Send emails to the given recipients
:param from_email:
:param to:
:param subject:
:param message:
:param html:
:return: Boolean value
"""
try:
email = EmailMessage(subject, message, from_email,... | 28751bc30f51148c0389d4127229e6352a18cacb | 12,556 |
import random
def attack(health, power, percent_to_hit):
"""Calculates health from percent to hit and power of hit
Parameters:
health - integer defining health of attackee
power - integer defining damage of attacker
percent to hit - float defining percent chance to hit of attacker
... | 83a74908f76f389c798b28c5d3f9035d2d8aff6a | 12,557 |
def signal_requests_mock_factory(requests_mock: Mocker) -> Mocker:
"""Create signal service mock from factory."""
def _signal_requests_mock_factory(
success_send_result: bool = True, content_length_header: str = None
) -> Mocker:
requests_mock.register_uri(
"GET",
"h... | 543f73ec004911c87e9986cbd940a733f03287bf | 12,558 |
def test_dwt_denoise_trace():
""" Check that sample data fed into dwt_denoise_trace() can be processed
and that the returned signal is reasonable (for just one trace)"""
# Loma Prieta test station (nc216859)
data_files, origin = read_data_dir('geonet', 'us1000778i', '*.V1A')
trace = []
trace = ... | 4c526e7e76c8672322bec0323974ca2ee20e25dd | 12,559 |
def get_networks(project_id=None,
auth_token=None):
"""
Get a list of all routed networks
"""
url = CATALOG_HOST + "/routednetwork"
try:
response_body = _api_request(url=url,
http_method="GET",
project... | c2c9bfe05cfa416c9e37d04aefcc640d5d2250f7 | 12,560 |
def feature_registration(source,target, MIN_MATCH_COUNT = 12):
"""
Obtain the rigid transformation from source to target
first find correspondence of color images by performing fast registration
using SIFT features on color images.
The corresponding depth values of the matching keypoints is then use... | d5839ef3586acd84c57341f19700de38660f9a9f | 12,561 |
def set_metadata(testbench_config, testbench):
"""
Perform the direct substitutions from the sonar testbench metadata into the
the testbench
Args:
testbench_config (Testbench): Sonar testbench description
testbench (str): The testbench template
"""
for key, value in testbench_co... | 375712b92f7467ee4d49e5d9e91250464c81337d | 12,562 |
def index(a, x):
"""Locate the leftmost value exactly equal to x"""
i = bisect_left(a, x)
if i != len(a) and a[i] == x:
return i
raise ValueError | f77aed5c55750b848fdf51b66b38f3774c812e23 | 12,563 |
def convert_secondary_type_list(obj):
"""
:type obj: :class:`[mbdata.models.ReleaseGroupSecondaryType]`
"""
type_list = models.secondary_type_list()
[type_list.add_secondary_type(convert_secondary_type(t)) for t in obj]
return type_list | d84d20f6d82b462bda5bf04f6784effea47a0265 | 12,564 |
import json
def load_data(path):
"""Load JSON data."""
with open(path) as inf:
return json.load(inf) | 531fc2b27a6ab9588b1f047e25758f359dc21b6d | 12,566 |
from pathlib import Path
def get_extension(file_path):
"""
get_extension(file)
Gets the extension of the given file.
Parameters
----------
file_path
A path to a file
Returns
-------
str
Returns the extension of the file if it exists or None otherwise.
... | 7b1c4ba4f20ac913bb38292d4a704869cab6937e | 12,567 |
def rank_in_group(df, group_col, rank_col, rank_method="first"):
"""Ranks a column in each group which is grouped by another column
Args:
df (pandas.DataFrame): dataframe to rank-in-group its column
group_col (str): column to be grouped by
rank_col (str): column to be ranked for... | f2ae45641339bf4bc71bc48a415a28602ccf8da3 | 12,568 |
import six
def get_layer_options(layer_options, local_options):
"""
Get parameters belonging to a certain type of layer.
Parameters
----------
layer_options : list of String
Specifies parameters of the layer.
local_options : list of dictionary
Specifies local parameters in a m... | e40945395c4a96c0a0b9447eeb1d0b50cf661bd7 | 12,569 |
def expr(term:Vn,add:Vt,expr:Vn)->Vn:
"""
expr -> term + expr
"""
return {"add":[term,expr]} | f66475ecbd255ac4c4a04b0d705f1c052c4ee123 | 12,570 |
import json
def gene_box(cohort, order='median', percentage=False):
"""Box plot with counts of filtered mutations by gene.
percentage computes fitness as the increase with respect to
the self-renewing replication rate lambda=1.3.
Color allows you to use a dictionary of colors by gene.
... | 851c166246144b14d51863b4c775baa88ab87205 | 12,571 |
from typing import Union
from typing import List
def _clip_and_count(
adata: AnnData,
target_col: str,
*,
groupby: Union[str, None, List[str]] = None,
clip_at: int = 3,
inplace: bool = True,
key_added: Union[str, None] = None,
fraction: bool = True,
) -> Union[None, np.ndarray]:
""... | 20673965557afdcf75b3201cf743fff100981ec3 | 12,572 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.