content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def expected_response(y: np.ndarray, w: np.ndarray, policy: np.ndarray,
mu: Optional[np.ndarray]=None, ps: Optional[np.ndarray]=None) -> float:
"""Estimate expected response.
Parameters
----------
y: array-like of shape = (n_samples)
Observed target values.
w: array-l... | 5,350,200 |
def get_type_for_field(field: Field) -> type:
"""
For optional fields, the field type_ is a :class:`typing.Union`, of
``NoneType`` and the actual type.
Here we extract the "actual" type from a Union with None
"""
if not field.sub_fields:
return field.type_
for f in field.sub_fields:... | 5,350,201 |
def read_program_data(program: List[str]) -> int:
"""Read program data from port computer system.
Args:
program (List[str]): the program code containing masks and memory
Returns:
int: sum of all values in memory
"""
memory = defaultdict(int)
for line in program:
if lin... | 5,350,202 |
def get_mgr_worker_msg(comm, status=None):
"""Get message to worker from manager.
"""
status = status or MPI.Status()
comm.probe(source=0, tag=MPI.ANY_TAG, status=status)
tag = status.Get_tag()
if tag in [STOP_TAG, PERSIS_STOP]:
return tag, None, None
Work = comm.recv(buf=None, sourc... | 5,350,203 |
def retry(exceptions, tries=4, delay=3, backoff=2, logger=None):
"""
Retry calling the decorated function using an exponential backoff.
Args:
exceptions: The exception to check. may be a tuple of
exceptions to check.
tries: Number of times to try (not retry) before giving up.
... | 5,350,204 |
def install_pip(module):
"""Method installs python module via pip
Args:
module (str): python module
Returns:
none
"""
modtok = module.split('>=') if ('>=' in module) else module.split('==')
module_name = modtok[0]
module_version = modtok[1] if (len(modtok) > 1) else None
... | 5,350,205 |
def test_resources_init():
"""
Test initialization of the resources module.
Expected results: resources.paths should have the argument directory and the directory
which resources.py lives in
"""
with TemporaryDirectory() as tmp_dir:
resources = Resources([tmp_dir])
assert resour... | 5,350,206 |
def list_effects(ctx: Context, param: Option, value: str) -> None:
"""
List the names and descriptions of the effects currently available then exit.
:param ctx: see callbacks for click options
:param param: see callbacks for click options
:param value: see callbacks for click options
:return: No... | 5,350,207 |
def load_dictionary(dicttimestamp, server='postgres-cns-myaura'):
""" Load dictionary from database
Args:
dicttimestamp (string): the version of dictionary (ex: 20210131)
server (string): the server name in db_config.ini
Returns:
tuple (termdictparser, pandas.DataFrame): A TermDict... | 5,350,208 |
def _test():
""" テスト """
print("rdbutils")
cm = connect("sqlite3", ":memory:")
# テーブル作成
with cm as cursor:
cursor.execute("CREATE TABLE `t_test`(`id` INTEGER PRIMARY KEY AUTOINCREMENT, `value` TEXT)")
# データ作成
with cm as cursor:
cursor.execute("INSERT INTO `t_test`(`value`) VALUES(?)", "name")
cursor.exe... | 5,350,209 |
def part1(data):
"""
>>> part1(((20, 30), (-10, -5)))
45
>>> part1(INPUT)
13203
"""
target_x, target_y = data
best = None
for dx in range(1, max(target_x) + 1):
for dy in range(0, - min(target_y) + 1):
hit_target, height = trajectory(target_x, target_y, dx, dy)
... | 5,350,210 |
def get_neighbors(p, exclude_p=True, shape=None, nNeighbors=1,
get_indices=False, direction=None, get_mask=False):
"""Determine pixel coordinates of neighboring pixels.
Includes also all pixels that neighbor diagonally.
Parameters
----------
p : tuple
Gives the coordinate... | 5,350,211 |
def _update_wgrad_clipped(learning_rate, loss, w1, w2):
"""same as above, clamped in unit sphere"""
for k in range(w1.size):
grad = loss * w2[k]
w1[k] = w1[k] - learning_rate * grad
if w1[k] < -1.: w1[k] = -1.
elif w1[k] > 1.: w1[k] = 1. | 5,350,212 |
def make_coordinate_grid(spatial_size, type):
"""
Create a meshgrid [-1,1] x [-1,1] of given spatial_size.
"""
h, w = spatial_size
x = torch.arange(w).type(type)
y = torch.arange(h).type(type)
x = (2 * (x / (w - 1)) - 1)
y = (2 * (y / (h - 1)) - 1)
yy = y.view(-1, 1).repeat(1, w)
... | 5,350,213 |
def add_wrong_column(data_frame):
"""
Adds wrong column to dataframe
:params dataframe data_frame:
:returns dataframe:
"""
new_df = data_frame.copy()
new_df['Ducks'] = 0
return new_df | 5,350,214 |
def p2l(X, Y, D, tol, inputTransform):
"""
Computes the Procrustean point-line registration between X and Y+nD with
anisotropic Scaling,
where X is a mxn matrix, m is typically 3
Y is a mxn matrix denoting line origin, same dimension as X
D is a mxn normalized matrix denoting line direction
R i... | 5,350,215 |
def test_federal_account_insert():
"""Test federal account creation from underlying TAS records."""
mommy.make(
TreasuryAppropriationAccount,
agency_id='abc',
main_account_code='7777',
account_title='Fancy slipper fund'
)
mommy.make(
TreasuryAppropriationAccount,
... | 5,350,216 |
def config_database(db_name):
"""
Create a database in sqlite3
:param db_name: The name of the file for the database
:return: A database objetc and his connections object
"""
db = Database()
connection = db.create_connection(db_name)
db.create_table(connection)
return db, connection | 5,350,217 |
def gaussian_blur(img, kernel_size):
"""Applies a Gaussian Noise kernel"""
return | 5,350,218 |
def parse_main_argument(argument, export_folder):
"""Function parsing the main_argument argument.
Returns a dataframe containing the search terms (or the urls if main_argument is a youtube file."""
# File or string
if Path(argument).is_file():
is_file = True
argument_file_content = open(... | 5,350,219 |
def validate_auth_header(headers):
"""Validate and decode auth token in request headers.
This helper function is used in each of the below wrappers, and is responsible to
validate the format of the `Authorization` header where the Lowball token is
supposed to reside.
Requirements for successful va... | 5,350,220 |
def shared_random_seed():
"""All workers must call this function, otherwise it will deadblock.
"""
seed = np.random.randint(2 ** 31)
all_seeds = all_gather(seed)
return all_seeds[0] | 5,350,221 |
def _version(base):
"""Get a chronological version from git or PKG-INFO
Args:
base (dict): state
Returns:
str: Chronological version "yyyymmdd.hhmmss"
str: git sha if available
"""
v1 = _version_from_pkg_info(base)
v2, sha = _version_from_git(base)
if v1:
if... | 5,350,222 |
def test_reset_workflow(
redis, session, reset_workflow, museum_object_factory,
museum_package_factory, museum_packages_dir):
"""
Reset workflow and ensure dangling packages are removed
"""
# Objects A and B will be reset, object C will remain
object_a = museum_object_factory(id=10)
... | 5,350,223 |
def paint_flag_iceland():
"""http://www.crwflags.com/fotw/flags/is.html"""
f = FlagPainter(18 / 25)
colors = [(0, 0, 204), (255, 255, 255), (255, 0, 0)]
f.background(colors[0])
f.draw_horizontal_band((7 / 18, 11 / 18), colors[1])
f.draw_vertical_band((7 / 25, 11 / 25), colors[1])
f.draw_hori... | 5,350,224 |
def run_adaptive_redundancy(host_num, coder_log_conf):
"""Run network application for multi-hop topology
:param host_num (int): Number of hosts
:param profile (int): To be tested profile
:param coder_log_conf (dict): Configs for logs of coders
"""
net = Containernet(controller=RemoteController... | 5,350,225 |
def average_link_distance_segment(D,stop=-1,qmax=1,verbose=0):
"""
Average link clustering based on a pairwise distance matrix.
Parameters
----------
D: a (n,n) distance matrix between some items
stop=-1: stopping criterion, i.e. distance threshold at which
further merges are forbi... | 5,350,226 |
def _process_get_set_Operand(column, reply):
"""Process reply for functions zGetOperand and zSetOperand"""
rs = reply.rstrip()
if column == 1:
# ensure that it is a string ... as it is supposed to return the operand
if isinstance(_regressLiteralType(rs), str):
return str(rs)
... | 5,350,227 |
def test_dict_similar_keys():
"""
unpackb() similar keys
This was a regression in 3.4.2 caused by using
the implementation in wy instead of wyhash.
"""
obj = {"cf_status_firefox67": "---", "cf_status_firefox57": "verified"}
assert ormsgpack.unpackb(ormsgpack.packb(obj)) == obj | 5,350,228 |
def generic_laplace(input, derivative2, output=None, mode="reflect",
cval=0.0, extra_arguments=(), extra_keywords=None):
"""Multi-dimensional Laplace filter using a provided second derivative
function.
Args:
input (cupy.ndarray): The input array.
derivative2 (callable): ... | 5,350,229 |
def find_zones_by_tld(graph, tpd, groups, mongo_connector):
"""
Technically, a "tld" is ".org" or ".com".
However, tld library that I use considers TLDs to be "example.org".
This code just rolls with that.
For the provided third-party-domain, find the zones that are associated with that tpd.
"""... | 5,350,230 |
def as_keras_metric(method):
""" from https://stackoverflow.com/questions/43076609/how-to-calculate-precision-and-recall-in-keras """
import functools
@functools.wraps(method)
def wrapper(self, args, **kwargs):
""" Wrapper for turning tensorflow metrics into keras metrics """
value, upd... | 5,350,231 |
def plot_gms_spectra(
gms_result: gms.GMSResult,
save_file: Path = None,
):
"""Plot of the pSA values of the realisations and
selected ground motions and the median, 16th,
and 84th percentile of the GCIM
Parameters
----------
gms_result: gms.GMSResult
save_file: Path, optional
... | 5,350,232 |
def main():
"""
TODO:
"""
read_dictionary()
boggle = []
for i in range(4):
words = input(str(i+1)+' row of letters:')
words = words.split()
row = []
for letter in words:
if letter.islower():
letter.upper()
if len(letter) != 1:
print('Illegal input')
break
else:
row.append(letter)... | 5,350,233 |
def do_get_video_capture_job(port_output_name: str = 'RAW') -> str:
"""
Function for configure the image retrieval job from video camera.
:param port_output_name: name you want to use for raw image in the application
:return: output image port name
"""
output_raw_port_name = transform_port_name_... | 5,350,234 |
def test_interact_functions():
"""Do the helper functions in the interact module run without syntax error?"""
import bokeh
from ..interact import (prepare_tpf_datasource, prepare_lightcurve_datasource,
get_lightcurve_y_limits, make_lightcurve_figure_elements,
... | 5,350,235 |
def sync_one(src: str, dst: str, *, dry_run: bool) -> Optional[date]:
"""
From the snapshots that are present in src and missing in dst, pick the one
that is closest to an existing snapshot in dst, and sync it. Returns the
snapshot synced, or none if src and dst are already in sync.
"""
src_subv... | 5,350,236 |
def version(ctx: click.Context, project_path: Path, strict: bool) -> None:
"""Calculate next version from Git history.
Given a Git repository, this command will find the latest version tag and
calculate the next version using the Conventional Commits (CC) specification.
Calculated version will be prin... | 5,350,237 |
def vgg8_S(*args, **kwargs):
"""VGG 16-layer model (configuration "D")
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
"""
model = VGG(make_layers(cfg['YS']), final_filter=256, **kwargs)
return model | 5,350,238 |
def createWords(word_str):
"""Cn Mandarin sentence to Cn Mandarin Words list"""
pre_func = IO.readList(r'docs/pre_punctuation.txt')[1:]
lat_func = IO.readList(r'docs/post_punctuation.txt')[1:]
en_letters = IO.readList(r'docs/special_English_letters.txt')[1:]
words = []
j = 0
tmp_word = ''
... | 5,350,239 |
def get_calib_driver(calib_dir: str):
""" Create left/right charuco point detectors and load calibration images from directory. """
reference_image = cv2.imread("tests/data/2020_01_20_storz/pattern_4x4_19x26_5_4_with_inset_9x14.png")
minimum_points = 50
number_of_squares = [19, 26]
square_tag_sizes... | 5,350,240 |
def stop_loading() -> dict:
"""Force the page stop all navigations and pending resource fetches."""
return {"method": "Page.stopLoading", "params": {}} | 5,350,241 |
def rename_model(model_name, new_name):
"""Assign a new name to a model in current database.
Parameters
----------
model_name : str
Current model name.
new_name : str
New name for model.
Returns
-------
None
"""
mdb.models.changeKey(fromName=model_name, toName=n... | 5,350,242 |
def drop_duplicates(df):
"""Drop duplicate rows and reindex.
Args:
df (pd.DataFrame): Dataframe.
Returns:
pd.DataFrame: Dataframe with the replaced value.
Examples:
>>> df = pd.DataFrame({'letters':['b','b','c'], 'numbers':[2,2,3]})
>>> drop_duplicates(df)
... | 5,350,243 |
def by_index(e, index):
"""Decompose error by an index.
TODO
Parameters
----------
e : array_like
index : array_like
"""
pass | 5,350,244 |
def estimate_progress(ihash, peers):
"""Estimate a percentage done based on client stats"""
progress = count = 0
log.debug("peers: %s" % peers)
size = float(get_size(ihash))
if not size:
return "Unknown"
stats = get_clientstats(ihash)
# log.debug("%s" % stats)
for peer in peers:
... | 5,350,245 |
async def update_state():
"""Updates state of the TV every 5 seconds."""
while True:
await TV.update()
await asyncio.sleep(5) | 5,350,246 |
def close(fd):
"""close(fd)
Close a file descriptor (for low level IO).
"""
rawio = FileDescriptors.get(fd)
_handle_oserror(rawio.close) | 5,350,247 |
def make_otf(
psf,
outpath=None,
dzpsf=0.1,
dxpsf=0.1,
wavelength=520,
na=1.25,
nimm=1.3,
otf_bgrd=None,
krmax=0,
fixorigin=10,
cleanup_otf=False,
max_otf_size=60000,
**kwargs
):
""" Generate a radially averaged OTF file from a PSF file
Args:
psf (str... | 5,350,248 |
def get_palette(dataset_name):
"""
Maps classes to colors in the style of PASCAL VOC.
Close values are mapped to far colors for segmentation visualization.
See http://host.robots.ox.ac.uk/pascal/VOC/voc2012/index.html#devkit
Takes:
num_classes: the number of classes
Gives:
palet... | 5,350,249 |
def is_number(input_string):
"""
if input_string includes number only, return corresponding number,
otherwise return input_string
"""
try:
return float(input_string)
except ValueError:
pass
try:
import unicodedata
return unicodedata.numeric(input_... | 5,350,250 |
def test_upgrade_db_26_to_27(user_data_dir): # pylint: disable=unused-argument
"""Test upgrading the DB from version 26 to version 27.
- Recreates balancer events, uniswap events, amm_swaps. Deletes balancer pools
"""
msg_aggregator = MessagesAggregator()
_use_prepared_db(user_data_dir, 'v26_rotke... | 5,350,251 |
def latest_active(name, at_time=None, **kwargs): # pylint: disable=unused-argument
"""
Initiate a reboot if the running kernel is not the latest one installed.
.. note::
This state does not install any patches. It only compares the running
kernel version number to other kernel versions al... | 5,350,252 |
def upload_file(file_name, bucket, object_name):
"""Upload a file to an S3 bucket
:param file_name: File to upload
:param bucket: Bucket to upload to
:param object_name: S3 object name. If not specified then file_name is used
:return: True if file was uploaded, else False
"""
s3_client = bo... | 5,350,253 |
def get_conf(bs_info, client_config, genesis_time, setup_oracle=None, setup_poet=None, args=None):
"""
get_conf gather specification information into one ContainerSpec object
:param bs_info: DeploymentInfo, bootstrap info
:param client_config: DeploymentInfo, client info
:param genesis_time: string... | 5,350,254 |
def generate_list(
bibliographies: Biblio, search_key: str
) -> Generator[CompletionItem, None, None]:
"""Given a bibliography and a search string, find all completion items
that might match the entry."""
key_regex = re.compile("^{}.*".format(search_key))
for key in list(filter(key_regex.match, bibl... | 5,350,255 |
def zeropad(tr, starttime, endtime):
"""
Zeropads an obspy.Trace so as to cover the time window specified by
`starttime`'and `endtime`
Parameters
----------
tr : obspy.Trace
starttime, endtime : obspy.UTCDateTime
Returns
-------
trace : obspy.Trace
Zeropadded c... | 5,350,256 |
def deepwalk(G, _filepath, o=1, num_walks_node=10, walk_length=80,
representation_size=128, window_size=5,):
"""not going to deal with memory exceeding case"""
output = _filepath + G.name
print("Walking...")
time_start = time.time()
walks = gu.build_deepwalk_corpus(G, num_paths=num_wal... | 5,350,257 |
def logship_status(host):
"""Report log shipping retstore delta and latency"""
crit = warn = 0
msg = ''
sql = """SELECT secondary_server, secondary_database, primary_server, primary_database,
last_restored_date, DATEDIFF(mi, last_restored_date, GETDATE()) last_restored_delta,
last_resto... | 5,350,258 |
def dice(y_true, y_pred):
"""
Attention:
y_true can be weighted to modify learning therefore
apply sign to get back to labels
y_pred have to be rounded to nearest integer to obtain labels.
"""
smooth = 1.
y_true_f = y_true.flatten()
y_pred_f = y_pred.flatten()
intersection = n... | 5,350,259 |
def output_video(input_file, output_file):
""" Given input_file video, save annotated video to output_file """
video = VideoFileClip(input_file)
final_video = video.fl_image(process_image)
final_video.write_videofile(output_file, audio=False) | 5,350,260 |
def get_long_description(filename):
"""Return entire contents of *filename*."""
with open(os.path.join(WORKING_DIR, filename)) as fh:
return fh.read() | 5,350,261 |
def get_default_language():
"""
Returns the default language code based on the data from LANGUAGES.json.
"""
for language_code, language_data in MEDICINE_LANGUAGE_DATA.items():
if 'DEFAULT' in language_data:
if language_data['DEFAULT']:
return language_code
r... | 5,350,262 |
def triple_triple(r, p=qt.QH([1, 0, 0, 0])):
"""Use three triple products for rotations and boosts."""
# Note: 'qtype' provides a record of what algrabric operations were done to create a quaternion.
return triple_sandwich(r, p).add(triple_2_on_1(r, p), qtype="triple_triple") | 5,350,263 |
def _pinv_trunc(x, miss):
"""Compute pseudoinverse, truncating at most "miss" fraction of varexp."""
u, s, v = linalg.svd(x, full_matrices=False)
# Eigenvalue truncation
varexp = np.cumsum(s)
varexp /= varexp[-1]
n = np.where(varexp >= (1.0 - miss))[0][0] + 1
logger.info(' Truncating at ... | 5,350,264 |
def mog_loglike(x, means, icovs, dets, pis):
""" compute the log likelihood according to a mixture of gaussians
with means = [mu0, mu1, ... muk]
icovs = [C0^-1, ..., CK^-1]
dets = [|C0|, ..., |CK|]
pis = [pi1, ..., piK] (sum to 1)
at locations given by x = [x1... | 5,350,265 |
def align_chunks(array: da.core.Array, scale_factors: Sequence[int]) -> da.core.Array:
"""
Ensure that all chunks are divisible by scale_factors
"""
new_chunks = {}
for idx, factor in enumerate(scale_factors):
aligned = aligned_coarsen_chunks(array.chunks[idx], factor)
if aligned != ... | 5,350,266 |
def getWordScore(word):
"""
Computes the score of a word (no bingo bonus is added).
word: The word to score (a string).
returns: score of the word.
"""
if len(word) == HAND_SIZE:
score = 50
else:
score = 0
for letter in word:
score = score + SCRABBLE_LETTER_VALU... | 5,350,267 |
def autolabel(rects, ax, error_bar, rotation=90, color="black", fontsize=None):
"""Attach a text label above each bar in *rects*, displaying its height."""
if isinstance(error_bar, dict):
error_bar = error_bar.values()
if error_bar is None:
error_bar = [np.nan for _ in range(len(rects))]
... | 5,350,268 |
def get_lang_list(source_text, key=None, print_meta_data=False):
"""
Inputs:
source_text - source text as a string
key - google api key, needed or function will raise and error
returns list of language identifiers
"""
#set up url request to google translate api
if not key:
raise... | 5,350,269 |
def single_value_rnn_regressor(num_units,
sequence_feature_columns,
context_feature_columns=None,
cell_type='basic_rnn',
num_rnn_layers=1,
optimizer_type='SGD',
... | 5,350,270 |
def token():
""" Return a unique 32-char write-token
"""
return str(uuid.uuid4().hex) | 5,350,271 |
def _get_caller_caller_module_name():
"""Return name of module which calls the function from which this function is invoked"""
frame = currentframe().f_back.f_back
return getmodule(frame).__name__ | 5,350,272 |
def percentile(x: np.ndarray, percentile: float = 99) -> Tuple[float, float]:
"""Get the (low, high) limit for the series by only including the data within the given percentile.
For example, if percentile is 99, (1st percentile, 99th percentile) will be returned.
Also, if percentile is 1, (1st percentile,... | 5,350,273 |
def get_versions_data(
hidden=None,
is_unreleased=None,
find_latest_release=None,
sort_key=None,
labels=None,
suffix_latest_release=' (latest release)',
suffix_unreleased=' (dev)',
find_downloads=None,
):
"""Get the versions data, to be serialized to json."""
if hidden is None:
... | 5,350,274 |
def cgan_training(Xtrain, Xdev, Ytrain, Ydev, use_gpu=False):
"""
Train using a conditional GAN
"""
if use_gpu:
device = torch.device("cuda")
else:
device = torch.device("cpu")
dtype = torch.double
vh = VariableHandler(device=device, dtype=dtype)
# Make sure inputs are ... | 5,350,275 |
def wheels(
package_name: str = Argument(..., help="The name of the package to show wheel info for"),
version: str = Argument(
None,
help="The version of the package to show info for, defaults to latest, can be omitted if using package_name==version",
),
supported_only: bool = Option(Fal... | 5,350,276 |
def _list_of_files() -> List[str]:
"""
Return the list of waypoint story files
:return:
"""
file_list = (
f for f in os.listdir(waypoint_directory_path) if f.endswith("." + "yml")
)
waypoint_list_file = []
for file in file_list:
if not file.startswith("_"):
w... | 5,350,277 |
def _parse_figsize(kwargs):
"""
Translate `figsize` into proplot-specific `figwidth` and `figheight` keys.
"""
# WARNING: Cannot have Figure.__init__() interpret figsize() because
# the figure manager fills it with the matplotlib default.
figsize = kwargs.pop('figsize', None)
figwidth = kwar... | 5,350,278 |
def p_jump_statement(t):
"""
jump_statement : CONTINUE SEMI
| BREAK SEMI
| RETURN expression_opt SEMI
"""
pass | 5,350,279 |
def extract_pvdata(h5file, timestamp, pvnames=None):
"""
Extract as a snapshot (PV values) nearest a timestamp from a BSA HDF5 file.
Parameters
----------
h5file: str
BSA HDF5 file with data that includes the timestamp
timestamp: datetime-like, str, int, float
This ... | 5,350,280 |
def decorate_func_with_plugin_arg(f):
"""Decorate a function that takes a plugin as an argument.
A "plugin" is a pair of simulation and postprocess plugins.
The decorator expands this pair.
"""
@functools.wraps(f)
def wrapper(self, plugins_tuple):
return f(self, plugins_tuple[0], plugin... | 5,350,281 |
def datestr(date=None):
"""Convert timestamps to strings in a predefined format
"""
if date is None:
date = datetime.utcnow()
if isinstance(date, str):
date = parse_time(date)
return date.strftime("%y-%m-%d %H:%M:%S") | 5,350,282 |
def validate_release_tag_param(arg_value):
"""
User defined helper function to validate that the release_tag parameter follows the correct naming convention
:param arg_value: release tag parameter passed through either the command line arguments
:return: arg_value
"""
release_tag_regex = re.co... | 5,350,283 |
def init():
"""Connect to the keyboard, switch all lights off"""
global bufferC # Buffer with the full key/lights mapping
global device
device=hid.device()
# 0x17cc: Native Instruments. 0x1410: KK S88 MK1
device.open(0x17cc, pid)
device.write([0xa0])
bufferC = [0x00] * n... | 5,350,284 |
def render(path):
"""
Render the knowledge post with all the related formatting.
"""
mode = request.args.get('render', 'html')
username, user_id = current_user.identifier, current_user.id
tmpl = 'markdown-rendered.html'
if mode == 'raw':
tmpl = 'markdown-raw.html'
elif mode == ... | 5,350,285 |
def compute_acc_bin(conf_thresh_lower, conf_thresh_upper, conf, pred, true):
"""
# Computes accuracy and average confidence for bin
Args:
conf_thresh_lower (float): Lower Threshold of confidence interval
conf_thresh_upper (float): Upper Threshold of confidence interval
conf (numpy.n... | 5,350,286 |
def list_consumers(ctx: click.Context, full_keys: bool, full_plugins: bool) -> None:
"""List all consumers along with relevant information."""
session = ctx.obj["session"]
tablefmt = ctx.obj["tablefmt"]
font = ctx.obj["font"]
print_figlet("Consumers", font=font, width=160)
consumers = get("con... | 5,350,287 |
def multi_backend_test(globals_dict,
relative_module_name,
backends=('jax', 'tensorflow'),
test_case=None):
"""Multi-backend test decorator.
The end goal of this decorator is that the decorated test case is removed, and
replaced with a set of n... | 5,350,288 |
def _get_typed_array():
"""Generates a TypedArray constructor.
There are nine types of TypedArrays and TypedArray has four constructors.
Types:
* Int8Array
* Int16Array
* Int32Array
* Uint8Array
* Uint16Array
* Uint32Array
* Uint8ClampedArray
* Float32Array
... | 5,350,289 |
def _is_valid_requirement(requirement: str) -> bool:
"""Returns True is the `requirement.txt` line is valid."""
is_invalid = (
not requirement or # Empty line
requirement.startswith('#') or # Comment
requirement.startswith('-r ') # Filter the `-r requirement.txt`
)
return not is_invalid | 5,350,290 |
def execute(cmd):
"""Execute a random string in the app context
"""
from kivy.clock import mainthread
_result = [None]
_event = threading.Event()
@mainthread
def _real_execute():
from kivy.app import App
app = App.get_running_app()
idmap = {"app": app}
try:
... | 5,350,291 |
def _election(__PIGS__):
"""
this method will perform an election after each revolution.
*note:*
as this is a communist module, the election is protected
and only __PIGS__ have access to it.
"""
party = random.choices(__PIGS__, k=min(10, len(__PIGS__)))
leader = random.choice(party)
... | 5,350,292 |
def UprevVersionedPackage(input_proto, output_proto, _config):
"""Uprev a versioned package.
See go/pupr-generator for details about this endpoint.
"""
chroot = controller_util.ParseChroot(input_proto.chroot)
build_targets = controller_util.ParseBuildTargets(input_proto.build_targets)
package = controller_... | 5,350,293 |
def is_scalar(element):
"""An `is_atomic` criterion. Returns `True` for scalar elements.
Scalar elements are : strings and any object that is not one of:
collections.Sequence, collections.Mapping, set, or attrs object.
```
import nifty_nesting as nest
flat = nest.flatten([1, [2, 3]], is_atom... | 5,350,294 |
def show_usage():
"""
It prints usage information.
"""
print "Usage:"
print " %s <network interface> <timeout in minutes>\n" % sys.argv[0]
print "Example:"
print " %s eth0 10\n" % sys.argv[0]
print "Available Interfaces:"
if platform.uname()[0].lower() == "windows":
print_win... | 5,350,295 |
def wrap_singleton_string(item: Union[Sequence, str]):
""" Wrap a single string as a list. """
if isinstance(item, str):
# Can't check if iterable, because a string is an iterable of
# characters, which is not what we want.
return [item]
return item | 5,350,296 |
def view_milestone_history(request, chosen_year=None):
"""
http://127.0.0.1:8000/milestones/by-columns/
:param request:
:return:
"""
(chosen_year, basic_query) = get_basic_milestone_history_query(chosen_year)
milestones = basic_query.order_by('due_on')
open_closed_cnts = get_is... | 5,350,297 |
def M_absolute_bol(lum):
"""Computes the absolute bolometric luminosity
Parameters
----------
lum : `float/array`
luminosity in solar luminosities
Returns
-------
M_bol : `float/array`
absolute bolometric magnitude
"""
log_lum = np.log10(lum)
M_bol = 4.75 - ... | 5,350,298 |
def codes_index_get_double(indexid, key):
# type: (cffi.FFI.CData, bytes) -> T.List[float]
"""
Get the list of double values associated to a key.
The index must be created with such a key (possibly together with other
keys).
:param bytes key: the keyword whose list of values has to be retrieved... | 5,350,299 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.