content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def remove_batch_from_layout(layout):
"""
The tf-mesh layout splits across batch size, remove it.
Useful for prediction steps, when you no longer want large batches.
:param layout: string describing tf-mesh layout
:return: layout minus batch dimension
"""
layout = layout.split(',')
ret_... | 5,313,800 |
def weighted_index(self, dim=None):
"""
Returns a tensor with entries that are one-hot along dimension `dim`.
These one-hot entries are set at random with weights given by the input
`self`.
Examples::
>>> encrypted_tensor = MPCTensor(torch.tensor([1., 6.]))
>>> index = encrypted_te... | 5,313,801 |
def _knapsack01_recur(val, wt, wt_cap, n):
"""0-1 Knapsack Problem by naive recursion.
Time complexity: O(2^n), where n is the number of items.
Space complexity: O(n).
"""
if n < 0 or wt_cap == 0:
return 0
if wt[n] > wt_cap:
# Cannot be put.
max_val = _knapsack01_re... | 5,313,802 |
def pixel_to_map(geotransform, coordinates):
"""Apply a geographical transformation to return map coordinates from
pixel coordinates.
Parameters
----------
geotransform : :class:`numpy:numpy.ndarray`
geographical transformation vector:
- geotransform[0] = East/West location of ... | 5,313,803 |
def newest_bugs(amount):
"""Returns the newest bugs.
This method can be used to query the BTS for the n newest bugs.
Parameters
----------
amount : int
the number of desired bugs. E.g. if `amount` is 10 the method
will return the 10 latest bugs.
Returns
-------
bugs : ... | 5,313,804 |
def matchElements(e1, e2, match):
"""
Test whether two elements have the same attributes. Used to check equality of elements
beyond the primary key (the first match option)
"""
isMatch = True
for matchCondition in match:
if(e1.attrib[matchCondition] != e2.attrib[matchCondition]):
... | 5,313,805 |
def change(args):
"""Wrapper function to use through argparse to change the Internet Proxy settings"""
manager = WindowsProxyManager()
if not manager.change(args.file):
sys.exit(1) | 5,313,806 |
def test_bool_of_empty_entry():
"""Test that the bool value of an empty entry is False"""
entry = config.ConfigurationEntry("empty", "")
assert not entry | 5,313,807 |
def checkout_latest(remote='origin'):
"""
Get the updated code
"""
run('cd %s; git fetch %s' % (app_config.SERVER_PROJECT_PATH, remote))
run('cd %s; git checkout %s; git pull %s %s' % (app_config.SERVER_PROJECT_PATH, env.branch, remote, env.branch)) | 5,313,808 |
def emoticons_tag(parser, token):
"""
Tag for rendering emoticons.
"""
exclude = ''
args = token.split_contents()
if len(args) == 2:
exclude = args[1]
elif len(args) > 2:
raise template.TemplateSyntaxError(
'emoticons tag has only one optional argument')
node... | 5,313,809 |
def auc_step(X, Y):
"""Compute area under curve using step function (in 'post' mode)."""
if len(X) != len(Y):
raise ValueError(
"The length of X and Y should be equal but got " + "{} and {} !".format(len(X), len(Y))
)
area = 0
for i in range(len(X) - 1):
delta_X = X[i... | 5,313,810 |
def apply_impulse_noise(x, severity=1, seed=None):
"""Apply ``impulse_noise`` from ``imagecorruptions``.
Supported dtypes
----------------
See :func:`~imgaug.augmenters.imgcorruptlike._call_imgcorrupt_func`.
Parameters
----------
x : ndarray
Image array.
Expected to have s... | 5,313,811 |
def get_username(org_id_prefix, first_name, last_name):
""" generiert aus Vor- und Nachnamen eine eindeutige Mitglied-ID """
first_name = check_name(first_name.strip().lower(), True)
last_name = check_name(last_name.strip().lower(), True)
n_len = len(first_name)
for n in xrange(n_len):
test_name = u'%s%s... | 5,313,812 |
def drawn_anomaly_boundaries(erp_data, appRes, index):
"""
Function to drawn anomaly boundary
and return the anomaly with its boundaries
:param erp_data: erp profile
:type erp_data: array_like or list
:param appRes: resistivity value of minimum pk anomaly
:type appRes: float
... | 5,313,813 |
def index(request):
"""
This index view/function will display the data that are stored in the database when a request is sent to it. The da
ta will be in the context argument and accessed in the template.
"""
context_data = Task.objects.all()
context = {
'data': context_data
}
re... | 5,313,814 |
def _send_message(service, user_id, message):
"""Send an email message.
Args:
service: Authorized Gmail API service instance.
user_id: User's email address. The special value "me"
can be used to indicate the authenticated user.
message: Message to be sent.
Returns:
Sent Message.
"""
try:
... | 5,313,815 |
def get_all_marbles_combinations_correctly_aligned(board):
"""
The board is a 6*6 board.
To check if we have 5 marbles aligned, we only need to start checking from positions described below:
┌─────────+─────────┐
| x x x | x x x |
| x x x | x x x |
| x x ◯ ... | 5,313,816 |
def calculate_num_modules(slot_map):
"""
Reads the slot map and counts the number of modules we have in total
:param slot_map: The Slot map containing the number of modules.
:return: The number of modules counted in the config.
"""
return sum([len(v) for v in slot_map.values()]) | 5,313,817 |
def main():
"""
The main body of the interpreter
"""
main_stack = []
aux_stack = []
in_gene = False
# Push additional command line arguments to the stack
for element in sys.argv[2:]:
try:
# Is the argument an integer?
main_stack.append(int(element))
... | 5,313,818 |
def get_team_training_data(training_issues, reporters_config):
"""
Extracts development team information from the training dataset.
:param training_issues: Dataframe with the issues for training
:return: A develoment team size generator, and another one for the bandwith.
"""
training_in_batche... | 5,313,819 |
def dice_coefficient(logits, labels, scope_name, padding_val=255):
"""
logits: [batch_size * img_height * img_width * num_classes]
labels: [batch_size * img_height * img_width]
"""
with tf.name_scope(scope_name, 'dice_coef', [logits, labels]) as scope:
sm = tf.nn.softmax(logits)
... | 5,313,820 |
def say_to(user, msg):
"""Sends a private message to another user."""
return say(user, msg) | 5,313,821 |
def update_search_indexes(sender, **kwargs):
"""Call haystack.update_index to update backend search indexes"""
instance = kwargs.get('instance')
if kwargs.get('created', True):
print('Created new instance...')
elif kwargs.get('updated', True):
print('Update instance...') | 5,313,822 |
def parse_linqs_pubmed_incidence_matrix(
cites_path: str,
content_path: str,
edge_list_path: str,
node_list_path: str
):
"""Parse PubMed incidence matrix and generates proper edge list and node file.
Parameters
-------------------
cites_path: str,
Path from where to load the cit... | 5,313,823 |
def depthload(filename):
"""Loads a depth image as a numpy array.
"""
if filename.split(".")[-1] == "txt":
x = np.loadtxt(filename)
else:
x = np.asarray(Image.open(filename))
x = (x * 1e-3).astype("float32")
return x | 5,313,824 |
def doc(ctx):
"""Generate all documentation."""
pass | 5,313,825 |
def pinit():
"""
Initialize the option parser and return it.
"""
usage = "usage: %prog [options] [xml_topology_filename]"
parser = OptionParser(usage)
parser.add_option(
"-b",
"--build_root",
dest="build_root_overwrite",
type="string",
help="Overwrite e... | 5,313,826 |
def launch_tuning(mode: str='grid', n_iter: int=1, n_gpu: int=1, devices: str='0',
params: dict=None, space: dict=None, root: str='../',
save_interval: int=0, candidate_list=None):
"""
Launch paramter search by specific way.
Each trials are launched asynchronously by fork... | 5,313,827 |
def window(window_type: WindowType, tmax: int):
"""Window functions generator.
Creates a window of type window_type and duration tmax.
Currently, hanning (also known as Hann) and hamming windows are available.
Args:
window_type: str, type of window function (hanning, squared_hanning,
ham... | 5,313,828 |
def download_project(token):
"""
Download a .trk/.npz file from a DeepCell Label project.
"""
project = Project.get(token)
if not project:
return abort(404, description=f'project {token} not found')
exporter = exporters.Exporter(project)
filestream = exporter.export()
return se... | 5,313,829 |
def cross_check_fields(new_instance, old_instance):
"""Check for changed fields between new and old instances."""
action_id = STATUS_ACTION.updated
class_name = get_class_name(new_instance)
changed_fields = []
usergroup_permission_fields = {}
for field in LOG_MODELS.get(new_instance.__class__.... | 5,313,830 |
def update_usage_plan(usagePlanId=None, patchOperations=None):
"""
Updates a usage plan of a given plan Id.
See also: AWS API Documentation
:example: response = client.update_usage_plan(
usagePlanId='string',
patchOperations=[
{
'op': 'add'|'remove'|... | 5,313,831 |
def restore_snapshot(args: argparse.Namespace) -> None:
"""
Apply a stored snapshot
:param args:
:return:
"""
try:
snapshot = get_snapshot_by_rel(args.snapshot)
if args.no_backup:
print("no-backup")
else:
create_snapshot(snapshot)
if args... | 5,313,832 |
def test_no_exception(interceptors):
"""An RPC with no exceptions should work as if the interceptor wasn't there."""
with dummy_client(special_cases={}, interceptors=interceptors) as client:
assert client.Execute(DummyRequest(input="foo")).output == "foo" | 5,313,833 |
def get(ctx, input_path, output_path, variable):
"""Prints the value of the requested variable. Mostly useful for debug."""
try:
output_directory = ctx.obj['batch_conf_dir'] / input_path.with_suffix('') if not output_path else output_path
except:
pass
from .config import outputs_commit, commit_branch, a... | 5,313,834 |
def print_statistics(train, test):
"""
Print some basic statistics about the train and test dataset
:param train: The train df
:param test: The test df
"""
train_size = train.shape[0]
test_size = test.shape[0]
total_size = train_size + test_size
print("Total data: %s. train data: %s(... | 5,313,835 |
def put(bucket, key, val, is_async=True):
"""
Writes key-value pair to storage.
:param bucket: (string) A bucket name.
:param key: (string) A key name.
:param val: (bytes) Value to write.
:param is_async: (bool) If true, issues rename coordinator call asynchronously.
"""
tk = _make_temp_... | 5,313,836 |
def derive_totals_analysis(df, portfolio_kpis, portfolio_group_by, claims_group_by):
""" Derives the totals amounts from a summary table
Arguments --> the dataframe, the kpis on which the total sums must be derived
the segmentation, i.e. on which features the analysis will be performed ... | 5,313,837 |
def crop(folder_path, file):
"""Crop image to dimensions 224 x 224
Args:
folder_path (str): pathname of directory where file lives
file (str): filename with extension
Returns:
path where resized image is saved
"""
im = Image.open(os.path.join(folder_path, file))
width, ... | 5,313,838 |
def set_default_data(file_path):
""" :param file_path: the file to write to\n
This function retrieves predetermined data from a given file, and then asigns the values to the global ui-vars"""
misconduct, gangs, decay, visibility, failure_conditions, events = get_general_settings(file_path)
var_misconduc... | 5,313,839 |
def fit_nGaussians (num, q, ws, hy, hx):
"""heights are fitted"""
h = np.random.rand(num) * np.average(hy) # array of guesses for heights
guesses = np.array([q, ws, *h])
errfunc = lambda pa, x, y: (nGaussians(x, num, *pa) - y)**2
# loss="soft_l1" is bad!
return optimize.least_squares(err... | 5,313,840 |
def build_preprocessors(md_instance):
""" Build the default set of preprocessors used by Markdown. """
preprocessors = odict.OrderedDict()
preprocessors['normalize_whitespace'] = NormalizeWhitespace(md_instance)
return preprocessors | 5,313,841 |
def generate_chunks(contents, n_chunks):
"""Generate equally sized chunks.
Args:
contents (list): A list to be split into chunks.
n_chunks (int): Number of chunks; must be smaller or equal to the length
of contents.
Returns:
output: Generator object of n_chunks elements.
"""
size = len(con... | 5,313,842 |
def odeCFL3(schemeFunc, tspan, y0, options, schemeData):
"""
odeCFL3: integrate a CFL constrained ODE (eg a PDE by method of lines).
[ t, y, schemeData ] = odeCFL3(schemeFunc, tspan, y0, options, schemeData)
Integrates a system forward in time by CFL constrained timesteps
using a third order... | 5,313,843 |
def p_expr_eval(p):
"""expr : SYMBOL EQUALS const
| SYMBOL NOTEQUALS const
| SYMBOL GT number
| SYMBOL LT number
| SYMBOL GTEQ number
| SYMBOL LTEQ number
| SYMBOL IN list
| SYMBOL COLON STR"""
p[0] = (p[2], p[1], p[3]) | 5,313,844 |
def greedy_action(model, state, device="cpu"):
"""
TODO
"""
with torch.no_grad():
Q = model(torch.Tensor(state).unsqueeze(0).to(device))
return torch.argmax(Q).item() | 5,313,845 |
def decode_lazy(rlp, sedes=None, **sedes_kwargs):
"""Decode an RLP encoded object in a lazy fashion.
If the encoded object is a bytestring, this function acts similar to
:func:`rlp.decode`. If it is a list however, a :class:`LazyList` is
returned instead. This object will decode the string lazily, avoi... | 5,313,846 |
def item_getter(obj):
"""default multiple dispatch func"""
raise TypeError('No item getter for object of type %r' % type(obj)) | 5,313,847 |
def slider_accel_constraint(env, safety_vars):
"""Slider acceleration should never go above threshold."""
slider_accel = safety_vars['slider_accel']
return np.less(slider_accel, env.limits['slider_accel_constraint'])[0] | 5,313,848 |
def calculate_component_overlap(matches, thresh_distance):
"""
Calculate how much each connected component is made redundant (percent of nodes that have a neighbor within some
threshold distance) by each of its candidates.
Args:
matches (dict): output from `nodewise_distance_connected_compo... | 5,313,849 |
def binary_otsus(image, filter:int=1):
"""Binarize an image 0's and 255's using Otsu's Binarization"""
if len(image.shape) == 3:
gray_img = cv.cvtColor(image, cv.COLOR_BGR2GRAY)
else:
gray_img = image
# Otsus Binarization
if filter != 0:
blur = cv.GaussianBlur(gray_img, (3,... | 5,313,850 |
def get_struct(str_type):
"""
>>> assert get_struct(type(1)) == 'h'
>>> assert get_struct(type(1.001)) == 'd'
"""
str_type = str(str_type)
return type_to_struct[str_type] | 5,313,851 |
def tkmount(TOKEN=None, mountpoint='/content/gdrive', force_remount=False):
"""Mont using a token already available."""
mountpoint = _os.path.expanduser(mountpoint)
# If we've already mounted drive at the specified mountpoint, exit now.
already_mounted = _os.path.isdir(_os.path.join(mountpoint, 'My Drive'))
... | 5,313,852 |
def dumps(obj, *transformers):
"""
Serializes Java primitive data and objects unmarshaled by load(s) before
into string.
:param obj: A Python primitive object, or one loaded using load(s)
:param transformers: Custom transformers to use
:return: The serialized data as a string
"""
marsha... | 5,313,853 |
def extract_lineage(p_id: int, partial_tree_ds: Tuple[List[int], List[int],
List[int], List[Item]]) -> Dict[int, List]:
"""Extract comment lineage."""
ids, indents, sorted_indents, items = partial_tree_ds
comment_lineage = {}
lineage = []
for index, item_id in enumerate(ids):
# if we're ... | 5,313,854 |
def get_or_import(value, default=None):
"""Try an import if value is an endpoint string, or return value itself."""
if isinstance(value, str):
return import_string(value)
elif value:
return value
return default | 5,313,855 |
def check_trails_in_db(trail_wikiloc_ids):
"""
Returns a list of tuples (wikiloc trail_id, database trail_id)
with every trail from trail_wikiloc_ids that is already in the database
return (wikiloc_trail_id,db_trail_id)
"""
try:
connection = get_connection()
with connection.curso... | 5,313,856 |
def from_saved_tracks(
output_format: str = None,
use_youtube: bool = False,
lyrics_provider: str = None,
threads: int = 1,
) -> List[SongObject]:
"""
Create and return list containing SongObject for every song that user has saved
`str` `output_format` : output format of the song
retur... | 5,313,857 |
def df2dicts(df):
"""
df to dicts list
"""
dicts = []
for line in df.itertuples():
ll = list(df.columns)
dicts.append(dict(zip(ll, list(line)[1:])))
return dicts | 5,313,858 |
def test_def_include_variable2():
"""Test that going to definition of a variable in an include file works."""
string = write_rpc_request(1, "initialize", {"rootPath": str(test_dir)})
file_path = test_dir / "subdir" / "test_inc2.f90"
string += def_request(file_path, 4, 3)
errcode, results = run_reque... | 5,313,859 |
def aligncheck(_, inputfiles, report, full_report, header):
"""
Check if input rasters are aligned.
"""
kwargs = dict(report=report, full_report=full_report, header=header)
result = check_alignment(inputfiles, **kwargs)
if result:
for row in result:
click.echo(row)
else:... | 5,313,860 |
def read_flash_hex(decode_hex=False, **kwargs):
"""Read data from the flash memory and return as a hex string.
Read as a number of bytes of the micro:bit flash from the given address.
Can return it in Intel Hex format or a pretty formatted and decoded hex
string.
:param address: Integer indicating... | 5,313,861 |
def naify_extreme_values(x, n_iqr=3):
"""
Replace extreme values in a pd.Series with NAs.
:param pd.Series x: a pandas Series which potentially has extreme values
:param int n_iqr: the number of IQR used to define extreme values. Default is 3.
:return:
"""
Q1 = np.nanquantile(x, 0.25)
Q3 = np.nanquantile(x, 0.... | 5,313,862 |
def saha(
graph, initial_partition=None, is_integer_graph=False
) -> SahaPartition:
"""
Returns an instance of the class :class:`SahaPartition` which can be used
to recompute the maximum bisimulation incrementally.
:param graph: The initial graph.
:initial_partition: The initial partition, or l... | 5,313,863 |
def load_model(LOAD_DIR):
"""
Load model from a given directory, LOAD_DIR.
Parameters
----------
LOAD_DIR : text
Path of load directory.
Returns
-------
inverse_mapping :numpy array (floats)
The {NUM_MODES x p} matrix transform that maps the image patches to
the... | 5,313,864 |
def parse_args():
"""
Parse input arguments
"""
parser = argparse.ArgumentParser(description='Train Repeat Buyer Prediction Model')
parser.add_argument('--model', dest='model_name',
help='model to use',
default='dnn', type=str)
parser.add_argument(... | 5,313,865 |
def files_differ(path_a, path_b):
"""
True if the files at `path_a` and `path_b` have different content.
"""
return not filecmp.cmp(path_a, path_b) | 5,313,866 |
def classical_mds(d, ndim=2):
"""
Metric Unweighted Classical Multidimensional Scaling
Based on Forrest W. Young's notes on Torgerson's (1952) algorithm as
presented in http://forrest.psych.unc.edu/teaching/p230/Torgerson.pdf:
Step 0: Make data matrix symmetric with zeros on the diagonal
Step 1... | 5,313,867 |
def get_room_occupation():
"""Parse room from query params and look up its occupation."""
room = request.args.get('room')
if room:
room_args = re.split('([0-9]+)', room)
room_args = [arg for arg in room_args if arg != '']
if len(room_args) == 2:
try:
occup... | 5,313,868 |
def calculate_ts_mac(ts, credentials):
"""Calculates a message authorization code (MAC) for a timestamp."""
normalized = ('hawk.{hawk_ver}.ts\n{ts}\n'
.format(hawk_ver=HAWK_VER, ts=ts))
log.debug(u'normalized resource for ts mac calc: {norm}'
.format(norm=normalized))
dig... | 5,313,869 |
def update_yarnpkgs():
"""Update yarnPkgs"""
repo = GitLabRepo()
yarnpkgs_dir = pathlib.Path(__file__).parent
# load rev from data.json
data = _get_data_json()
rev = data['rev']
with open(yarnpkgs_dir / 'yarn.lock', 'w') as f:
f.write(repo.get_file('yarn.lock', rev))
with ope... | 5,313,870 |
def select_largest(evaluator, minNumber=None, tolerance=None):
""" Selector of integer variables or value having the largest evaluation according to a given evaluator.
This function returns a selector of value assignments to a variable that selects all values having the
largest evaluation according to the ... | 5,313,871 |
def correct_atom_props(atom):
"""
Used during fragmentation to correct atom properties where an
adjacent atom is removed.
Parameters
----------
atom : rdkit.Chem.rdchem.Atom
Atom to correct.
"""
if atom.GetIsAromatic() and atom.GetAtomicNum() != 6:
atom.SetNumExplicitHs... | 5,313,872 |
def nfs_dataset_activate(ctx, from_json, rw, world, ip, subnet_mask_length, name, appliance_profile):
"""
1. Get all the datasets
2. Check if the dataset name provided exists in the received datasets
1. If it exists, check if it is sealed
1. If sealed, reopen and activate the dataset
... | 5,313,873 |
async def test_air_quality(
hass: HomeAssistant,
init_integration: MockConfigEntry,
) -> None:
"""Test the Ambee Air Quality sensors."""
entry_id = init_integration.entry_id
entity_registry = er.async_get(hass)
device_registry = dr.async_get(hass)
state = hass.states.get("sensor.air_quality... | 5,313,874 |
def plot_pendulum(trajs):
"""
Plot trajectory of inverted pendulum
"""
fig, ax = plt.subplots(figsize=(12, 8), nrows=2, ncols=2, sharex=True)
ax[0][0].set_title("Pendulum Plant")
plot_component(ax[0][0], trajs, "plant", "states", 0, "position (m)")
plot_component(ax[0][0], trajs, "maneuver",... | 5,313,875 |
def m2(topic_srs, topic_vol, sharpe, ref_vol, cum=False, annual_factor=1):
"""Calcs m2 return which is a port to mkt vol adjusted return measure.
The Sharpe ratio can be difficult to interpret since it's a ratio, so M2
converts a Sharpe to a return number.
Args:
topic_srs (Pandas DataFram... | 5,313,876 |
def test_up():
"""Tests get_pts's ability to plot upward directions
"""
assert get_pts(['U3']) == [(0,0), (0,1), (0,2), (0,3)], \
"Should be [(0,0), (0,1), (0,2), (0,3)]" | 5,313,877 |
def model_dir_str(model_dir, hidden_units, logits, processor, activation,
uuid=None):
"""Returns a string for the model directory describing the network.
Note that it only stores the information that describes the layout of
the network - in particular it does not describe any trainin... | 5,313,878 |
def init_process_group(backend,
init_method=None,
world_size=None,
rank=None):
"""
Initializes the default distributed process group and the AdaptDL
collectives module.
Args:
backend (str or Backend): The backend to use. Use "... | 5,313,879 |
def parse_mets_with_metsrw(mets_file):
"""Load and Parse the METS.
Errors which we encounter at this point will be critical to the
caller and so an exception is returned when we can't do any better.
"""
try:
mets = metsrw.METSDocument.fromfile(mets_file)
except AttributeError as err:
... | 5,313,880 |
def configureLogging():
"""Define logging & loglevels using an external yaml config file
"""
# this was useful: https://gist.github.com/glenfant/4358668
from .local import AppLocalDir
log_config_dir = AppLocalDir("logging")
# now we have directory "~/.skeleton/logging"
if not log_config_di... | 5,313,881 |
def default_argument_parser():
"""
Returns the argument parser with the default options.
Inspired by the implementation of FAIR's detectron2
"""
parser = argparse.ArgumentParser(
formatter_class=argparse.RawDescriptionHelpFormatter,
)
parser.add_argument(
"--config-file",
... | 5,313,882 |
def check_dangling_bonds(pattern):
"""
Check for dangling bonds in a PySB ComplexPattern/ReactionPattern
Raises a DanglingBondError if a dangling bond is found
"""
if isinstance(pattern, ReactionPattern):
for cp in pattern.complex_patterns:
check_dangling_bonds(cp)
retur... | 5,313,883 |
def has_gain_user_privileges(description, cvssv2, cpe_type):
"""
Function determines whether particular CVE has "Gain user privileges
on system" as its impact.
:param description: description of CVE
:param cvssv2: CVSS version 2
:param cpe_type: One of {'a', 'o', 'h'} = application, operating s... | 5,313,884 |
def empty_orgstable():
"""Delete all organizations"""
cursor = db.cursor()
cursor.execute("DELETE FROM organizations WHERE 1")
db.commit() | 5,313,885 |
def __scores(clf, testset):
"""
"""
accuracy_ = accuracy(clf, testset)
precision_, recall_ = precision_recall(clf, testset)
f1score_ = f1score(precision_, recall_)
return accuracy_, precision_, recall_, f1score_ | 5,313,886 |
def format_recipe_tree_components_data(
recipe_tree_components: List[Dict]
) -> Dict:
"""
Returns a dictionary containing total weight of recipe and
subrecipe details.
"""
net_weight = 0
gross_weight = 0
standalone_recipe_items = []
for recipe_tree_component in recipe_tree_components... | 5,313,887 |
def test_cluster_network_acl():
"""
This method return all cluster network_acl
:return:
"""
assert len(tag_cluster_resources.cluster_network_acl()) >= 0 | 5,313,888 |
def clean_nodes(root: ElementTree.Element, used_nodes: set):
"""Remove unwanted or unused nodes and node attribs."""
trash = [n for n in root.iterfind('node') if n.get('id') not in used_nodes]
for item in trash:
root.remove(item)
for node in root.iterfind('node'):
attribs = [a for a in ... | 5,313,889 |
def choose(n, k):
"""
A fast way to calculate binomial coefficients by Andrew Dalke (contrib).
"""
if np.isnan(n):
return np.nan
else:
n = np.int64(n)
if 0 <= k <= n:
ntok = 1
ktok = 1
for t in range(1, min(k, n - k) + 1):
ntok *= n
... | 5,313,890 |
def uniform1(a, b):
"""One number in a uniform distribution between a and b."""
return np.random.random() * (b - a) + a | 5,313,891 |
def copy(srcdir, destination):
"""
Recursive copy
"""
for name in os.listdir(srcdir):
fullname = os.path.join(srcdir, name)
if os.path.isdir(fullname):
if name in ('.cache', '__pycache__'):
continue
outdir = os.path.join(destination, name)
... | 5,313,892 |
def manage_admin():
""" 管理员资料页面路由 """
if 'adminname' in session:
the_result = manage_the_admin(db, Option, request.form)
return the_result
else:
abort(404) | 5,313,893 |
def fetch_map():
"""Method for generating folium map with custom event for clicking inside."""
home_m = folium.Map(location=[41.8902142, 12.4900369], zoom_start=5, width=550, height=350)
home_m.add_child(folium.LatLngPopup())
home_m = home_m.get_root().render()
home_p = [r.start() for r in re.findit... | 5,313,894 |
def calc_residual_ver(list_ulines, xcenter, ycenter):
"""
Calculate the distances of unwarped dots (on each vertical line) to each
fitted straight line which is used to assess the straightness of unwarped
lines.
Parameters
----------
list_ulines : list of 2D arrays
List of the c... | 5,313,895 |
def _SafeShutdownInstanceDisks(lu, instance, disks=None):
"""Shutdown block devices of an instance.
This function checks if an instance is running, before calling
_ShutdownInstanceDisks.
"""
CheckInstanceState(lu, instance, INSTANCE_DOWN, msg="cannot shutdown disks")
ShutdownInstanceDisks(lu, instance, di... | 5,313,896 |
def CleanJobFolder_basic(rstdir):# {{{
"""Clean the jobfolder after finishing: the basic function"""
flist =[
"%s/remotequeue_seqindex.txt"%(rstdir),
"%s/torun_seqindex.txt"%(rstdir)
]
for f in flist:
if os.path.exists(f):
try:
os.remov... | 5,313,897 |
def create_stop_feedback(request):
"""stop feedback api endpoint"""
# verify that the calling user has a valid secret key
secret = request.headers.get('Secret')
if secret is None:
return request_response(unAuthenticatedResponse, ErrorCodes.INVALID_CREDENTIALS,
"Se... | 5,313,898 |
def private_with_master(message):
""" Is a private message from bot owner?"""
return is_from_master(message) and message.chat.type == 'private' | 5,313,899 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.