content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def warp_containing_points(img, pts, H, border=4, shape_only=False):
"""
display = img.copy()
for pt in pts.reshape((-1,2)).astype(int):
cv2.circle(display, tuple(pt), 4, (255, 0, 0),
-1, cv2.LINE_AA)
debug_show('warp', display)
"""
pts2 = cv2.perspectiveTransform(pt... | 5,342,400 |
def generate_parallelogrammatic_board(width=5, height=5):
"""
Creates a board with a shape of a parallelogram.
Width and height specify the size (in fields) of the board.
"""
return [[1] * height for _ in range(width)] | 5,342,401 |
def function_is_even(latex_dict: dict) -> str:
"""
colloquially,
sympy.cos(x)==sympy.cos(-x)
sympy.cos(x) - sympy.cos(-x) == 0
>>> latex_dict = {}
>>> latex_dict['input'] = [{'LHS': parse_latex(''), 'RHS': parse_latex('')}]
>>> latex_dict['feed'] = [parse_latex('')]
>>> latex_dict['out... | 5,342,402 |
def process_json(args, json_raw):
"""
Verarbeitung des geparsten JSON und suchen der Metrik
"""
if args.debug:
print(f"DEBUG: [process_json] count = {len(json_raw)}, metric = {args.metric} ")
for metric in json_raw:
if metric['name'] == args.metric:
if args.debug:
print(f"DEBUG: [proc... | 5,342,403 |
def summarize_curriculum(
curriculum: AbstractCurriculum,
) -> str:
"""
Generate a detailed string summarizing the contents of the curriculum.
:return: A string that would print as a formatted outline of this curriculum's contents.
"""
def maybe_plural(num: int, label: str):
return f"{... | 5,342,404 |
def get_solarsample():
"""
NAME:
get_solarsample
PURPOSE:
get the RC sample at solar abundances
INPUT:
None so far
OUTPUT:
sample
HISTORY:
2015-03-18 - Started - Bovy (IAS)
"""
# Get the full sample first
data= get_rcsample()
# Now cut it
lo... | 5,342,405 |
def _fem_xref_methods_check(fem1: BDF):
"""
testing that these methods work with xref
"""
log = fem1.log
log.debug('_fem_xref_methods_check(fem1)')
fem1._get_rigid()
common_node_ids = list(fem1.nodes.keys())
fem1.get_rigid_elements_with_node_ids(common_node_ids)
for spc_id in set(l... | 5,342,406 |
def register_filters(app):
"""Jinja filters."""
app.jinja_env.globals["DEBUG"] = app.config["DEBUG"]
app.jinja_env.globals["EXTENSIONS"] = get_valid_extensions()
app.jinja_env.globals["SITE_TITLE"] = app.config["LNBITS_SITE_TITLE"] | 5,342,407 |
def main(level):
"""Damona is an environment manager for singularity containers.
It is to singularity container what conda is to packaging.
The default environment is called 'base'. You can create and activate
a new environment as follows:
\b
damona env --create TEST
damona activ... | 5,342,408 |
def perform_context_selection(
estimation_tasks: List[EstimationTask],
) -> List[EstimationTask]:
"""Changes the circuits in estimation tasks to involve context selection.
Args:
estimation_tasks: list of estimation tasks
"""
output_estimation_tasks = []
for estimation_task in estimation... | 5,342,409 |
def where(condition, x, y):
"""Wrapper of `torch.where`.
Parameters
----------
condition : DTensor of bool
Where True, yield x, otherwise yield y.
x : DTensor
The first tensor.
y : DTensor
The second tensor.
"""
return torch.where(condition, x, y) | 5,342,410 |
def test_cdf_accuracy():
"""Compare accuracy of the cumulative distribution function.
Compare the results with the ones obtained with the R poibin package
[Rpoibin]_.
"""
p = [0.1, 0.1]
pb = PoiBin(p)
assert np.all(np.abs(pb.cdf([0, 2]) - np.array([0.81, 1.])) < 1e-10)
p = [0.5, 1.0]
... | 5,342,411 |
def ukhls_wave_prefix(columns, year):
""" Determine wave prefix for ukhls wave data.
Parameters
----------
columns : list
A list of column names to add wave prefixes to.
year : int
Which wave year is being processed.
Returns
-------
columns : list
Column names w... | 5,342,412 |
def sort_converters(converters: Iterable[Optional[GenericConverter]]) -> List[GenericConverter]:
"""
Sort a list of converters according to their priority.
"""
converters = cast(Iterable[GenericConverter], filter(bool, converters))
return sorted(converters, key=lambda c: c.priority, reverse=True) | 5,342,413 |
def test_news_removal():
"""tests whether the news removed are returned in a list"""
data = news_removal()
assert isinstance(data, list) | 5,342,414 |
def _make_path_relative(origin, dest):
"""
Return the relative path between origin and dest.
If it's not possible return dest.
If they are identical return ``os.curdir``
Adapted from `path.py <http://www.jorendorff.com/articles/python/path/>`_ by Jason Orendorff.
"""
origin = os.path.abs... | 5,342,415 |
def print_mf_weight_statistics():
""" Prints debug info about size of weights. """
def callback(i_epoch, model, loss_train, loss_val, subset=None, trainer=None, last_batch=None):
models, labels = [], []
try:
models.append(model.outer_transform)
labels.append("outer trans... | 5,342,416 |
def createPolygon(fire):
"""
create a Polygon object from list of points
"""
points = []
for coordinate in fire["geometry"]["coordinates"][0]:
points.append(tuple(coordinate))
polygon = Polygon(points)
return polygon | 5,342,417 |
def change_anim_nodes(node_object="", in_tangent='linear', out_tangent='linear'):
"""
Changes the setting on all anim nodes.
:param node_object:
:param in_tangent:
:param out_tangent:
:return: <bool> True for success. <bool> False for failure.
"""
anim_nodes = object_utils.get_connected_... | 5,342,418 |
def is_x_degenerated(x, codon, table):
"""Determine if codon is x-fold degenerated.
@param codon the codon
@param table code table id
@param true if x <= the degeneration of the codon
"""
return (x <= len(altcodons(codon, table))) | 5,342,419 |
def get_long_tensor(tokens_list, batch_size, pad_id=constant.PAD_ID):
""" Convert (list of )+ tokens to a padded LongTensor. """
sizes = []
x = tokens_list
while isinstance(x[0], list):
sizes.append(max(len(y) for y in x))
x = [z for y in x for z in y]
tokens = torch.LongTensor(batch... | 5,342,420 |
def test_subdomain_against_pattern_asterix_prefix(create_user):
"""Test user email on subdomain against pattern """
emails = ["harold@help.bar.com"]
patterns = ["*bar.com"]
assert create_user.preprocess_pattern(emails, patterns) == True | 5,342,421 |
def business():
"""
show business posts
"""
business = Post.query.filter_by(category="Business").all()
return render_template('business.html', post=business) | 5,342,422 |
def tile_image(x_gen, tiles=()):
"""Tiled image representations.
Args:
x_gen: 4D array of images (n x w x h x 3)
tiles (int pair, optional): number of rows and columns
Returns:
Array of tiled images (1 x W x H x 3)
"""
n_images = x_gen.shape[0]
if not tiles:
for i in range(int(np.sqrt(n_im... | 5,342,423 |
def note_updated_data(note, role):
"""Return the data for updated date
:param note: the note that holds the data
:type note: :class:`jukeboxcore.djadapter.models.Note`
:param role: item data role
:type role: QtCore.Qt.ItemDataRole
:returns: data for the updated date
:rtype: depending on rol... | 5,342,424 |
def _xyz_atom_coords(atom_group):
"""Use this method if you need to identify if CB is present in atom_group and if not return CA"""
tmp_dict = {}
for atom in atom_group.atoms():
if atom.name.strip() in {"CA", "CB"}:
tmp_dict[atom.name.strip()] = atom.xyz
if 'CB' in tmp_dict:
... | 5,342,425 |
def InitBareRepository(path):
"""Returns the Repo object"""
assert isinstance(path, str)
pathlib.Path(path).parent.mkdir(parents=True,exist_ok=True)
return git.Repo.init(path,bare=True) | 5,342,426 |
def test_line_insert_before_after(tempfile_name, get_body):
"""
Test for file.line for insertion before specific line, using pattern and no patterns.
See issue #38670
:return:
"""
file_content = os.linesep.join(
[
"file_roots:",
" base:",
" - /srv... | 5,342,427 |
def test_syncFromSynapse():
"""This function tests recursive download as defined in syncFromSynapse
most of the functionality of this function are already tested in the
tests/integration/test_command_line_client::test_command_get_recursive_and_query
which means that the only test if for path=None
... | 5,342,428 |
def clone_variants(sender, request, original_release, release, **kwargs):
"""
Clone all variants and arches from `original_release` to new instance. All
newly created objects are logged into a changeset. Since nor Variant nor
VariantArch has an export method, their string representation is used
inst... | 5,342,429 |
def get_http_exception(code):
"""Return an exception class based on its code"""
try:
return http_exceptions[int(code)]
except:
return None | 5,342,430 |
def _zoom(restricted_func_and_grad, wolfe_one, wolfe_two, a_lo, phi_lo,
dphi_lo, a_hi, phi_hi, dphi_hi, g_0, pass_through):
"""
Implementation of zoom. Algorithm 3.6 from Wright and Nocedal, 'Numerical
Optimization', 1999, pg. 59-61. Tries cubic, quadratic, and bisection methods
of zooming.
"""
st... | 5,342,431 |
def _gradients_input(model: Union[tf.keras.models.Model, 'keras.models.Model'],
x: tf.Tensor,
target: Union[None, tf.Tensor]) -> tf.Tensor:
"""
Calculates the gradients of the target class output (or the output if the output dimension is equal to 1)
with respect to ... | 5,342,432 |
def fixBadSets(sets):
"""Splits bad sets into a series of valid, incomplete sets."""
from Totoro.dbclasses import Set as Set
toRemove = []
toAdd = []
for ss in sets:
if ss.getStatus(silent=True)[0] != 'Bad':
continue
toRemove.append(ss)
if len(ss.totoroExpos... | 5,342,433 |
def get_databases():
"""Return an ordered dict of (dbname: database). The order is
according to search preference, the first DB to contain a document
should be assumed to be the authoritative one."""
sql_dbs = [
_SQLDb(
XFormInstanceSQL._meta.db_table,
lambda id_: XFormIn... | 5,342,434 |
def save_qa_result(resource_id, qa_result, log):
"""
Saves the results of the QA check to the qa table.
"""
import ckan.model as model
from ckanext.qa.model import QA
now = datetime.datetime.now()
qa = QA.get_for_resource(resource_id)
if not qa:
qa = QA.create(resource_id)
... | 5,342,435 |
def get_app_data_path(app_name):
"""Returns the OS-specific path to Application Data for the given App.
Creates the path if it doesn't already exist.
NOTE: Darwin: https://developer.apple.com/reference/foundation/1414224-nssearchpathfordirectoriesindoma?language=objc
"""
assert type(app_name) == st... | 5,342,436 |
def list_examples():
"""List all examples"""
examples = ExampleModel.query()
form = ExampleForm()
if form.validate_on_submit():
example = ExampleModel(
example_name=form.example_name.data,
example_description=form.example_description.data,
added_by=users.get_c... | 5,342,437 |
def protocol(ctx: Context, protocol_id: PublicId) -> None:
"""Push a protocol to the registry or save it in local registry."""
if ctx.config.get("local"):
_save_item_locally(ctx, PROTOCOL, protocol_id)
else:
push_item(ctx, PROTOCOL, protocol_id) | 5,342,438 |
def parse_direct_mention(message_text):
"""
Finds a direct mention (a mention that is at the beginning) in message text
and returns the user ID which was mentioned. If there is no direct mention, returns None
"""
matches = re.search(_MENTION_REGEX, message_text)
# the first group contain... | 5,342,439 |
def test_load_db_1():
"""
Properly load the dataset
"""
transaction, bit_map, b2i_dict, i2b_dict = load_db(
"./data/contextIGB.txt", 1.0, 0.0, False,
)
t = np.array(
[
[1, 2, 4, 5],
[2, 3, 5],
[1, 2, 4, 5],
[1, 2, 3, 5],
... | 5,342,440 |
def prepare_deep(schema: types.Schema, schemas: types.Schemas):
"""
Resolve $ref and merge allOf including for object properties and items.
Assume the schema is a valid JSONSchema.
Args:
schema: The schema to prepare.
schemas: The schemas from which to resolve any $ref.
Returns:
... | 5,342,441 |
def test_assert_response_bad_status_code_with_json_errors():
"""Different status code than expected, with the server including errors."""
errors = [{"foo": "bar"}]
test_content = {"errors": errors}
response = create_response(status_code=404, json_content=test_content)
with pytest.raises(CommandError... | 5,342,442 |
def _resize_and_center_fundus(image, diameter):
"""
Helper function for scale normalizing image.
"""
copy = image.copy()
# Find largest contour in image.
contours = _find_contours(image)
# Return unless we have gotten some result contours.
if contours is None:
return None
... | 5,342,443 |
def _create_qApp():
"""
Create QApplicaiton if one does not exist. Return QApplication.instance().
Vendored from matplotlib.backends.backend_qt5 with changes:
- Assume Qt5, removing tolerance for Qt4.
- Applicaiton has been changed (matplotlib -> bluesky).
"""
global qApp
if qApp is No... | 5,342,444 |
def _pad_X_delta(X, delta, indices, padded_group_size):
"""Currently Unused."""
X_group = onp.take(X, indices, axis=0)
X_group = onp.pad(X_group, [(0, padded_group_size - X_group.shape[0]),
(0, 0)])
delta_group = onp.take(delta, indices, axis=0)
delta_group = onp.pad(delta_group... | 5,342,445 |
def test_ratelimit_bg_on(ctx):
"""
Test resolving a ratelimited domain with a background worker.
"""
ctx.set_option("ratelimit:", "1")
ctx.set_option("ratelimit-factor:", "0")
total_runs = 6
success_threshold = 4 # 2/3*total_runs
successes = 0
for i in range(total_runs):
cb... | 5,342,446 |
def union(x, y=None):
"""Get sorted list of elements combined for two iterables."""
x, y = de_list_pair(x, y)
return sorted(list(set(x) | set(y))) | 5,342,447 |
def is_tuple(typ) -> bool:
"""
Test if the type is `typing.Tuple`.
"""
try:
return issubclass(get_origin(typ), tuple)
except TypeError:
return typ in (Tuple, tuple) | 5,342,448 |
def _skip_if(cond, reason):
"""Skip test if cond(self) is True"""
def decorator(impl):
@functools.wraps(impl)
def wrapper(self, *args, **kwargs):
if cond(self):
raise unittest.SkipTest(reason)
else:
impl(self, *args, **kwargs)
retur... | 5,342,449 |
def run_loop(agents, env, max_frames=0):
"""A run loop to have agents and an environment interact."""
total_frames = 0
start_time = time.time()
observation_spec = env.observation_spec()
action_spec = env.action_spec()
for agent, obs_spec, act_spec in zip(agents, observation_spec, action_spec):
agent.se... | 5,342,450 |
def main():
""" This is a prefix calculator """
print("This is a prefix calculator. The first 3 goes are free!\nType \"q\" to quit.")
goes = 0
while goes < 3:
initial_input = get_input()
#initial_input = "(+ 2 (^ 3 3) (* 3 2))"
check_input(initial_input)
answer = chew_th... | 5,342,451 |
def _smash_all(job_context: Dict) -> Dict:
"""Perform smashing on all species/experiments in the dataset.
"""
start_smash = log_state("start smash", job_context["job"].id)
# We have already failed - return now so we can send our fail email.
if job_context['job'].success is False:
return job_... | 5,342,452 |
def permute_columns(df,
column_to_order: str,
ind_permute: bool = False,
columns_to_permute: list = []):
"""
Author: Allison Wu
Description: This function permutes the columns specified in columns_to_permute
:param df:
:param column_to_orde... | 5,342,453 |
def reset_dismissed(institute_id, case_name):
"""Reset all dismissed variants for a case"""
institute_obj, case_obj = institute_and_case(store, institute_id, case_name)
controllers.reset_all_dimissed(store, institute_obj, case_obj)
return redirect(request.referrer) | 5,342,454 |
def create_xst_script(config):
"""
given the configuration file create a script that will
build the verilog files declared within the configuration file
Args:
config (dictionary): configuraiton dictionary
Return:
(string) script file name
Raises:
Nothing
"""
xs... | 5,342,455 |
def fetch_quarters():
"""
This method fetches all sections in the roadmap project, then
using some regex magic, filters out all sections that are not
named like quarter names. For example:
Q1 2020
q1 2021
q3 2020
are all matches.
"""
sections = ASANA_CLIENT.sections.find_by_pro... | 5,342,456 |
def texts_from_array(x_train, y_train, x_test=None, y_test=None,
class_names = [],
max_features=MAX_FEATURES, maxlen=MAXLEN,
val_pct=0.1, ngram_range=1, preprocess_mode='standard', verbose=1):
"""
Loads and preprocesses text data from arrays.
Args:
... | 5,342,457 |
def display2(depts, level=0):
"""
[[a, 1], [b, 2], [c, 3], [d, 3], [a, 1]]
:param depts:
:return:
"""
lists = []
for d in depts:
lists.append([d, level])
children = Department.objects.filter(parent_id=d.id)
if children:
lists.extend(display2(children, leve... | 5,342,458 |
def _get_target_id_to_skill_opportunity_dict(suggestions):
"""Returns a dict of target_id to skill opportunity summary dict.
Args:
suggestions: list(BaseSuggestion). A list of suggestions to retrieve
opportunity dicts.
Returns:
dict. Dict mapping target_id to corresponding skil... | 5,342,459 |
def test_bah(S):
""" Fees for BAH should be equal to 1 * fee. """
FEE = 0.01
result = algos.BAH().run(S)
wealth_no_fees = result.total_wealth
result.fee = FEE
wealth_with_fees = result.total_wealth
assert abs(wealth_no_fees * (1 - FEE) - wealth_with_fees) < EPS | 5,342,460 |
def test_check_tag_exist_only_key_true():
"""
GIVEN List of EC2 instance tags.
WHEN check_tag_exist() is called.
THEN The key is on the provided list of tags.
"""
dummy_tags = [
{'Key': 'Environment', 'Value': 'dev'},
{'Key': 'Project', 'Value': 'ansible-lab'},
{'Key': 'N... | 5,342,461 |
def default_loc_scale_fn(
is_singular=False,
loc_initializer=tf.random_normal_initializer(stddev=0.1),
untransformed_scale_initializer=tf.random_normal_initializer(
mean=-3., stddev=0.1),
loc_regularizer=None,
untransformed_scale_regularizer=None,
loc_constraint=None,
untransformed_s... | 5,342,462 |
def db_eval_boundary(args):
"""
Compute mean,recall and decay from per-frame evaluation.
Calculates precision/recall for boundaries between foreground_mask and
gt_mask using morphological operators to speed it up.
Arguments:
foreground_mask (ndarray): binary segmentation image.
... | 5,342,463 |
def angle_trunc(a):
"""
helper function to map all angles onto [-pi, pi]
"""
while a < 0.0:
a += pi * 2
return ((a + pi) % (pi * 2)) - pi | 5,342,464 |
def get_tag_or_default(
alignment: pysam.AlignedSegment, tag_key: str, default: Optional[str] = None
) -> Optional[str]:
"""Extracts the value associated to `tag_key` from `alignment`, and returns a default value
if the tag is not present."""
try:
return alignment.get_tag(tag_key)
except Key... | 5,342,465 |
def vtln_warp_mel_freq(vtln_low_cutoff, vtln_high_cutoff, low_freq, high_freq,
vtln_warp_factor, mel_freq):
"""
Inputs:
vtln_low_cutoff (float): lower frequency cutoffs for VTLN
vtln_high_cutoff (float): upper frequency cutoffs for VTLN
low_freq (float): lower freq... | 5,342,466 |
def _squared_loss_and_spatial_grad_derivative(X, y, w, mask, grad_weight):
"""
Computes the derivative of _squared_loss_and_spatial_grad.
Parameters
----------
X : ndarray, shape (n_samples, n_features)
Design matrix.
y : ndarray, shape (n_samples,)
Target / response vector.
... | 5,342,467 |
def destructor(cfunc):
"""
Make a C function a destructor.
Destructors accept pointers to void pointers as argument. They are also wrapped as a staticmethod for usage in
classes.
:param cfunc: The C function as imported by ctypes.
:return: The configured destructor.
"""
cfunc.argtypes ... | 5,342,468 |
def invalid_auth_header(jwt):
"""Produce invalid JWT tokens for use in tests."""
return {'Authorization': 'Bearer ' + jwt.create_jwt(claims=TestJwtClaims.invalid, header=JWT_HEADER)} | 5,342,469 |
def update_file_info_in_job(job, file_infos):
"""
Update the 'setup.package.fileInformations' data in the JSON to append new file information.
"""
for file_info in file_infos:
try:
job['setup']['package']['fileInformations'].append(file_info)
except (KeyError, TypeError, Attr... | 5,342,470 |
def _FirstStatementsInScriptElements(contents):
"""Returns a list of first statements found in each <script> element."""
soup = parse_html.BeautifulSoup(contents)
script_elements = soup.find_all('script', src=None)
return [_FirstStatement(e.get_text()) for e in script_elements] | 5,342,471 |
def load_image(input_file_path):
"""
Load the 'input_file_path' and return a 2D numpy array of the image it contains.
"""
image_array = np.array(pil_img.open(input_file_path).convert('L'))
return image_array | 5,342,472 |
def pickle_compat_enforcer(obj):
"""i only need to make 1 distinction: container?""" | 5,342,473 |
def ask_the_user(runner: Runner) -> Direction:
"""Ask the user what to do (in absolute UP, DOWN, etc.)"""
return runner.ask_absolute() | 5,342,474 |
def patents_hgh(path):
"""Dynamic Relation Between Patents and R\\&D
a panel of 346 observations from 1975 to 1979
*number of observations* : 1730
*observation* : production units
*country* : United States
A dataframe containing :
obsno
firm index
year
year
cusip
Compustat's ... | 5,342,475 |
def available_domain_names():
"""
This function takes godaddy credentials from the user and generates all the
available domain names in a text file.
"""
godaddy_credentials()
domain_name = input("\nEnter required DOMAIN Name: ")
url = get_url(domain_name)
print("\nSearching for... | 5,342,476 |
def explore_pca(x_train, y_train, n_components=TOTAL_PCA_COMPONENTS):
"""Create plots of Principal Component Analysis decomposition
Find the first TOTAL_PCA_COMPONENTS PCA components of the argument. Create
a plot of the explained variance ratio and a plot of the cumulative sum of
the explained varianc... | 5,342,477 |
def assert_allclose(actual: List[int], desired: numpy.ndarray):
"""
usage.scipy: 4
"""
... | 5,342,478 |
def test_pvt():
"""Test PVT backbone."""
with pytest.raises(TypeError):
# Pretrained arg must be str or None.
PyramidVisionTransformer(pretrained=123)
# test pretrained image size
with pytest.raises(AssertionError):
PyramidVisionTransformer(pretrain_img_size=(224, 224, 224))
... | 5,342,479 |
def set_config(variable,value):
"""
This function is used to reset global environment variables.
Following variables can be accessed:
- X: Transformed dataset (X)
- y: Transformed dataset (y)
- X_train: Transformed train dataset (X)
- X_test: Transformed test/holdout dataset (X)
- y_... | 5,342,480 |
def optimize_spot_bid(ctx, instance_type, spot_bid):
"""
Check whether the bid is sane and makes an effort to place the instance in a sensible zone.
"""
spot_history = _get_spot_history(ctx, instance_type)
if spot_history:
_check_spot_bid(spot_bid, spot_history)
zones = ctx.ec2.get_all_z... | 5,342,481 |
def test_search_with_type(context):
"""
Search with type filter
"""
# When create a query block
t = QuerySet("localhost", index="foo")
# And there are records
add_document("foo", {"bar": 1})
add_document("foo", {"bar": 2})
add_document("foo", {"bar": 3}, doc_type="bar")
# And I... | 5,342,482 |
def _generator(batch_size, classes, X, y, augment):
"""Generate batches of training data forever."""
while 1:
batch_X, batch_y = [], []
for i in range(batch_size):
# random.seed(random.randint(0, 9001))
class_i = random.randint(0, NUM_CLASSES - 1)
# sample_ind... | 5,342,483 |
def new_hassle_participants():
"""Select participants for the room helpers."""
# Get a list of all current members.
members = helpers.get_all_members()
return flask.render_template('hassle_new_participants.html', members=members) | 5,342,484 |
def main():
"""Main program."""
initialize_megatron(extra_args_provider=add_text_generate_args,
args_defaults={'tokenizer_type': 'GPT2BPETokenizer'})
# Set up model and load checkpoint.
model = get_model(model_provider)
args = get_args()
if args.load is not None:
... | 5,342,485 |
def data_store_remove_folder(request):
"""
remove a sub-folder/sub-collection in hydroshareZone or any federated zone used for HydroShare
resource backend store. It is invoked by an AJAX call and returns json object that include a
status of 'success' if succeeds, and HttpResponse of status code of 403, ... | 5,342,486 |
def distance(x1: float, y1: float, x2: float, y2: float) -> float:
"""
Finds distance between two given points
Parameters:
x1, y1 : The x and y coordinates of first point
x2, y2 : The x and y coordinates of second point
Returns:
Distance ... | 5,342,487 |
def load_target_class(input_dir):
"""Loads target classes."""
df = pd.read_csv(join(input_dir, "target_class.csv"), header=None, index_col=0, names=["Target"])
return df | 5,342,488 |
def dict_to_tf_example(data,
dataset_directory,
label_map_path,
ignore_difficult_instances=False,
image_subdirectory='Images',
is_debug=False):
"""Convert XML derived dict to tf.Example proto.
Notice ... | 5,342,489 |
def fix_labels(ply_gt, ply_seg):
"""
Remove extra vertices from the ground truth
"""
size = len(ply_gt.elements[0]["x"])
gt_x = np.array(ply_gt.elements[0]["x"])
seg_x = np.array(ply_seg.elements[0]["x"])
new_gt_label = np.zeros_like(seg_x)
gt_label = np.array(ply_gt.elements[0]["labe... | 5,342,490 |
def visual(openPath, imgPath):
"""Visualize the use of homoglyph stegonography.
Args:
openPath (string): path to the text file to analyse
imgPath (string): image file path
"""
with open(openPath, encoding="utf-8") as openFile:
data = openFile.read()
visualAnsi = []
for char in data:
if ord(char) < 128:
... | 5,342,491 |
def test_set_and_get():
"""
Проверяем, что новые значения уровней по ключу устанавливаются, и потом считываются.
"""
Levels.set('kek', 10000)
assert Levels.get('kek') == 10000
Levels.set('kek', 5)
assert Levels.get('kek') == 5 | 5,342,492 |
def get_coin_price(api_url: str, currency: str) -> float:
"""
Get the USD price of a coin from Gemini
Args:
api_url: The API URL for Gemini
currency: The cryptocurrency the bot is monitoring
Returns:
coin_price: The price the coin currently holds in USD
"""
# Instantiate Gemini and... | 5,342,493 |
def GenerateAuthToken(key_name, user_id, action_id='', when=None):
"""Generates a URL-safe token based on XSRFToken but for generla purpose.
Args:
key_name (str): name of secret key to generate token.
user_id (str): the user ID of the authenticated user.
action_id (str): a string identifier of the acti... | 5,342,494 |
def test_run_error(check_output_mock):
"""There was a bad command made, therefore no output"""
check_output_mock.side_effect = CalledProcessError(
returncode=2, cmd='Bad Command!')
# pytest.set_trace()
with catch_stdout() as caught_output:
with pytest.raises(SystemExit):
run(... | 5,342,495 |
def run_optimization() -> None:
"""Run an optimization sequence based on preferential Bayesian optimization."""
num_dims = 5
strategy = pysls.CurrentBestSelectionStrategy.LastSelection
optimizer = pysls.PreferentialBayesianOptimizer(
num_dims=num_dims,
initial_query_generator=gen_initi... | 5,342,496 |
def download_dataset(file_url, file_name):
"""
Utility to download a dataset
"""
# %%
new_dir = up(up(up(up(os.path.abspath(__file__)))))
os.chdir(new_dir)
file_path = r'artificial_neural_networks/datasets/' + file_name
exists = os.path.isfile(file_path)
if exists:
... | 5,342,497 |
def get_dataset_psnr(device, model, dataset, source_img_idx_shift=64,
batch_size=10, max_num_scenes=None):
"""Returns PSNR for each scene in a dataset by comparing the view predicted
by a model and the ground truth view.
Args:
device (torch.device): Device to perform PSNR calcu... | 5,342,498 |
def smallest_continuous_multiple(max_multiple):
"""
Function takes an int, and returns the smallest natural number evenly divisible by all numbers
less than or equal to the input max_multiple.
REQ: max_multiple >= 0 and whole
:param max_multiple: {int}
:return: smallest natural number evenly d... | 5,342,499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.