content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def handle_group_helper(msg):
"""
处理群消息
:param msg:
:return:
"""
conf = config.get('group_helper_conf')
if not conf.get('is_open'):
return
text = msg['Text']
# 如果开启了 『艾特才回复』,而群用户又没有艾特你。不处理消息
if conf.get('is_at') and not msg.isAt:
return
uuid = msg.fromUserN... | 52,700 |
def split_list(data, splits={'train': 8, 'test': 2}, shuffle=True, seed=0):
"""
Split the list according to a given ratio
Args:
data (list): a list of data to split
splits (dict): a dictionary specifying the ratio of splits
shuffle (bool): shuffle the list before
seed (int):... | 52,701 |
def testExpandEnvironmentVars(loggingMixin):
""" Test the YAML constructor to expand environment vars. """
testYaml = """
normalVar: 3
normalWithDollarSign: "$ Hello World"
environmentVar: !expandVars $HOME
expandedWithoutVar: !expandVars "Hello world"
"""
# Setup the YAML to be read fro... | 52,702 |
def set_implied(span, data):
"""Update the the implied value in the data dict."""
implied = [i for t in span if (i := IMPLIED.get(t.lower_)) is not None]
if implied:
data['elev_implied'] = implied[0]
data['ori_elev_implied'] = implied[0] | 52,703 |
def decoder_gen(
original_input: tuple,
decoder_config: dict
):
"""
Create the architecture for the VAE decoder
"""
decoder_inputs = keras.layers.Input(shape=[decoder_config["latent_dim"]])
print("decoder_inputs", decoder_inputs._keras_shape)
# Reshape input to be an image
#for ori... | 52,704 |
def get_ents_by_label(
data: List[Example], case_sensitive: bool = False
) -> DefaultDict[str, List[str]]:
"""Get a dictionary of unique text spans by label for your data
# TODO: Ok so this needs to return more than just a set for each label.
We want to return a dictionary that maps labels to Annotati... | 52,705 |
def root():
"""
root - returns 200 OK
"""
return Response("It's alive!", status=200) | 52,706 |
def testplugin(module):
"""returns True if module has nessesary parameters"""
logger.write( module.title )
return True | 52,707 |
def client_with_remote(client, tmpdir_factory):
"""Return a client with a (local) remote set."""
# create remote
path = str(tmpdir_factory.mktemp('remote'))
Repo().init(path, bare=True)
origin = client.repo.create_remote('origin', path)
client.repo.git.push('--set-upstream', 'origin', 'master')... | 52,708 |
async def test_async_state():
"""Test various cases for AsyncState."""
loop = asyncio.get_event_loop()
state = AsyncState()
# check set/get
value = 1
state.set(value)
assert state.get() == value
# check set/get with state property
value = 3
state.state = 3
assert state.stat... | 52,709 |
def put(*args, **kwargs):
"""Sends an HTTP PUT Request.
:param args: URL argument on the first index(args[1]).
:param kwargs: Optional arguments that ``requests.put`` takes.
:returns: :class:`Response` object or `None` if an error occurred.
:rtype: :class:`requests.Response` or `None`
"""
... | 52,710 |
async def save_transform(data):
"""
Calculate the transormation matrix that calibrates the gantry to the deck
:param data: Information obtained from a POST request.
The content type is application/json.
The correct packet form should be as follows:
{
'token': UUID token from current sessio... | 52,711 |
def data_trending_dashboard(start=default_start, end=now):
"""Bulilds dashboard
Parameters
----------
start : time
configures start time for query and visualisation
end : time
configures end time for query and visualisation
Return
------
plot_data : list
A list co... | 52,712 |
def add_damageprobs(locns, intensName, fragilityCurve, useMedian=True):
""" Add damage probabilities based on the intensities"""
# TODO: Check input is a dataframe
# TODO: Check required fields are there in locns
# TODO: Check match of intensity names
if not useMedian:
print("WARNING: opti... | 52,713 |
def register_task(task):
"""
Registers the given task to the global TASK_LIST, producing a warning if a
task with the same name as the new task already exists, and overwriting the
old task in that case. Note that registration should be used for abstract
tasks, and copies of registered tasks should be used to ... | 52,714 |
def run_task(snapshot_config, *_):
"""Run task."""
with LocalRunner(snapshot_config=snapshot_config) as runner:
n_epochs = 100
n_epoch_cycles = 20
sampler_batch_size = 500
num_timesteps = n_epochs * n_epoch_cycles * sampler_batch_size
env = gym.make('PongNoFrameskip-v4')... | 52,715 |
def dl2_to_sensitivity(
dl2_dir,
log_from_dl1_dl2,
gamma_offset="off0.0deg",
prod_id=None,
source_env="",
wait_jobs_dl1_dl2="",
):
"""
Function to run the `script_dl2_to_sensitivity` for the gamma (and the different gamma offsets) and gamma-diffuse
particles.
Creates the sensitiv... | 52,716 |
def test_with_html():
"""Runs the unit tests with html."""
tests = unittest.TestLoader().discover('./app/test', pattern='test*.py')
outfile = open("./Report.html", "wb")
runner = HTMLTestRunner(
stream=outfile,
title='Unit Test Backend Report',
description... | 52,717 |
def cpm_what_channels(folder):
"""Helper functions to print available channels given a folder with
polysomnography files"""
pg = PSGcompumedics(folder)
return pg.available_channel | 52,718 |
def all_close(goal, actual, tolerance):
"""
Convenience method for testing if a list of values are within a tolerance of
their counterparts in another list
@param: goal A list of floats, a Pose or a PoseStamped
@param: actual A list of floats, a Pose or a PoseStamped
@param: tolerance ... | 52,719 |
def cloud_to_clusters(cloud: np.array) -> np.array:
"""Converts provided cloud into a set of clusters."""
clusters = defaultdict(lambda: [])
for vertex in cloud:
center = tuple(vertex[6:9])
if center != (0, 0, 0):
clusters[center].append(vertex)
print(' * [INFO]', len(list(c... | 52,720 |
def create_one_shuffled_shard(args, fasta_path, shard_index):
"""Create a blast DB from the shard."""
log = Logger(args['log_file'], args['log_level'])
shard = '{}.{:03d}.blast'.format(args['blast_db'], shard_index + 1)
blast.create_db(log, args['temp_dir'], fasta_path, shard) | 52,721 |
def split_remote_url(url):
"""check if the user provided a local file path or a
remote. If remote, try to strip off protocol info.
"""
remote_url = is_remote_url(url)
if not remote_url:
return url
for prefix in REMOTE_PREFIXES:
url = url.replace(prefix, '')
if '@' in ur... | 52,722 |
def load_json(filename, user_limit=0, badge_limit=0):
"""
Loads data form JSON
"""
with open(filename) as f:
data = json.loads(f.read())
if user_limit:
data['transactions'] = data['transactions'][:user_limit]
if badge_limit:
data['badges'] = data['badges'][:badge_limit]
... | 52,723 |
def lon2decimal(input):
"""
Convert a Longitude into decimal angle.
"""
lng_degrees = int(input[0:3])
lng_minutes = int(input[3:5])
lng_seconds = float(input[5:-2])
lng_negative = ('W' == input[-1])
return dms2decimal(lng_degrees, lng_minutes, lng_seconds, lng_negative) | 52,724 |
def get_coordinate_color(color_image, coordinate, colors: list):
"""
Takes a color_image, coordinate (tuple), and list of color thresholds in HSV.
If the pixel is within a color threshold, return the index of the color in the list.
Coordinate should be in y, x format.
"""
try:
if coordinate == None:
return... | 52,725 |
def constraint_wrapper(fun, constraint):
"""
Wrap a function such that it's first argument is constrained
"""
def inner(x, *args, **kwargs):
"""the wrapped function"""
return fun(constraint(x), *args, **kwargs)
return inner | 52,726 |
def display_all_tasks(ordered: bool, all: bool):
"""
Function defined to display the tasks saved in the leveldb
database.
Parameters:
-----------
- ordered: bool, if True tasks will be orderer and display by priority
- all: bool, if True all tasks including the one already done will be disp... | 52,727 |
async def test_clear_player_role_no_challonge(mocker):
"""Removes the player roles of all players not present in the challonge."""
cog, mock_bot, _ = init_mocks()
with pytest.raises(base.NoChallonge):
await cog.clear_player_role(cog, tosurnament_mock.CtxMock(mock_bot)) | 52,728 |
def extract_zip(base64String, extract_to):
"""
1. Decode base64String to zip
2. Extract zip to files
"""
# Decode base64String to zip
if not os.path.exists(extract_to): os.makedirs(extract_to)
zipfile_path = extract_to + "/package.zip"
with open(zipfile_path, "wb") as fout:
fout... | 52,729 |
def parse():
"""Parse input. Return the polymer template, its pairs, and the rules."""
with open('../data/day14.txt') as f:
polymer = f.readline().strip()
pairs = collections.defaultdict(int)
for i in range(len(polymer) - 1):
pairs[polymer[i:i+2]] += 1
f.readline()
... | 52,730 |
def _trial_summary(hparams, model_dir, examples_path,
output_dir, semisupervised_configs=None):
"""Writes a tensorboard text summary of the trial."""
model_dir_summary = tf.summary.text(
'model_dir', tf.constant(model_dir, name='model_dir'), collections=[])
data_summaries = []
if semis... | 52,731 |
def tourney_key(proto_obj):
"""Build a key from a scores_messages.Tournament protobuf object."""
return tourney_key_full(proto_obj.id_str) | 52,732 |
def timedelta_from_duration_string(s):
"""Convert time duration string to number of seconds."""
if re.match(r'^\d+$', s):
return timedelta(seconds=int(s))
td_args = {}
for part in s.split(','):
part = part.strip()
m = re.match(r'(\d+)\s+(year|month|day|hour|minute|second)s?', pa... | 52,733 |
def wrapped(wrapped_function, additional_result_wrapper=None, self_index=0):
"""
Using these decorators will take care of unwrapping and rewrapping the target object.
Thus all following code is written as if the methods live on the wrapped object
Also perfect to adapt free functions as instance met... | 52,734 |
def train(model, optim, sche, db, opt, exp_id):
"""
Args:
model: the model to be trained
optim: pytorch optimizer to be used
db : prepared torch dataset object
opt: command line input from the user
exp_id: experiment id
"""
best_model_dir = os.path.join(opt.s... | 52,735 |
def main(
project_dir: Path = typer.Argument(
..., help="Path to the CGEMs/CCAD project you want to create a new run for."
)
):
"""Copy settings to a new CGEMs/CCAD production QC run.
This command is only meant to be used on CGEMs/CCAD. It copies the
config.yml and cgr_sample_sheet.csv to ... | 52,736 |
def format_y_ticks_as_percents(plot):
"""Formats y ticks as nice-looking percents.
Args:
plot: matplotlib.AxesSubplot object.
"""
y_ticks = plot.get_yticks()
plot.set_yticklabels(get_percent_strings(y_ticks))
return plot | 52,737 |
def test_select_clause_with_duplicates(dupcols):
"""Test the select clause method for a data frame schema with duplicate
column names.
"""
# -- Use only the columns name (returns the first 'A' column) -------------
columns = ['Name', 'A']
colnames, colidxs = select_clause(dupcols.columns, column... | 52,738 |
def can_cast(value, class_type):
"""
Check if the value can be cast to the class_type, used in the parse tcl string function for tcl expressions like
[Ada inputs 0] or [Ada alias robotblur]
Args:
value (object): The object we're attempting to cast.
class_type (class): The class we're at... | 52,739 |
def conv(
value,
filter_size,
output_dim,
dropout=0.0,
activation="linear",
padding="valid",
weight_source=None):
"""
Perform a single scale of convolution and optionally add spatial dropout.
"""
if weight_source is None:
conv_layer = Conv1... | 52,740 |
def insert_row(dataset_name, position, validate=False):
"""Create instance of insert row command.
Parameters
----------
dataset_name: string
Name of the dataset
position: int
Index position where row is inserted
validate: bool, optional
Validate the created command speci... | 52,741 |
def build(argmap, data):
"""Builds an array of arguments from the provided map and data.
The argmap must consist of a mapping of keys to argbuilder functions.
keys in the argmap are indexed into data, and if they are present, the
corresponding values are passed to the corresponding argmap function. Th... | 52,742 |
def cli():
"""This LEAP example program evolves agent controllers for the problems
in the OpenAI Gym problem set. It supports a couple of different
evolutionary representations.
Note that you may need to install OpenGL packages for your system (such as
'freeglut' or 'glu' in order for the v... | 52,743 |
def execute_cmd(cmd):
"""execute a request as python module"""
method = get_method(cmd)
# check if whitelisted
if webnotes.session['user'] == 'Guest':
if (method not in webnotes.guest_methods):
webnotes.response['403'] = 1
raise Exception, 'Not Allowed, %s' % str(method)
else:
if not method in webnotes.... | 52,744 |
def get_prox_dist_points_cll(ppCll1, key=[]):
""" get prox and dist ends of the centerline assuming that origin is cranial,
right, anterior
"""
# Get prox and dist point for ppCll1
pends1 = np.array([ppCll1[0], ppCll1[-1]]) # pp centerline is in order of centerline points
if 'vLRA' in key... | 52,745 |
def proxy_a_distance(source_X, target_X, verbose=False):
"""
Compute the Proxy-A-Distance of a source/target representation
"""
nb_source = np.shape(source_X)[0]
nb_target = np.shape(target_X)[0]
if verbose:
print('PAD on', (nb_source, nb_target), 'examples')
multiple_search = Fals... | 52,746 |
def pubkey_to_bech32_address(data: bytes, witver: int) -> BTCAddress:
"""
Bitcoin pubkey to bech32 address
Source:
https://github.com/bitcoin/bips/blob/master/bip-0141.mediawiki#witness-program
https://github.com/mcdallas/cryptotools/blob/master/btctools/address.py
May raise:
- EncodingErr... | 52,747 |
def get_gender(id):
"""
:param id: feature id
:return: feature dictionary
"""
for gender in __gender_dict:
if __gender_dict[gender] == id:
return gender
raise ValueError("Id does not correspond to a Universal Dependency gender") | 52,748 |
def create_supervised_evaluator(
model, prepare_batch, metrics=None, device=None, non_blocking=False, output_transform=val_transform,
):
"""Factory function for creating an evaluator for supervised segmentation models.
Args:
model (`torch.nn.Module`): the model to train.
prepare_batch (callab... | 52,749 |
def cipher_core():
"""
This is the general function of Cipher, it is from it that users can encrypt or decrypt their various messages.
"""
def display_options_message():
"""
Allows the user to choose to encrypt or decrypt a message he has in his possession.
"""
choiceOfF... | 52,750 |
def save_diff_image(expected: str, actual: str, output: str):
"""Creates a diff image from an expected and actual image.
Args:
expected : File path of expected image.
actual : File path of actual image.
output : File path to save difference image to.
Raises:
ImageComparison... | 52,751 |
def fit_datapack(datapack,template_datapack,ant_idx = -1, time_idx=-1, dir_idx=-1, freq_idx=-1):
"""Fit a datapack to a template datapack using Bayesian optimization
of given kernel. Conjugation occurs at 350km."""
antennas,antenna_labels = datapack.get_antennas(ant_idx)
directions, patch_names = datap... | 52,752 |
def get_similar_pkg_installed_by_conda(ggd_recipe):
"""Method to get a list of similarly installed package names, referring to package installed by conda
get_similar_pkg_installed_by_conda
==================================
Method to identify if there are similar packages to the one provided installed ... | 52,753 |
def pinv(mat: T.Tensor) -> T.Tensor:
"""
Compute matrix pseudoinverse.
Args:
mat: A square matrix.
Returns:
tensor: The matrix pseudoinverse.
"""
return numpy.linalg.pinv(mat) | 52,754 |
def devices_date_stamper(devices):
"""
Return a function that given a date time will return the dates when devices
will make their requests.
:param devices:
:return:
"""
def mapper(date):
def stamper(x):
return date + timedelta(seconds=x)
return map(stamper, next... | 52,755 |
def test_dll_remove_from_list_of_one(dll_push_one):
"""Test doubly linked list remove method on only node."""
dll_push_one.remove(5)
assert len(dll_push_one) == 0
assert dll_push_one.head is None
assert dll_push_one.tail is None | 52,756 |
def getTestFragments() -> List[str]:
"""
Returns a small list of testing fragments.
>>> len(getTestFragments())
5
"""
return ['tttttt', 'ttttgg', 'tggaga', 'agacgc', 'cgcggg'] | 52,757 |
def json_response(data, code=200, mimetype='application/json'):
"""
For ajax(json) response, wrapper json data to convert HttpResponse.
"""
resp = HttpResponse(data, mimetype)
resp.code = code
return resp | 52,758 |
def get_funds_list(country=None):
"""
This function retrieves all the available funds and returns a list of each one of them.
All the available funds can be found at: https://www.investing.com/funds/
Args:
country (:obj:`str`, optional): name of the country to retrieve all its available funds f... | 52,759 |
def yaml_dump(filepath, data):
"""Dumps data to a yaml file"""
with open(filepath, "w") as file_descriptor:
yaml.dump(data, file_descriptor) | 52,760 |
def test_bias():
"""decrease bias for contradictory facts
given a False And, for all True inputs
"""
model = Model()
n = 1000
prop = [f'P{i}' for i in range(n)]
for p in prop:
model[f'{p}'] = Proposition()
model.add_facts({f'{p}': TRUE})
model['and'] = And(*[model[f'{p}'... | 52,761 |
def powerlaw_dl(p, x):
"""
p are parameters of the model
"""
return p[0]*(x/80.)**(p[1]+2) | 52,762 |
def poisson_trunc(expectation, top):
"""
Returns a random variable following a Poisson distribution with expected
value `expectation`, truncated so that values greater than `n` are not
possible.
The probability that the value exceeds `n` is added onto the probability
for `n`.
"""
dist... | 52,763 |
def start_run(param_prefix: Optional[str] = None,
experiment_name: Optional[str] = None,
run_name: Optional[str] = None,
artifact_location: Optional[str] = None,
**args) -> mlf.ActiveRun:
"""Close alias of mlflow.start_run. The only difference is that uv.start_r... | 52,764 |
def get_forecast_metadata_variables(ds):
"""
Returns a list of variables that represent forecast reference time
metadata.
:param netCDF4.Dataset ds: An open netCDF4 Dataset.
:rtype: list
"""
forecast_metadata_standard_names = {
"forecast_period",
"forecast_reference_time",
... | 52,765 |
def feet(i):
"""
feet(i)
Return i (in inches) converted to feet.
"""
return i / 12 | 52,766 |
def confirm_action(msg):
"""Ultra-lightweight confirmation dialog"""
return ConfirmAction(app.window, _("Are you sure?"), msg).run() | 52,767 |
def test_importing_from_another_lazy_package():
"""Test that we can access the namespace of another LazyPackage.
"""
pack = LazyPackage({}, 'ctypes', '',
{'test2': LazyPackage({'ThreadPoolExecutor':
'futures.ThreadPoolExecutor'},
... | 52,768 |
def rawFull(data):
"""Prints out all raw data for debugging"""
pprint(data) | 52,769 |
def create_dataset(path, column_name, label_name, defaults, batch_size, shuffle):
""" Create tf.dataset from csv file.
Args:
path (str): Path to the csv file.
column_names (list:str): List of string to specify which columns to use in dataset (including label).
label_name (str): Colu... | 52,770 |
def test_related_field_kind_validation(e, m):
"""Detect invalid config definition.
If mapper defines related field, the corresponding data source field
should resolve to only one object.
"""
expected = ""
with pytest.raises(MapperError) as exc_info:
Mapper(
e.Chat,
... | 52,771 |
def canonical_letter_permute_form(F, word):
"""
Apply a permutation of the letters of F so
that the different letters appearing in the
word appear in order (1,2,3,...).
"""
assert is_FreeGroup(F), "F must be a free group"
r = F.rank()
assert word in F, "word must be in F"
word_rep =... | 52,772 |
def get_16bytes_from_seed(n):
"""TI pseudo-random number generator"""
mod1 = 2147483563
mod2 = 2147483399
mult1 = 40014
mult2 = 40692
if n:
seed1 = (mult1 * n) % mod1
seed2 = n % mod2
else:
seed1 = 12345
seed2 = 67890
result_arr = bytearray(16)
for i... | 52,773 |
def remove_first_space(x):
"""
remove_first_space from word x
:param x: word
:type x: str
:return: word withou space in front
:rtype: str
"""
try:
if x[0] == " ":
return x[1:]
else:
return x
except IndexError:
return x | 52,774 |
def prevalent_analysis(df):
"""
#TODO Build Example:
import pandas as pd
import numpy as np
import plotly.express as px
fig = px.scatter(df_prevalent, x='Threshold', y='Dropped columns amount')
fig.show()
arr_bool = np.empty(shape=(len(df_preva... | 52,775 |
def sum_merge_tables(df1, df2, policy_id_column_name, df1_group_by, df2_group_by, df1_kpis, df2_kpis, df_no_dupl=None):
"""
Sums separately two dataframes and merge them
Arguments --> the two 2 dataframes to sum and merge, the policy id column name
the variables to aggregate on... | 52,776 |
def thcf_partial1(x):
""" Partial derivative of the Three-Hump Camel Function with respect to x1.
"""
partial = x[1] + 4 * x[0] - 4.2 * (x[0] ** 3) + (x[0] ** 5)
return partial # Gradient 1 | 52,777 |
def props(prop_name: str, *prop_names: str) -> "PropertyFilter":
"""
Factory to create filter using list of props
"""
def prop_filter(*, prop: "PropertyName", path: "PropertyPath") -> bool:
return any(str(prop) == p for p in (prop_name, *prop_names))
return prop_filter | 52,778 |
def add_coords(filtered_lst):
""" Find coordinates for list of films """
for line in filtered_lst:
try:
location = line[2]
location = location.split(", ")
geolocator = geopy.Nominatim(user_agent="main.py")
geocode = RateLimiter(geolocator.geocode, min_del... | 52,779 |
def rphiz_to_xyz(values):
"""Converts axis values from cylindrical coordinates into cartesian coordinates
Parameters
----------
values: array
Values of the axis to convert (Nx3)
Returns
-------
ndarray of the axis (Nx3)
"""
r = values[:, 0]
phi = values[:, 1]
z = va... | 52,780 |
def test_atomic_unsigned_long_total_digits_1_nistxml_sv_iv_atomic_unsigned_long_total_digits_2_5(mode, save_output, output_format):
"""
Type atomic/unsignedLong is restricted by facet totalDigits with value
5.
"""
assert_bindings(
schema="nistData/atomic/unsignedLong/Schema+Instance/NISTSche... | 52,781 |
def build_load_statement(tablename, retry=True, options=""):
"""build a command line statement to upload data.
Upload is performed via the :doc:`csv2db` script.
The returned statement is suitable to use in pipe expression.
This method is aware of the configuration values for database
access and th... | 52,782 |
async def lins_command(ctx, ticker: str = "", num: int = 10):
"""Display insider activity for a given stock ticker. [Source: Finviz]
Parameters
----------
ticker : Stock Ticker
num : Number of latest insider activity to display
"""
try:
# Debug
if cfg.DEBUG:
logg... | 52,783 |
def recentlist():
""" Return a list of recently completed games for the indicated user """
rq = RequestData(request)
user_id = rq.get("user")
versus = rq.get("versus")
count = rq.get_int("count", 14) # Default number of recent games to return
# Limit count to 50 games
if count > 50:
... | 52,784 |
def nice_std(ls):
"""
Method to return standard deviation of a list or equivalent array with NaN values
Args:
ls: (list), list of values
Returns:
(numpy array), array containing standard deviation of list of values or NaN if list has no values
"""
if len(ls) > 0:
ret... | 52,785 |
def wait_for_port(port: int, host: Text = "127.0.0.1", timeout: float = 5.0):
"""
Wait until a port starts accepting TCP connections.
"""
start_time = time.perf_counter()
while True:
try:
with socket.create_connection((host, port), timeout=timeout):
break
... | 52,786 |
def check_pano_submission(path):
"""Checks if all files required for the submission exist and are in the right format."""
ready_for_submission = True
# check if path contains a predictions.json
json_path = path / 'predictions.json'
print('Checking for "predictions.json" ... ', end='', flush=True)
if json_path... | 52,787 |
def test_new_quiz():
"""creation of a new default quiz"""
with app.test_request_context():
Quiz.max_questions = 2
Quiz.max_time_in_seconds = 0.1
client = app.test_client()
data = dict(
username="pietje",
action="creategame"
)
rv = client.... | 52,788 |
def leftmostNonzeroEntries(M):
"""Returns the leftmost nonzero entries of M."""
return [ abs(M[l][M.nonzero_positions_in_row(l)[0]])
for l in range(0,M.dimensions()[0])
if M.nonzero_positions_in_row(l) != [] ] | 52,789 |
def tophat_binary(image, kernel=None, n=None):
"""
It is the difference between input image and
opening of the image
"""
tophat = cv2.morphologyEx(image,cv2.MORPH_TOPHAT, kernel)
return tophat | 52,790 |
def kl_div(input, label, reduction='mean', name=None):
"""
This operator calculates the Kullback-Leibler divergence loss
between Input(X) and Input(Target). Notes that Input(X) is the
log-probability and Input(Target) is the probability.
KL divergence loss is calculated as follows:
$$l(x, y) =... | 52,791 |
def _json_target_decode(dct):
"""Target json object decoder"""
if "itf" in dct:
dct["itf"] = CanedgeInterface[dct["itf"].upper()]
if "chn" in dct:
dct["chn"] = CanedgeChannel[dct["chn"].upper()]
if "db" in dct:
dct["db"] = dct["db"].lower()
if "method" in dct:
dct["me... | 52,792 |
def init_ax(fontsize=24, nrows=1, ncols=1):
"""
:param fontsize:
:return:
"""
font = {'family': 'Times New Roman'}
mpl.rc('font', **font)
mpl.rcParams['legend.fontsize'] = fontsize
mpl.rcParams['axes.labelsize'] = fontsize
mpl.rcParams['xtick.labelsize'] = fontsize
mpl.rcParams[... | 52,793 |
def is_sequence(arg):
"""Returns True is passed arg is a list or a tuple"""
return isinstance(arg, list) or isinstance(arg, tuple) | 52,794 |
def pipeline(d, segments):
""" Transient search pipeline running on single node.
Processes one or more segments of data (in which a single bgsub, (u,v,w), etc. can be used).
Can search completely, independently, and saves candidates.
If segments is a list of segments, then it will parallelize read/searc... | 52,795 |
async def validate_captcha(data: str) -> bool:
"""Verify `data` with hcaptcha's API."""
url = f'https://hcaptcha.com/siteverify'
data = {
'secret': zconfig.hCaptcha_secret,
'response': data
}
async with zglob.http.post(url, data=data) as resp:
if not resp or resp.status != ... | 52,796 |
def _Levy(x):
"""
Global Minimum at `z_1 = (1, 1, ..., 1)` with `f(z_1) = 0`.
"""
w = 1 + (x - 1) / 4
w_mid = w[:, :-1]
f = np.sum(np.multiply((w_mid - 1)**2, 1 + 10 * np.sin(np.pi * w_mid + 1)**2), axis = 1)
f += np.sin(np.pi * w[:, 0])**2 + (w[:, -1] - 1)**2 * (1 + np.sin(2 * np.pi * w[:, -1])**2)
... | 52,797 |
def test_functions_called_correctly_failure(mocker, basic_app):
"""Check functionality if login fails"""
mock_function1 = mocker.patch("src.app_functions.menu.change_credentials.input_credentials")
mock_function2 = mocker.patch(
"src.app_functions.menu.change_credentials.duolingo_login", side_effect... | 52,798 |
def write_expanded_xconfig_files(config_dir, all_layers):
""" This functions writes config_dir/xconfig.expanded.1 and
config_dir/xconfig.expanded.2, showing some of the internal stages of
processing the xconfig file before turning it into config files.
"""
try:
xconfig_file_out = open(config... | 52,799 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.