content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def get_viewer_frame(frame, viewer_size):
"""Get viewer frame.
Parameters
----------
frame : numpy.ndarray
viewer_size : tuple
Returns
-------
viewer_frame : numpy.ndarray
"""
return cv2.resize(frame, (viewer_size[1], viewer_size[0]),
interpolation=cv2.IN... | 53,700 |
def preprocess_waveform(y, sample_rate,
target_sample_rate,
preemphasis_coeff=0.95,
stft_args={}):
"""Resample, preemphasize, and compute the magnitude spectrogram.
Inputs:
y: 1D numpy array containing signal to featurize (np.ndarra... | 53,701 |
def patients_from_tissue(df: pd.DataFrame, tissue: str) -> List[str]:
"""Given a tissue, return all patients within that tissue"""
return df[df.tissue == tissue].id.tolist() | 53,702 |
def asst70_gene_descriptors(moa_abl1):
"""Create assertion70 gene_descriptors test fixture."""
return [moa_abl1] | 53,703 |
def config(ctx: ContextObject, get: str, add: str, is_list: bool, unset: str, input_type: str, key: str) -> None:
"""Set and view config."""
res = process(get, add, is_list, unset, key, input_type)
click.echo(res) | 53,704 |
def get_all_pokemon_info() -> List[Dict[str, Any]]:
"""
Retrieves all pokemon information from PokeAPI.
"""
logger.info("Retrieving all pokemon data.")
api_query = urljoin(POKEAPI_URL_PREFIX, POKEMON_API_PREFIX)
def add_pokemon_url(query):
results = []
logging.debug("Pokemon url... | 53,705 |
def basic_auth(function):
"""Require HTTP Basic Auth."""
@functools.wraps(function)
def wrapper(*args, **kwargs):
auth = flask.request.authorization
if auth is not None:
if auth.username == os.environ.get('AUTELION_USERNAME'):
if auth.password == os.environ.get('A... | 53,706 |
def medoid(collection, bands=None, discard_zeros=False):
""" Medoid Composite
:param collection: the collection to composite
:type collection: ee.ImageCollection
:param bands: the bands to use for computation. The composite will include
all bands
:type bands: list
:param discard_zeros: ... | 53,707 |
def download_zip(url: str) -> BytesIO:
"""Download data from url."""
logger.warning(
"start patched secure https chromium download.\n"
"Download may take a few minutes."
)
with urllib3.PoolManager(
cert_reqs="CERT_REQUIRED", ca_certs=certifi.where()
) as https:
# Get... | 53,708 |
def match_bool(value: bool) -> models.Match:
"""_summary_
Args:
value (bool): _description_
Returns:
models.Match: _description_
"""
# Check
if value:
# Return
return models.Match(
accuracy=models.Accuracy.RIGHT,
direction=models.Directio... | 53,709 |
def p_ibd_1(f):
"""Compute Joint-PMF for sibling pair genotypes given IBD1.
Args:
f : :class:`float`
allele frequency
Returns:
P : :class:`~numpy:numpy.array`
matrix of probabilities
"""
fmatrix = np.array([[0.0,1.0,0.0],[1.0,1.0,2.0],[0.0,2.0,3.0]])
mi... | 53,710 |
def argument(*args: Any, **kwargs: Any) -> Callable[[Any], Any]:
"""Create command-line argument.
SeeAlso:
:func:`click.argument`
"""
return click.argument(*args, **kwargs) | 53,711 |
def nvctl(*args, **kwargs):
"""
Run the nvctl command with the specified args returning the output as
a parsed json object by default. The kwargs support 'json=false' and
'no_login=true'.
Exception is raised for errors.
"""
cmd_list = list(args)
json_out = True
if 'json' in kwargs an... | 53,712 |
def load_libgmt(env=None):
"""
Find and load ``libgmt`` as a :py:class:`ctypes.CDLL`.
By default, will look for the shared library in the directory specified by
the environment variable ``GMT_LIBRARY_PATH``. If it's not set, will let
ctypes try to find the library.
Parameters
----------
... | 53,713 |
def validate(board: list) -> bool:
"""
Main functrion of the module.
Recieves board and checks if it is a valid one or not
with the help of other functions.
>>> board = board = [\
"**** ****",\
"***1 ****",\
"** 3****",\
"* 4 1****",\
" 9 5 ",\
"... | 53,714 |
def build_table_separator(outer_left='╠', inner='╬', outer_right='╣'):
"""
Builds formatted unicode header for the stopwatch table.
:return: formatted unicode header
"""
return f"{outer_left}{'═' * 14}{inner}{'═' * 18}{inner}{'═' * 20}{outer_right}" | 53,715 |
def _hash_feature(feature):
"""Calculate SHA256 hash of feature geometry as WKT"""
geom = shape(feature["geometry"])
return hashlib.sha256(geom.wkt.encode("utf-8")).hexdigest() | 53,716 |
def review_pull_request_event(event):
"""Determine whether this is a valid pull request review event."""
try:
source = event["source"]
detail_type = event["detail-type"]
event_type = event["detail"]["event"]
return (
source == "aws.codecommit"
and detail_... | 53,717 |
def FMAXP(cpu_context: ProcessorContext, instruction: Instruction):
"""Floating-point maximum pairwise (vector and scalar form)"""
logger.debug("%s instruction not currently implemented.", instruction.mnem) | 53,718 |
def copy(args):
"""Perform the copy on required instances.
args list of arg values
"""
# parse the command args
parser = argparse.ArgumentParser(prog='swarm copy',
description='This plugin is used to copy a file to many instances.')
parser.add_argument('... | 53,719 |
def safe_eval(expr: ast.expr, culprit: ast.AST) -> Optional[Any]:
"""Return the given expression as evaluated at compile-time.
NOTE
Use this instead of Python's `eval` to avoid potential arbitrary code
execution.
"""
_error = "unable to evaluate {} at compile-time"
if isinstance(e... | 53,720 |
def bert_cos_score_idf(model, refs, hyps, tokenizer, idf_dict,
verbose=False, batch_size=64, device='cuda:0'):
"""
Compute BERTScore.
Args:
- :param: `model` : a BERT model in `pytorch_pretrained_bert`
- :param: `refs` (list of str): reference sentences
- :para... | 53,721 |
def search_tickets(request, **kwargs):
"""Return the tickets search page."""
template = 'tickets/search_tickets.html'
check_groups(request.user, [GROUP_SUPERVISOR, GROUP_SUPPORT])
# If the REFERER is a page other than the tickets
# search page, don't do any extra work, and don't render the table
... | 53,722 |
def test_square() -> None:
"""testing square"""
assert multiply(4, 3) == 12 | 53,723 |
def test_op_handle_selection():
"""
When serializing graphs, we can optionally add metadata to
those nodes we pass in, and return only those nodes when deserializing.
This is useful for ngraph transparent testing since it is common in
ngraph to use the final op as the 'handle' to the entire graph.
... | 53,724 |
def add_port_filter_by_host_interface(query, hostid, interfaceid):
"""Adds a port-specific host and interface filter to a query.
Filters results by host id and interface id if supplied hostid and
interfaceid are integers, otherwise attempts to filter results by
host uuid and interface uuid.
:param... | 53,725 |
def lidar_classify_phase(instrument, model, beta_p_phase_thresh=None,
convert_zeros_to_nan=False, remove_sub_detect=True):
"""
Phase classification based on fixed thresholds of a lidar's LDR and
tot beta_p variables.
Parameters
----------
instrument: Instrument
... | 53,726 |
def compute_cog(d):
"""
Args:
d: dict
Returns:
percentage
"""
accuracy=(d['22']+d['25']+d['23']+d['24'])/27
return round(accuracy*100, 3) | 53,727 |
def get_builddir() -> PathLike:
"""Obtain Sphinx base build directory for a given docset.
Returns:
Base build path.
"""
parser = get_parser()
args = parser.parse_args()
return (Path(args.outputdir) / ".." / "..").resolve() | 53,728 |
def set_script_prefix(prefix):
"""
Set the script prefix for the current thread.
为当前的线程设置脚本前缀
"""
if not prefix.endswith('/'):
prefix += '/'
_prefixes.value = prefix | 53,729 |
def main(list_packed_vars):
"""
Model simulation
Parameters
----------
list_packed_vars : list
list of packed variables that enable the use of parallels
Returns
-------
netcdf files of the simulation output (specific output is dependent on the output option)
"""... | 53,730 |
def validate(project_path, autocorrect):
"""Validates an Assembly/Resource project"""
logger.debug('Validating project at: {0}'.format(project_path))
project = lifecycle_cli.open_project(project_path)
controller = lifecycle_cli.ExecutionController(VALIDATE_HEADER)
controller.start('{0} at {1}'.forma... | 53,731 |
def _prepare_file_arg(
file: Union[str, List[str], TextIO, Path, BinaryIO, bytes], **kwargs: Any
) -> ContextManager[Union[str, BinaryIO, List[str], List[BinaryIO]]]:
"""
Utility for read_[csv, parquet]. (not to be used by scan_[csv, parquet]).
Returned value is always usable as a context.
A `Strin... | 53,732 |
def read_file(file):
"""Reads in a data file and generates insert statements for the sql dump."""
rs = "\n"
with open(file, "r", encoding='utf-8') as f:
data = json.load(f)
# Insert conf
rs += '''INSERT INTO Conference (conf_name, time, location) VALUES ("{}", "{}", "{}");\n'''\
... | 53,733 |
def retrieve_price(user: Optional[UserProtocol], price_id: str) -> PriceSubscription:
"""
Retrieve a single price with subscription info
"""
price_future = executor.submit(stripe.Price.retrieve, price_id)
subscription_info = is_subscribed_and_cancelled_time(user, price_id=price_id)
price = _mini... | 53,734 |
def pool_wrapper(func, iterprocs, nprocs=None, chunksize=1):
""" Wrapper for submitting multithreaded jobs to the pool
need to check len(processes) because if len==0 the pool hangs
http://bugs.python.org/issue6433
"""
listprocs = list(iterprocs)
if len(listprocs) > 0:
# optimizes for th... | 53,735 |
def transform(claims):
"""label encode value of claims
Parameters
----------
claims: panda.DataFrame
a data frame [source_id, object_id, value] where source_id, and object_id is already label encoded.
Returns
-------
claims_value_enc: pandas.DataFrame
a data frame [... | 53,736 |
def set_callback(ar, cb):
"""
Runs when confimation is requred, checks if answer is present in request data, if so, runs corisponding function
Otherwise returns with data that will pop up a dialog.
"""
cb_id = cb.uid
answer = ar.xcallback_answers.get("xcallback__" + cb_id, None)
if answer is... | 53,737 |
def composite_qc(df_orig, size=(16, 12)):
"""Plot composite QC figures"""
df = df_orig.rename(
columns={
"hli_calc_age_sample_taken": "Age",
"hli_calc_gender": "Gender",
"eth7_max": "Ethnicity",
"MeanCoverage": "Mean coverage",
"Chemistry": "Se... | 53,738 |
def PyUnicode_DecodeUTF7Stateful(space, s, size, errors, consumed):
"""If consumed is NULL, behave like PyUnicode_DecodeUTF7(). If
consumed is not NULL, trailing incomplete UTF-7 base-64 sections will not
be treated as an error. Those bytes will not be decoded and the number of
bytes that have been de... | 53,739 |
def get_map_crs(dem, longitude, latitude):
""" Get map coordinate system.
Notes:
If `dem` is a file, the map coordinate system should be
the same as that of the dem file; otherwise define a UTM coordinate system
based on the longitude and latitude.
Arguments:
dem: str or floa... | 53,740 |
def parse_args():
"""
Parses the command line arguments.
"""
# Override epilog formatting
OptionParser.format_epilog = lambda self, formatter: self.epilog
parser = OptionParser(usage="usage: %prog -i INPUT_STRING | --input INPUT_STRING "
"| --load FILE",
epilog=EXAMPLES)
parser.add_option("-i",... | 53,741 |
def clicked_watchtime_reward(responses):
"""Calculates the total clicked watchtime from a list of responses.
Args:
responses: A list of IEvResponse objects
Returns:
reward: A float representing the total watch time from the responses
"""
reward = 0.0
for response in responses:
if response.clicke... | 53,742 |
def plot_counts(counts, gene_type):
"""Plot expression counts. Return a Figure object"""
from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
from matplotlib.figure import Figure
import matplotlib
import seaborn as sns
import numpy as np
sns.set_style('white')
sns.... | 53,743 |
def watersheds_gdb_reader():
"""reader watersheds gdb into geopandas"""
#watersheds_gdb = 'WRIWatersheds.gdb'
# watersheds_gdb = 'AQID_Watwershed_Jan2020/AQID_Watwershed_Jan2020.shp'
# watersheds = geopandas.read_file(watersheds_gdb)
# watersheds.set_index("aqid",inplace=True)
#pfaf_id, ar... | 53,744 |
def cast_to_list(emoticons_list):
"""
Fix list of emoticons with a single name
to a list for easier future iterations,
and cast iterables to list.
"""
emoticons_tuple = []
for emoticons, image in emoticons_list:
if isinstance(emoticons, basestring):
emoticons = [emoticons... | 53,745 |
def merge_sorted(arr1: t.List[float], arr2: t.List[float]) -> t.List[float]:
"""
Merge two sorted arrays into a third sorted array.
Using two pointers, this algorithm is in O(n1 + n2), where n1 and n2 are
respectively the lengths of ``arr1`` and ``arr2``.
Args:
arr1: The first array to mer... | 53,746 |
def main(names): # {{{1
"""
Entry point for default_options.py
Arguments:
names: package names to check
"""
# Look for required programs.
err = sys.stderr
try:
for prog in ("pkg", "make"):
sp.run([prog], stdout=sp.DEVNULL, stderr=sp.DEVNULL)
except FileNotFo... | 53,747 |
def history(locs: ArrayLike, name: int) -> np.void:
"""Creates a named and sorted location history.
Args:
locs: An iterable of location numpy structured arrays.
name: A 64-bit int that labels the history.
Returns:
A structured array with attributes "name" and "locs".
"""
lo... | 53,748 |
def remove_role(context, email, role):
"""
Update a given user (email) to not have a role (Admin, Staff, Internal, Researcher, Contributor, Exporter)
"""
from app.modules.users.models import User
from app.extensions import db
user = User.find(email=email)
if user is None:
print("Us... | 53,749 |
def test_regression_diagonal():
"""Regression test - was using one-connected instead of 3-connected structuring element"""
x = cellprofiler.modules.identifyprimaryobjects.IdentifyPrimaryObjects()
x.use_advanced.value = True
x.y_name.value = "my_object"
x.x_name.value = "my_image"
x.exclude_size.... | 53,750 |
def conv1x1(in_planes, out_planes, stride=1, bias=False):
"""1x1 convolution"""
return nn.Conv2d(
in_planes,
out_planes,
kernel_size=1,
stride=stride,
bias=bias
) | 53,751 |
def run_circular_pattern(duration: float, speed: str):
"""
:param duration:
:param speed:
:return:
"""
width, height = pyautogui.size()
speed_float = get_speed(speed_value=speed)
radius = min(width, height)/2
validate_duration_and_speed(duration=duration, speed=speed_float)
for ... | 53,752 |
def argv_obj(input):
"""argv_obj(PyObject * input) -> char **"""
return _strumpack.argv_obj(input) | 53,753 |
def create_folder_if_not_exists(folder_name: str) -> None:
"""
Check if a folder exists and create one if not.
Args:
folder_name: name of the folder to be checked.
"""
Path(folder_name).mkdir(parents=True, exist_ok=True) | 53,754 |
def palettise_image(img, palette):
"""Map image to nearest colours in a given palette"""
img_palette = img.getcolors()
if img_palette is None:
sys.exit("error: source image has too many colours!")
col_map = {x[1] : closest_palette_index(x[1], palette) for x in img_palette}
img_pal = Image.n... | 53,755 |
def atom(token: str) -> types.Atom:
"""Convert token to proper types
When parsing, we get all tokens represented as strings.
Here we convert all integers and floats to their proper
types, and keep all other types as `types.Symbol` objects.
"""
try:
return int(token)
except ValueErro... | 53,756 |
def _descend_namespace(caller_globals, name):
"""
Given a globals dictionary, and a name of the form "a.b.c.d", recursively
walk the globals expanding caller_globals['a']['b']['c']['d'] returning
the result. Raises an exception (IndexError) on failure.
"""
names = name.split('.')
cur = call... | 53,757 |
def test_get_db(mongo_client):
"""Return the database for the collection"""
assert Dragon.get_db() == mongo_client['mongoframes_test'] | 53,758 |
def str_to_int(string):
"""Converts a DNA sequence to a list of integers.
Parameters
----------
string : str
The string of nucleobases.
Returns
-------
list of int
A list with the integer value for each nucleobase in the string.
"""
return [ut.nucleotide[nb] for nb... | 53,759 |
def _get_extension_point_url_from_name(domain, category, pluggable_name):
"""Get the extension point URL based on a pluggable method name"""
return '{}/{}/{}'.format(domain, category, pluggable_name).replace('//', '/') | 53,760 |
def get_feature(feature_name,
example):
"""Gets Tensorflow feature by name.
Args:
feature_name: The name of the feature.
example: A Tensorflow example.
Returns:
The Tensorflow feature with the given feature name in the example.
Raises:
ValueError: If the given feature name is ... | 53,761 |
def fcn_VR_FMS(r_div_R):
""" Transversal velocity factor of FMS in Eq. (31) in [2]
"""
return (1/4.)*(3.*r_div_R - r_div_R**3.0 + 2.0) | 53,762 |
def deprecated(func):
"""This is a decorator which can be used to mark functions
as deprecated. It will result in a warning being emitted
when the function is used."""
# C.f. http://wiki.python.org/moin/PythonDecoratorLibrary
def newFunc(*args, **kwargs):
warnings.warn("Call to deprecated fu... | 53,763 |
def test_dbt_compile_non_existent_model(profiles_file, dbt_project_file, model_files):
"""Test execution of DbtCompileOperator with a non-existent file."""
op = DbtCompileOperator(
task_id="dbt_task",
project_dir=dbt_project_file.parent,
profiles_dir=profiles_file.parent,
models=... | 53,764 |
def externalCC():
"""External Chaincode"""
pass | 53,765 |
def geo_to_msh(geo, msh, dim):
"""
Meshes the .geo file `geo` into the .msh file `msh` using the gmsh CLI.
"""
if shutil.which("gmsh") is None:
raise RuntimeError(
"You have to provide the 'gmsh' executable in your PATH to use this feature."
)
gmsh_cmd = ["gmsh", "-" + s... | 53,766 |
def ss_inference(model,
img,
ori_shape,
is_slide,
base_size,
stride_size,
crop_size,
num_classes,
rescale_from_ori=False):
"""
Single-scale inference for image.
Arg... | 53,767 |
def temperature(wair,pres,entr=None,temp=None,airf=None,dhum=None,
chkvals=False,chktol=_CHKTOL,airf0=None,temp0=None,dhum0=None,
chkbnd=False,mathargs=None):
"""Calculate icy air temperature.
Calculate the temperature of icy air.
:arg float wair: Total dry fraction in kg/kg.
:arg floa... | 53,768 |
def function(args):
"""Do something.
This is a malformed explicit markup block in RST:
..
Alpha
Beta
Gamma
and so on to Omega.
That line about Omega should be indented or preceded
by a blank line.
"""
pass | 53,769 |
def check_gnn_get_sampled_neighbors(method):
"""A wrapper that wraps a parameter checker around the GNN `get_sampled_neighbors` function."""
@wraps(method)
def new_method(self, *args, **kwargs):
[node_list, neighbor_nums, neighbor_types, _], _ = parse_user_args(method, *args, **kwargs)
che... | 53,770 |
def bound(x, lower, upper):
"""
Bound x between lower and upper, where x is a numpy array.
"""
# Lower bound.
y = np.where(x < lower, lower, x)
# Upper bound.
z = np.where(y > upper, upper, y)
return z | 53,771 |
def esc(code: int) -> str:
"""
Converts the integer code to an ANSI escape sequence
:param code: code
:return: escape sequence
"""
return f"\033[{code}m" | 53,772 |
def stop(message):
""" Handles the `stop` command.
Syntax: `start <message>`
Function: stop the timer.
Precondition on argument `message`:
- `message` is an non-empty string as the the input validation has already been handled by the do_stop() function in
interpreter stage.
"""
# noins... | 53,773 |
def call_and_notificate(args, opts):
"""
Execute specified arguments and send notification email
Parameters
----------
args : list
A execution command/arguments list
opts : object
A option instance
"""
# store starttime
stctime = time.clock()
stttime = time.time(... | 53,774 |
def compare(
line1,
line2,
method='frechet_dist',
precision=6,
clip=True,
clip_max=0.5
):
"""
Compute similarity between two (Multi)LineStrings.
Returns value 0.0 (completely dissimilar) to 1.0 (completely similar)
Based on Frechet distance
Param... | 53,775 |
def test_bias_words_no_duplicates():
"""Ensure no duplicates in slant.bias_words"""
assert len(slant.bias_words) == len(set(slant.bias_words)) | 53,776 |
def Phi_gradient(x: np.ndarray, mu: np.ndarray, Sigma: np.ndarray) -> np.ndarray:
"""
Compute gradient of CDF of multivariate Gaussian distribution.
:param x: Location where the gradient is evaluated.
:param mu: Mean of the multivariate Gaussian.
:param Sigma: Covariance of the multivariate Gaussia... | 53,777 |
def list_files(directory, extension):
""" List files with specified suffixes in the directory (exclude subdirectories)
"""
file_list = listdir(directory)
included_list = []
for f in file_list:
for ext in extension:
if f.endswith('.' + ext):
included_list.append(f)... | 53,778 |
def ensure_user_settings():
"""Create a default 'User' settings file for ApplySyntax if it doesn't exist."""
user_settings_file = os.path.join(sublime.packages_path(), 'User', PLUGIN_SETTINGS)
if os.path.exists(user_settings_file):
return
# file doesn't exist, let's create a bare one
with ... | 53,779 |
def generate_reference(nodal_position, mesh, image, settings, image_id=None):
"""
Generates a Reference object
The Reference object contains all internals that will be used during the correlation procedure.
Parameters
----------
nodal_position : ndarray
2D array with floats.
The co... | 53,780 |
def _estimate_df_regression(
y: Float64Array, trend: Literal["n", "c", "ct", "ctt"], lags: int
) -> RegressionResults:
"""Helper function that estimates the core (A)DF regression
Parameters
----------
y : ndarray
The data for the lag selection
trend : {"n","c","ct","ctt"}
The tr... | 53,781 |
def list_streams(region_name='us-west-2', Limit=10):
"""
Executes Kinesis.Client.describe_stream_summary function
"""
client = boto3.client('kinesis', region_name=region_name)
result = client.list_streams(Limit=Limit)
streams = []
if 'StreamNames' in result:
for st in result['Stream... | 53,782 |
def last_quantiles(series, title='', step=1, ax=None, inf=0.95):
"""Represent last quantiles of input series. Implementation optimized for values distributing over diverse orders of magnitude"""
bins = [round(e, 4) for e in np.linspace(inf, 1, 21)]
if ax is None:
fig, ax = plt.subplots()
quantiles = series.q... | 53,783 |
def store_cache_object(obj, filename, method_args=[], method_params={}):
"""
Creates a smart cache object in the file.
:param obj:
The object to cache.
:param filename:
The location of the cache file.
:param method_args:
Any arguments which were passed to the cached method... | 53,784 |
def set_all(r, g, b):
"""Set all backlight zones.
:param r: amount of red from 0 to 255
:param g: amount of green from 0 to 255
:param b: amount of blue from 0 to 255
"""
for p in range(6):
set_pixel(p, r, g, b) | 53,785 |
def as_json_object(element: YAMLRoot, contexts: CONTEXTS_PARAM_TYPE = None, inject_type = True) -> JsonObj:
"""
Return the representation of element as a JsonObj object
:param element: element to return
:param contexts: context(s) to include in the output
:param inject_type: if True (default), add a... | 53,786 |
def csv_to_list(csv):
"""Convert a csv string to an array, while ommitting empty entries."""
for val in csv.split(','):
if val != '':
yield val | 53,787 |
def floor_divide(input_, other):
"""Wrapper of `torch.floor_divide`.
Parameters
----------
input_ : DTensor
The first operand.
other : DTensor
The second operand.
"""
return torch.floor_divide(input_._data, other._data) | 53,788 |
def firstTokenPredicate(field):
"""Finds first word/token in the field.
Examples:
.. code:: python
> print(firstTokenPredicate('John Woodward'))
> ('John',)
"""
first_token = start_word(field)
if first_token:
return first_token.groups()
else:
return () | 53,789 |
def cancel_gesture():
"""
:doc: gesture
Cancels the current gesture, preventing the gesture from being recognized.
This should be called by displayables that have gesture-like behavior.
"""
renpy.display.gesture.recognizer.cancel() | 53,790 |
def ALMAFetchOutFiles( pickleFile='manifest.pickle', logFile=None):
"""
Fetch a pickled python object that holds pipeline output files. Check that
each output file still exists. If it does not, remove it from the object,
and print a warning.
* pickleFile = pickle file to be fetched
"""
if... | 53,791 |
def penalty_of_soft_constraint_1(schedule: Schedule, schedule_param: ScheduleParam, unit_penalty, _inspect=False):
"""
1. Instructors should only take certain courses they are are assigned to.
"""
violation_count = 0
for c in schedule.classes:
if c.section.course.idx not in c.instructor.assi... | 53,792 |
def test_dc_12():
"""
Checker should be able to handle contingent links with lb == ub
"""
# A =======[10,10]=====> C
c1 = SimpleContingentTemporalConstraint('e1', 'e3', 10, 10, 'c1')
network = TemporalNetwork([c1])
checker = DCCheckerBE(network)
feasible, conflict = checker.is_controlla... | 53,793 |
def run_arima_model(df, ts, p, d, q):
"""
Run ARIMA model
"""
from statsmodels.tsa.arima_model import ARIMA
# fit ARIMA model on time series
model = ARIMA(df[ts], order=(p, d, q))
results_ = model.fit(disp=-1)
# get lengths correct to calculate RSS
len_results = len(results_.fittedvalues)
ts... | 53,794 |
def is_type_bitfld(*args):
"""is_type_bitfld(type_t t) -> bool"""
return _idaapi.is_type_bitfld(*args) | 53,795 |
def query_av_summary_rpt(transaction_id, uploaded_file_name="",
web_server_ip="127.0.0.1", web_server_port="80"):
""" Query the 'AV summary report', for the specified
'server transaction_id' OR
'uploaded_file_name'
value.
(If a transaction_id is su... | 53,796 |
def get_arxiv_categories(arxiv_id=None, title=None, doi=None):
"""
Return a list of arxiv categories based on the specified arXiv identifier and/or title and/or doi.
The identifier and title (if given) are both forwarded to the arXiv api.
First element of the returned list is the primary category.
... | 53,797 |
def set_token(key, token_name, token_value=None):
"""
Set a token.
Overwrites the existing token for a given key, if one exists.
If a token value is not specified, a random value is generated.
Args:
key: the unique identifier object
token_name: the name of the token to set
... | 53,798 |
def get_custom_annotations_for_alias(data_type):
"""
Given a Stone data type, returns all custom annotations applied to it.
"""
# annotations can only be applied to Aliases, but they can be wrapped in
# Nullable. also, Aliases pointing to other Aliases don't automatically
# inherit their custom ... | 53,799 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.