content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def add_X_to_both_sides(latex_dict: dict) -> str:
"""
https://docs.sympy.org/latest/gotchas.html#double-equals-signs
https://stackoverflow.com/questions/37112738/sympy-comparing-expressions
Given a = b
add c to both sides
get a + c = b + c
>>> latex_dict = {}
>>> latex_dict['input'] =... | 5,337,500 |
def init_var_dict(init_args, var_list):
"""Init var with different methods.
"""
var_map = {}
_, max_val = init_args
for i, _ in enumerate(var_list):
key, shape, method = var_list[i]
if key not in var_map.keys():
if method in ['random', 'uniform']:
var_map[... | 5,337,501 |
def get_member_name(refobject):
""" return the best readable name
"""
try:
member_name = refobject.__name__
except AttributeError:
member_name = type(refobject).__name__
except Exception as error:
logger.debug('get_member_name :'+str(error))
member_name = str(refobj... | 5,337,502 |
def test_get_timeseries_cum():
"""Test if get_timeseries_cum returns the right timeseries list
Given an in_list"""
in_list = [[1, 245], [5, 375], [10, 411]]
duration = 13
x = an.get_timeseries_cum(in_list, duration, False)
answer = [0, 245, 245, 245, 245, 245 + 375, 245 + 375,
2... | 5,337,503 |
def _check_path(path=None):
"""
Returns the absolute path corresponding to ``path`` and creates folders.
Parameters
----------
path : None, str or list(str)
Absolute path or subfolder hierarchy that will be created and returned.
If None, os.getcwd() is used.
"""
if path is ... | 5,337,504 |
def _eval_bernstein_1d(x, fvals, method="binom"):
"""Evaluate 1-dimensional bernstein polynomial given grid of values.
experimental, comparing methods
Parameters
----------
x : array_like
Values at which to evaluate the Bernstein polynomial.
fvals : ndarray
Grid values of coeff... | 5,337,505 |
def exp_bar(self, user, size=20):
"""\
Returns a string visualizing the current exp of the user as a bar.
"""
bar_length = user.exp * size // exp_next_lvl(user.lvl)
space_length = size - bar_length
bar = '#' * bar_length + '.' * space_length
return '[' + bar + ']' | 5,337,506 |
def test_get_bucket_vs_certs():
"""Integration test for bucket naming issues."""
import boto.s3.connection
aws_access_key = os.getenv('AWS_ACCESS_KEY_ID')
# Add dots to try to trip up TLS certificate validation.
bucket_name = 'wal-e.test.dots.' + aws_access_key.lower()
with pytest.raises(boto... | 5,337,507 |
def linear(input_, output_size, scope=None, stddev=0.02, with_w=False):
"""Define lienar activation function used for fc layer.
Args:
input_: An input tensor for activation function.
output_dim: A output tensor size after passing through linearity.
scope: variable scope, if None... | 5,337,508 |
def generate_patches(patch_cache_location,
axis,
image_input_channels,
brain_mask_channel,
classification_mask,
patch_size,
k_fold_count,
patients=None,
... | 5,337,509 |
def _parse_locals_to_data_packet(locals_dict):
"""
Takes the locals object (i.e. function inputs as a dict), maps keys from.
TODO retire this function, its pretty hacky
:param locals_dict:
:return: parsed locals object
"""
if 'self' in locals_dict:
locals_dict.pop('self')
if 'kwa... | 5,337,510 |
def query_user_joins(user_group: Union[User, Sequence[User], None]) \
-> List[JoinRecord]:
"""
:param user_group: User or user group as an iterable of users.
:return:
"""
# Input validation
user_list = [user_group] if isinstance(user_group, User) else user_group
# Query
query = ... | 5,337,511 |
def plotexpwake(Re_D, quantity, z_H=0.0, save=False, savepath="",
savetype=".pdf", newfig=True, marker="--ok",
fill="none", figsize=(10, 5)):
"""Plots the transverse wake profile of some quantity. These can be
* meanu
* meanv
* meanw
* stdu
"""
U = Re... | 5,337,512 |
def cd(b, d, n):
"""Try to cd to the given path. In case of an error go back to ../../Scripts
and try again (maybe the last run had an error or
the script did not reach the end)."""
# Check if already there
try:
if [b, d, n] == get_input():
# print('Already there:', os.getcwd())... | 5,337,513 |
def save_vocab(count=[], name='vocab.txt'):
"""Save the vocabulary to a file so the model can be reloaded.
Parameters
----------
count : a list of tuple and list
count[0] is a list : the number of rare words\n
count[1:] are tuples : the number of occurrence of each word\n
e.g. [... | 5,337,514 |
def is_running(process):
"""Returns True if the requested process looks like it's still running"""
if not process[0]:
return False # The process doesn't exist
if process[1]:
return process[1].poll() == None
try:
# check if the process is active by sending a dummy signal
... | 5,337,515 |
def rec_test(test_type: str):
"""
Rec test decorator
"""
def decorator(f):
@wraps(f)
def w(*args, **kwargs):
return f(*args, **kwargs)
# add attributes to f
w.is_test = True
w.test_type = test_type
try:
w.test_desc = f.__doc__.lstr... | 5,337,516 |
def display_convw(w, s, r, c, fig, vmax=None, vmin=None, dataset='mnist', title='conv_filters'):
"""
w2 = np.zeros(w.shape)
d = w.shape[1]/3
print w.shape
for i in range(w.shape[0]):
for j in range(w.shape[1]/3):
w2[i, j] = w[i, 3*j]
w2[i, j + d] = w[i, 3*j+1]
w2[i, j + 2*d] = w[i, 3*j+... | 5,337,517 |
def get_optional_list(all_tasks=ALL_TASKS, grade=-1, *keys) -> list:
"""获取可选的任务列表
:param keys: 缩小范围的关键字,不定长,定位第一级有一个键,要定位到第二级就应该有两个键
:param all_tasks: dict,两级, 所有的任务
:param grade: 字典层级 第0层即为最外层,依次向内层嵌套,默认值-1层获取所有最内层的汇总列表
:return:
"""
optional_list = []
# 按照指定层级获取相应的可选任务列表
if grade ... | 5,337,518 |
def process_genotypes(filepath, snp_maf, snp_list=None, **kwargs):
"""
Process genotype file.
:param filepath:
:param snp_maf:
:param snp_list: get specified snp if provided
:param bool genotype_label: True if first column is the label of specimen, default False
:param bool skip_none_rs: Tr... | 5,337,519 |
def stop_trigger():
"""
Stops the Glue trigger so that the trigger does not run anymore.
"""
glue.stop_trigger(Name=GLUE_TRIGGER) | 5,337,520 |
def check_output(*cmd):
"""Log and run the command, raising on errors, return output"""
print >>sys.stderr, 'Run:', cmd
return subprocess.check_output(cmd) | 5,337,521 |
def table_exists(conn, table_name, schema=False):
"""Checks if a table exists.
Parameters
----------
conn
A Psycopg2 connection.
table_name : str
The table name.
schema : str
The schema to which the table belongs.
"""
cur = conn.cursor()
table_exists_sql =... | 5,337,522 |
def _dict_from_dir(previous_run_path):
"""
build dictionary that maps training set durations to a list of
training subset csv paths, ordered by replicate number
factored out as helper function so we can test this works correctly
Parameters
----------
previous_run_path : str, Path
p... | 5,337,523 |
def aggregate_pixel(arr,x_step,y_step):
"""Aggregation code for a single pixel"""
# Set x/y to zero to mimic the setting in a loop
# Assumes x_step and y_step in an array-type of length 2
x = 0
y = 0
# initialize sum variable
s = 0.0
# sum center pixels
left = int(ceil(x_step[x]))... | 5,337,524 |
def plot_offer_utilization(df_offer):
"""
Make a plot for distribution of offer utilization.
Parameters
----------
df_offer: pandas.DataFrame
The data set of offer.
Returns
-------
None
"""
offer_use = df_offer.groupby(['person', 'is_offer_used']).count()['offer_id'].u... | 5,337,525 |
def SetTexNodeColorSpace(texNode):
""" set Base Color to sRGB and all others to Non-Color """
try:
if texNode.label == 'Base Color':
texNode.image.colorspace_settings.name = 'sRGB'
else:
texNode.image.colorspace_settings.name = 'Non-Color'
except Exception:
pr... | 5,337,526 |
def simplify_datatype(config):
""" Converts ndarray to list, useful for saving config as a yaml file """
for k, v in config.items():
if isinstance(v, dict):
config[k] = simplify_datatype(v)
elif isinstance(v, tuple):
config[k] = list(v)
elif isinstance(v, np.ndarr... | 5,337,527 |
def _strict_random_crop_image(image,
boxes,
labels,
is_crowd,
difficult,
masks=None,
sem_seg=None,
min_object_... | 5,337,528 |
def aggregate_by_player_id(statistics, playerid, fields):
"""
Inputs:
statistics - List of batting statistics dictionaries
playerid - Player ID field name
fields - List of fields to aggregate
Output:
Returns a nested dictionary whose keys are player IDs and whose values
a... | 5,337,529 |
def temp_volttron_home(request):
"""
Create a VOLTTRON_HOME and includes it in the test environment.
Creates a volttron home, config, and platform_config.yml file
for testing purposes.
"""
dirpath = tempfile.mkdtemp()
os.environ['VOLTTRON_HOME'] = dirpath
with open(os.path.join(dirpath, ... | 5,337,530 |
async def gtfo(ctx):
"""Makes Botboy leave (go offline)"""
conn.close()
await ctx.send("Bye!")
await bot.logout()
quit() | 5,337,531 |
def _visualize(ax, data, labels, centers):
"""
将模型结果可视化
"""
colors = ["#82CCFC", "k", "#0C5FFA"]
ax.scatter(data[:, 0], data[:, 1], c=[colors[i] for i in labels], marker="o", alpha=0.8)
ax.scatter(centers[:, 0], centers[:, 1], marker="*", c=colors, edgecolors="white",
s=700., line... | 5,337,532 |
def test_21_upgrade_baseline_current(capsys):
"""Verify baseline-current and baseline-info and get_version()"""
try:
os.unlink(TEST_DB_FILE)
except:
pass
config = pydbvolve.initialize(TEST_CONFIG_FILE, 'upgrade', 'r1.1.0', True, False)
assert (config is not None)
rc = p... | 5,337,533 |
def loadStatesFromFile(filename):
"""Loads a list of states from a file."""
try:
with open(filename, 'rb') as inputfile:
result = pickle.load(inputfile)
except:
result = []
return result | 5,337,534 |
def get_configuration_item(configuration_file, item, default_values):
"""Return configuration value on file for item or builtin default.
configuration_file Name of configuration file.
item Item in configuation file whose value is required.
default_values dict of default values f... | 5,337,535 |
def tflite_stream_state_external_model_accuracy(
flags,
folder,
tflite_model_name='stream_state_external.tflite',
accuracy_name='tflite_stream_state_external_model_accuracy.txt',
reset_state=False):
"""Compute accuracy of streamable model with external state using TFLite.
Args:
flags: mod... | 5,337,536 |
def rm_magic(kernel, args):
"""Remove files on microcontroller
If path is a directory and the option -f is not specified, the command is sliently ignored.
Examples:
%rm a # delete file a if it exists, no action if it's a directory, error otherwise
%rm -f a # delete file or directory a... | 5,337,537 |
def sexa2deg(ra, dec):
"""Convert sexagesimal to degree; taken from ryan's code"""
ra = coordinates.Angle(ra, units.hour).degree
dec = coordinates.Angle(dec, units.degree).degree
return ra, dec | 5,337,538 |
def verify_grad(fun, pt, n_tests=2, rng=None, eps=None,
out_type=None, abs_tol=None,
rel_tol=None, mode=None, cast_to_output_type=False):
"""Test a gradient by Finite Difference Method. Raise error on failure.
Example:
>>> verify_grad(theano.tensor.tanh,
... | 5,337,539 |
def get_filenames():
""" get file names given path """
files = []
for file in os.listdir(cwd):
if file.endswith(".vcf"):
fullPath = cwd + file
files.append(fullPath)
return files | 5,337,540 |
def is_mismatch_before_n_flank_of_read(md, n):
"""
Returns True if there is a mismatch before the first n nucleotides
of a read, or if there is a mismatch before the last n nucleotides
of a read.
:param md: string
:param n: int
:return is_mismatch: boolean
"""
is_mismatch = False
... | 5,337,541 |
def get_county() -> Dict:
"""Main method for populating county data"""
api = SocrataApi('https://data.marincounty.org/')
notes = ('This data only accounts for Marin residents and does not '
'include inmates at San Quentin State Prison. '
'The tests timeseries only includes the numb... | 5,337,542 |
def optimize_player_strategy(
player_cards: List[int], opponent_cards: List[int], payoff_matrix: Matrix
) -> Strategy:
"""
Get the optimal strategy for the player, by solving
a simple linear program based on payoff matrix.
"""
lp = mip.Model("player_strategy", solver_name=mip.CBC)
lp.verbose... | 5,337,543 |
def _write_dihedral_information(gsd_snapshot, structure):
"""Write the dihedrals in the system.
Parameters
----------
gsd_snapshot :
The file object of the GSD file being written
structure : parmed.Structure
Parmed structure object holding system information
Warnings
------... | 5,337,544 |
def saveFIG(filename='tmp.pdf',
axis=False,
transparent=True):
"""save fig for publication
Args:
filename (str, optional): filename to save figure. (Default value = 'tmp.pdf')
axis (bool, optional): if True then show axis. (Default value = False)
transparent (bool, opt... | 5,337,545 |
def address_book(request):
"""
This Endpoint is for getting contact
details of all people at a time.
We will paginate this for 10 items at a time.
"""
try:
paginator = PageNumberPagination()
paginator.page_size = 10
persons = Person.objects.all()
paginated_perso... | 5,337,546 |
def decrement_items (inventory, items):
"""
:param inventory: dict - inventory dictionary.
:param items: list - list of items to decrement from the inventory.
:return: dict - updated inventory dictionary with items decremented.
"""
return add_or_decrement_items (inventory, items, 'minus') | 5,337,547 |
def global_ave_pool(x):
"""Global Average pooling of convolutional layers over the spatioal dimensions.
Results in 2D tensor with dimension: (batch_size, number of channels) """
return th.mean(x, dim=[2, 3]) | 5,337,548 |
def train_models(models, train_data, target, logger, dask_client=None, randomized_search=False, scoring_metric=None):
"""Trains a set of models on the given training data/labels
:param models: a dictionary of models which need to be trained
:param train_data: a dataframe containing all possible features (... | 5,337,549 |
def get_output(interpreter, top_k=1, score_threshold=0.0):
"""Returns no more than top_k classes with score >= score_threshold."""
scores = output_tensor(interpreter)
classes = [
Class(i, scores[i])
for i in np.argpartition(scores, -top_k)[-top_k:]
if scores[i] >= score_threshold
]
return so... | 5,337,550 |
def bag_of_words_features(data, binary=False):
"""Return features using bag of words"""
vectorizer = CountVectorizer(
ngram_range=(1, 3), min_df=3, stop_words="english", binary=binary
)
return vectorizer.fit_transform(data["joined_lemmas"]) | 5,337,551 |
def gen_batch_iter(random_instances, batch_s=BATCH_SIZE):
""" a batch 2 numpy data.
"""
num_instances = len(random_instances)
offset = 0
while offset < num_instances:
batch = random_instances[offset: min(num_instances, offset + batch_s)]
num_batch = len(batch)
lengths = np.ze... | 5,337,552 |
def duration(func):
"""
计时装饰器
"""
def wrapper(*args, **kwargs):
print('2')
start = time.time()
f = func(*args, **kwargs)
print(str("扫描完成, 用时 ") + str(int(time.time()-start)) + "秒!")
return f
return wrapper | 5,337,553 |
def enumerate_assignments(max_context_number):
"""
enumerate all possible assignments of contexts to clusters for a fixed
number of contexts. Has the hard assumption that the first context belongs
to cluster #1, to remove redundant assignments that differ in labeling.
:param max_context_number:... | 5,337,554 |
def main():
""" Execute package updater
"""
try:
updater = PackageUpdater()
updater.run(sys.argv[1:])
except Exception as error:
print(termcolor.colored("ERROR: {}".format(error), 'red'))
sys.exit(1) | 5,337,555 |
def KL_monte_carlo(z, mean, sigma=None, log_sigma=None):
"""Computes the KL divergence at a point, given by z.
Implemented based on https://www.tensorflow.org/tutorials/generative/cvae
This is the part "log(p(z)) - log(q(z|x)) where z is sampled from
q(z|x).
Parameters
----------
z : (B, N... | 5,337,556 |
def get_order_discrete(p, x, x_val, n_full=None):
""" Calculate the order of the discrete features according to the alt/null ratio
Args:
p ((n,) ndarray): The p-values.
x ((n,) ndarray): The covaraites. The data is assumed to have been preprocessed.
x_val ((n_val,) ndarray): All possible... | 5,337,557 |
def revoke_grant(KeyId=None, GrantId=None):
"""
Revokes a grant. You can revoke a grant to actively deny operations that depend on it.
See also: AWS API Documentation
Examples
The following example revokes a grant.
Expected Output:
:example: response = client.revoke_grant(
... | 5,337,558 |
def _read_txt(file_path: str) -> str:
"""
Read specified file path's text.
Parameters
----------
file_path : str
Target file path to read.
Returns
-------
txt : str
Read txt.
"""
with open(file_path) as f:
txt: str = f.read()
return t... | 5,337,559 |
def init_statick():
"""Fixture to initialize a Statick instance."""
args = Args("Statick tool")
return Statick(args.get_user_paths(["--user-paths", os.path.dirname(__file__)])) | 5,337,560 |
def BssResultComparison(S_synth, tc_synth, S_pca, tc_pca, S_ica, tc_ica, pixel_mask, title):
""" A function to plot the results of PCA and ICA against the synthesised sources
Inputs:
S_synth | rank 2 array | synthesised sources images as rows (e.g. 2 x 5886)
tc_synth | rank 2 array | synthes... | 5,337,561 |
def test_can_tests_load():
"""Make sure pytest finds this test."""
print("I am a test.")
assert 1 == 1 | 5,337,562 |
def dedupe(entries):
"""
Uses fuzzy matching to remove duplicate entries.
"""
return thefuzz.process.dedupe(entries, THRESHOLD, fuzz.token_set_ratio) | 5,337,563 |
def generate_openssl_rsa_refkey(key_pub_raw, # pylint: disable=too-many-locals, too-many-branches, too-many-arguments, too-many-statements
keyid_int, refkey_file,
key_size, encode_format="", password="nxp",
cert=""):
""... | 5,337,564 |
async def fetch_ongoing_alerts(
requester=Security(get_current_access, scopes=[AccessType.admin, AccessType.user]),
session=Depends(get_session)
):
"""
Retrieves the list of ongoing alerts and their information
"""
if await is_admin_access(requester.id):
query = (
alerts.sel... | 5,337,565 |
def data_to_graph_csvs(corpus_context, data):
"""
Convert a DiscourseData object into CSV files for efficient loading
of graph nodes and relationships
Parameters
----------
data : :class:`~polyglotdb.io.helper.DiscourseData`
Data to load into a graph
directory: str
Full path... | 5,337,566 |
def process_discover(data_export, file, limit, environment_id):
"""
Convert the discovery query to a CSV, writing it to the provided file.
"""
try:
processor = DiscoverProcessor(
discover_query=data_export.query_info, organization_id=data_export.organization_id
)
except E... | 5,337,567 |
def main():
"""
Test running the function in script mode
"""
process_cloudwatch_metric_event() | 5,337,568 |
def breweryBeers(id):
"""Finds the beers that belong to the brewery with the id provided
id: string
return: json object list or empty json list
"""
try:
# [:-1:] this is because the id has a - added to the end to indicate
# that it is for this method, removes the last charact... | 5,337,569 |
def min_max_date(rdb, patient):
""" Returns min and max date for selected patient """
sql = """SELECT min_date,max_date FROM patient WHERE "Name"='{}'""".format(patient)
try:
df = pd.read_sql(sql, rdb)
min_date, max_date = df['min_date'].iloc[0].date(), df['max_date'].iloc[0].date()
ex... | 5,337,570 |
def integrate(f, a, b, N, method):
"""
@param f: function to integrate
@param a: initial point
@param b: end point
@param N: number of intervals for precision
@param method: trapeze, rectangle, Simpson, Gauss2
@return: integral from a to b of f(x)
"""
h = (b-a)/(N)
if method == "... | 5,337,571 |
def test_get_all_names(code, target):
"""Tests get_all_names function."""
res = kale_ast.get_all_names(code)
assert sorted(res) == sorted(target) | 5,337,572 |
def sum_naturals(n):
"""Sum the first N natural numbers.
>>> sum_naturals(5)
15
"""
total, k = 0, 1
while k <= n:
total, k = total + k, k + 1
return total | 5,337,573 |
def load_data(data_map,config,log):
"""Collect data locally and write to CSV.
:param data_map: transform DataFrame map
:param config: configurations
:param log: logger object
:return: None
"""
for key,df in data_map.items():
(df
.coalesce(1)
.write
.csv(f'{co... | 5,337,574 |
def getAdjacentes(qtde_v, MATRIZ):
"""Método getAdjacentes p/ pegar os adjacentes do Grafo"""
aMATRIZ = []
for i in range(qtde_v):
linha = []
for j in range(qtde_v):
if MATRIZ[i][j] == 1:
linha.append("v" + str(j))
aMATRIZ.append(linha)
y = 0
for... | 5,337,575 |
def root(ctx, sources, output, _open):
"""
Computes and shows the root of the biggest tree on a bibliography collection.
"""
show("root", ctx.obj["sapper"], sources, output, _open) | 5,337,576 |
def get_config(config_file, exp_dir=None, is_test=False):
""" Construct and snapshot hyper parameters """
# config = edict(yaml.load(open(config_file, 'r'), Loader=yaml.FullLoader))
config = edict(yaml.load(open(config_file, 'r'), Loader=yaml.FullLoader))
# create hyper parameters
config.run_id = str(os.getp... | 5,337,577 |
def _filter_credential_warning(record) -> bool:
"""Rewrite out credential not found message."""
if (
not record.name.startswith("azure.identity")
or record.levelno != logging.WARNING
):
return True
message = record.getMessage()
if ".get_token" in message:
if message.s... | 5,337,578 |
def import_module_from_path(mod_name, mod_path):
"""Import module with name `mod_name` from file path `mod_path`"""
spec = importlib.util.spec_from_file_location(mod_name, mod_path)
mod = importlib.util.module_from_spec(spec)
spec.loader.exec_module(mod)
return mod | 5,337,579 |
def test_optimizer_can_fit():
"""Test that TestOptimizer can call fit with the proper API"""
syms = ['A', 'B', 'C']
targ = [-100, 0, 10]
opt = TestOptimizer(Database())
opt.fit(syms, {}, targ)
for sym, t in zip(syms, targ):
assert sym in opt.dbf.symbols
assert np.isclose(opt.dbf.... | 5,337,580 |
def preprocessing(text, checkpoint_dir, minocc):
"""
This time, we cannot leave the file as it is. We have to modify it first.
- replace "\n" by " \n " -> newline is a word
- insert space between punctuation and last word of sentence
- create vocab, but only for those words that occur more than once... | 5,337,581 |
def test():
"""Run the prediction and routing tests"""
printf("Testing benzlim...")
test_predict()
test_route() | 5,337,582 |
def run_histogram_extr(splopter=None, z_high=370.0, z_low=70.0, fig=None, show=False, normalise_v=True, species=2,
t_flag=False, fitter=None):
"""
NOTE: This has been implemented more generally as a method - splopter.extract_histograms() - and therefore this
function has now b... | 5,337,583 |
def dwave_chimera_graph(
m,
n=None,
t=4,
draw_inter_weight=draw_inter_weight,
draw_intra_weight=draw_intra_weight,
draw_other_weight=draw_inter_weight,
seed=0,
):
"""
Generate DWave Chimera graph as described in [1] using dwave_networkx.
Parameters
----------
m: int
... | 5,337,584 |
def extract_first_value_in_quotes(line, quote_mark):
"""
Extracts first value in quotes (single or double) from a string.
Line is left-stripped from whitespaces before extraction.
:param line: string
:param quote_mark: type of quotation mark: ' or "
:return: Dict: 'value': extracted value;
... | 5,337,585 |
def test_check_param_grids_single():
"""Test the check of a single parameter grid."""
init_param_grids = {'svr__C': [0.1, 1.0], 'svr__kernel': ['rbf', 'linear']}
param_grids = check_param_grids(init_param_grids, ['lr', 'svr', 'dtr'])
exp_param_grids = [
{'svr__C': [0.1], 'svr__kernel': ['rbf'], ... | 5,337,586 |
def dynamic(graph):
"""Returns shortest tour using dynamic programming approach.
The idea is to store lengths of smaller sub-paths and re-use them
to compute larger sub-paths.
"""
adjacency_M = graph.adjacency_matrix()
tour = _dynamic(adjacency_M, start_node=0)
return tour | 5,337,587 |
def perform_test_complete_operations(test_stat):
"""
Performs all operations related to end quiz
:param test_stat: TestStat object
:return: None
"""
if test_stat.has_completed:
return
test_stat.has_completed = True
test_stat.save()
send_test_complete_email(test_stat) | 5,337,588 |
def read_login_file():
"""
Parse the credentials file into username and password.
Returns
-------
dict
"""
with open('.robinhood_login', 'r') as login_file:
credentials = yaml.safe_load(login_file)
return credentials | 5,337,589 |
def flatten(ls):
"""
Flatten list of list
"""
return list(chain.from_iterable(ls)) | 5,337,590 |
def test_get_smoothies_recipes(test_client):
"""
GIVEN a Flask application configured for testing
WHEN the '/smoothies/' page is requested (GET)
THEN check the response is valid
"""
recipes = [b'Berry Smoothie', b'Chocolate Milk Shake']
response = test_client.get('/smoothies/')
assert re... | 5,337,591 |
def gaussian_kernel(size, size_y=None):
""" Gaussian kernel.
"""
size = int(size)
if not size_y:
size_y = size
else:
size_y = int(size_y)
x, y = np.mgrid[-size:size+1, -size_y:size_y+1]
g = np.exp(-(x**2/float(size)+y**2/float(size_y)))
fwhm = size
fwhm_aper = photut... | 5,337,592 |
def test_remove_news_articles():
""" Checks that the function can remove news articles"""
news_articles.clear()
test_article = {
'title': 'test title',
'content': 'test content'
}
prev_removed_article = {
'title': 'previously removed',
'content': 'previously remov... | 5,337,593 |
def parse_property_value(prop_tag: int, raw_values: list, mem_id: int = 0) -> Any:
"""
Parse property raw values
:param prop_tag: The property tag, see 'PropertyTag' enum
:param raw_values: The property values
:param mem_id: External memory ID (default: 0)
"""
if prop_tag not in PRO... | 5,337,594 |
async def kickme(leave):
""" Basically it's .kickme command """
await leave.edit("**Nope, no, no, I go away**")
await leave.client.kick_participant(leave.chat_id, "me") | 5,337,595 |
def scan_stanzas_string(
s: str,
*,
separator_regex: Optional[RgxType] = None,
skip_leading_newlines: bool = False,
) -> Iterator[List[Tuple[str, str]]]:
"""
.. versionadded:: 0.4.0
Scan a string for zero or more stanzas of RFC 822-style header fields and
return a generator of lists of ... | 5,337,596 |
def _StripLinkerAddedSymbolPrefixes(raw_symbols):
"""Removes prefixes sometimes added to symbol names during link
Removing prefixes make symbol names match up with those found in .o files.
"""
for symbol in raw_symbols:
full_name = symbol.full_name
if full_name.startswith('startup.'):
symbol.flag... | 5,337,597 |
def format_dependency(dependency: str) -> str:
"""Format the dependency for the table."""
return "[coverage]" if dependency == "coverage" else f"[{dependency}]" | 5,337,598 |
def _addSuffixToFilename(suffix, fname):
"""Add suffix to filename, whilst preserving original extension, eg:
'file.ext1.ext2' + '_suffix' -> 'file_suffix.ext1.ext2'
"""
head = op.split(fname)[0]
fname, ext = _splitExts(fname)
return op.join(head, fname + suffix + ext) | 5,337,599 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.