content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def cherry_pick_cli(
ctx, dry_run, pr_remote, abort, status, push, config_path, commit_sha1, branches
):
"""cherry-pick COMMIT_SHA1 into target BRANCHES."""
click.echo("\U0001F40D \U0001F352 \u26CF")
chosen_config_path, config = load_config(config_path)
try:
cherry_picker = CherryPicker(
... | 5,336,500 |
def category(category: str) -> List[str]:
"""Get list of emojis in the given category"""
emoji_url = f"https://emojipedia.org/{category}"
page = requests.get(emoji_url)
soup = BeautifulSoup(page.content, 'lxml')
symbols: List[str]
try:
ul = soup.find('ul', class_="emoji-list")
... | 5,336,501 |
def calc_cumulative_bin_metrics(
labels: np.ndarray,
probability_predictions: np.ndarray,
number_bins: int = 10,
decimal_points: Optional[int] = 4) -> pd.DataFrame:
"""Calculates performance metrics for cumulative bins of the predictions.
Args:
labels: An array of true binary labels represented... | 5,336,502 |
def rootbeta_cdf(x, alpha, beta_, a, b, bounds=(), root=2.):
"""
Calculates the cumulative density function of the log-beta distribution, i.e.::
F(z; a, b) = I_z(a, b)
where ``z=(ln(x)-ln(a))/(ln(b)-ln(a))`` and ``I_z(a, b)`` is the regularized incomplete beta function.
Parameters
... | 5,336,503 |
def get_scores(treatment, outcome, prediction, p, scoring_range=(0,1), plot_type='all'):
"""Calculate AUC scoring metrics.
Parameters
----------
treatment : array-like
outcome : array-like
prediction : array-like
p : array-like
Treatment policy (probability of treatment for each row... | 5,336,504 |
def get_arima_nemo_pipeline():
""" Function return complex pipeline with the following structure
arima \
linear
nemo |
"""
node_arima = PrimaryNode('arima')
node_nemo = PrimaryNode('exog_ts')
node_final = SecondaryNode('linear', nodes_from=[node_arima, node_nemo])
... | 5,336,505 |
def conditional_entropy(x,
y,
nan_strategy=REPLACE,
nan_replace_value=DEFAULT_REPLACE_VALUE):
"""
Calculates the conditional entropy of x given y: S(x|y)
Wikipedia: https://en.wikipedia.org/wiki/Conditional_entropy
**Returns:** floa... | 5,336,506 |
def peaks_in_time(dat, troughs=False):
"""Find indices of peaks or troughs in data.
Parameters
----------
dat : ndarray (dtype='float')
vector with the data
troughs : bool
if True, will return indices of troughs instead of peaks
Returns
-------
nadarray of i... | 5,336,507 |
def read_submod_def(line):
"""Attempt to read SUBMODULE definition line"""
submod_match = SUBMOD_REGEX.match(line)
if submod_match is None:
return None
else:
parent_name = None
name = None
trailing_line = line[submod_match.end(0):].split('!')[0]
trailing_line = tr... | 5,336,508 |
def predict(model, images, labels=None):
"""Predict.
Parameters
----------
model : tf.keras.Model
Model used to predict labels.
images : List(np.ndarray)
Images to classify.
labels : List(str)
Labels to return.
"""
if type(images) == list:
i... | 5,336,509 |
def process_span_file(doc, filename):
"""Reads event annotation from filename, and add to doc
:type filename: str
:type doc: nlplingo.text.text_theory.Document
<Event type="CloseAccount">
CloseAccount 0 230
anchor 181 187
CloseAccount/Source 165 170
CloseAccount/Source 171 175
Clos... | 5,336,510 |
def versions(output, libraries):
"""
(DEPRECATED) List installed dependencies. This is a wrapper for
`pip freeze` and will be removed in wq.core 2.0.
"""
click.echo(
"Warning: wq versions is now an alias for pip freeze",
err=True,
)
print_versions(output, libraries) | 5,336,511 |
def main(debug, env_file, no_env_files):
"""
Will assume there is a .env file in the root of the package. This is for simple development.
To use .env files as in production use the --env-file arg to specify path.
To make force the application to discard all .env files use the --no-env-files flag.
"... | 5,336,512 |
def mask_frame_around_position(
frame: np.ndarray,
position: Tuple[float, float],
radius: float = 5,
) -> np.ndarray:
"""
Create a circular mask with the given ``radius`` at the given
position and set the frame outside this mask to zero. This is
sometimes required for the ``Gaussian2D``-base... | 5,336,513 |
def label(Z, n):
"""Correctly label clusters in unsorted dendrogram."""
uf = LinkageUnionFind(n)
for i in range(n - 1):
x, y = int(Z[i, 0]), int(Z[i, 1])
x_root, y_root = uf.find(x), uf.find(y)
if x_root < y_root:
Z[i, 0], Z[i, 1] = x_root, y_root
else:... | 5,336,514 |
def apogeeid_digit(arr):
"""
NAME:
apogeeid_digit
PURPOSE:
Extract digits from apogeeid because its too painful to deal with APOGEE ID in h5py
INPUT:
arr (ndarray): apogee_id
OUTPUT:
apogee_id with digits only (ndarray)
HISTORY:
2017-Oct-26 - Written - Hen... | 5,336,515 |
def transform_user_weekly_artist_chart(chart):
"""Converts lastfm api weekly artist chart data into neo4j friendly
weekly artist chart data
Args:
chart (dict): lastfm api weekly artist chart
Returns:
list - neo4j friendly artist data
"""
chart = chart['weeklyartistchart']
a... | 5,336,516 |
def plotter(fdict):
""" Go """
pgconn = get_dbconn('isuag')
ctx = get_autoplot_context(fdict, get_description())
threshold = 50
threshold_c = temperature(threshold, 'F').value('C')
hours1 = ctx['hours1']
hours2 = ctx['hours2']
station = ctx['station']
oldstation = XREF[station]
... | 5,336,517 |
def config_namespace(config_file=None, auto_find=False,
verify=True, **cfg_options):
"""
Return configuration options as a Namespace.
.. code:: python
reusables.config_namespace(os.path.join("test", "data",
"test_config.ini"))
... | 5,336,518 |
def extract_peaks(peaks, sequences, signals, controls=None, chroms=None,
in_window=2114, out_window=1000, max_jitter=128, min_counts=None,
max_counts=None, verbose=False):
"""Extract sequences and signals at coordinates from a peak file.
This function will take in genome-wide sequences, signals, and optionally
c... | 5,336,519 |
def findfiles(which, where='.'):
"""Returns list of filenames from `where` path matched by 'which'
shell pattern. Matching is case-insensitive.
# findfiles('*.ogg')
"""
# TODO: recursive param with walk() filtering
rule = re.compile(fnmatch.translate(which), re.IGNORECASE)
fn_names = [na... | 5,336,520 |
def map_feature(value, f_type):
""" Builds the Tensorflow feature for the given feature information """
if f_type == np.dtype('object'):
return bytes_feature(value)
elif f_type == np.dtype('int'):
return int64_feature(value)
elif f_type == np.dtype('float'):
return float64_featur... | 5,336,521 |
def is_text_area(input):
"""
Template tag to check if input is file
:param input: Input field
:return: True if is file, False if not
"""
return input.field.widget.__class__.__name__ == "Textarea" | 5,336,522 |
def print_album_list(album_list):
"""Print album list and return the album name choice.
If return is all then all photos on page will be download."""
for i in range(len(album_list)):
print("{}. {} ({} photo(s))".format(
i + 1, album_list[i]['name'], album_list[i]['count']))
choice... | 5,336,523 |
def dprepb_imaging(vis_input):
"""The DPrepB/C imaging pipeline for visibility data.
Args:
vis_input (array): array of ARL visibility data and parameters.
Returns:
restored: clean image.
"""
# Load the Input Data
# ---------------------------------------------------... | 5,336,524 |
def test_change_tone(test_file, tone):
"""
Test the tone changing function.
"""
# change audio file tone
change_tone(infile=test_file, tone=tone)
# check result
fname = "%s_augmented_%s_toned.wav" % (test_file.split(".wav")[0], str(tone))
time.sleep(5)
assert_file_exists(fname) | 5,336,525 |
def request_mult(n=100, size=1024):
"""Method sends multiple TCP requests
Args:
n (int): count of requests
size (int): size
Returns:
void
"""
for i in range(n):
c = socket()
try:
c.connect(('127.0.0.1', 22))
c.sendall(('0' * size).e... | 5,336,526 |
def procure_data(args):
"""Load branches from specified file as needed to calculate
all fit and cut expressions. Then apply cuts and binning, and
return only the processed fit data."""
# look up list of all branches in the specified root file
# determine four-digit number of DRS board used
# apply shorthand (a1... | 5,336,527 |
def after_file_name(file_to_open):
"""
Given a file name return as:
[file_to_open root]_prep.[file-to_open_ending]
Parameters
----------
file_to_open : string
Name of the input file.
Returns
--------
after_file : string
Full path to the (new) file.
Examples
... | 5,336,528 |
def display_image(img):
""" Show an image with matplotlib:
Args:
Image as numpy array (H,W,3)
"""
#
# You code here
#
plt.figure()
plt.imshow(img)
plt.axis('off')
plt.show() | 5,336,529 |
def read_bool(data):
"""
Read 1 byte of data as `bool` type.
Parameters
----------
data : io.BufferedReader
File open to read in binary mode
Returns
-------
bool
True or False
"""
s_type = "=%s" % get_type("bool")
return struct.unpack(s_type, data.read(1))[0... | 5,336,530 |
def sectorize(position):
""" Returns a tuple representing the sector for the given `position`.
Parameters
----------
position : tuple of len 3
Returns
-------
sector : tuple of len 3
"""
x, y, z = normalize(position)
x, y, z = x // GameSettings.SECTOR_SIZE, y // GameSettings.S... | 5,336,531 |
def add_random_phase_shift(hkl, phases, fshifts=None):
"""
Introduce a random phase shift, at most one unit cell length along each axis.
Parameters
----------
hkl : numpy.ndarray, shape (n_refls, 3)
Miller indices
phases : numpy.ndarray, shape (n_refls,)
phase values in degr... | 5,336,532 |
def hierarchical_dataset(root, opt, select_data="/", data_type="label", mode="train"):
"""select_data='/' contains all sub-directory of root directory"""
dataset_list = []
dataset_log = f"dataset_root: {root}\t dataset: {select_data[0]}"
print(dataset_log)
dataset_log += "\n"
for dirpath, dir... | 5,336,533 |
def main() -> None:
"""Run main entrypoint."""
# Parse command line arguments
get_args()
# Ensure environment tokens are present
try:
SLACK_TOKEN = os.environ["PAGEY_SLACK_TOKEN"]
except KeyError:
print("Error, env variable 'PAGEY_SLACK_TOKEN' not set", file=sys.stderr)
... | 5,336,534 |
def save_vistrail_bundle_to_zip_xml(save_bundle, filename, vt_save_dir=None, version=None):
"""save_vistrail_bundle_to_zip_xml(save_bundle: SaveBundle, filename: str,
vt_save_dir: str, version: str)
-> (save_bundle: SaveBundle, vt_save_dir: str)
save_bundle: a SaveBundl... | 5,336,535 |
def parse_cluster_file(filename):
"""
Parse the output of the CD-HIT clustering and return a dictionnary of clusters.
In order to parse the list of cluster and sequences, we have to parse the CD-HIT
output file. Following solution is adapted from a small wrapper script
([source code on Github](... | 5,336,536 |
def app(par=None):
"""
Return the Miniweb object instance.
:param par: Dictionary with configuration parameters. (optional parameter)
:return: Miniweb object instance.
"""
return Miniweb.get_instance(par) | 5,336,537 |
def openTopics():
"""Opens topics file
:return: list of topics
"""
topicsFile = 'topics'
with open(topicsFile) as f:
topics = f.read().split()
return topics | 5,336,538 |
def fix_behaviour_widget_render_forced_renderer(utils):
"""
Restore the behaviour where the "renderer" parameter of Widget.render() may not be supported by subclasses.
"""
from django.forms.boundfield import BoundField
original_as_widget = BoundField.as_widget
def as_widget(self, widge... | 5,336,539 |
def split_blocks(blocks:List[Block], ncells_per_block:int,direction:Direction=None):
"""Split blocks is used to divide an array of blocks based on number of cells per block. This code maintains the greatest common denominator of the parent block. Number of cells per block is simply an estimate of how many you want.... | 5,336,540 |
def get_entry_details(db_path, entry_id):
"""Get all information about an entry in database.
Args:
db_path: path to database file
entry_id: string
Return:
out: dictionary
"""
s = connect_database(db_path)
# find entry
try:
sim = s.query(Main).filter(Main.... | 5,336,541 |
def pose_interp(poses, timestamps_in, timestamps_out, r_interp='slerp'):
"""
:param poses: N x 7, (t,q)
:param timestamps: (N,)
:param t: (K,)
:return: (K,)
"""
# assert t_interp in ['linear', 'spline']
assert r_interp in ['slerp', 'squad']
assert len(poses)>1
assert... | 5,336,542 |
def checklist_saved_action(report_id):
"""
View saved report
"""
report = Report.query.filter_by(id=report_id).first()
return render_template(
'checklist_saved.html',
uid=str(report.id),
save_date=datetime.now(),
report=report,
title='Отчет | %s' % TITLE
) | 5,336,543 |
def get_sensor_data():
"""Collect sensor data."""
log.debug("get_sensor_data() called")
get_seneye_data()
get_atlas_data() | 5,336,544 |
def train(train_loader, model, criterion, optimizer, epoch):
"""
One epoch's training.
:param train_loader: DataLoader for training data
:param model: model
:param criterion: content loss function (Mean Squared-Error loss)
:param optimizer: optimizer
:param epoch: epoch number
"""
m... | 5,336,545 |
def annotate_plot(fig, domain, outcome, metric):
"""Adds x/y labels and suptitles."""
fig.supxlabel('Epoch')
fig.supylabel(METRIC_FULL_NAME[metric], x=0)
fig.suptitle(f'Continual Learning model comparison \n'
f'Outcome: {outcome} | Domain Increment: {domain}', y=1.1) | 5,336,546 |
def test_default_transfer_syntaxes():
"""Test that the default transfer syntaxes are correct."""
assert len(DEFAULT_TRANSFER_SYNTAXES) == 4
assert "1.2.840.10008.1.2" in DEFAULT_TRANSFER_SYNTAXES
assert "1.2.840.10008.1.2.1" in DEFAULT_TRANSFER_SYNTAXES
assert "1.2.840.10008.1.2.1.99" in DEFAULT_TRA... | 5,336,547 |
def plot_histogram(
args: SharedArgs,
vector: torch.Tensor,
step: int,
prefix: str = "train",
cols: int = 3,
rows: int = 6,
bins: int = 30,
):
"""Plot a histogram over the batch"""
vector = torch.flatten(vector, start_dim=1).detach().cpu()
vector_np = vector.numpy()
matplotli... | 5,336,548 |
def trilinear_memory_efficient(a, b, d, use_activation=False):
"""W1a + W2b + aW3b."""
n = tf.shape(a)[0]
len_a = tf.shape(a)[1]
len_b = tf.shape(b)[1]
w1 = tf.get_variable('w1', shape=[d, 1], dtype=tf.float32)
w2 = tf.get_variable('w2', shape=[d, 1], dtype=tf.float32)
w3 = tf.get_variable('w3', shape=[... | 5,336,549 |
def private_questions_get_unique_code(assignment_id: str):
"""
Get all questions for the given assignment.
:param assignment_id:
:return:
"""
# Try to find assignment
assignment: Assignment = Assignment.query.filter(
Assignment.id == assignment_id
).first()
# Verify that t... | 5,336,550 |
def make_ngram(tokenised_corpus, n_gram=2, threshold=10):
"""Extract bigrams from tokenised corpus
Args:
tokenised_corpus (list): List of tokenised corpus
n_gram (int): maximum length of n-grams. Defaults to 2 (bigrams)
threshold (int): min number of n-gram occurrences before inclusion
... | 5,336,551 |
def bw_estimate(samples):
"""Computes Abraham's bandwidth heuristic."""
sigma = np.std(samples)
cand = ((4 * sigma**5.0) / (3.0 * len(samples)))**(1.0 / 5.0)
if cand < 1e-7:
return 1.0
return cand | 5,336,552 |
def process_coins():
"""calculate the amount of money paid based on the coins entered"""
number_of_quarters = int(input("How many quarters? "))
number_of_dimes = int(input("How many dimes? "))
number_of_nickels = int(input("How many nickels? "))
number_of_pennies = int(input("How many pennies? "))
... | 5,336,553 |
def predict_Seq2Seq(training_args, name, model, dataset, tokenizer, data_collator, compute_metrics):
"""
"""
trainer = Seq2SeqTrainer(
model=model,
args=training_args,
tokenizer=tokenizer,
data_collator=data_collator,
compute_metrics=compute_metrics
)
pr... | 5,336,554 |
def test_expand_single_quoted_symbol():
"""TEST 1.12: Quoting is a shorthand syntax for calling the `quote` form.
Examples:
'foo -> (quote foo)
'(foo bar) -> (quote (foo bar))
"""
assert_equals(["foo", ["quote", "nil"]], parse("(foo 'nil)")) | 5,336,555 |
def getLastSegyTraceHeader(SH,THN='cdp',data='none', bheadSize = 3600, endian='>'): # added by A Squelch
"""
getLastSegyTraceHeader(SH,TraceHeaderName)
"""
bps=getBytePerSample(SH)
if (data=='none'):
data = open(SH["filename"]).read()
#... | 5,336,556 |
def get_data_url(data_type):
"""Gets the latest url from the kff's github data repo for the given data type
data_type: string value representing which url to get from the github api; must be either 'pct_total' or 'pct_share'
"""
data_types_to_strings = {
'pct_total': 'Percent of Total Populatio... | 5,336,557 |
def kl(p, q):
"""Kullback-Leibler divergence D(P || Q) for discrete distributions
Parameters
----------
p, q : array-like, dtype=float, shape=n
Discrete probability distributions.
"""
p = np.asarray(p, dtype=np.float)
q = np.asarray(q, dtype=np.float)
return np.sum(np.wher... | 5,336,558 |
def get_loaders(opt):
""" Make dataloaders for train and validation sets
"""
# train loader
opt.mean = get_mean(opt.norm_value, dataset=opt.mean_dataset)
# opt.std = get_std()
if opt.no_mean_norm and not opt.std_norm:
norm_method = transforms.Normalize([0, 0, 0], [1, 1, 1])
elif not opt.std_norm:
norm_method... | 5,336,559 |
def trapezoidal(f, a, b, n):
"""Trapezoidal integration via iteration."""
h = (b-a)/float(n)
I = f(a) + f(b)
for k in xrange(1, n, 1):
x = a + k*h
I += 2*f(x)
I *= h/2
return I | 5,336,560 |
def writetree(tree, sent, key, fmt, comment=None, morphology=None,
sentid=False):
"""Convert a tree to a string representation in the given treebank format.
:param tree: should have indices as terminals
:param sent: contains the words corresponding to the indices in ``tree``
:param key: an identifier for this tr... | 5,336,561 |
def xor_string(hash1, hash2, hash_size):
"""Encrypt/Decrypt function used for password encryption in
authentication, using a simple XOR.
Args:
hash1 (str): The first hash.
hash2 (str): The second hash.
Returns:
str: A string with the xor applied.
"""
xored = [h1 ^ h2 fo... | 5,336,562 |
def test_gas_generic(dev, apdev):
"""Generic GAS query"""
bssid = apdev[0]['bssid']
params = hs20_ap_params()
params['hessid'] = bssid
hostapd.add_ap(apdev[0]['ifname'], params)
dev[0].scan()
req = dev[0].request("GAS_REQUEST " + bssid + " 00 000102000101")
if "FAIL" in req:
rai... | 5,336,563 |
def test_prod_create(
testing_opentrons_emulation_configuration: OpentronsEmulationConfiguration,
prod_create_virtual_machine_cmd: List[str],
) -> None:
"""Confirm that prod virtual-machine is created correctly."""
cmds = (
TopLevelParser(testing_opentrons_emulation_configuration)
.parse... | 5,336,564 |
def create_secret_key(string):
"""
:param string: A string that will be returned as a md5 hash/hexdigest.
:return: the hexdigest (hash) of the string.
"""
h = md5()
h.update(string.encode('utf-8'))
return h.hexdigest() | 5,336,565 |
def _maybe_echo_status_and_message(request, servicer_context):
"""Sets the response context code and details if the request asks for them"""
if request.HasField("response_status"):
servicer_context.set_code(request.response_status.code)
servicer_context.set_details(request.response_status.messag... | 5,336,566 |
def decode_password(base64_string: str) -> str:
"""
Decode a base64 encoded string.
Args:
base64_string: str
The base64 encoded string.
Returns:
str
The decoded string.
"""
base64_bytes = base64_string.encode("ascii")
sample_string_bytes = bas... | 5,336,567 |
def test_consistency(hr_name, sample):
"""
Check that the result of loading a *_hr.dat file and converting it
back to that format creates a result that is consistent with the
original file.
"""
hr_file = sample(hr_name)
model = tbmodels.Model.from_wannier_files(hr_file=hr_file, occ=28, spars... | 5,336,568 |
def specific_temperature(battery):
"""
@brief generate list of temperature values based on battery object
@param battery : battery object with module voltages
"""
global temperature_values
temperature_values = [(int(module.temperatures_cel[0] * 1000),
int(module.tempe... | 5,336,569 |
def _generate_overpass_api(endpoint=None):
""" Create and initialise the Overpass API object.
Passing the endpoint argument will override the default
endpoint URL.
"""
# Create API object with default settings
api = overpass.API()
# Change endpoint if desired
if endpoint is not None:
... | 5,336,570 |
def train(train_loader, model,
proxies, criterion, optimizer, epoch, scheduler):
"""Training loop for one epoch"""
batch_time = AverageMeter()
data_time = AverageMeter()
val_loss = AverageMeter()
val_acc = AverageMeter()
# switch to train mode
model.train()
end = time.time()... | 5,336,571 |
def to_pascal_case(value):
"""
Converts the value string to PascalCase.
:param value: The value that needs to be converted.
:type value: str
:return: The value in PascalCase.
:rtype: str
"""
return "".join(character for character in value.title() if not character.isspace()) | 5,336,572 |
def drop(n: int, it: Iterable[Any]) -> List[Any]:
"""
Return a list of N elements drop from the iterable object
Args:
n: Number to drop from the top
it: Iterable object
Examples:
>>> fpsm.drop(3, [1, 2, 3, 4, 5])
[4, 5]
"""
return list(it)[n:] | 5,336,573 |
def kill_services():
"""On 10.12, both the locationd and cfprefsd services like to not respect
preference changes so we force them to reload."""
proc = subprocess.Popen(['/usr/bin/killall', '-9', 'cfprefsd'],
stdout=subprocess.PIPE,
stderr=subprocess.P... | 5,336,574 |
def _ci_configure_impl(repository_ctx):
"""This repository rule tells other rules whether we're running in CI.
Other rules can use this knowledge to make decisions about enforcing certain
things on buildkite while relaxing restrictions during local development.
"""
running_in_ci = repository_ctx.os... | 5,336,575 |
def test_bool_int_value_info(tests_path, json_filename):
"""
Check consistency of boolean and integer info in JSON parameter files.
"""
path = os.path.join(tests_path, '..', json_filename)
with open(path, 'r') as pfile:
pdict = json.load(pfile)
maxint = np.iinfo(np.int16).max
for par... | 5,336,576 |
def generate_classification_style_dataset(classification='multiclass'):
"""
Dummy data to test models
"""
x_data = np.array([
[1,1,1,0,0,0],
[1,0,1,0,0,0],
[1,1,1,0,0,0],
[0,0,1,1,1,0],
[0,0,1,1,0,0],
[0,0,1,1,1,0]])
if classification=='multiclass':
y_data = np.array([
[1, 0, 0],
[1, 0, 0],
... | 5,336,577 |
def c2_get_platform_current_status_display(reference_designator):
"""
Get C2 platform Current Status tab contents, return current_status_display.
Was: #status = _c2_get_instrument_driver_status(instrument['reference_designator'])
"""
start = dt.datetime.now()
timing = False
contents = []
... | 5,336,578 |
def getSupportedDatatypes():
"""
Gets the datatypes that are supported by the framework
Returns:
a list of strings of supported datatypes
"""
return router.getSupportedDatatypes() | 5,336,579 |
def run_stacking(named_data, subjects_data, cv=10, alphas=None,
train_sizes=None, n_jobs=None):
"""Run stacking.
Parameters
----------
named_data : list(tuple(str, pandas.DataFrame))
List of tuples (name, data) with name and corresponding features
to be used for predict... | 5,336,580 |
def add_random_shadow(img, w_low=0.6, w_high=0.85):
"""
Overlays supplied image with a random shadow poligon
The weight range (i.e. darkness) of the shadow can be configured via the interval [w_low, w_high)
"""
cols, rows = (img.shape[0], img.shape[1])
top_y = np.random.random_sample() * rows
... | 5,336,581 |
def csv_args(value):
"""Parse a CSV string into a Python list of strings.
Used in command line parsing."""
return map(str, value.split(",")) | 5,336,582 |
def sync_dashboards(app=None):
"""Import, overwrite fixtures from `[app]/fixtures`"""
if not cint(frappe.db.get_single_value('System Settings', 'setup_complete')):
return
if app:
apps = [app]
else:
apps = frappe.get_installed_apps()
for app_name in apps:
print("Updating Dashboard for {app}".format(app=app... | 5,336,583 |
def get_tokens():
"""
Returns a tuple of tokens in the format {{site/property}} that will be used to build the dictionary passed into execute
"""
return (HAWQMASTER_PORT, HAWQSTANDBY_ADDRESS) | 5,336,584 |
def projl1_epigraph(center):
"""
Project center=proxq.true_center onto the l1 epigraph. The bound term is
center[0], the coef term is center[1:]
The l1 epigraph is the collection of points $(u,v): \|v\|_1 \leq u$
np.fabs(coef).sum() <= bound.
"""
norm = center[0]
coef = center[1:]
... | 5,336,585 |
def crypto_command(text):
""" <ticker> -- Returns current value of a cryptocurrency """
try:
encoded = quote_plus(text)
request = requests.get(API_URL.format(encoded))
request.raise_for_status()
except (requests.exceptions.HTTPError, requests.exceptions.ConnectionError) as e:
... | 5,336,586 |
def ListELB(region, node_types=None):
"""Print load balancer configuration in this region. If 'node_types' is not None, only return the corresponding
load balancers.
"""
elbs = GetLoadBalancers(region, node_types)
for l in elbs:
zone_count = {z:0 for z in l.availability_zones}
instances = ListInstance... | 5,336,587 |
def byol_loss_multi_views_func(p: torch.Tensor, z: torch.Tensor,p1: torch.Tensor, z1: torch.Tensor, simplified: bool = True) -> torch.Tensor:
"""Computes BYOL's loss given batch of predicted features p and projected momentum features z.
Args:
p, p1 (torch.Tensor): NxD Tensor containing predicted featur... | 5,336,588 |
def a_test_model(n_classes=2):
"""
recover model and test data from disk, and test the model
"""
images_test, labels_test, data_num_test = load_test_data_full()
model = load_model(BASE_PATH + 'models/Inception_hemorrhage_model.hdf5')
adam_optimizer = keras.optimizers.Adam(
lr=0.0001,
... | 5,336,589 |
def generate_synchronous_trajectory(initial_state):
"""
Simulate the network starting from a given initial state in the synchronous strategy
:param initial_state: initial state of the network
:return: a trajectory in matrix from, where each row denotes a state
"""
trajectory = [initial_state]
... | 5,336,590 |
def _add_remove_peaks(axis, add_peak):
"""
Gives options to add, edit, or remove peaks and peak markers on the figure.
Parameters
----------
axis : plt.Axes
The axis to add or remove peaks from. Contains all of the
peaks information within axis.lines. Each line for a peak
ha... | 5,336,591 |
def arg_names(level=2):
"""Try to determine names of the variables given as arguments to the caller
of the caller. This works only for trivial function invocations. Otherwise
either results may be corrupted or exception will be raised.
level: 0 is current frame, 1 is the caller, 2 is caller of the call... | 5,336,592 |
def check_cuda():
""" Check Cuda for Linux or Windows """
if OS_VERSION[0] == "Linux":
check_cuda_linux()
elif OS_VERSION[0] == "Windows":
check_cuda_windows() | 5,336,593 |
def test_good_values(capsys, threads):
"""Test for valid values."""
config_expected = dict(
flac_bin='/bin/bash',
lame_bin='/bin/bash',
ignore_art=False,
ignore_lyrics=False,
threads=threads,
flac_dir='/tmp',
mp3_dir='/tmp',
quiet=False,
)
... | 5,336,594 |
def test_expose_header_return_header_true(client, monkeypatch, mock_uuid):
"""
Tests that it does return the Access-Control-Allow-Origin when EXPOSE_HEADER is set to True
and RETURN_HEADER is True
"""
from django_guid.config import settings as guid_settings
monkeypatch.setattr(guid_settings, 'E... | 5,336,595 |
def render_template(path, ctx):
"""Render a Jinja2 template"""
with path.open() as f:
content = f.read()
tmpl = jinja2.Template(content)
return html_minify(tmpl.render(**ctx)) | 5,336,596 |
def define_visualizations():
"""Unfortunately, these mappings are defined in the database, when they probably
should be defined in code. This routine pre-populates the database with the expected
visualizations."""
norm = HtmlVisualizationFormat()
norm.slug = "norm"
norm.button_title = "normaliz... | 5,336,597 |
def linux_compute_tile_singlecore(optimsoc_buildroot):
"""
Module-scoped fixture: build a Linux image for a single-core compute tile
"""
# Get the buildroot base directory from the optimsoc_buildroot() fixture.
# Note that this directory is cached between pytest runs. Make sure the
# commands e... | 5,336,598 |
def reverse( sequence ):
"""Return the reverse of any sequence
"""
return sequence[::-1] | 5,336,599 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.