content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def export_result(fname, num_trans, candidate_rules, minsup, minconf, itemset_sups, rule_confs, processing_time):
"""Prints association rules to Rules file."""
try:
f = open("Rules", "w")
try:
print("Summary:", file=f)
print("--------------------------------------------... | 5,326,800 |
def children_shape_ranks(rank, n):
"""
Return the partition of leaves associated
with the children of the tree of rank `rank`, and
the ranks of each child tree.
"""
part = []
for prev_part in partitions(n):
num_trees_with_part = num_tree_pairings(prev_part)
if rank < num_tree... | 5,326,801 |
def url_mapper(url, package):
"""
In a package.json, the "url" field is a redirection to a package download
URL published somewhere else than on the public npm registry.
We map it to a download url.
"""
if url:
package.download_urls.append(url)
return package | 5,326,802 |
def electricPotential(n, V_SD_grid, V_G_grid):
"""
Function to compute the electric potential of the QDot.
:param n: the number of electrons in the dot
:param V_SD_grid: the 2d array of source-drain voltage values
:param V_G_grid: the 2d array of gate voltage values
:return: The Electric Potent... | 5,326,803 |
def mettre_a_jour_uids(nom_fichier, organisateurs, uids):
""" Met à jour le fichier CSV UID,EMAIL à partir du dictionnaire """
nouveaux_uids = False
for id_reunion in organisateurs:
if organisateurs[id_reunion]["id_organisateur"] not in uids:
uids[organisateurs[id_reunion]["id_organisate... | 5,326,804 |
def _spectrogram(signal, dB=True, log_prefix=20, log_reference=1,
yscale='linear', unit=None,
window='hann', window_length=1024, window_overlap_fct=0.5,
cmap=mpl.cm.get_cmap(name='magma'), ax=None):
"""Plot the magnitude spectrum versus time.
See pyfar.line.sp... | 5,326,805 |
def _merge_cwlinputs(items_by_key, input_order, parallel):
"""Merge multiple cwl records and inputs, handling multiple data items.
Special cases:
- Single record but multiple variables (merging arrayed jobs). Assign lists
of variables to the record.
"""
items_by_key = _maybe_nest_bare_single(... | 5,326,806 |
def polar_distance(x1, x2):
"""
Given two arrays of numbers x1 and x2, pairs the cells that are the
closest and provides the pairing matrix index: x1(index(1,:)) should be as
close as possible to x2(index(2,:)). The function outputs the average of
the absolute value of the differences abs(x1(index(1... | 5,326,807 |
def _calc_data_point_locations(num_points, x_values=None):
"""Returns the x-axis location for each of the data points to start at.
Note: A numpy array is returned so that the overloaded "+" operator can be
used on the array.
The x-axis locations are scaled by x_values if it is provided, or else the
... | 5,326,808 |
def _update_config(args, config_dict):
"""update param_dict by args. config in args is prior to config_dict.
Args:
args (ArgumentParser): [in] parsed aguemnt parser
config_dict (dict): [in/out] config dict
Returns: None
Raises: NULL
"""
if 'trainer' in config_dict:
tra... | 5,326,809 |
def is_base(base_pattern, str):
"""
base_pattern is a compiled python3 regex.
str is a string object.
return True if the string match the base_pattern or False if it is not.
"""
return base_pattern.match(str, 0, len(str)) | 5,326,810 |
def stations_by_river(stations):
"""For a list of MonitoringStation objects (stations),
returns a dictionary that maps river names (key) to a list of MonitoringStation objects on a given river."""
# Dictionary containing river names and their corresponding stations
rivers = {}
for station in stati... | 5,326,811 |
def dQ_dY(time):
"""Derivative of transformation matrix for nutation/presession with regards to the Y coordinate of CIP in GCRS
"""
# Rotation matrices
R3_E = R3(E(time))
R3_s = R3(s(time))
R2_md = R2(-d(time))
R3_mE = R3(-E(time))
dR3_s = dR3(s(time))
dR3_E = dR3(E(time))
dR3_mE... | 5,326,812 |
def calculate(x: int, y: int = 1, operation: str = None) -> int:
"""Calculates the sum (or difference) of two numbers.
Parameters:
`x` : int
The first number
`y` : int, optional
The second number (default is `1`)
`operation`: str, optional
Pass "subtract" to perform subtract... | 5,326,813 |
def test_client_get_payment_related_invalid_id(client, endpoint, errorstr):
"""An invalid formatted object ID should raise an error."""
with pytest.raises(IdentifierError, match=errorstr):
getattr(client, endpoint).with_parent_id("tr_12345").get("invalid") | 5,326,814 |
def get_power_state(instance):
"""Return the power state of the received instance.
:param instance: nova.objects.instance.Instance
:return: nova.compute.power_state
"""
instance_info = manage.VBoxManage.show_vm_info(instance)
return instance_info.get(constants.VM_POWER_STATE) | 5,326,815 |
def toBoolean(val, default=True):
"""convert strings from CSV to Python bool
if they have an empty string - default to true unless specified otherwise
"""
if default:
trueItems = ["true", "t", "yes", "y", "1", "on", ""]
falseItems = ["false", "f", "no", "n", "none", "0"]
else:
... | 5,326,816 |
def cache_put(
connection: 'Connection', cache: Union[str, int], key, value,
key_hint=None, value_hint=None, binary=False, query_id=None,
) -> 'APIResult':
"""
Puts a value with a given key to cache (overwriting existing value if any).
:param connection: connection to Ignite server,
:param cach... | 5,326,817 |
def _process_rows(app, sheet_name, rows, names_map, lang=None):
"""
Processes the rows of a worksheet of translations.
This is the complement of get_bulk_app_sheets_by_name() and
get_bulk_app_single_sheet_by_name(), from
corehq/apps/translations/app_translations/download.py, which creates
these... | 5,326,818 |
def parse_line(line, metric):
"""Parses statistics from a line an experiment log file"""
if "top-k" in line:
return f"top-k.{metric}", parse_csv(line)
elif "bottom-k" in line:
return f"bottom-k.{metric}", parse_csv(line)
else:
return f"ml.{metric}", parse_csv(line) | 5,326,819 |
def lock(pth):
"""
Lock file
"""
assert exists(pth), "%s does not exist!" % pth
svnopen(['lock', pth]) | 5,326,820 |
def test_for_usb_ext4():
"""Test Purpose: Verify that if the EXT4 filesystem support is enable in the kernel
Args:
None
"""
cmd = "cat /boot/config-* | grep ^CONFIG_EXT4_FS="
ret = subprocess.call(cmd + " > /dev/null 2>&1", shell=True)
assert ret == 0, "EXT4 support is disabled in ... | 5,326,821 |
def print_menu():
"""Prints main categories of animals"""
animal_menu = {'1': 'Fish', '2': 'Birds', '3': 'Mammals', '4': 'Insects', '5': 'Exit'}
print('Learn about Animal Migration Patterns!!\nChoose a category...')
for key in animal_menu:
print(key + ". " + animal_menu[k... | 5,326,822 |
def get_adjusted_pvalues(pvals: pd.Series, fdr_thresh: float = 0.05) \
-> Tuple[pd.Series, float]:
"""
Function that controls FDR rate.
Accepts an unsorted list of p-values and an FDR threshold (1).
Returns:
1) the FDR associated with each p-value,
2) the p-value cutoff for the given FDR... | 5,326,823 |
def solve_nonogram(constraints):
"""this function is solving all kinds of boards of the game and returning
the all possible solutions for it""" # BTM
return [solve_easy_nonogram(constraints)] | 5,326,824 |
def get_libs():
"""
Get all of the libraries defined in lib/definitions.
This is called automatically when the package is imported.
"""
print(">> Checking for libraries to download..")
definitions = os.listdir("lib/definitions")
tried = 0
downloaded = 0
failed = 0
exists = 0
... | 5,326,825 |
def adjust_list_human_readable(entry_context_with_spaces, entry_context):
"""Change keys in human readable data to match the headers.
"""
entry_context_with_spaces["ID"] = entry_context.get("ID", "") | 5,326,826 |
def downsample_data(data, scale_factor, order):
"""
Downsample data
TODO: Scikit-image has a transform module that works better,
this function should have the option to use either
"""
return scipy.ndimage.interpolation.zoom(data, scale_factor, order=order, mode="constant") | 5,326,827 |
def uwid(string):
"""Return the width of a string"""
if not PY3:
string = string.decode('utf-8', 'ignore')
return sum(utf_char_width(c) for c in string) | 5,326,828 |
def check_double_quote(inpstring):
"""
Check if some strings needs of a double quote (if some space are inside the string, it will need to be inside two double quote). E.g.: --sfmt="TIFF (unstitched, 3D)"
Input:
inpstring: input string or array of strings
Output:
newstring = new string (or... | 5,326,829 |
def get_wheel_index_data(py_version, platform_version, url=torch_nightly_wheel_index, override_file=torch_nightly_wheel_index_override):
"""
"""
if os.path.isfile(override_file) and os.stat(override_file).st_size:
with open(override_file) as f:
data = f.read()
else:
r = reque... | 5,326,830 |
def get_linear_schedule_with_warmup(
num_warmup_steps, num_training_steps, last_epoch=-1
):
"""
Create a schedule with a learning rate that decreases linearly from the initial lr set in the optimizer to 0,
after a warmup period during which it increases linearly from 0 to the initial lr set in the optim... | 5,326,831 |
def search_image_targets_for_tag(trust_data: dict, image: Image):
"""
Searches in the `trust_data` for a digest, given an `image` with tag.
"""
image_tag = image.tag
if image_tag not in trust_data:
return None
base64_digest = trust_data[image_tag]["hashes"]["sha256"]
return base64.b... | 5,326,832 |
def cleanup():
"""Cleanup method on Ctrl+C"""
global ledc, pif, switch_listener
switch_listener.deactivate()
for x in range(8):
pif.leds[x].turn_off()
pif.deinit_board()
print ("")
print ("PiFace cleanup complete.") | 5,326,833 |
def convert_gene_ids(geneList,target):
"""
takes a list of gene ids (int) and returns the target field
Normally, the database can be used, however this script is
used for example if a species has not yet been entered in the db.
"""
if target not in ['taxid','symbol']:
raise Exception(... | 5,326,834 |
def calculate_intersection(a: BoundingBox, b: BoundingBox) -> int:
"""Calculate the intersection of two bounding boxes.
:param BoundingBox a: The first bounding box.
:param BoundingBox b: The second Bounding box.
:returns iou: The intersection of ``a`` and ``b``.
:rtype: int
"""
left = max(... | 5,326,835 |
def get_linux_ip(eth):
"""在Linux下获取IP"""
assert os.name == 'posix', NotLinuxSystemError('不是Linux系统')
import fcntl
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
ip = socket.inet_ntoa(fcntl.ioctl(s.fileno(), 0x8915, struct.pack('256s', eth[:15])))
return ip[20:24] | 5,326,836 |
def callback_help(call: CallbackQuery):
"""
Help statement detailed help
:param call:
:return:
"""
try:
d_id = int(call.data[5:])
dispatchers = get_manager().dispatchers
show_usage_for(call.message, dispatchers[d_id])
except Exception as e:
logger.error(f'{cal... | 5,326,837 |
def test_out_of_date_range(client: FlaskClient):
"""
We have generated summaries for this product, but the date is out of the product's date range.
"""
html = get_html(client, "/wofs_albers/2010")
# The common error here is to say "No data: not yet generated" rather than "0 datasets"
assert che... | 5,326,838 |
def build_nn_model(input_shape):
"""Generate NN model
:param: input_shape (tuple): shape of the input
:return model: NN model
"""
model = keras.Sequential([
# input layer
# multi demensional array and flatten it out
# inputs.shape[1]: the intervals
... | 5,326,839 |
def main():
"""
Main routine for this workload; spawn a single proposer and a variable
number of acceptors (NETWORK_SIZE - 1).
"""
# a network is a dictionary of names => (host, port)
# we first build a network; then we spawn proposers, and finally
# spawn replicas
network = {}
# i... | 5,326,840 |
def save_checkpoint(state, is_best, filename='checkpoint.pth.tar'):
"""
Save the given Pytorch object as a checkpoint.
If is_best is true, create a copy of the object called 'model_best.pth.tar'
Parameters
----------
state : PyTorch object
The object to save
is_best : bool
... | 5,326,841 |
def window_sumsquare(
window,
n_frames,
hop_length=512,
win_length=None,
n_fft=2048,
dtype=np.float32,
norm=None,
):
"""Compute the sum-square envelope of a window function at a given hop length.
This is used to estimate modulation effects induced by windowing observations
in sh... | 5,326,842 |
def main():
"""The main file of the script."""
parser = argparse.ArgumentParser()
parser.add_argument('--create_backup', action='store_true', dest='create_backup', default=False,
help='Create a new backup of terminator config and remove all previous autobash sections from it.')
... | 5,326,843 |
def getLatestCode(appDbConnStr: str) -> Optional[ICode]:
"""get latest created code from db
Args:
appDbConnStr (str): app db connection string
Returns:
Optional[ICode]: code object
"""
latestIdFetchsql = """
select id
from code_book.op_codes
whe... | 5,326,844 |
async def create_arrest_csv(data: list, FILE="./data/csv/arrest/arrest.csv"):
"""
:param data:
:param FILE:
:return:
"""
header = "arrest_time, case_number, arrest_location, offense, arrestee_name, arrestee_birthday, city, state, zip, status, officer\n"
with open(FILE, 'w+') as fp:
... | 5,326,845 |
def start_initialization_pd(update: Update, context: CallbackContext) -> str:
"""When touch "Заполнить данные"."""
u = User.get_user(update, context)
current_text = update.effective_message.text
update.effective_message.edit_text(
text=current_text
)
context.bot.send_message(
c... | 5,326,846 |
def rpm_comments(table=RPMComment, prefix='comment_', relationships=False):
"""Get filters for rpm comments.
:param sqlalchemy.ext.declarative.api.declarativemeta table: database model
:param string prefix: prefix of the name of the filter
:return dict: dict of filters
"""
filters = dict(
... | 5,326,847 |
def split_line(line) -> list:
"""Split a line from a dmp file"""
return [x.strip() for x in line.split(" |")] | 5,326,848 |
def test_qguiapplication_functions():
"""Test functions mapping for QtGui.QGuiApplication."""
assert QtGui.QGuiApplication.exec_ is not None | 5,326,849 |
def translate(text):
"""."""
return text | 5,326,850 |
def stream_bytes(data, chunk_size=default_chunk_size):
"""Gets a buffered generator for streaming binary data.
Returns a buffered generator which encodes binary data as
:mimetype:`multipart/form-data` with the corresponding headers.
Parameters
----------
data : bytes
The data bytes to stream
chunk_size : int... | 5,326,851 |
def helper(n, big):
"""
:param n: int, an integer number
:param big: the current largest digit
:return: int, the final largest digit
"""
n = abs(n)
if n == 0:
return big
else:
# check the last digit of a number
if big < int(n % 10):
big = int(n % 10)
# check the rest of the digits
return helper(n/1... | 5,326,852 |
def test_phrase_search(query, output):
"""Makes sure searching for individual instances of a query works."""
corpus = Corpus(
["The dog ran to the cat", "The dog ran to the other dog", "The cat sat"]
)
assert corpus.search_occurrences(query) == output | 5,326,853 |
async def get_transfer_list(request: Request):
"""This function checks for transfer list for an authenticated user"""
transfer_status_list = []
# Code for globus
tokens = await globus.verify_globus_code(request)
if tokens:
globus_item_count = 10
if 'globus_item_count' in... | 5,326,854 |
def conv_out_shp(IR, IC, KR, KC, border_mode, subsample):
"""
.. todo::
WRITEME
"""
ssR, ssC = subsample
def ceildiv(x, y):
r = x // y
if r * y < x:
return r + 1
return r
if border_mode == 'valid':
OR, OC = ceildiv(IR - KR + 1,ssR), ceildiv(IC... | 5,326,855 |
def getPageNumber(ffile):
"""
Extract the page number from the file name
:param ffile:
:return: image URI as a string
"""
return str(ffile).split('_')[-1].split('.')[0] | 5,326,856 |
def colors_stepsort(r,g,b,repetitions=1):
"""
Sort colors in hue steps for more perceptually uniform colormaps
"""
lum = np.sqrt( .241 * r + .691 * g + .068 * b )
h, s, v = colorsys.rgb_to_hsv(r,g,b)
h2 = int(h * repetitions)
lum2 = int(lum * repetitions)
v2 = int(v * repetitions)
if... | 5,326,857 |
def _verify_monotonic(haystack):
"""Haystack items shall be non-descending. Dups are OK."""
prev = haystack[0]
for item in haystack:
assert item >= prev, item
prev = item | 5,326,858 |
def get_string_hash(string: str, algorithm_name: str):
"""Calculates the hash digest of a string.
Args:
string: str: The string to digest.
algorithm_name: str: The name of the algorithm to hash the string with.
Returns:
A hash digest in string form.
"""
hash_algorithm = _get_alg... | 5,326,859 |
def psd_error(times,rates,errors):
"""
obtain errors for the best frequency estimate of the signal
"""
"""
print(len(times),len(rates),len(errors))
newdatachoice = np.random.choice(len(times),size=int(0.1*len(times)))
newtimes = list(np.array([times[0]])) + list(np.array([times[-1]])) + list(times[np.array(lis... | 5,326,860 |
def solve(global_step):
"""add solver to losses"""
# learning reate
lr = _configure_learning_rate(82783, global_step)
optimizer = _configure_optimizer(lr)
tf.summary.scalar('learning_rate', lr)
# compute and apply gradient
losses = tf.get_collection(tf.GraphKeys.LOSSES)
regular_losses =... | 5,326,861 |
def get_features_from_policy(env, policy):
"""Represent policies with average feature vector.
This only makes sense for linear reward functions, but it is only used for the
HighwayDriving environment.
"""
assert isinstance(env.unwrapped, HighwayDriving)
assert isinstance(policy, FixedPolicy)
... | 5,326,862 |
def get_files_from_folder(directory, extension=None):
"""Get all files within a folder that fit the extension """
# NOTE Can be replaced by glob for newer python versions
label_files = []
for root, _, files in os.walk(directory):
for some_file in files:
label_files.append(os.path.abs... | 5,326,863 |
def predicate(line):
"""
Remove lines starting with ` # `
"""
if "#" in line:
return False
return True | 5,326,864 |
def pad_slices(ctvol, max_slices): #Done testing
"""For <ctvol> of shape (slices, side, side) pad the slices to shape
max_slices for output of shape (max_slices, side, side)"""
padding_needed = max_slices - ctvol.shape[0]
assert (padding_needed >= 0), 'Image slices exceed max_slices by'+str(-1*padding_n... | 5,326,865 |
def average_img_from_dir(path_data_dir,filepat="*", \
parentaslabel=False,\
labels=[],\
sampling_rate=0.001,\
title="average image") :
"""
create and visualize average image of given dataset
dataset_path = path to dataset
sampling_rate = sampling r... | 5,326,866 |
def register_socketio(socketio_in : SocketIO) -> None:
"""Register the socket.io connection manager for room management.
Args:
socketio_in (SocketIO): The socket.io connection manager.
"""
global socketio
socketio = socketio_in | 5,326,867 |
def get_size(positions):
"""Get the size of bounding rectangle that embodies positions.
Args:
positions (dict of Dendrogram: np.array): positions xy coordinates of dendrograms
Returns:
Tuple of width and height of bounding rectangle.
"""
max_y_list = [dendrogram.height + coords[1] ... | 5,326,868 |
def getContactInfo(dic):
"""Returns the Contact info for Chapters.
dic -- Dictionary from the JSON with all values.
"""
return str(dic["content"]["$t"]).split(',')[1].split(':')[1].strip() | 5,326,869 |
def draw_pointcloud(x: torch.Tensor, x_mask: torch.Tensor, grid_on=True):
""" Make point cloud image
:param x: Tensor([B, N, 3])
:param x_mask: Tensor([B, N])
:param grid_on
:return: Tensor([3 * B, W, H])
"""
tic = time.time()
figw, figh = 16., 12.
W, H = 256, int(256 * figh / figw)
... | 5,326,870 |
def semantic_dsm(word_list, keyed_vectors):
"""Calculate a semantic dissimilarity matrix."""
vectors = np.array([keyed_vectors.word_vec(word) for word in word_list])
dsm = np.clip(pdist(vectors, metric="cosine"), 0, 1)
return dsm | 5,326,871 |
def prompt_id_num(message, length=ID_WIDTH):
""" Asks the user to enter a identifier which is a numeric string.
The length is the length of the identifier asked.
:param message: message to ask the input
:param length: the length of the identifier
:return: input
"""
response = input(message... | 5,326,872 |
def click_snr(wl, Spec):
"""Calculate snr in a specific range given by clicks on a plot """
plt.figure()
plt.plot(wl, Spec)
plt.show(block=True)
# points from click
# temp values untill implement above
point2 = np.max(wl)
point1 = np.min(wl)
map2 = wl < point2
map1 = wl > point1... | 5,326,873 |
def plot_spectrogram(f, t, Sxx):
"""This function plots a spectrogram using matplotlib
Arguments
----------
f: the frequency output of the scipy.signal.spectrogram
t: the time series output of the scipy.signal.spectrogram
Sxx: the spectrogram output of scipy.signal.spectrogram
Returns
... | 5,326,874 |
def rnn_cell_forward(xt, a_prev, parameters):
"""
Implements a single forward step of the RNN-cell
Arguments:
xt -- your input data at timestep "t", numpy array of shape (n_x, m).
a_prev -- Hidden state at timestep "t-1", numpy array of shape (n_a, m)
parameters -- python dictionary containing:... | 5,326,875 |
def load_random_batch(cfg, data_paths):
"""
Loads a random batch (batch_size, image, masks, weights)
Parameters:
-----------
cfg: contains the cfg.BATCH_SIZE
data_paths: list containing strings
paths to the folder where the images, masks and weights are in
Returns:
--------
... | 5,326,876 |
def test_stars_pickleable():
"""
Verify that EPSFStars can be successfully
pickled/unpickled for use multiprocessing
"""
from multiprocessing.reduction import ForkingPickler
# Doesn't need to actually contain anything useful
stars = EPSFStars([1])
# This should not blow up
ForkingPic... | 5,326,877 |
def test_memory_consumption_before_backward_hessian():
"""Check memory consumption during splitting."""
_ = example_sequence()
print("No splitting")
mem_stat1 = memory_report()
_ = example_sequence_parallel()
print("With splitting")
mem_stat2 = memory_report()
assert mem_stat1 == mem_st... | 5,326,878 |
def load_song(trainsize=5000, testsize=5000):
""" The million song dataset
Not a good dataset for feature selection or regression
Standard linear regression performs only a little bit better than a random vector.
Additional complex models, such as interesting kernels, are needed
To improve per... | 5,326,879 |
def convert_node(node_data: NodeData):
"""
Convenience method for converting NodeData to a packed TLV message.
:param core.emulator.data.NodeData node_data: node data to convert
:return: packed node message
"""
node = node_data.node
services = None
if node.services is not None:
... | 5,326,880 |
def parse_null_value(
null_value_node: "NullValueNode", schema: "GraphQLSchema"
) -> None:
"""
Returns the value of an AST null value node.
:param null_value_node: AST null value node to treat
:param schema: the GraphQLSchema instance linked to the engine
:type null_value_node: NullValueNode
... | 5,326,881 |
def SetDataTypesFromColInfo(df, tblCI):
"""
Use colinfo dictionaries to set newly-imported (CSV) DataFrame column types and Boolean Flag columns
"""
for col in df.columns:
#If col is a flag column (1/blank), convert to Boolean for memory and feather file size efficiency
if (col in tblCI... | 5,326,882 |
def cli_purge_rainbowagent_logs(host, port, password, rootpassword):
"""Summary
Args:
host (TYPE): Description
port (TYPE): Description
password (TYPE): Description
"""
check_host_option(host)
oxe_purge_rainbowagent_logs(host, port, password, rootpassword) | 5,326,883 |
def run_and_wait(request, _):
"""Implementation of RunAndWait."""
process_runner = new_process.ProcessRunner(request.executable_path,
request.default_args)
args = {}
protobuf_utils.get_protobuf_field(args, request.popen_args, 'bufsize')
protobuf_utils.get_protobuf_... | 5,326,884 |
def import_dicom_series(path, files_start_with=None, files_end_with=None,
exclude_files_end_with=('.dat', '.txt', '.py', '.pyc', '.nii', '.gz')):
"""Rudimentary file to load dicom serie from a directory. """
N = 0
paths = []
slices = []
files = os.listdir(path)
for file_... | 5,326,885 |
def quick_bench(iterations, size):
"""Convenience entry point to time different function samples"""
functions = {}
for name, func in globals().items():
if name.startswith("_bench"):
name = name[1:]
functions[name] = partial(func, size)
bench = BenchmarkRunner(functions, ... | 5,326,886 |
def fight(player, enemy):
"""
This starts a round of combat between the user and their selected enemy.
It returns a list of information relating to combat, to be used in the
view function to display it, if required.
"""
# Random player damage based on 80-100% of player damage stat.
dmg_ran... | 5,326,887 |
async def completed(trace_name='',
name='',
sleep_interval=0.05,
streams: List[torch.cuda.Stream] = None):
"""Async context manager that waits for work to complete on given CUDA
streams."""
if not torch.cuda.is_available():
yield
re... | 5,326,888 |
async def POST_Dataset(request):
""" Handler for POST /datasets"""
log.request(request)
app = request.app
params = request.rel_url.query
if not request.has_body:
msg = "POST_Dataset with no body"
log.error(msg)
raise HTTPBadRequest(reason=msg)
body = await request.json(... | 5,326,889 |
def draw_platform_family_by_age(id, title):
"""draws how many users listened or not a track in a certain
platform_family by age"""
sub_sample = sample[['platform_family','user_age','is_listened']]
sub_sample = sub_sample[(sub_sample.platform_family == id)]
ages = sub_sample['user_age'].unique()
... | 5,326,890 |
def sort_list_by_list(L1,L2):
"""Sort a list by another list"""
return [x for (y,x) in sorted(zip(L2,L1), key=lambda pair: pair[0])] | 5,326,891 |
def _to_protobuf_value(value: type_utils.PARAMETER_TYPES) -> struct_pb2.Value:
"""Creates a google.protobuf.struct_pb2.Value message out of a provide
value.
Args:
value: The value to be converted to Value message.
Returns:
A google.protobuf.struct_pb2.Value message.
Raises:
... | 5,326,892 |
def setup(bot: Bot) -> None:
"""
This function is called automatically when this cog is loaded by the bot.
It's only purpose is to load the cog above, and to pass the Bot instance into it.
"""
bot.add_cog(LemonFacts(bot)) | 5,326,893 |
def remove_image_permissions(apps, schema_editor):
"""Reverse the above additions of permissions."""
ContentType = apps.get_model("contenttypes.ContentType")
Permission = apps.get_model("auth.Permission")
image_content_type = ContentType.objects.get(
model="image",
app_label="wagtailimag... | 5,326,894 |
def umap(adata, **kwargs) -> Union[Axes, List[Axes], None]:
"""\
Scatter plot in UMAP basis.
Parameters
----------
{adata_color_etc}
{edges_arrows}
{scatter_bulk}
{show_save_ax}
Returns
-------
If `show==False` a :class:`~matplotlib.axes.Axes` or a list of it.
"""
r... | 5,326,895 |
def _prepare_grid(times, time_step):
"""Prepares grid of times for path generation.
Args:
times: Rank 1 `Tensor` of increasing positive real values. The times at
which the path points are to be evaluated.
time_step: Scalar real `Tensor`. Maximal distance between time grid points
Returns:
Tupl... | 5,326,896 |
def parse_res_list(res_list, file, *operator):
"""传入一个 Resource 实例的列表,并传入一个临时文件名,将调出默认程序修改名字,并调用对象的 operation 方法"""
if file:
with open(file, 'w', encoding='utf_8') as f:
for res in res_list:
f.write(str(res) + '\n')
os.startfile(file)
input('修改完文件名后按回车继续。')
... | 5,326,897 |
def delete_row_by_id(table, id_):
"""
Deletes the row matching the given ID from the given table, raises
MissingRecordError if it can not be found
:param table: the table to be searched
:param id_: the id of the record to delete
"""
log.info(" Deleting row from %s with ID: %s", table.__tabl... | 5,326,898 |
def run_setup(command):
"""Run setup.py file
:return:
"""
virtual_env = get_virtual_env()
if virtual_env:
with virtualenv(virtual_env):
with lcd(BASE_DIR):
local('python setup.py {}'.format(str(command)))
else:
print 'Virtual environment needs to b... | 5,326,899 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.