content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def swig_py_object_2_list_int(object, size : int) -> List[int]:
"""
Converts SwigPyObject to List[float]
"""
y = (ctypes.c_float * size).from_address(int(object))
new_object = []
for i in range(size):
new_object += [int(y[i])]
return new_object | 5,351,200 |
def ParseAttributesFromData(attributes_data, expected_param_names):
"""Parses a list of ResourceParameterAttributeConfig from yaml data.
Args:
attributes_data: dict, the attributes data defined in
command_lib/resources.yaml file.
expected_param_names: [str], the names of the API parameters that the A... | 5,351,201 |
async def reactionFromRaw(payload: RawReactionActionEvent) -> Tuple[Message, Union[User, Member], emojis.BasedEmoji]:
"""Retrieve complete Reaction and user info from a RawReactionActionEvent payload.
:param RawReactionActionEvent payload: Payload describing the reaction action
:return: The message whose r... | 5,351,202 |
def cancelDelayedCalls(expected=2):
"""
:param expected:
The number of calls to cancel. If the number found does not match this,
none of them will be cancelled so that trial's cleanup can tell you
more about them.
Why the default of 2? Hopefully you're only testing one delayed calll
... | 5,351,203 |
def poisson2d(N,dtype='d',format=None):
"""
Return a sparse matrix for the 2d poisson problem
with standard 5-point finite difference stencil on a
square N-by-N grid.
"""
if N == 1:
diags = asarray( [[4]],dtype=dtype)
return dia_matrix((diags,[0]), shape=(1,1)).asformat(format)... | 5,351,204 |
def qa():
"""Works on qa environment"""
global c
c.env = 'qa' | 5,351,205 |
def get_factory():
"""随机获取一个工厂类"""
return random.choice([BasicCourseFactory, ProjectCourseFactory])() | 5,351,206 |
def delay_class_factory(motor_class):
"""
Create a subclass of DelayBase that controls a motor of class motor_class.
Used in delay_instace_factory (DelayMotor), may be useful for one-line
declarations inside ophyd Devices.
"""
try:
cls = delay_classes[motor_class]
except KeyError:
... | 5,351,207 |
def check_and_makedir(folder_name):
""" Does a directory exist? if not create it. """
if not os.path.isdir(folder_name):
os.mkdir(folder_name)
return False
else:
return True | 5,351,208 |
def _get_all_files_in_directory(dir_path, excluded_glob_patterns):
"""Recursively collects all files in directory and
subdirectories of specified path.
Args:
dir_path: str. Path to the folder to be linted.
excluded_glob_patterns: set(str). Set of all glob patterns
to be excluded... | 5,351,209 |
def lonlat2px_gt(img, lon, lat, lon_min, lat_min, lon_max, lat_max):
"""
Converts a pair of lon and lat to its corresponding pixel value in an
geotiff image file.
Parameters
----------
img : Image File, e.g. PNG, TIFF
Input image file
lon : float
Longitude
lat : float
... | 5,351,210 |
def patchwise_contrastive_metric(image_sequence: torch.Tensor,
kpt_sequence: torch.Tensor,
method: str = 'norm',
time_window: int = 3,
patch_size: tuple = (7, 7),
... | 5,351,211 |
def array_wishart_rvs(df, scale, **kwargs):
""" Wrapper around scipy.stats.wishart to always return a np.array """
if np.size(scale) == 1:
return np.array([[
scipy.stats.wishart(df=df, scale=scale, **kwargs).rvs()
]])
else:
return scipy.stats.wishart(df=df, scale=scal... | 5,351,212 |
def get_mpl_colors():
"""
==================
Colormap reference
==================
Reference for colormaps included with Matplotlib.
This reference example shows all colormaps included with Matplotlib. Note that
any colormap listed here can be reversed by appending "_r" (e.g., "pin... | 5,351,213 |
def list_sequences(bam):
"""
List the sequences involved and whether they are forward or reverse
:param bam: the bam object from pysam
:type bam: pysam.AlignmentFile
:return:
:rtype:
"""
for template in locations:
for primer in locations[template]:
start, end = locat... | 5,351,214 |
async def async_setup_entry(hass, entry):
"""Set up Jenkins from a config entry."""
hass.async_create_task(
hass.config_entries.async_forward_entry_setup(entry, "sensor")
)
return True | 5,351,215 |
def signal_to_dataset(raw, fsamp, intvs, labels):
"""Segmentize raw data into list of epochs.
returns dataset and label_array : a list of data, each block is 1
second, with fixed size. width is number of channels in certain standard
order.
Args:
raw: EEG signals. Shape: (n_channel,... | 5,351,216 |
def project_dynamic_property_graph(graph, v_prop, e_prop, v_prop_type, e_prop_type):
"""Create project graph operation for nx graph.
Args:
graph (:class:`nx.Graph`): A nx graph.
v_prop (str): The node attribute key to project.
e_prop (str): The edge attribute key to project.
v_p... | 5,351,217 |
def show__machines(args):
"""
Show the machines user is offering for rent.
:param argparse.Namespace args: should supply all the command-line options
:rtype:
"""
req_url = apiurl(args, "/machines", {"owner": "me"})
r = requests.get(req_url)
r.raise_for_status()
rows = r.json()["mach... | 5,351,218 |
def eqfm_(a, b):
"""Helper for comparing floats AND style names."""
n1, v1 = a
n2, v2 = b
if type(v1) is not float:
return eq_(a, b)
eqf_(v1, v2)
eq_(n1, n2) | 5,351,219 |
def play_env_problem_randomly(env_problem, num_steps):
"""Plays the env problem by randomly sampling actions for `num_steps`."""
# Reset all environments.
env_problem.reset()
# Play all environments, sampling random actions each time.
for _ in range(num_steps):
# Sample batch_size actions from the action... | 5,351,220 |
def flatten_comment(seq):
"""Flatten a sequence of comment tokens to a human-readable string."""
# "[CommentToken(value='# Extra settings placed in ``[app:main]`` section in generated production.ini.\\n'), CommentToken(value='# Example:\\n'), CommentToken(value='#\\n'), CommentToken(value='# extra_ini_settings... | 5,351,221 |
def test_countstore_reset_dates():
"""Dates attrs are all set to None"""
c = CountStore()
c.start = 42
c.start_date = now()
c.end = 52
c.end_date = now()
c.reset()
assert c.start is None
c.start_date is None
c.end is None
c.end_date is None | 5,351,222 |
def get_community(community_id):
"""
Verify that a community with a given id exists.
:param community_id: id of test community
:return: Community instance
:return: 404 error if doesn't exist
"""
try:
return Community.objects.get(pk=community_id)
except Community.DoesNotExist:
... | 5,351,223 |
def load_labeled_info(csv4megan_excell, audio_dataset, ignore_files=None):
"""Read labeled info from spreat sheet
and remove samples with no audio file, also files given in ignore_files
"""
if ignore_files is None:
ignore_files = set()
with open(csv4megan_excell) as csvfile:
read... | 5,351,224 |
def de_dupe_list(input):
"""de-dupe a list, preserving order.
"""
sam_fh = []
for x in input:
if x not in sam_fh:
sam_fh.append(x)
return sam_fh | 5,351,225 |
def donwload_l10ns():
"""Download all l10ns in zip archive."""
url = API_PREFIX + 'download/' + FILENAME + KEY_SUFFIX
l10ns_file = urllib2.urlopen(url)
with open('all.zip','wb') as f:
f.write(l10ns_file.read())
return True | 5,351,226 |
def test_space_translation():
"""Compare code-transformed waveform to analytically transformed waveform"""
print("")
ell_max = 8
for s in range(-2, 2 + 1):
for ell in range(abs(s), ell_max + 1):
print("\tWorking on spin s =", s, ", ell =", ell)
for m in range(-ell, ell + ... | 5,351,227 |
def _constant_velocity_heading_from_kinematics(kinematics_data: KinematicsData,
sec_from_now: float,
sampled_at: int) -> np.ndarray:
"""
Computes a constant velocity baseline for given kinematics data, time window
... | 5,351,228 |
def arg_int(name, default=None):
""" Fetch a query argument, as an integer. """
try:
v = request.args.get(name)
return int(v)
except (ValueError, TypeError):
return default | 5,351,229 |
def db(app, request):
"""Session-wide test database."""
if os.path.exists(os.path.join(INSTANCE_FOLDER_PATH, 'test.sqlite')):
os.unlink(os.path.join(INSTANCE_FOLDER_PATH, 'test.sqlite'))
def teardown():
_db.drop_all()
os.unlink(os.path.join(INSTANCE_FOLDER_PATH, 'test.sqlite'))
... | 5,351,230 |
def adapter_rest(request, api_module_rest, api_client_rest):
"""Pass."""
return {
"adapter": request.param,
"api_module": api_module_rest,
"api_client": api_client_rest,
} | 5,351,231 |
def extract(lon, lat, dep, prop=['rho', 'vp', 'vs'], **kwargs):
"""
Simple CVM-S extraction
lon, lat, dep: Coordinate arrays
prop: 'rho', 'vp', or 'vs'
nproc: Optional, number of processes
Returns: (rho, vp, vs) material arrays
"""
lon = numpy.asarray(lon, 'f')
lat = numpy.asarray(... | 5,351,232 |
def test_meridian_arc(lat1, lat2, arclen):
"""
meridianarc(deg2rad(40), deg2rad(80), wgs84Ellipsoid)
"""
assert lox.meridian_arc(lat1, lat2) == approx(arclen) | 5,351,233 |
def remove_quotes(string):
"""Function to remove quotation marks surrounding a string"""
string = string.strip()
while len(string) >= 3 and string.startswith('\'') and string.endswith('\''):
string = string[1:-1]
string = quick_clean(string)
string = quick_clean(string)
return... | 5,351,234 |
def create_chain_widget(rig, bone_name, radius=0.5, invert=False, bone_transform_name=None):
"""Creates a basic chain widget
"""
obj = create_widget(rig, bone_name, bone_transform_name)
if obj != None:
r = radius
rh = radius/2
if invert:
verts = [(rh, rh, rh), (r, -r,... | 5,351,235 |
def compute_list_featuretypes(
data,
list_featuretypes,
fourier_n_largest_frequencies,
wavelet_depth,
mother_wavelet,
):
"""
This function lets the user choose which combination of features they
want to have computed.
list_featuretypes:
"Basic" - min, max, mean, kurt ,skew, ... | 5,351,236 |
def select(locator):
"""
Returns an :class:`Expression` for finding selects matching the given locator.
The query will match selects that meet at least one of the following criteria:
* the element ``id`` exactly matches the locator
* the element ``name`` exactly matches the locator
* the elemen... | 5,351,237 |
def send_image(filename):
"""Route to uploaded-by-client images
Returns
-------
file
Image file on the server (see Flask documentation)
"""
return send_from_directory(app.config['UPLOAD_FOLDER'], filename) | 5,351,238 |
def update(key, view, errors):
"""
Update updates the set of shown errors.
The method shos a given list of errors on the given
view, keyed by `key`, each tool uses a different key.
"""
set = PhantomSet(view, key)
all = []
for err in errors:
if buffer.filename(view) == err.file:
all.append(... | 5,351,239 |
def swissPairings():
"""Returns a list of pairs of players for the next round of a match.
Assuming that there are an even number of players registered, each player
appears exactly once in the pairings. Each player is paired with another
player with an equal or nearly-equal win record, that is, a playe... | 5,351,240 |
def split(data, batch):
"""
PyG util code to create graph batches
"""
node_slice = torch.cumsum(torch.from_numpy(np.bincount(batch)), 0)
node_slice = torch.cat([torch.tensor([0]), node_slice])
row, _ = data.edge_index
edge_slice = torch.cumsum(torch.from_numpy(np.bincount(batch[row])), 0)
edge_slice = torch.c... | 5,351,241 |
def test_add_asset_conflict_error(cli, init_assets):
"""Tests the method ``add_asset`` of the class ``InventoryClient`` with an
already existing asset."""
asset_id = init_assets[2].asset_id
asset = Asset(asset_id)
timestamp = datetime.fromisoformat('2022-01-01T01:00:00+00:00')
expiration = date... | 5,351,242 |
def add_drop_subcommand(subparser_factory):
"""Add a subparser for the drop subcommand."""
drop_help = "Drop a database from the test server."
subparser = subparser_factory.add_parser('drop', help=drop_help,
description=drop_help)
dbname_help = "The name of... | 5,351,243 |
def test_value_repr():
"""Test string representations for archive values."""
value = SingleVersionValue(
value=1,
timestamp=Timestamp(intervals=[TimeInterval(start=1, end=3)])
)
assert str(value) == '(1 [[1, 3]])'
value = MultiVersionValue([
SingleVersionValue(
va... | 5,351,244 |
def test_withdrawal_request_status(mocker, response, uclient) -> None:
"""Test the test_withdrawal_request_status method of the sync client"""
url = f'{LunoSyncClient.BASE_URI}withdrawals/1234'
data = {}
mocker.patch('requests.Session.request', return_value=response)
response = uclient.withdra... | 5,351,245 |
def _get_shadowprice_data(scenario_id):
"""Gets data necessary for plotting shadow price
:param str/int scenario_id: scenario id
:return: (*tuple*) -- interconnect as a str, bus data as a data frame, lmp data
as a data frame, branch data as a data frame and congestion data as a data
frame
... | 5,351,246 |
def get_city_reviews(city):
"""
Given a city name, return the data for all reviews.
Returns a pandas DataFrame.
"""
with open(f"{DATA_DIR}/{city}/review.json", "r") as f:
review_list = []
for line in f:
review = json.loads(line)
review_list.append(review)
... | 5,351,247 |
def extract_rows_from_table(dataset, col_names, fill_null=False):
""" Extract rows from DB table.
:param dataset:
:param col_names:
:return:
"""
trans_dataset = transpose_list(dataset)
rows = []
if type(col_names).__name__ == 'str':
col_names = [col_names]
for col_name in col... | 5,351,248 |
def CalculateHydrogenNumber(mol):
"""
#################################################################
Calculation of Number of Hydrogen in a molecule
---->nhyd
Usage:
result=CalculateHydrogenNumber(mol)
Input: mol is a molecule object.
... | 5,351,249 |
def check_update ():
"""Return the following values:
(False, errmsg) - online version could not be determined
(True, None) - user has newest version
(True, (version, url string)) - update available
(True, (version, None)) - current version is newer than online version
"""
version... | 5,351,250 |
def draw_and_save(data_img_dir, img_fname, output, output_type, results_path, tfr_func=None):
"""Draws on the images for the detected object and saves them on the given location.
Parameters:
-----------
data_img_dir (str): directory path where images are saved
img_fname (str): name of an image stored in t... | 5,351,251 |
def count_regularization_baos_for_both(z, count_tokens, count_pieces, mask=None):
"""
Compute regularization loss, based on a given rationale sequence
Use Yujia's formulation
Inputs:
z -- torch variable, "binary" rationale, (batch_size, sequence_length)
percentage -- the percentage of w... | 5,351,252 |
def main():
"""
Example for solving CC-Lagrangian and then computing 1-RDM and 2-RDM
"""
import pyscf
import openfermion as of
from openfermion.chem.molecular_data import spinorb_from_spatial
from openfermionpyscf import run_pyscf
from pyscf.cc.addons import spatial2spin
from pyscf i... | 5,351,253 |
def unsqueeze_samples(x, n):
"""
"""
bn, d = x.shape
x = x.reshape(bn//n, n, d)
return x | 5,351,254 |
def f_snr(seq):
"""compute signal to noise rate of a seq
Args:
seq: input array_like sequence
paras: paras array, in this case should be "axis"
"""
seq = np.array(seq, dtype=np.float64)
result = np.mean(seq)/float(np.std(seq))
if np.isinf(result):
print "marker"
result = 0
return result | 5,351,255 |
def prepare_dataset_with_flair(args, data_path, tokenizer, pos_tokenizer):
"""使用flair标注的dirty,和由词表构建的tokenizer,来把token和pos转换成token_id和pos_id,并构建pos2word
Args:
write_path ([string]): [写vocab的路径]
"""
pos2word = [set() for i in range(len(pos_tokenizer.tag_vocab))]
# tokenizer.vocab_size+2 包括了 ... | 5,351,256 |
def main():
"""Runs label studio server using given config."""
global input_args
input_args = parse_input_args()
server.input_args = input_args
# setup logging level
if input_args.log_level:
print(f"log level is {input_args.log_level}")
logging.root.setLevel(input_args.log_leve... | 5,351,257 |
def _lorentzian_pink_beam(p, x):
"""
@author Saransh Singh, Lawrence Livermore National Lab
@date 03/22/2021 SS 1.0 original
@details the lorentzian component of the pink beam peak profile
obtained by convolution of gaussian with normalized back to back
exponentials. more details can be found in... | 5,351,258 |
def get_q_HPU_ave(Q_HPU):
"""1時間平均のヒートポンプユニットの平均暖房出力 (7)
Args:
Q_HPU(ndarray): 1時間当たりのヒートポンプユニットの暖房出力 (MJ/h)
Returns:
ndarray: 1時間平均のヒートポンプユニットの平均暖房出力 (7)
"""
return Q_HPU * 10 ** 6 / 3600 | 5,351,259 |
def run(self):
"""Run the Electrical module"""
if self.parent is None:
raise InputError("The Electrical object must be in a Simulation object to run")
if self.parent.parent is None:
raise InputError("The Simulation object must be in an Output object to run")
self.get_logger().info("Star... | 5,351,260 |
def android_example():
"""A basic example of how to use the android agent."""
env = holodeck.make("AndroidPlayground")
# The Android's command is a 94 length vector representing torques to be applied at each of his joints
command = np.ones(94) * 10
for i in range(10):
env.reset()
fo... | 5,351,261 |
def create_table_ISI():
""" create ISI (inter spike interval) table """
commands = [
"""
CREATE TABLE ISI_tb (
cluster_no SMALLINT NOT NULL,
analysis_ts TIMESTAMP NOT NULL,
tetrode_no SMALLINT NOT NULL,
session_name VARCHAR NOT NULL,
... | 5,351,262 |
def particles(t1cat):
"""Return a list of the particles in a T1 catalog DataFrame.
Use it to find the individual particles involved in a group of events."""
return particles_fromlist(t1cat.particles.tolist()) | 5,351,263 |
def interp_coeff_lambda3(i2,dx2,nx):
"""
NOTE:
input and output index from 0 to nx-1 !!!
"""
i2=i2+1 # TODO, waiting for script to be updated
# Find index of other cells
i1 = i2 - 1
i3 = i2 + 1
i4 = i2 + 2
# Find normalised distance to other cells
dx1 = dx2 + 1.0
dx3 = ... | 5,351,264 |
def prime_list(num):
"""
This function returns a list of prime numbers less than natural number entered.
:param num: natural number
:return result: List of primes less than natural number entered
"""
prime_table = [True for _ in range(num+1)]
i = 2
while i ** 2 <= num:
if prime_... | 5,351,265 |
def check_deadline_exceeded_and_store_partial_minimized_testcase(
deadline, testcase_id, job_type, input_directory, file_list,
file_to_run_data, main_file_path):
"""Store the partially minimized test and check the deadline."""
testcase = data_handler.get_testcase_by_id(testcase_id)
store_minimized_testcas... | 5,351,266 |
def _item_to_python_repr(item, definitions):
"""Converts the given Capirca item into a typed Python object."""
# Capirca comments are just appended to item strings
s = item.split("#")[0].strip()
# A reference to another network
if s in definitions.networks:
return s
# IPv4 address / ne... | 5,351,267 |
def test_resolve_interpreter_with_nonexistent_interpreter(mock_exists):
"""Should SystemExit with an nonexistent python interpreter path"""
mock_exists.return_value = False
with pytest.raises(SystemExit):
virtualenv.resolve_interpreter("/usr/bin/python53")
mock_exists.assert_called_with("/usr/... | 5,351,268 |
def floor_divide(x1, x2, out=None, where=True, **kwargs):
"""
Return the largest integer smaller or equal to the division of the inputs.
It is equivalent to the Python ``//`` operator and pairs with the
Python ``%`` (`remainder`), function so that ``a = a % b + b * (a // b)``
up to roundoff.
A... | 5,351,269 |
def node_args_argument(command: Callable[..., None]) -> Callable[..., None]:
"""
Decorate a function to allow choosing arguments to run on a node.
"""
function = click.argument(
'node_args',
type=str,
nargs=-1,
required=True,
)(command) # type: Callable[..., None]
... | 5,351,270 |
def _tag_error(func):
"""Decorates a unittest test function to add failure information to the TestCase."""
@functools.wraps(func)
def decorator(self, *args, **kwargs):
"""Add failure information to `self` when `func` raises an exception."""
self.test_failed = False
try:
... | 5,351,271 |
def create_drizzle_products(total_obj_list, custom_limits=None):
"""
Run astrodrizzle to produce products specified in the total_obj_list.
Parameters
----------
total_obj_list: list
List of TotalProduct objects, one object per instrument/detector combination is
a visit. The TotalPr... | 5,351,272 |
def get_submission_praw(n, sub, n_num):
"""
Returns a list of results for submission in past:
1st list: current result from n hours ago until now
2nd list: prev result from 2n hours ago until n hours ago
"""
mid_interval = datetime.today() - timedelta(hours=n)
timestamp_mid = int(mid_interva... | 5,351,273 |
def preprocess(dframe, log_dir, log_name):
""" Convert date type and save to disk"""
dframe['date'] = lookup_date(dframe['date'])
dframe.to_csv(os.path.join(log_dir, log_name + ".csv_preprocessed")) | 5,351,274 |
def memory_kernel_logspace(dt, coeffs, dim_x, noDirac=False):
"""
Return the value of the estimated memory kernel
Parameters
----------
dt: Timestep
coeffs : Coefficients for diffusion and friction
dim_x: Dimension of visible variables
noDirac: Remove the dirac at time zero
Returns... | 5,351,275 |
def create_tables(cur, conn):
"""
Creates each table using the queries in `create_table_queries` list.
Returns: None
"""
for query in create_table_queries:
cur.execute(query)
conn.commit() | 5,351,276 |
async def aclose_forcefully(resource: AsyncResource) -> None:
"""
Close an asynchronous resource in a cancelled scope.
Doing this closes the resource without waiting on anything.
:param resource: the resource to close
"""
async with open_cancel_scope() as scope:
await scope.cancel()
... | 5,351,277 |
def _is_constant(x, atol=1e-7, positive=None):
"""
True if x is a constant array, within atol
"""
x = np.asarray(x)
return (np.max(np.abs(x - x[0])) < atol and
(np.all((x > 0) == positive) if positive is not None else True)) | 5,351,278 |
def load_db_data_from_json(initial_database_data: pathlib.Path) -> None:
"""Load database data from a JSON file.
Args:
initial_database_data (Path): JSON file.
"""
with open(initial_database_data, "r", encoding=cfg.glob.FILE_ENCODING_DEFAULT) as json_file:
json_data = json.load(json_fil... | 5,351,279 |
def test_is_valid_password_v2_false2():
"""
Test of is_valid_password_v2() with a false example, take 2
"""
result = is_valid_password_v2(
{"low": 1, "high": 2, "letter": "w", "password": "aa"}
)
assert not result | 5,351,280 |
def estimate_M(X, estimator, B, ratio):
"""Estimating M with Block or incomplete U-statistics estimator
:param B: Block size
:param ratio: size of incomplete U-statistics estimator
"""
p = X.shape[1]
x_bw = util.meddistance(X, subsample = 1000)**2
kx = kernel.KGauss(x_bw)
if estimator ==... | 5,351,281 |
def load_nf_conntrack():
"""
Try to force the nf_conntrack_netlink kernel module to be loaded.
"""
_log.info("Running conntrack command to force load of "
"nf_conntrack_netlink module.")
try:
# Run a conntrack command to trigger it to load the kernel module if
# it's no... | 5,351,282 |
def query_yes_no(question, default="yes"):
"""Queries user for confimration"""
valid = {"yes": True, "y": True, "ye": True,
"no": False, "n": False}
if default is None:
prompt = " [y/n] "
elif default == "yes":
prompt = " [Y/n] "
elif default == "no":
prompt = "... | 5,351,283 |
def decode(password, encoded, notice):
"""
:type password: str
:type encoded: str
"""
dec = []
try:
encoded_bytes = base64.urlsafe_b64decode(encoded.encode()).decode()
except binascii.Error:
notice("Invalid input '{}'".format(encoded))
return
for i in range(len(en... | 5,351,284 |
def read_file_unlabelled_data(file_name):
"""
read_file_unlabelled_data reades from file_name
These files are to be in csv-format with one token per line (see the example project).
returns text_vector:
Ex:
[['7_7', 'perhaps', 'there', 'is', 'a_a', 'better', 'way', '._.'], ['2_2', 'Why', 'are', ... | 5,351,285 |
def replace(data, replacements):
""" Allows to performs several string substitutions.
This function performs several string substitutions on the initial ``data`` string using a list
of 2-tuples (old, new) defining substitutions and returns the resulting string.
"""
return reduce(lambda a, kv: a.re... | 5,351,286 |
def fake_kafka() -> FakeKafka:
"""Fixture for fake kafka."""
return FakeKafka() | 5,351,287 |
def rr20(prec: pd.Series) -> Union[float, int]:
"""Function for count of heavy precipitation (days where rr greater equal 20mm)
Args:
prec (list): value array of precipitation
Returns:
np.nan or number: the count of icing days
"""
assert isinstance(prec, pd.Series)
op = opera... | 5,351,288 |
def get_neg_label(cls_label: np.ndarray, num_neg: int) -> np.ndarray:
"""Generate random negative samples.
:param cls_label: Class labels including only positive samples.
:param num_neg: Number of negative samples.
:return: Label with original positive samples (marked by 1), negative
samples (m... | 5,351,289 |
def G12(x, a):
"""
Eqs 20, 24, 25 of Khangulyan et al (2014)
"""
alpha, a, beta, b = a
pi26 = np.pi ** 2 / 6.0
G = (pi26 + x) * np.exp(-x)
tmp = 1 + b * x ** beta
g = 1.0 / (a * x ** alpha / tmp + 1.0)
return G * g | 5,351,290 |
def custom_uwg(directory):
"""Generate UWG json with custom reference BEMDef and SchDef objects."""
# override at 5,2 and add at 18,2
# SchDef
default_week = [[0.15] * 24] * 3
schdef1 = SchDef(elec=default_week, gas=default_week, light=default_week,
occ=default_week, cool=defa... | 5,351,291 |
def update_table_params(switch_inst, table_name, params, find_params=None, row_id=None, validate_updates=True):
"""Configure port parameters in table.
Args:
switch_inst(object): Switch instance to work with
table_name(str): The name of table to work with
params(dict): Parameters and ... | 5,351,292 |
def binomial(n, k):
""" binomial coefficient """
if k < 0 or k > n:
return 0
if k == 0 or k == n:
return 1
num = 1
den = 1
for i in range(1, min(k, n - k) + 1): # take advantage of symmetry
num *= (n + 1 - i)
den *= i
c = num // den
return c | 5,351,293 |
def pagination(page):
"""
Generates the series of links to the pages in a paginated list.
"""
paginator = page.paginator
page_num = page.number
#pagination_required = (not cl.show_all or not cl.can_show_all) and cl.multi_page
if False: #not pagination_required:
page_range = []
e... | 5,351,294 |
def send_apns_push_message():
"""
a sample to show hwo to send web push message
:return:
"""
message = messaging.Message(
apns=apns_push_config,
# TODO:
token=['your token']
)
try:
# Case 1: Local CA sample code
# response = messaging.send_message(mes... | 5,351,295 |
def bubbleSort(arr):
"""
>>> bubbleSort(arr)
[11, 12, 23, 25, 34, 54, 90]
"""
n = len(arr)
for i in range(n-1):
for j in range(0, n-i-1):
if arr[j] > arr[j+1]:
arr[j], arr[j+1] = arr[j+1], arr[j]
return arr | 5,351,296 |
def generate_kronik_feats(fn):
"""Generates features from a Kronik output file"""
header = get_tsv_header(fn)
return generate_split_tsv_lines(fn, header) | 5,351,297 |
def regressor_contrast(model1:RegressorMixin,
model2:RegressorMixin,
test_data:pd.DataFrame,
label_data:pd.Series,
threshold:int=10)->pd.DataFrame:
"""Compute 11 metrics to compare a Sckit-learn regression models
and make sta... | 5,351,298 |
def delete_product(uuid: str, db: Session = Depends(auth)):
"""Delete a registered product."""
if product := repo.get_product_by_uuid(db=db, uuid=uuid):
if product.taken:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Cannot delete prod... | 5,351,299 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.