content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def merge(arr1: Array, arr2: Array) -> Array:
"""
:param arr1, arr2: Two sorted arrays (descending order)
"""
if len(arr1) == 0: return arr2
if len(arr2) == 0: return arr1
resArr = Array(arr1.type)
it1, it2 = iter(arr1), iter(arr2)
tmp1, tmp2 = map(next, [it1, it2])
while True:
... | a2465b18e3eba9e079580173e419089a8482f875 | 3,612,314 |
def _get_storage_service(storage_service_id):
"""Return Storage Service with ID or None.
Unlike elsewhere in our application, here we do not fall back to
a different StorageService if the user-supplied ID is invalid to
prevent inaccurate information from being returned.
:param storage_service_id: ... | 2dbd9a71767479df5807e3d077d6d52598cc45cf | 3,612,315 |
def phases_from_complex(wts, continuous=False, do_detrend=False):
"""Calculates phases from 1d or 2d wavelet/hilbert arrays, dim0 is time"""
if len(wts.shape) == 1:
#1d
phasen = n.arctan2(wts.imag,wts.real)
if not (continuous or do_detrend):
return phasen
else:
... | ef0dc62e5f9212db6b01b1c753c3e2a3c63bd80e | 3,612,318 |
import time
def create_shared_link(folder_id):
"""
Creates an Internet accessible shared link of folder given its identifier.
:param folder_id: Folder identifier.
:return: Shared link if the creation was successful, None otherwise.
"""
box_client = Client(JWTAuth.from_settings_file(BOX_CONFIG_... | 7bebeba7e1243741c4799d9bff7e387fca0785e1 | 3,612,319 |
def lstr(filepath: str) -> str:
"""Alias for lstring"""
return lstring(filepath) | 86eb2a378078de2c566269904be30a69a95023c1 | 3,612,320 |
def movingaverage(inputs, pvalues, dbcur):
"""
inputs: #sensor0, #sensor1, #number
outputs : value
"""
n = inputs["#number"].getvalue()
v = inputs["#sensor1"].getvalue()
if pvalues is None or len(pvalues) == 0:
# first time
values = [v, deque([v] * n)]
else:
q =... | 6b00d33aa1544f18fd93cda84c7ddcbc88368a3f | 3,612,321 |
def pjax(template_names, request, default="pjax_base.html"):
"""
Returns template name for request.
:param request: Django request or boolean value
:param template_names: Base theme name or comma-separated names of base and
pjax templates.
Examples::
{% extends "base.html"|pjax:requ... | e74b1c76abfc68999c316021e6b70f6210125a2a | 3,612,322 |
import functools
def opt(arg, help=None, type=None, abbrev=None, choices=None, metavar=None):
"""
Decorator for annotating optional arguments
"""
abbrev = abbrev or arg[0]
return functools.partial(
_annotate, arg, (help, 'option', abbrev, type, choices, metavar)) | a16fc8ebb2aa7d4baeb1047904abf65181acdb13 | 3,612,323 |
def wrap_scikit_classifier(scikit_class):
"""Wrap a sklearn classifier as a BaseNode subclass.
The wrapper maps these node methods to their sklearn equivalents:
- _stop_training -> fit
- _execute -> predict
"""
newaxis = numpy.newaxis
# create a wrapper class for a sklearn classifier
... | 70b71f1cf7f3bc250a77e12f19b183f17fc6e680 | 3,612,324 |
def for_each_client_jit(client_init: ClientInit, client_step: ClientStep,
client_final: ClientFinal) -> ForEachClient:
"""Creates a for each client function backed by `jax.jit`."""
client_init_jit = jax.jit(client_init)
client_step_jit = jax.jit(client_step)
client_final_jit = jax.jit(cl... | ffac17b20b389f7819e6d6224e39f866a702ff5e | 3,612,326 |
import re
def normalize_buffer(input_buffer):
"""Clear color from input_buffer and special characters.
:param str input_buffer: input buffer string from device
:return: str
"""
# \033[1;32;40m
# \033[ - Escape code
# 1 - style
# 32 - text color
# 40 - Background colour
... | a5922a2df22c58f7f6c4c4bf3ade7bf47a22eb7d | 3,612,327 |
def make_header(ob_size):
"""Make the log header.
This needs to be done dynamically because the observations used as input
to the NN may differ.
"""
entries = []
entries.append("t")
for i in range(ob_size):
entries.append("ob{}".format(i))
for i in range(4):
entries.app... | 82aa8359dad2e78f8d161a1811a7d71b2e496b49 | 3,612,328 |
def reconstruct_3D(*arg):
"""
Reconstruct full size image from a cropped image
Parameters
----------
arg[0] : string
The path and image file name of the original image.
arg[1] : string
The path and image file name of the segmented image.
arg[2]: ndarray
Coordenates of th... | 9cc5ef68fcd4fa11da3a877a2ed6ab23e42a46a4 | 3,612,329 |
def rowslice(table, *sliceargs):
"""
Choose a subsequence of data rows. E.g.::
>>> import petl as etl
>>> table1 = [['foo', 'bar'],
... ['a', 1],
... ['b', 2],
... ['c', 5],
... ['d', 7],
... ['f', 42]]
... | 5da57bd651e6093dda783d1ade9dde1a55ecf2a4 | 3,612,330 |
def evaluate_g8( mu, kappa, nu, sigma, s8 ):
"""
Evaluate the eighth constraint equation and also return the jacobian
:param float mu: The value of the modulus mu
:param float kappa: The value of the modulus kappa
:param float nu: The value of the modulus nu
:param float sigma: The value of the... | d1be8deb9f38dae55082a341e2501044d7b2aef7 | 3,612,331 |
def normalize_company_id_length(business_id):
"""
Normalize given Company ID to 8-digits format.
Example:
========
>>> company_id = "27074358"
>>> normalize_company_id_length(company_id) == "27074358"
True
>>> company_id = "2707435"
>>> normalize_company_id_leng... | 894d455a684e5d8b490af55577e4c22c27020875 | 3,612,333 |
def create_cnn_model() -> tf.keras.Model:
"""Returns a sequential keras CNN Model."""
return tf.keras.Sequential(
[
tf.keras.layers.Conv2D(
16,
8,
strides=2,
padding="same",
activation="relu",
inp... | f4d0850fd4a600cd17252775975e40cad1a8b814 | 3,612,334 |
import math
def calculateXYZByPCAMethod(df, clusterNumber=20, threshold=0.5):
"""
- copy given matrix
- remove all rows/columns where all values are below given
- apply spectral analysis for colouring --> colour
- apply PCA dimension reduction --> x,y,z
- add x,y,z and colour and return matr... | 005ffb405f911e8f8a2a98a63a6c882d170c7c25 | 3,612,335 |
from typing import Callable
from typing import Any
def task(
fn: Callable, **task_init_kwargs: Any
) -> "prefect.tasks.core.function.FunctionTask":
"""
A decorator for creating Tasks from functions.
Args:
- fn (Callable): the decorated function
- **task_init_kwargs (Any): keyword argu... | 52215df1b18612ca9f67a05e5084dc18cf8ff314 | 3,612,336 |
def load_data(messages_filepath, categories_filepath):
"""
Load Messages data and Categories data, and merge then into unique dataframe.
Arguments:
messages_filepath -> Path to the CSV file containing messages
categories_filepath -> Path to the CSV file containing ca... | 9c0fdd93a8c1a1b1a807e75f40337e5195e847c2 | 3,612,337 |
import string
def format_filename(s):
"""
Take a string and return a valid filename constructed from the string.
Uses a whitelist approach: any characters not present in valid_chars are
removed. Also spaces are replaced with underscores.
Note: this method may produce invalid filenames such as ``,... | ce2e2d7ae801390251d2d7de760780099d68b81e | 3,612,338 |
import typing
def load_star(file_name: str) -> pd.DataFrame:
"""
Load a star file.
Arguments:
file_name - Path to the star file
Returns:
Pandas dataframe containing the star file
"""
header_names: typing.List[str]
import_names: typing.List[str]
skip_index: int
star_data: ... | deae28ec048c73829c1adf77d97bff37cca9ed92 | 3,612,341 |
def approve_draft(request, draft_pk):
"""Approves current draft
:param request: mostly for user
:param draft_pk: Unique id for current draft
:return: DraftRegistrationApproval obj
"""
draft = get_draft_or_error(draft_pk)
user = request.user.osf_user
draft.approve(user)
return redire... | bdf0d54250f516aa8343579994285790856c081a | 3,612,342 |
from pathlib import Path
from typing import Dict
from typing import Any
from typing import Optional
def update_dvc_config(
path: Path,
config: Dict[str, Any],
workflow: Optional[str] = None,
verbose: bool = False,
silent: bool = False,
force: bool = False,
) -> bool:
"""Re-run the DVC comm... | 73f76d8ebce2be40e44c9e54cc8679ee4946c7ce | 3,612,344 |
def IsRuntype_RealTrade():
"""运行模式: 是否实盘交易"""
run_type = Environment.get_instance().config.base.run_type
return run_type == RUN_TYPE.LIVE_TRADING | 16dd39dc5a3bd2d45e020ed056cc1631eff17005 | 3,612,345 |
def load_model(opts):
"""
Load models (here we refer to them as data) from load_path
"""
load_data = {}
load_datas = []
path = opts.load_path if opts.load_path is not None else []
if path is not None:
print(" [*] Loading data from {}".format(path))
load_data = torch_load_cpu... | 6fd806358fbd4a60bfba693c46d19b3b36d938ac | 3,612,346 |
import numpy
def hi_lo(data_series, current_max, current_min):
"""Determine the new highest and lowest value."""
try:
highest = numpy.max(data_series)
except:
highest = max(data_series)
if highest > current_max:
new_max = highest
else:
new_max = current_ma... | 63bca68d4af2e50b1c27b5095261c575b35c75d8 | 3,612,347 |
def ChangeBackslashToSlashInPatch(diff_text):
"""Formats file paths in the given patch text to Unix-style paths."""
if not diff_text:
return None
diff_lines = diff_text.split('\n')
for i in range(len(diff_lines)):
line = diff_lines[i]
if line.startswith('--- ') or line.startswith('+++ '):
diff... | 88dce5e16fb400ef2aa1c16950e45491baa5c961 | 3,612,348 |
def parse_line(text: str) -> str:
"""Parses one line into a word."""
text = text.rstrip()
if text[0] == "+":
return text[1:]
if text[0] == "@" or text[0] == "!" or text[0] == "$":
w = text.split("\t")[1]
if "#" in w:
return w.split("#")[0].rstrip()
else:
... | 44e8bd0defc071438aea15002d3e3c6838e61bfb | 3,612,349 |
from typing import Tuple
from typing import Sequence
def map_gauss_coef_pares(
node_coef_pares: Tuple[float, float], seg_a: float, seg_b: float
) -> Sequence[Tuple[float, float]]:
"""
Linearly maps node_coef_pares on [seg_a, seg_b] to [-1, 1],
Given the pares of nodes and coefficient finds the approx... | 226e95eea61c9534fd7b548eea7e4294e2ceb7de | 3,612,350 |
from typing import Union
def vpt(candles: np.ndarray, source_type: str = "close", sequential: bool = False) -> Union[float, np.ndarray]:
"""
Volume Price Trend (VPT)
:param candles: np.ndarray
:param source_type: str - default: "close"
:param sequential: bool - default=False
:return: float |... | 7889b6f54485afd29fc4b9b0d5df5e73838dfcbf | 3,612,351 |
import locale
def get_shell_lc() -> str:
"""取得當前shell的語言代碼。
Returns:
str: 當前shell的語言代碼。
"""
loc = locale.getdefaultlocale()
lc = loc[0]
return lc | 1ea0f09ede398fa1be09cec78d7704dd0db2385c | 3,612,352 |
def wilder_ma(series: nda.NdType, periods: int = 14, warm_periods: tp.Union[int, None] = None):
"""
Wilder's Moving Average
"""
if warm_periods is None:
warm_periods = periods
return ema(series, periods * 2 - 1, warm_periods) | dcbf4b4baac0955a4718a746f119dfb82edf9f9c | 3,612,353 |
def dict_to_cidr(obj):
"""
Take an dict of a Network object and return a cidr-formatted string.
:param obj:
Dict of an Network object
"""
return '%s/%s' % (obj['network_address'], obj['prefix_length']) | c915c16f28b42322c2f63743cdc43a58b964ba27 | 3,612,354 |
def replace_tuple(tuple_obj, replace_obj, replace_index):
"""Create a new tuple with a new object at index"""
if len(tuple_obj) - 1 <= replace_index:
return tuple_obj[:replace_index] + (replace_obj,)
else:
return tuple_obj[:replace_index] + (replace_obj,) + tuple_obj[replace_index+1:] | 28c32ab516eddd7feb90e6b62221f56e8106a2f5 | 3,612,355 |
from typing import Dict
def validate(business: Business, annual_report: Dict) -> Error:
"""Validate the annual report JSON."""
if not business or not annual_report:
return Error(HTTPStatus.BAD_REQUEST, [{'error': _('A valid business and filing are required.')}])
err = validate_ar_year(business=bu... | 792a7943b49947fe80640ecfcca0d0cbe3981b50 | 3,612,356 |
def _timedelta_str_to_schedule_time(time_value: str) -> str:
"""Convert time string to schedule start/end time to hexadecimale.
Args:
data: time to convert. e.g. "21:00".
Return:
Hexadecimal representation of time_value argument.
Raises:
aioswitcher.erros.EncodingError: when failed ... | db61c6f054f83dc0cb5e988ab562387e71b408aa | 3,612,357 |
def submit_WMS(job, infileList):
""" Submit the job locally or to the WMS
"""
dirac = Dirac()
job.setInputData(infileList)
job.setJobGroup('SimpleCtapipe-test')
res = dirac.submit(job)
Script.gLogger.notice('Submission Result: ', res)
return res | 92e6c1a607549a5e3c90720b0934502f49aaf45d | 3,612,358 |
def get_attachment(msg, file_filter=default_attach_filter):
"""
获取邮件里的附件
:param msg:
:param file_filter:
:return:
"""
attachments = []
for part in msg.walk():
if part.get_content_maintype() == 'multipart': continue
if part.get_content_maintype() == 'text': continue
... | 65642e533651efc1990b8713210d0d23a00dea7a | 3,612,361 |
def search_specific(name_or_address):
"""
Allows for direct searches through the URL (not the same as the API)
"""
user = http_auth.username()
answer = {}
answer[name_or_address] = str(searcher.query(name_or_address)).split(' ', 1)[1]
return render_template('search_results.html', title='Sear... | 7ec884a84bca5a0ee2f479a9c0ae254b4e4e9fc7 | 3,612,363 |
def find_unused_port(addr="localhost", start=53589, track=True):
"""Find an unused port starting at `start` port
If track=False the returned port will not be marked as in-use and the code
will rely entirely on the ability to connect to addr:port as detection
mechanism. Note this may cause problems if p... | 508eb9907732ef049053d30cd872e4d18d554a48 | 3,612,364 |
def create_GBM(s0, mu, sigma):
"""
Generates a price following a Geometric Brownian Motion process based on the input of the arguments:
- s0: Asset inital price.
- mu: Interest rate expressed annual terms.
- sigma: Volatility expressed annual terms.
"""
sp = s0
# Generate stock value for the current s... | 12d0b9dd754e460a9da2385e151bf157255b780e | 3,612,365 |
def partial_to_query_filter(partial: Expression, model: Model, **kwargs):
"""
Convert a partial expression to a django query ``Q`` object.
Example expression structure::
Expression(And, [
Expression(Isa, [
Variable('_this'),
Pattern(test_app::Post, {})])... | 9b7503509c98d777c4177b8d98463749481821eb | 3,612,366 |
def closer_than(x1, y1, x2, y2, limitsq):
"""
Helper function to determine whether the square of the distance
between points (x1,y1) and (x2,y2) is less than or equal to limitsq.
The squares of the distances are compared to save computation time.
:Parameters:
x1: float
X ... | ae27e9432bd52c46834b085fa55d8a27523fd806 | 3,612,367 |
from typing import List
from typing import Dict
import json
def get_cloudrun_revisions(cloudrun: Resource, project_id: str) -> List[Dict]:
"""
Returns a list of Cloud Run Revisions for a given project.
:type cloudrun: Resource
:param cloudrun: The cloudrun resource created by googleapicli... | 8160cfad77ee86c2f070261c2cf55ae7a1ac02b9 | 3,612,369 |
import re
def do_rss_latest(parser, token):
"""
A template tag to grab the latest articles from a given feed.
The first argument is the category.
The second argument is the number of items to retrieve.
The third argument (after 'as') is the variable to store the result in.
"""
try:
... | 9029cd5e1b79630712260cc45a31737e9e6959a4 | 3,612,370 |
import torch
def random_sequence(batch_size, seq_size, seq_length, random_state=None):
"""
Args:
batch_size: Number of different sequences of the same size.
seq_size: Number of amino acids that are posible at each residue.
seq_length: Length of each sequence.
Returns:
Gen... | e7b95cffd104c43c0e4fd37b6d311612a8f04616 | 3,612,371 |
def center_crop_images(images, crop_resolution: int):
"""
Crops the center of the images
Args:
images: shape: (B, H, W, 3), H should be equal to W
crop_resolution: target resolution for the crop
Returns:
cropped images which has the shape: (B, crop_resolution, crop_resolution, 3... | 3831dde49fba737f24706c5c19c380bf7d9f9222 | 3,612,372 |
def EER(roc):
"""
Obtain the EER for one fold
"""
far, frr = roc['far'].values, roc['frr'].values
def perp(a):
b = np.empty_like(a)
b[0] = -a[1]
b[1] = a[0]
return b
# line segment a given by endpoints a1, a2
# line segment b given by endpoints b1, b2
de... | 92fe6f93f9c1f4f2e21c86974f6aee39277117e0 | 3,612,373 |
from grudge.trace_pair import interior_trace_pair
from grudge.dof_desc import as_dofdesc
from mirgecom.operators import div_operator
def test_lazy_op_divergence(op_test_data, order):
"""Test divergence operation in lazy context."""
eager_actx, lazy_actx, get_discr = op_test_data
discr = get_discr(order)
... | 3bd79b61992c2f575caa1accaeba55c311230655 | 3,612,374 |
def get_file_name(patch):
"""Return the name of the file to which the patch should be written"""
file_name = None
for line in patch:
if line.startswith('Patch-Filename: '):
file_name = line[len('Patch-Filename: '):]
break
# If no patch-filename header, munge the subject.
if not file_name:
... | 5511b4e4d5f8ada3db17e3236c846b5af2d2303a | 3,612,376 |
def generate_n_random_symbols(n):
"""Returns `n` random upper case ASCII symbols
Args:
number_of_symbols (int): Number of symbols required
Raises:
ValueError: If n is greater than 26 and less than 0
"""
if n in range(27):
upper_case_ascii_characters = [chr(i) for i in range... | 0d0ebf747617717fbaff8b8d1baec7eee540d1dc | 3,612,377 |
def GetActiveEditorDocument():
"""Returns the active editor document and view, or (None,None) if no
active document or its not an editor document.
"""
view = GetActiveView()
if view is None or isinstance(view, TreeView):
return (None, None)
doc = view.GetDocument()
if hasattr(doc, "MarkerAdd"): # Is it an Edit... | 2cdc8367f5234d15c9074175d5db6ca53dfe05ab | 3,612,378 |
def _load_hess_inv(nrows, method, card):
"""loads inverse power"""
alpha_omega_default = None
LJ_default = None
if method == 'INV':
alpha_omega_default = 0.0
LJ_default = 1.0
alphaAjs = []
alphaBjs = []
omegaAjs = []
omegaBjs = []
#mblkszs = []
#iblkszs = []
... | 3b7bdc3974aef1453a6415b92c8e16fe79885848 | 3,612,379 |
def default_exception_serializer(exception):
"""
The default exception serializer for user exceptions in eval.
"""
return '%s: %s' % (type(exception).__name__, str(exception)) | c630ddb9ec6ffc5381c11c4b06c277e4e55910de | 3,612,380 |
def rload(path):
"""Load a dict of data from an R dump format file.
"""
with open(path, 'r') as fd:
lines = fd.readlines()
data = {}
for line in lines:
lhs, rhs = [item.strip() for item in line.split('<-')]
if rhs.startswith('structure'):
vals, dim = rhs.replace('... | d55b7ca6fdfd40c26d079ec0045862940cdbaa0c | 3,612,381 |
def _read_locs(filepath, chs, egi_info):
"""Read channel locations."""
fname = op.join(filepath, 'coordinates.xml')
if not op.exists(fname):
return chs
numbers = np.array(egi_info['numbers'])
coordinates = parse(fname)
sensors = coordinates.getElementsByTagName('sensor')
for sensor i... | 8345cf9777ed6e74a88f8c865fb98ed159b38d11 | 3,612,382 |
def link_edges(strong_edges, weak_edges):
""" Find weak edges connected to strong edges and link them.
Iterate over each pixel in strong_edges and perform breadth first
search across the connected pixels in weak_edges to link them.
Here we consider a pixel (a, b) is connected to a pixel (c, d)
if (... | 785ece94808fe405f8faa539803ee2e88474a393 | 3,612,383 |
def heading(angle):
"""
Computes cardinal direction based on heading/orientation. Assumes
robot heading is parallel to cartesian axes and 0 heading is south.
Args:
angle (float): Angle of yaw orientation
Returns:
(str): Cardinal direction
"""
if -5*np.pi/9 <= angle <= -4*np.pi/... | 4d13afbd65d8f5d0b5ab3e352023ebc13d9efeac | 3,612,384 |
import copy
def remove_candidates(orders, candidates_to_remove):
"""
Remove a set of candidates from a list representing a preference order.
"""
projection = []
for c_vote in orders:
temp_vote = copy.copy(c_vote)
for c_remove in candidates_to_remove:
temp_vote.remove(c_remove)
projection... | bd0b98acefacaf9891b4ab7109d01d187f1de85a | 3,612,386 |
import time
def timethis(func):
"""Report execution time of function."""
@wraps(func)
def wrapper(*args, **kwargs):
start = time.time()
result = func(*args, **kwargs)
end = time.time()
print(func.__name__, f"took {end-start:3.2f}s")
return result
return wrappe... | bac11d68378d2251c31abcf864f560b0d5f7a666 | 3,612,387 |
import random
def dummytable(numrows=100,
fields=(('foo', partial(random.randint, 0, 100)),
('bar', partial(random.choice, ('apples', 'pears',
'bananas', 'oranges'))),
('baz', random.random)),
... | b38a1f76bd44390000a4e1f47fed42ab27fd0b50 | 3,612,388 |
def scores_plot(scores, plot_num, threashold, title = ""):
"""Plotting the scores over episodes for different networks
Params
======
scores (list of dict): Containing at least 'scores', 'fc1_units', and 'fc2_units' for plotting
plot_num (int): dimensionality of plot (is N for an NxN plo... | 25e05520881ad1a84b1fd77c6c431ab9956a07a4 | 3,612,389 |
def rank(values, axis=0, method='average', na_option='keep',
ascending=True):
"""
"""
if values.ndim == 1:
f, values = _get_data_algo(values, _rank1d_functions)
ranks = f(values, ties_method=method, ascending=ascending)
elif values.ndim == 2:
f, values = _get_data_algo(... | 46854f0a067f3fc8342266ded9bc2a82cbe5651e | 3,612,390 |
def one_move(pos=start, step=1):
"""
Make one move from the given position `pos`.
"""
board[pos[0]][pos[1]] = step
if step == cnt:
fmt = "{{:{}d}}".format(ceil(log10(rows*cols))+1)*cols
for i in range(rows):
print(fmt.format(*board[i]))
return True
step += 1
... | 8fc2dd7c1b0191ee8b896961020d87d300c6eab6 | 3,612,391 |
import re
def _get_mainfunc_from_js(js):
""" Return main signature decryption function from javascript as dict. """
dbg("Scanning js for main function.")
m = re.search(r'\w\.sig\|\|([$\w]+)\(\w+\.\w+\)', js)
funcname = m.group(1)
dbg("Found main function: %s", funcname)
function = _extract_fun... | 42ad48777bfd045397ada7e353b10b3c9569d868 | 3,612,392 |
def dissociate(op, args):
""" Given an associative operator, return a flattened list result """
result = []
def collect(subargs):
for arg in subargs:
if arg.func == op:
collect(arg.args)
else:
result.append(arg)
collect(args)
return r... | 1b517738d5c27cd27f308483673e3f5c5fb40bbc | 3,612,393 |
from pgxnclient.zip import ZipArchive
from pgxnclient.tar import TarArchive
def from_file(filename):
"""Return an `Archive` instance to handle the file *filename*"""
for cls in (ZipArchive, TarArchive):
a = cls(filename)
if a.can_open():
return a
raise PgxnClientException(
... | 519d92fdc780f4b40ead75896d433703162f897d | 3,612,394 |
def deserialize_population_frame(frame, inplace=False):
"""Deserializes a population `pd.DataFrame` from plain text.
Args:
frame: A `pd.DataFrame` produced by `serialize_population_frame`.
inplace: Whether to deserialize `frame` inplace instead of creating a copy.
Returns:
A `pd.DataFrame` with dese... | ad8fecd593cb918f0bbf0c43ef876059e865cc2e | 3,612,395 |
import torch
def latent_kl(prior_mean, posterior_mean):
"""
:param prior_mean:
:param posterior_mean:
:return:
"""
kl = 0.5 * torch.pow(prior_mean - posterior_mean, 2)
kl = torch.sum(kl, dim=[1, 2, 3])
kl = torch.mean(kl)
return kl | 2785902d758c45a4ad8be4f38b88e8cfb5bbc6ce | 3,612,396 |
def query_index(index, query):
"""Returns search results for your given query"""
es = get_elastic_client()
if not es:
return []
search = es.search(
index=index,
body={
"query": {
"multi_match": {
"query": query,
... | 731036ff858e55d5b5d1d5af80a548fbd858efd1 | 3,612,398 |
def get_db_dir():
"""
Just return the default dir listed above
:return: the default location for the sqllite database
"""
return defaultdir | 1d5bb8ac177e65abb2788e686d2db30bec70bbd8 | 3,612,399 |
def channel_is_size(channel):
"""Checks if a channel is of set size (see: /setsize handler)"""
channel_number = bot.get_chat_members_count(channel)
if channel_number >= min_channel_size:
return True
else:
return False | 33b0e71bbc24b400a5ef759efb1e783707deacfc | 3,612,400 |
def factorial(n):
"""
Calculate n!
Args:
n(int): factorial to be computed
Returns:
n!
"""
if n == 0:
return 1 # by definition of 0!
return n * factorial(n-1) | a0e8e6edbf03bb1fb1e6a11d7ace41e37992b54f | 3,612,401 |
def discover(scan_attempts=10, scan_interval=1):
"""Creates a Harmony client and initializes session.
Args:
scan_attempts (int): Number of times to scan the network
scan_interval (int): Seconds between running each network scan
Returns:
A list of Hub devices found and their configs... | 1b8fd49732260f942e5008b696cfd173f3469d2e | 3,612,402 |
import re
def getMonetaryQuantityQuantUnit(words):
"""
from training data:
count perc cum_sum cum_perc
kind_c
dollar 133 60.454545 133 60.454545
yuan 36 16.363636 169 76.818182
euro 23 10.454545 192 87.27... | 406a21ea1fb7617a93fbc656b3cb85ac449efba7 | 3,612,404 |
def get_env_config(config_type: str, config_set: str, dist_name: str = None) -> dict:
"""Function for drawing some built-in configuration dictionaries
:param config_type: Type of configuration to draw.
:param config_set: Which set to draw from.
:param dist_name: Name of the distribution within a set.
... | b8f1c52b089543e1b02b534ef5ab60d1fb050753 | 3,612,406 |
from twisted.internet import defer, reactor
from invoke.tasks import Task, task as task_decoracor
def task_on_callbacks(*task_args, **task_kwargs):
"""
A proxy for ``invoke.tasks.task`` parameterized decorator.
"""
def decorator(function):
"""
A decorator which wraps original Deferred... | 181b64245cb9e4c6c8bcdad40e4e40b2e448d91d | 3,612,407 |
from typing import Sequence
from typing import Optional
from typing import Tuple
def traj_loss_antithetic_es(
p_yses: Sequence[truncated_step_mod.TruncatedUnrollOut],
n_yses: Sequence[truncated_step_mod.TruncatedUnrollOut],
vec_pos: MetaParams,
std: float,
loss_type: str,
clip_loss_diff: Optio... | c662848702066ec6f6f95d9e0e67317d9e6fd435 | 3,612,408 |
import numpy
def compareMentorsAndTeams(mentor_sch, team_sch):
"""
Teams can only meet with the mentors when the mentors are available, so
for each mentor multiply the 0..1 mentor value against the team team
availability count to use the mentor schedule as a mask over the team
schedule.
We co... | cd500c6354af616523e5842770e256be9638e19e | 3,612,409 |
def get_word_count(text, keywords):
"""
Args:
text (str):
keywords (list):
Returns:
"""
count_dict = {}
for keyword in keywords:
count_dict[keyword] = text.count(keyword)
return count_dict | eaf5258b07cb861c2cce8c55ede2342aaf141f8d | 3,612,410 |
import re
def handle_special_operator(formula, operator):
"""
如果有 "*-", "-*", "/-", "-/" 这些运算符,
提取负号,去掉重复的运算符
:param formula:
:param operator:
:return:
"""
temp = ""
regex = "\d*[.]?\d+"
opera = operator.replace("*", "[*]")
ret = re.compile(opera.join([regex, reg... | c9e4795d4ccb07549d12e13d2f7050036f018e45 | 3,612,411 |
import copy
def cosmicmed(data, sigma=1.5):
"""
Precise cosmic ray elimination for measurements of the same point or very
similar spectras.
:type data: list[float]
:param data: List of spectras to remove cosmic rays.
:type sigma: float
:param sigma: Factor to modify the criteria to i... | b9212779a49d01c2c2168bb3a421b14c1d3a7504 | 3,612,412 |
from typing import Any
def schema(
var_name: str,
data_type: Any,
) -> str:
"""Returns a YAML-like string for our data type; these are used for
pretty-printing and comparison between the OpenAPI type
definitions and these Python data types, as part of
schema is a glorified repr of a data type... | 20fc1a642c4543e9b520aa08d0312deca5349377 | 3,612,414 |
def get_user(username=None, email=None, apikey=None):
"""Return the user for the given username, email or apikey.
Return None if no such user.
"""
if username:
rows = flask.g.db.view("users", "username",
key=username.lower(), include_docs=True)
elif email:
... | 7ef19acf5f4274c51d7966756add31049ef154a5 | 3,612,415 |
def resolveVarStrDashMuts(varStr):
"""If there is a sequence of mutations like T28144- followed by -28144C, get rid of the T>-
and replace the ->C with T>C. Get rid of solo basePos- because they can occur in very long
lists when samples have long stretches of Ns, not helpful."""
if (not varStr):
... | 3ee09c6191f6ae361d6b309395292bb09447f0dd | 3,612,416 |
import re
def get_urls(text):
"""Extract urls from text.
Parameters
----------
text : text that contains url(s)
Returns
-------
links : a list of Links of urls in the text.
"""
# URL
URL_REGEX = r"""(?i)\b((?:https?:(?:/{1,3}|[a-z0-9%])|[a-z0-9.\-]+[.](?:com|net|org|edu|gov|m... | 14ac292ca6d4cabc515201152051734bc66e852e | 3,612,417 |
def get_fund_id():
"""
Use this function when you want to find the fund_id using the fund name.
Returns
-------
fund_id: string
The CNPJ of the fund, that is the brazilian tax id and used in this
script as fund_id.
"""
funds = pd.read_sql("SELECT DISTINCT denom_social FROM... | b38214d2ab2bb7c740c8d365cd9420d9487ebe91 | 3,612,418 |
import json
def readJson(filename):
"""
Returns a list of all the objects in the .json set
"""
with open(filename, 'r') as f:
data = json.load(f)
info = str(data)
info.split(":")
keys = []
for i in data:
keys.append(i)
obj = []
for i in keys:
obj.append(... | 79e8f1ce74594ca215c490a7447fea9974c296a0 | 3,612,419 |
from typing import Any
async def game_over(_: models.User = Depends(dependencies.get_current_user)) -> Any:
"""
User completed answering all questions.
"""
await LOGGER.info("User completed answering all questions")
return {"message": "Congratulations, you have answered all questions!"} | bb723f684a727536e3118366ec85b932385066c4 | 3,612,420 |
def convert_categorical(categorical):
"""
"""
cat = categorical.copy()
is_gridslice = '{' in cat.name
if is_gridslice:
resp_prefix = cat.name.split('[{')[0] + 'a'
else:
resp_prefix = categorical.name + 'a'
if not cat.dtype == 'object':
cat = cat.apply(lambda x:
... | c227b3822f69dbc8cb64fee8f1a2eaa15370748c | 3,612,421 |
import copy
def make(model):
"""Create a new model to avoid overwriting the global variable."""
return copy.copy(model) if isinstance(model, Forward) else Backward(model) | d4cdb6b4eef38de843e6d928dec47b767b3e2493 | 3,612,422 |
import torch
def aggregate_mean(h):
"""mean aggregation"""
return torch.mean(h, dim=1) | c897e4c36f2ba6fc9719cc8d7437086970886085 | 3,612,423 |
def rm2v(r):
"""
Wrapper for ERFA function ``eraRm2v``.
Parameters
----------
r : double array
Returns
-------
w : double array
Notes
-----
The ERFA documentation is below.
- - - - - - - -
e r a R m 2 v
- - - - - - - -
Express an r-matrix as an r-vector.... | 1506fa459f61241094ca86a42ce25b2e9d737d94 | 3,612,424 |
from re import T
def get_conv_torch(mask):
""" Get 2d torch convolution with mask """
in_chan, out_chan = 1, 1
shape = mask.shape
l = T.nn.Conv3d(in_chan, out_chan, shape
, stride=shape
, padding=0
, bias = False
... | f3a646041b8f403cee0f5dbb2a9726f29b00f150 | 3,612,425 |
from typing import List
def prepare_electrodes_positions(
configuration: str, n_sites: int = 384
) -> List[ActiveElectrode]:
"""
Defines the position along the probe (in coordinates from the first electrode)
of each active electrode
"""
if configuration == "b0":
Y = 20 * np.rep... | 8bb4b4d29d8e751e205ce05598f7d0a9eda9faae | 3,612,426 |
def player_exists(selected_id: str, already_taken_ids: list = []):
"""Verifies if the player selected by the user exists.
Args:
selected_id (str): Player chosen by the user.
already_taken_ids (list, optional): List of ids the user cannot choose from. Defaults to [].
Returns:
bool: ... | df7cde112742db1a20ca3f325f848eef41367bac | 3,612,427 |
def subspace(P, k, precision, mode):
"""
Computes isometries `V1` and `V2` respectively mapping into the column and
null space of a rank-`k` projection matrix `P`.
Args:
P: The input matrix, expected to be a projector as described in the
docstring.
k: The rank of `P`.
precision: The matmul p... | eb63ec26f15d5d8d6be785093c35ad4aba23f9b9 | 3,612,428 |
def combine_results(partitions, destination_dict):
"""
Combines partitioned results into single csv file
:param partitions: list containing aws partition addresses
:param destination_dict: folder where results are saved
"""
df = pd.DataFrame()
for part_id in partitions:
partial_df = ... | 472e033480011ef0ecd29e59843e9303aa84599f | 3,612,429 |
def make_prediction(*, input_data: t.Union[pd.DataFrame, dict],) -> dict:
"""Make prediction using a saved model pipeline."""
# load trained model from local storage
pipeline_file_name = f'{config.PIPELINE_SAVE_FILE}{_version}.pkl'
_price_pipe = load_pipeline(file_name=pipeline_file_name)
# valida... | 7bf0c52635525b35cb43295e5e632b5d4d1beb54 | 3,612,431 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.