content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def _draw_subpath(subpath_list, width, height, brush, pen):
"""
Rasterize Bezier curves.
TODO: Replace aggdraw implementation with skimage.draw.
"""
from PIL import Image
import aggdraw
mask = Image.new('L', (width, height), 0)
draw = aggdraw.Draw(mask)
pen = aggdraw.Pen(**pen) if p... | 5,312,300 |
def parse_devices(metadata, parser):
"""
Iterate device ``metadata`` to use ``parser`` to create and return a
list of network device objects.
:param metadata:
A collection of key/value pairs (Generally returned from
`~trigger.rancid.parse_rancid_file`)
:param parser:
A call... | 5,312,301 |
def preprocess_chunk(raw_chunk, subtract_mean=True, convert_to_milivolt=False):
"""
Preprocesses a chunk of data.
Parameters
----------
raw_chunk : array_like
Chunk of raw_data to preprocess
subtract_mean : bool, optional
Subtract mean over all other channels, by default True
... | 5,312,302 |
def generate_presigned_url(s3_client, client_method, method_parameters, expires_in):
"""
Generating a presigned Amazon S3 URL that can be used to perform an action.
"""
try:
url = s3_client.generate_presigned_url(
ClientMethod=client_method,
Params=method_parameters,
... | 5,312,303 |
def update_topic(zkurl, topic, partitions, replica=None, kafka_env=None):
"""Alter a topic in Kafka instances from zkurl list"""
return _exec_topic_cmd(TOPIC_CLASS, 'alter', zkurl, topic,
partitions, replica=replica, kafka_env=kafka_env) | 5,312,304 |
def main():
"""
Main entry point function for program.
"""
env = gym_super_mario_bros.make('SuperMarioBros-v0')
env = JoypadSpace(env, RIGHT_ONLY)
action_size = len(RIGHT_ONLY)
cdqn = CDQN(action_size, memory_size=10000, image_shape=(45, 64, 1))
batch_size = 1024
games = 10000
... | 5,312,305 |
def get_list_peaks(matrix, image_size):
"""Return a list of class Peak form H5
gets a matrix with data for all peas given
file h5
Returns
-------
peaks : list
List of class Peak object.
"""
try:
# array[:,] next rows
peaks = [Peak(posx=(row[0] + image_size[1]/2.0... | 5,312,306 |
async def add_report_history(
id: int,
search_id: str,
search_start: datetime,
search_end: datetime,
search_type: str,
session: str):
"""Add report history
Adds reports to the history.
Args:
id: the user_id
search_id: the id of the searc... | 5,312,307 |
def get_latest_featuregroup_version(featuregroup, featurestore=None):
"""
Utility method to get the latest version of a particular featuregroup
Example usage:
>>> featurestore.get_latest_featuregroup_version("teams_features_spanish")
Args:
:featuregroup: the featuregroup to get the latest... | 5,312,308 |
def nyt_articles(dates):
"""
This function retreive the articles data give a list of tuples (year, months).
Each article will have the following structure: headline, abstract, document_type, type_of_material, keywords, news desk, section name, subsection name, word count, date.
Args:
dates (lis... | 5,312,309 |
def test_query_deleted_4():
"""Test query with --deleted-only"""
import json
import osxphotos
import os
import os.path
from osxphotos.__main__ import query
runner = CliRunner()
cwd = os.getcwd()
result = runner.invoke(
query, ["--json", "--db", os.path.join(cwd, PHOTOS_DB_14... | 5,312,310 |
def guardian(badger: BadgerSystem, startBlock, endBlock, pastRewards, test=False):
"""
Guardian Role
- Check if there is a new proposed root
- If there is, run the rewards script at the same block height to verify the results
- If there is a discrepency, notify admin
(In case of a one-off failur... | 5,312,311 |
def abs(x: float32) -> float:
"""
Return the absolute value of x.
"""
... | 5,312,312 |
def cutMapById(data, subcatchmap, id, x, y, FillVal):
"""
:param data: 2d numpy array to cut
:param subcatchmap: 2d numpy array with subcatch
:param id: id (value in the array) to cut by
:param x: array with x values
:param y: array with y values
:return: x,y, data
"""
if len(data... | 5,312,313 |
def train_step(input_image, target):
"""Run a single training step and return losses."""
with tf.GradientTape() as gen_tape, tf.GradientTape() as disc_tape:
gen_output = GENERATOR(input_image, training=True)
disc_real_output = DISCRIMINATOR([input_image, target], training=True)
disc_gen... | 5,312,314 |
def _process_models(model_class, batch_size, delete=False, model_map_fn=None):
"""Fetch all rows in batches."""
assert (delete or model_map_fn) or (not delete and model_map_fn)
reportable_chunk = batch_size * 10
total_count = 0
cursor = None
while True:
batch_count, cursor = _process_mod... | 5,312,315 |
def flow(flow):
"""Decorator:
decorator = flow(flow)
The decorator then transforms a method:
method = decorator(method)
so that the "flow" kwarg is set the argument to the decorator.
A nonsense value of "flow" will raise and Exception in
Componenet.__select_flow
"""
from functools... | 5,312,316 |
def do_tags_for_model(parser, token):
"""
Retrieves a list of ``Tag`` objects associated with a given model
and stores them in a context variable.
The model is specified in ``[appname].[modelname]`` format.
If specified - by providing extra ``with counts`` arguments - adds
a ``count`` ... | 5,312,317 |
def use(alpha, beta):
"""Sum 2 things."""
return functions.func(alpha, beta) | 5,312,318 |
def controller_enabled_provisioned(hostname):
""" check if host is enabled """
try:
with openstack.OpenStack() as client:
hosts = get_hosts(client.admin_token,
client.conf['region_name'])
for host in hosts:
if (hostname == host.name a... | 5,312,319 |
def get_humans_with_age(city, age_histogram, conf, rng):
"""
Creats human objects corresponding to the numbers in `age_histogram`.
Args:
city (covid19sim.location.City): simulator's city object
age_histogram (dict): a dictionary with keys as age bins (a tuple) and values as number of humans... | 5,312,320 |
def place_ontop_obj_pos(
env: "BehaviorEnv",
obj: Union["URDFObject", "RoomFloor"],
place_rel_pos: Array,
rng: Optional[Generator] = None,
) -> Optional[Tuple[List[List[float]], List[List[float]]]]:
"""Parameterized controller for placeOnTop.
Runs motion planning to find a feasible trajectory t... | 5,312,321 |
def set2Floats(plug, values):
"""
Updates the 2 float values for the supplied plug.
:type plug: om.MPlug
:type values: tuple[float, float]
:rtype: None
"""
plug.child(0).setFloat(float(values[0]))
plug.child(1).setFloat(float(values[1])) | 5,312,322 |
def make_htc_proxy_X(X: np.ndarray):
"""
Makes HTC proxy values from data series.
The value of the HTC proxy is sum(gas) / mean(in_temp - out_temp).
"""
return np.array([[np.sum(x[:,2]) / np.sum(x[:,0] - x[:,1])] for x in X]) | 5,312,323 |
def recovery_invalid_token(
) -> str:
"""Return a valid auth token"""
return 'wrong' | 5,312,324 |
def squeeze(input_vector):
"""Ensure vector only has one axis of dimensionality."""
if input_vector.ndim > 1:
return np.squeeze(input_vector)
else:
return input_vector | 5,312,325 |
def summarize_darshan_perf(darshan_logs):
"""
Given a list of Darshan log file paths, calculate the performance observed
from each file and identify OSTs over which each file was striped. Return
this summary of file performances and stripes.
"""
results = {
'file_paths': [],
'pe... | 5,312,326 |
def test_hybrid_broadcasting(grad):
"""tests new-dim and keep-dim broadcasting
(3, 1, 2) -> (5, 3, 4, 2)"""
var_shape = (3, 1, 2)
reduced = reduce_broadcast(grad=grad, var_shape=var_shape)
answer = grad.sum(axis=0).sum(axis=-2, keepdims=True)
assert_allclose(actual=reduced, desired=answer) | 5,312,327 |
def login(request, template_name="lfs/customer/login.html"):
"""Custom view to login or register/login a user.
The reason to use a custom login method are:
* validate checkout type
* integration of register and login form
It uses Django's standard AuthenticationForm, though.
"""
# sho... | 5,312,328 |
def is_string(var):
"""Check if `var` is a string (or unicode)."""
target = (str, unicode) if python2 else str
return isinstance(var, target) | 5,312,329 |
def get_parameter_name(argument):
"""Return the name of the parameter without the leading prefix."""
if argument[0] not in {'$', '%'}:
raise AssertionError(u'Unexpectedly received an unprefixed parameter name, unable to '
u'determine whether it is a runtime or tagged paramet... | 5,312,330 |
def find_distance(a1, num_atoms, canon_adj_list, max_distance=7):
"""
Calculate graph distance between atom a1 with the remaining atoms using BFS
"""
distance = np.zeros((num_atoms, max_distance))
radial = 0
# atoms `radial` bonds away from `a1`
adj_list = set(canon_adj_list[a1])
# atoms less than `radi... | 5,312,331 |
def print_run_total(starttime):
"""Print total information for the entire run.
"""
print()
stoptime = time.time()
runtime = int(stoptime - starttime + 0.5)
minute = int(runtime / 60)
sec = int(runtime % 60)
if min == 0:
print("{0} seconds total run time".format(sec))
else:
... | 5,312,332 |
def _get_pixel_coords(plot_params):
"""A helper method to define coordinates for a plotting window.
This routine builds a coordinate surface map for the plotting window defined
for by the user. If no window was defined, then this routine uses the outer
bounding box around the geometry as the plotting w... | 5,312,333 |
def parse_nasa_catalog(mission, product, version, from_date=None, to_date=None, min_max=False):
"""
Function to parse the NASA Hyrax dap server via the catalog xml.
Parameters
----------
missions : str, list of str, or None
The missions to parse. None will parse all available.
products ... | 5,312,334 |
def open_pdb(f_loc):
"""
This function reads in a .pdb file and returns the atom names and coordinates.
Parameters
----------
f_loc : str
File path to .pdb file
Returns
-------
symbols, coordinates : np.ndarray
Numpy arrays of the atomic symbols (str) and coordinates (f... | 5,312,335 |
def test_co2(technique):
"""3N-5 with center of inversion"""
clear_caches()
ir = ir_from_smiles('C(=O)=O', technique)
modes = filter_modes(ir.modes)
raman_intensities = get_raman_modes(modes)
assert len(raman_intensities) == 1
ir_intensities = get_ir_modes(modes)
assert len(ir_intensi... | 5,312,336 |
def update_name(name, mapping):
"""Makes an improvement in the address (name) according to the dictionary (mapping)"""
m = street_type_re.search(name)
not_good_type = m.group()
try:
name = name.replace(not_good_type, mapping[not_good_type])
return name
except:
return False | 5,312,337 |
def print_list_text(img_src, str_list, origin = (0, 0), color = (0, 255, 255), thickness = 2, fontScale = 0.45, y_space = 20):
""" prints text list in cool way
Args:
img_src: `cv2.math` input image to draw text
str_list: `list` list with text for each row
origin: `tuple` (X, Y) coordi... | 5,312,338 |
def get_extension_modules(config):
"""Handle extension modules"""
EXTENSION_FIELDS = ("sources",
"include_dirs",
"define_macros",
"undef_macros",
"library_dirs",
"libraries",
... | 5,312,339 |
def configure_ibgp_vrrp_vxlan(module):
"""
Method to configure iBGP, VRRP and Vxlan for DCI.
:param module: The Ansible module to fetch input parameters.
:return: String describing details of all configurations.
"""
global CHANGED_FLAG
output = ''
cluster_dict_info = find_clustered_switc... | 5,312,340 |
def part_has_modifier(data, part, modifier):
"""Returns true if the modifier is in the given subject/object part
:param dict data: A PyBEL edge data dictionary
:param str part: either :data:`pybel.constants.SUBJECT` or :data:`pybel.constants.OBJECT`
:param modifier: The modifier to look for
:rtype:... | 5,312,341 |
def unbox_unchecked_bool(stage: ImportStage, value: ir.Value) -> ir.Value:
"""Unboxes an object value to a bool, not checking for success."""
return d.UnboxOp(d.ExceptionResultType.get(), d.BoolType.get(),
value).primitive | 5,312,342 |
def step4_pfg(data_input, col, g_list, nfrag):
"""
Parallel FP-Growth
"""
g_list = g_list[0]
result = [[] for _ in range(nfrag)]
df = read_stage_file(data_input, col)
for transaction in df[col].to_numpy():
# group_list has already been pruned, but item_set hasn't
item_set =... | 5,312,343 |
def camera_to_points_world(camera,robot,points_format='numpy',color_format='channels'):
"""Same as :meth:`camera_to_points`, but converts to the world coordinate
system given the robot to which the camera is attached.
Points that have no reading are stripped out.
"""
assert isinstance(camera,SimR... | 5,312,344 |
def array_size(arr):
""" Return size of an numpy.ndarray in bytes """
return np.prod(arr.shape) * arr.dtype.itemsize | 5,312,345 |
def lockGUI():
"""lockGUI() : lock lsdcGui"""
daq_lib.lockGUI() | 5,312,346 |
def is_deprecated(image_array, blank_rate):
"""whether to deprecate the patches with blank ratio greater than max_blank_ratio"""
blank_num = np.sum(image_array == (255, 255, 255)) / 3
height, width = image_array.shape[:2]
if blank_num / (height * width) >= blank_rate:
return True
else:
... | 5,312,347 |
def get_one_hot_labels(labels, n_classes):
"""
Function for creating one-hot vectors for the labels, returns a tensor of shape (?, num_classes).
Parameters:
labels: tensor of labels from the dataloader, size (?)
n_classes: the total number of classes in the dataset, an integer scalar
"""... | 5,312,348 |
def cmpHash(file1, file2):
"""Compare the hash of two files."""
hash1 = hashlib.md5()
with open(file1, 'rb') as f:
hash1.update(f.read())
hash1 = hash1.hexdigest()
hash2 = hashlib.md5()
with open(file2, 'rb') as f:
hash2.update(f.read())
hash2 = hash2.hexdigest()
... | 5,312,349 |
def gsfLoadDepthScaleFactorAutoOffset(
p_mb_ping,
subrecord_id: c_int,
reset: c_int,
min_depth: c_double,
max_depth: c_double,
last_corrector,
p_c_flag,
precision: c_double,
) -> int:
"""
:param p_mb_ping: POINTER(gsfpy3_09.gsfSwathBathyPing.c_gsfSwathBathyPing)
:param subrec... | 5,312,350 |
def preprocess_onnx(img: Image, width: int, height: int, data_type, scale: float, mean: list,
stddev: list):
"""Preprocessing function for ONNX imagenet models based on:
https://github.com/onnx/models/blob/master/vision/classification/imagenet_inference.ipynb
Args:
img (PIL.Imag... | 5,312,351 |
def boxerFrameStack(framestackpath, parttree, outstack, boxsize,framelist):
"""
boxes the particles and returns them as a list of numpy arrays
"""
start_frame = framelist[0]
nframe = len(framelist)
apDisplay.printMsg("boxing %d particles from sum of total %d frames starting from frame %d using mmap" % (len(parttr... | 5,312,352 |
def validate_optional_prompt(val, error_msg=None):
"""Dummy validation function for optional prompts. Just returns val"""
# TODO Should there just be an option in prompt()? If input is non-blank you'll probably still wanna validate it
return val | 5,312,353 |
def one_browser_logs(thisbrowser):
"""
get the logs from localStorage of a browser managed by selenium
"""
try:
thisbrowser.set_window_position(-3000, 0)
thisbrowser.get('https://tenhou.net/2/')
for i in range(0, 40):
log = thisbrowser.execute_script("return localSto... | 5,312,354 |
def acorr_grouped_df(
df,
col = None,
by = 'date',
nfft = 'pad',
func = lambda x: x,
subtract_mean = 'total',
norm = 'total',
return_df = True,
debias = True,
**kwargs
):
... | 5,312,355 |
def normalize_pyte(raw_result: str) -> str:
"""ta metoda normalizacji używa emulatora terminala
do wyrenderowania finalnej planszy
wymaga zainstalowania paczki `pyte` z pip
pyte nie wspiera następujących ansi escape codes:
Esc[s -- save cursor position
Esc[u -- restore cursor position
i pot... | 5,312,356 |
def delete(isamAppliance, id, check_mode=False, force=False):
"""
Deleting a Password Strength
"""
if force is True or _check(isamAppliance, id) is True:
if check_mode is True:
return isamAppliance.create_return_object(changed=True)
else:
return isamAppliance.invo... | 5,312,357 |
def netdevices_delete(context, netdevice_id):
"""Delete existing network device."""
session = get_session()
with session.begin():
device = with_polymorphic(models.Device, '*')
query = model_query(context, device, session=session,
project_only=True)
query =... | 5,312,358 |
def register(style, func=None):
"""注册一个拼音风格实现
::
@register('echo')
def echo(pinyin, **kwargs):
return pinyin
# or
register('echo', echo)
"""
if func is not None:
_registry[style] = func
return
def decorator(func):
_registry[styl... | 5,312,359 |
def save_project_files(project_path):
"""."""
project_path = project_path.replace('\\', '/')
wins = sublime.windows()
for win in wins:
views = win.views()
for view in views:
file_path = view.file_name()
if file_path:
file_path = file_path.replace('... | 5,312,360 |
def pickoff_image(ap_obs, v2_obj, v3_obj, flux_obj, oversample=1):
"""
Create an unconvolved image of filled pixel values that have
been shifted via bilinear interpolation. The image will then
be convolved with a PSF to create the a focal plane image that
is the size of the NIRCam pick-off mirror. ... | 5,312,361 |
def draw_titleblock(frame: str, sheet: 'Sheet', orientation: str, layer: 'Layer'):
"""
Draw each box in the title block on the specified layer
:param layer: Layer to draw the box on
:param frame: Title block is fitted to this frame
:param sheet: Frame is drawn on this Sheet (sizing info)
:pa... | 5,312,362 |
def kms_encrypt(value, key, aws_config=None):
"""Encrypt and value with KMS key.
Args:
value (str): value to encrypt
key (str): key id or alias
aws_config (optional[dict]): aws credentials
dict of arguments passed into boto3 session
example:
aws_c... | 5,312,363 |
def pd_expand_json_column(df, json_column):
"""
https://stackoverflow.com/a/25512372
"""
df = pd.concat(
[df, json_column.apply(lambda content: pd.Series(list(content.values()), index=list(content.keys())))],
axis=1
)
return df.drop(columns=['data']) | 5,312,364 |
def correct_spellings(text):
"""
converts incorrectly spelled words into correct spelling
"""
corrected_text = []
misspelled_words = spell.unknown(text.split())
for word in text.split():
if word in misspelled_words:
corrected_text.append(spell.correction(word))
else... | 5,312,365 |
def xception_module(inputs,
depth_list,
skip_connection_type,
stride,
unit_rate_list=None,
rate=1,
activation_fn_in_separable_conv=False,
regularize_depthwise=False,
... | 5,312,366 |
def addCloudColImg(oldBandsClass=CsvFileClass.Asserted,oldImgsClass=CsvFileClass.Asserted,colNumber=5):
"""Add cloud column to imgs csv"""
oldBandsCsv = FileNames.BandsCsv%oldBandsClass
imgsCsvName = FileNames.ImgsCsv%CsvFileClass.Cloud
oldImgsCsv = FileNames.ImgsCsv%oldImgsClass
with open(Path... | 5,312,367 |
def greatest_common_divisor(a: int, b: int) -> int:
"""
Euclid's Lemma : d divides a and b, if and only if d divides a-b and b
Euclid's Algorithm
>>> greatest_common_divisor(7,5)
1
Note : In number theory, two integers a and b are said to be relatively prime,
mutually prime, or co-pri... | 5,312,368 |
def ReadSchema(inf, is_local, xsd_path, el: ET.Element, xsd_dic: Dict[str, SchemaElement]):
"""スキーマファイルの内容を読む。
"""
uri, tag_name = split_uri_name(el.tag)
if tag_name == 'schema':
target_ns = el.get('targetNamespace')
# スキーマのURIを正規化する。
target_ns = norm_uri(target_ns)
if ... | 5,312,369 |
def bfmt(num, size=8):
""" Returns the printable string version of a binary number <num> that's length <size> """
if num > 2**size:
return format((num >> size) & (2**size - 1), 'b').zfill(size)
try:
return format(num, 'b').zfill(size)
except ValueError:
return num | 5,312,370 |
def test_standardize_parking_bay(spark):
"""Test data transform"""
# Arrange
schema = standardize.get_schema("in_parkingbay_schema")
parkingbay_sdf = spark.read.json("./data/MelbParkingBayData.json", multiLine=True, schema=schema)
load_id = 1
loaded_on = datetime.datetime.now()
# Act
t_p... | 5,312,371 |
def add_fake_chats(count: int) -> None:
"""
Adds fake chats in DB.
"""
i = 0
error_count = 0
while (i != count):
if (error_count >= 5):
raise PossibleInfiniteLoopError(
"Too many errors in a row"
)
chat = Chat.create_fake(None)
us... | 5,312,372 |
def text_to_NAF(text,
nlp,
dct,
layers,
title=None,
uri=None,
language='en',
layer_to_attributes_to_ignore=dict(),
naf_version='v3',
cdata=True,
replace_hidden_... | 5,312,373 |
def getContextRect(
context: Context,
obj: Optional[TextContainerObject] = None
) -> Optional[locationHelper.RectLTRB]:
"""Gets a rectangle for the specified context."""
if context == Context.FOCUS:
return getObjectRect(obj or api.getFocusObject())
elif context == Context.NAVIGATOR:
return getObjectRect(obj ... | 5,312,374 |
def spans_to_binary(spans, length=None):
"""
Converts spans to a binary array indicating whether each character is in the span.
Args: spans (list of lists of two ints): Spans.
Returns: np array [length]: Binarized spans.
"""
length = np.max(spans) if length is None else length
binary = np.ze... | 5,312,375 |
def ensure_index_file(app: Sphinx, exception: Optional[Exception]) -> None:
"""Ensure that an index.html exists for HTML builds.
This is required when navigating to the site, without specifying a page,
which will then route to index.html by default.
"""
index_path = Path(app.outdir).joinpath("index... | 5,312,376 |
def check_dataset_access_permission(view_func):
"""
Decorator ensuring that the user has access to dataset.
Arg: 'dataset'.
Return: the dataset or raise an exception
Notice: its gets an id in input and returns the full object in output (not an id).
"""
def decorate(request, *args, **kwargs):
dataset... | 5,312,377 |
def check_barcode_is_off(alignment, tags, log=None):
"""
See if the barcode was recognised with soft clipping.
if so, it returns True and can be counted in the optional log
:param alignment: the read
:param tags: alignment tags as dict
:return:
"""
if 'RG' in tags:
if ... | 5,312,378 |
def flatten_all_lists_in_dict(obj):
"""
>>> flatten_all_lists_in_dict({1: [[2], [3, {5: [5, 6]}]]})
{1: [2, 3, {5: [5, 6]}]}
"""
if isinstance(obj, dict):
for key, value in obj.items():
obj[key] = flatten_all_lists_in_dict(value)
return obj
elif isinstance(obj, list):... | 5,312,379 |
def already_visited(string):
"""
Helper method used to identify if a subroutine call or definition has
already been visited by the script in another instance
:param string: The call or definition of a subroutine/function
:return: a boolean indicating if it has been visited already or not
"""
... | 5,312,380 |
def _validate_partitioning(device):
"""Validate the final partition table.
Check if after writing the image to disk we have a valid partition
table by trying to read it. This will fail if the disk is junk.
"""
try:
# Ensure we re-read the partition table before we try to list
# part... | 5,312,381 |
def series_to_dict(ts, cat=None, dynamic_feat=None):
"""Given a pandas.Series object, returns a dictionary encoding the time series.
ts -- a pands.Series object with the target time series
cat -- an integer indicating the time series category
Return value: a dictionary
"""
obj = {"start": str(... | 5,312,382 |
def hello_test():
"""
This defines the expected usage, which can then be used in various test cases.
Pytest will not execute this code directly, since the function does not contain the suffex "test"
"""
hello_world() | 5,312,383 |
def expected_loss_t(u_m, lgd, ead, new):
""" Total expected loss.
Shape (K,)"""
el = np.sum(expected_loss_g_i_t(u_m, lgd, ead, new), axis=0)
el = np.sum(el, axis=0)
return el | 5,312,384 |
def tool_pred_class_label(log_likelyhood, cutoff=0):
"""
Infer class label based on log-likelyhood
Args:
log_likelyhood:
Returns:
"""
if log_likelyhood > cutoff + EPSLONG:
return 1
return 0 | 5,312,385 |
def select_polymorph(polymorphs, args):
"""Determine the polymorphic signature that will match a given argument list.
This is the mechanism used to reconcile Java's strict-typing polymorphism with
Python's unique-name, weak typing polymorphism. When invoking a method on the
Python side, the number and t... | 5,312,386 |
def add_summary(name, value, hide=False):
"""
Add a known floating-point value summary to the current reporter.
If hide is set to true, this summary is not printed during
advance().
"""
context().reporter.add_summary(name, value, hide) | 5,312,387 |
def logout():
"""Log user out"""
# Forget any user_id
session.clear()
# Redirect user to login form
return redirect("/main") | 5,312,388 |
def get_stem_name(file_name: pathlib.Path | str | None) -> str:
"""Get the stem name from a file name.
Args:
file_name (pathlib.Path | str | None): File name or file path.
Returns:
str: Stem name.
"""
if file_name is None:
return ""
if isinstance(file_name, str):
... | 5,312,389 |
def getSingleIndexedParamValue(request, param_name, values=()):
"""Returns a value indexed by a query parameter in the HTTP request.
Args:
request: the Django HTTP request object
param_name: name of the query parameter in the HTTP request
values: list (or tuple) of ordered values; one of which is
... | 5,312,390 |
def actions(board):
"""
Returns set of all possible actions (i, j) available on the board.
"""
#if the state is a terminal state, then there is no possible action
if terminal(board):
return "game over"
else:
#traverse through the board and add the location of empty cells to the p... | 5,312,391 |
def main():
"""
First show the original picture. Then show the shrinked picture.
"""
original = SimpleImage("images/poppy.png")
original.show()
after_shrink = shrink("images/poppy.png")
after_shrink.show() | 5,312,392 |
def requestLanguage(request, try_user=True):
"""
Return the user interface language for this request.
The user interface language is taken from the user preferences for
registered users, or request environment, or the default language of
the wiki, or English.
This should be called once per req... | 5,312,393 |
def register_json_formatter(cls: Type, to_dict_method_name: str = 'to_dict'):
"""
TODO
:param cls:
:param to_dict_method_name:
:return:
"""
if not hasattr(cls, to_dict_method_name) or not callable(getattr(cls, to_dict_method_name)):
raise ValueError(f'{cls} must define a {to_dict_met... | 5,312,394 |
def validate(args, kwargs) -> None:
"""Run validator, trying to fix missed imports on the way.
"""
base = Validator(validator=contract, exception=deal.ContractError)
if func is not Ellipsis:
base.function = func
old_name = None
for _ in range(10): # maximum 10 tries, just in case
... | 5,312,395 |
def get_best_muscle_hits(subject_seq, query_aln,threshold,use_shorter=True):
"""Returns subset of query_aln with alignment scores above threshold.
- subject_seq is sequence aligned against query_aln seqs.
- query_aln is dict or Alignment object with candidate seqs to be
aligned with sub... | 5,312,396 |
def _hrf_d_basis(d, t_r, n_times_atom):
""" Private helper to define the double gamma HRF 2/3 basis function.
Parameters
----------
d : int, the number of atoms in the HRF basis, possible values are 2 or 3
t_r : float, Time of Repetition, fMRI acquisition parameter, the temporal
resolution
... | 5,312,397 |
def deal_all_event(parameter):
"""
读日志,处理mysqlbinlog的日志
:param parameter: 用户的命令行的参数和一些全局的变量
:return:
:except:如果有问题,会抛出异常
"""
events=[]
if parameter.skip_insert is False:
events.append(WriteRowsEvent)
if parameter.skip_update is False:
events.append(UpdateRowsEvent)
... | 5,312,398 |
def parse_argparser_transport_selector(args):
"""Return a transport loop as specified from the argparse args."""
if args.transport == 'ascii':
from lhrhost.messaging.transport.ascii import transport_loop
elif args.transport == 'firmata':
from lhrhost.messaging.transport.firmata import transp... | 5,312,399 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.