content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def add_units_to_query(df, udict=None):
"""
"""
for k, u in udict.items():
if k not in df.colnames:
continue
try:
df[k].unit
except Exception as e:
print(e)
setattr(df[k], 'unit', u)
else:
df[k] *= u / df[k].unit # ... | 5,344,600 |
def update_lr(it_lr, alg, test_losses, lr_info=None):
"""Update learning rate according to an algorithm."""
if lr_info is None:
lr_info = {}
if alg == 'seung':
threshold = 10
if 'change' not in lr_info.keys():
lr_info['change'] = 0
if lr_info['change'] >= 4:
... | 5,344,601 |
def ocr_page_image(
doc_path,
page_num,
lang,
**kwargs
):
"""
image = jpg, jpeg, png
On success returns ``mglib.path.PagePath`` instance.
"""
logger.debug("OCR image (jpeg, jpg, png) document")
page_path = PagePath(
document_path=doc_path,
page_num=page_num,
... | 5,344,602 |
def factors(n):
"""
return set of divisors of a number
"""
step = 2 if n%2 else 1
return set(reduce(list.__add__,
([i, n//i] for i in range(1, int(sqrt(n))+1, step) if n % i == 0))) | 5,344,603 |
def round_decimal(x, digits=0):
"""This function returns the round up float.
Parameters
----------
x : a float
digits : decimal point
Returns
----------
Rounded up float
"""
x = decimal.Decimal(str(x))
if digits == 0:
return int(x.quantize(decima... | 5,344,604 |
def basic_gn_stem(model, data, **kwargs):
"""Add a basic ResNet stem (using GN)"""
dim = 64
p = model.ConvGN(
data, 'conv1', 3, dim, 7, group_gn=get_group_gn(dim), pad=3, stride=2
)
p = model.Relu(p, p)
p = model.MaxPool(p, 'pool1', kernel=3, pad=1, stride=2)
return p, dim | 5,344,605 |
def log_scale(start,end,num):
"""Simple wrapper to generate list of numbers equally spaced in logspace
Parameters
----------
start: floar
Inital number
end: Float
Final number
num: Float
Number of number in the list
Returns
-------
list: 1d arr... | 5,344,606 |
def test_all_nodes_masters():
"""
Set a list of nodes with random masters/slaves config and it shold be possible
to itterate over all of them.
"""
n = NodeManager(startup_nodes=[{"host": "127.0.0.1", "port": 7000}, {"host": "127.0.0.1", "port": 7001}])
n.initialize()
nodes = [node for node ... | 5,344,607 |
def init_test_subdirs(test_name):
"""Create all necessary test sub-directories if they don't already exist"""
dirs_to_create = ['input', 'logs', 'output', 'src', 'test_files', 'work']
for dd in dirs_to_create:
adir = TEST+"tests/"+test_name+'/'+dd
if not os.path.exists(adir):
os... | 5,344,608 |
def measure_xtran_params(neutral_point, transformation):
"""
Description: Assume that the transformation from robot coord to camera coord is: RotX -> RotY -> RotZ -> Tranl
In this case: RotX = 180, RotY = 0; RotZ = -90; Tranl: unknown
But we know coords of a determined neutral ... | 5,344,609 |
def getPrefix(routetbl, peer_logical):
""" FUNCTION TO GET THE PREFIX """
for route in routetbl:
if route.via == peer_logical:
return route.name
else:
pass | 5,344,610 |
def Logger_log(level, msg):
"""
Logger.log(level, msg)
logs a message to the log.
:param int level: the level to log at.
:param str msg: the message to log.
"""
return _roadrunner.Logger_log(level, msg) | 5,344,611 |
def setup(bot):
"""Entry point for loading cogs. Required for all cogs"""
bot.add_cog(ConnectFour(bot)) | 5,344,612 |
def p4_system(cmd):
"""Specifically invoke p4 as the system command. """
real_cmd = p4_build_cmd(cmd)
expand = not isinstance(real_cmd, list)
retcode = subprocess.call(real_cmd, shell=expand)
if retcode:
raise CalledProcessError(retcode, real_cmd) | 5,344,613 |
def obj_test(**field_tests: typing.Callable[[typing.Any], bool]) -> typing.Callable[[typing.Any], bool]:
"""Return a lambda that tests for dict with string keys and a particular type for each key"""
def test(dat: typing.Any) -> bool:
type_test(dict)(dat)
dom_test = type_test(str)
for do... | 5,344,614 |
def dump_yaml(file_path, data):
""" Writes data to a YAML file and replaces its contents"""
with open(file_path, 'w+') as usernames_yaml:
yaml.dump(data, usernames_yaml) | 5,344,615 |
def hist2D(x, y, xbins, ybins, **kwargs):
""" Create a 2 dimensional pdf vias numpy histogram2d"""
H, xedg, yedg = np.histogram2d(x=x, y=y, bins=[xbins,ybins], density=True, **kwargs)
xcen = (xedg[:-1] + xedg[1:]) / 2
ycen = (yedg[:-1] + yedg[1:]) / 2
return xcen, ycen, H | 5,344,616 |
def generate_ngram_dict(filename, tuple_length):
"""Generate a dict with ngrams as key following words as value
:param filename: Filename to read from.
:param tuple_length: The length of the ngram keys
:return: Dict of the form {ngram: [next_words], ... }
"""
def file_words(file_pointer):
... | 5,344,617 |
def pytest_addoption(parser):
"""Add pytest-bdd options."""
add_bdd_ini(parser)
cucumber_json.add_options(parser)
generation.add_options(parser)
gherkin_terminal_reporter.add_options(parser) | 5,344,618 |
def get_end_point(centerline, offset=0):
"""
Get last point(s) of the centerline(s)
Args:
centerline (vtkPolyData): Centerline(s)
offset (int): Number of points from the end point to be selected
Returns:
centerline_end_point (vtkPoint): Point corresponding to end of centerline.... | 5,344,619 |
def set_env_vars(args):
"""
From the user's input, set the right environmental
variables to run the container.
"""
# Get the parameters from the command line.
reference_data_path = args.reference_data_path
test_data_path = args.test_data_path
results_dir = args.results_dir
# If they... | 5,344,620 |
def gen_group_tests(mod_name):
"""mod_name is the back-end script name without the.py extension.
There must be a gen_test_cases() function in each module."""
mod = importlib.import_module(mod_name)
mod.gen_test_cases() | 5,344,621 |
def test_MultiLocus_offsets_even_inverted():
"""Offsets are assigned to the nearest locus."""
multi_locus = MultiLocus([(1, 3), (7, 9)], True)
invariant(
multi_locus.to_position, 5, multi_locus.to_coordinate, (1, 2, 0))
invariant(
multi_locus.to_position, 4, multi_locus.to_coordinate, (... | 5,344,622 |
def test_custom_name(name, container, expected):
"""
When name or container arguments are given, builder should use them to
greet.
"""
builder = HelloHTML(name=name, container=container)
assert builder.greet() == expected | 5,344,623 |
def random_train_test_split(df, train_frac, random_seed=None):
"""
This function randomizes the dta based on the seed and then splits the dataframe into train and test sets which are changed to their list of vector representations.
Args:
df (Dataframe): The dataframe which is to be used to generate... | 5,344,624 |
def test_parser_record_str_input(change_dir, clean_output):
"""Verify the hook call works successfully."""
o2 = tackle(
'.',
no_input=True,
record=clean_output,
)
with open(clean_output) as f:
record_output = yaml.load(f)
assert 'stuff' in o2
assert 'stuff' in r... | 5,344,625 |
def calc_XY_pixelpositions(calibration_parameters, DATA_Q, nspots, UBmatrix=None,
B0matrix=IDENTITYMATRIX,
offset=0,
pureRotation=0,
... | 5,344,626 |
def check_tx_trytes_length(trytes):
"""
Checks if trytes are exactly one transaction in length.
"""
if len(trytes) != TransactionTrytes.LEN:
raise with_context(
exc=ValueError('Trytes must be {len} trytes long.'.format(
len= TransactionTrytes.LEN
)),
... | 5,344,627 |
def load_csv(path):
"""
Function for importing data from csv. Function uses weka implementation
of CSVLoader.
:param path: input file
:return: weka arff data
"""
args, _sufix = csv_loader_parser()
loader = Loader(classname='weka.core.converters.CSVLoader',
options=ar... | 5,344,628 |
def from_stream(stream, storage, form):
"""Reverses to_stream, returning data"""
if storage == "pure-plain":
assert isinstance(stream, str)
if isinstance(stream, str):
txt = stream
else:
assert not stream.startswith(MAGIC_SEAMLESS)
assert not stream.st... | 5,344,629 |
def draw_random_graph(i):
"""
Draw a random graph with 2**i nodes,
and p=i/(2**i)
"""
g_random = nx.gnp_random_graph(2**i,2*i/(2**i))
nx.draw(g_random,node_size=20)
plt.savefig("./random_graph.svg")
plt.close()
# plt.show() | 5,344,630 |
def volume100():
"""Function for setting volume."""
os.system('vol 100')
return render_template('fmberryremote.html', GENRES=GENRES, choosenStation=STATION) | 5,344,631 |
def UniformExploration(j, state):
"""Fake player j that always targets all arms."""
return list(np.arange(state.K)) | 5,344,632 |
def deduction_limits(data):
"""
Apply limits on itemized deductions
"""
# Split charitable contributions into cash and non-cash using ratio in PUF
cash = 0.82013
non_cash = 1. - cash
data['e19800'] = data['CHARITABLE'] * cash
data['e20100'] = data['CHARITABLE'] * non_cash
# Apply st... | 5,344,633 |
def get_args() -> argparse.Namespace:
"""Setup the argument parser
Returns:
argparse.Namespace:
"""
parser = argparse.ArgumentParser(
description='A template for python projects.',
add_help=False)
# Required Args
required_args = parser.add_argument_group('Required Argume... | 5,344,634 |
def cli(source, destination, fm_type, root, directives):
"""A flavor-agnostic extension framework for Markdown.
Reads from <SOURCE> and writes to <DESTINATION>.
If <SOURCE> is a single file, it will be converted to Markdown and written
to <DESTINATION> (default: stdout).
If <SOURCE> is a director... | 5,344,635 |
def select_interacting(num_mtx, bin_mtx, labels):
"""
Auxiliary function for fit_msa_mdels.
Used for fitting the models in hard EM; selects observations with a hidden
variable value of 1.
"""
if labels is None:
# This is the case when initializing the models
return num_mtx, bin_m... | 5,344,636 |
def _GenDiscoveryDoc(service_class_names, doc_format,
output_path, hostname=None,
application_path=None):
"""Write discovery documents generated from a cloud service to file.
Args:
service_class_names: A list of fully qualified ProtoRPC service names.
doc_format: T... | 5,344,637 |
def after_all(context):
"""
Closing the driver
:param context:
:return:
"""
context.driver.quit() | 5,344,638 |
def nitestr(nite,sep=''):
"""
Convert an ephem.Date object to a nite string.
Parameters:
-----------
nite : ephem.Date object
sep : Output separator
Returns:
--------
nitestr : String representation of the nite
"""
import dateutil.parser
if isinstance(nite,bas... | 5,344,639 |
def passrotPat():
"""Test passive rotation of a pattern. There are two sub-requests possible
and two input configs: full 3D output of 2D-cuts with input, single-pol
pattern or dual-pol.
"""
def doTrack():
#(thetas, phis) = pntsonsphere.cut_az(0.*math.pi/2) #Good for some tests.
(thet... | 5,344,640 |
def register():
"""Register user"""
form = RegistrationForm()
if form.validate_on_submit():
# only allow 1 user on locally hosted version
if len(User.query.all()) == 0:
# add user to database
hashed_password = bcrypt.generate_password_hash(form.password.data).decode('utf-8')
user = User(username=form.... | 5,344,641 |
def test_black_tool_plugin_parse_invalid():
"""Verify that we can parse the normal output of black."""
btp = setup_black_tool_plugin()
output = "invalid text"
issues = btp.parse_output(output)
assert not issues | 5,344,642 |
def dump_tuple(tup):
"""
Dump a tuple to a string of fg,bg,attr (optional)
"""
return ','.join(str(i) for i in tup) | 5,344,643 |
def test_tas_account_filter_later_qtr_award_financial():
""" Ensure the fiscal year and quarter filter is working, later quarter - award_financial"""
# Create FederalAccount models
fed_acct1 = mommy.make("accounts.FederalAccount")
fed_acct2 = mommy.make("accounts.FederalAccount")
# Create Program A... | 5,344,644 |
def get_single_endpoint(name):
"""
TODO - Add docstring
"""
class EndpointWithID(Resource):
def get(self, pid):
# TODO - Add return
pass
# TODO - Add `get.__doc__`
EndpointWithID.__name__ = name
return EndpointWithID | 5,344,645 |
def generate_fermi_question(cfg, logratio, filter_single_number_lhs=True):
"""
Generates one Fermi question.
Args:
cfg: Expression config
logratio: Log ratio standard deviation (for RHS)
filter_single_number_lhs: Whether to exclude lhs of a single numerical term
round_bound:... | 5,344,646 |
def build_dataset(cfg, default_args=None):
"""Build a dataset from config dict.
Args:
cfg (dict): Config dict. It should at least contain the key "type".
default_args (dict | None, optional): Default initialization arguments.
Default: None.
Returns:
Dataset: The constru... | 5,344,647 |
def Packet_genReadUserTag(errorDetectionMode, buffer, size):
"""Packet_genReadUserTag(vn::protocol::uart::ErrorDetectionMode errorDetectionMode, char * buffer, size_t size) -> size_t"""
return _libvncxx.Packet_genReadUserTag(errorDetectionMode, buffer, size) | 5,344,648 |
def prefetch(tensor_dict, capacity):
"""Creates a prefetch queue for tensors.
Creates a FIFO queue to asynchronously enqueue tensor_dicts and returns a
dequeue op that evaluates to a tensor_dict. This function is useful in
prefetching preprocessed tensors so that the data is readily available for
consumers.
... | 5,344,649 |
def get_total_shares():
"""
Returns a list of total shares (all, attending, in person, represented) for all voting principles.
"""
total_shares = {
'heads': [0, 0, 0, 0] # [all, attending, in person, represented]
}
principle_ids = VotingPrinciple.objects.values_list('id', flat=True)
... | 5,344,650 |
def test_multi_cpu_sample_splitting(data_input, models_from_data, num_cpus):
"""
Tests simulator's _determine_num_cpu_samples() by ensuring that all samples
will be used and that the difference in number of samples between processes
is never greater than one.
"""
total_samples = 100
sample_... | 5,344,651 |
def base_test_version(dl_class):
"""
Args:
dl_class (type): subclass of Dataloader.
"""
if isinstance(dl_class, str):
dl_class = Dataloader.load_class(dl_class)
assert hasattr(dl_class, '_version')
version = dl_class._version
version_path = str(version_dir / '{}_v{}.jsonl'.format(dl_class.__name__, version)... | 5,344,652 |
def gen_check_box_idx():
""" Generate a list containing the coordinate of three
finder patterns in QR-code
Args:
None
Returns:
idx_check_box: a list containing the coordinate each pixel
of the three finder patterns
"""
idx_check_box = []
for i in range(7... | 5,344,653 |
async def test_template_with_unavailable_entities(hass, states, start_ha):
"""Test unavailability with value_template."""
_verify(hass, states[0], states[1], states[2], states[3], states[4], None) | 5,344,654 |
def preprocess_mc_parameters(n_rv, dict_safir_file_param, index_column='index'):
"""
NAME: preprocess_mc_parameters
AUTHOR: Ian Fu
DATE: 18 Oct 2018
DESCRIPTION:
Takes a dictionary object with each item represents a safir input variable, distributed or static, distributed
input parameter mus... | 5,344,655 |
def test_no_existing_transaction(session):
"""Assert that the payment is saved to the table."""
payment_account = factory_payment_account()
payment_account.save()
invoice = factory_invoice(payment_account)
invoice.save()
factory_invoice_reference(invoice.id).save()
fee_schedule = FeeSchedule... | 5,344,656 |
def AdjustColour(color, percent, alpha=wx.ALPHA_OPAQUE):
""" Brighten/Darken input colour by percent and adjust alpha
channel if needed. Returns the modified color.
@param color: color object to adjust
@param percent: percent to adjust +(brighten) or -(darken)
@keyword alpha: amount to adjust alpha ... | 5,344,657 |
def db_fill_tables(source_path: str, models: list = export_models_ac) -> None:
"""
Consecutively execute converters and send data to the database
! The execution order is important for at least the following data types:
Type -> Word -> Definition,
because the conversion of definitions depends on... | 5,344,658 |
def getdates(startdate, utc_to_local, enddate=None):
"""
Generate '~astropy.tot_time.Time' objects corresponding to 16:00:00 local tot_time on evenings of first and last
nights of scheduling period.
Parameters
----------
startdate : str or None
Start date (eg. 'YYYY-MM-DD'). If None, de... | 5,344,659 |
def resolve_fix_versions(
service: VulnerabilityService,
result: Dict[Dependency, List[VulnerabilityResult]],
state: AuditState = AuditState(),
) -> Iterator[FixVersion]:
"""
Resolves a mapping of dependencies to known vulnerabilities to a series of fix versions without
known vulnerabilties.
... | 5,344,660 |
def alerts_matcher(base_name, pattern, alerter, second_order_resolution_hours):
"""
Get a list of all the metrics that would match an ALERTS pattern
:param base_name: The metric name
:param pattern: the ALERT pattern
:param alerter: the alerter name e.g. smtp, syslog, hipchat, pagerdaty
:param... | 5,344,661 |
def multitask_bed_generation(
target_beds_file,
feature_size=1000,
merge_overlap=200,
out_prefix="features",
chrom_lengths_file=None,
db_act_file=None,
db_bed=None,
ignore_auxiliary=False,
no_db_activity=False,
ignore_y=False,
):
"""Merge multiple bed files to select sample s... | 5,344,662 |
def get_dataframe_tail(n):
""" Returns last n rows of the DataFrame"""
return dataset.tail(n) | 5,344,663 |
def json_formatter(result, verbose=False, indent=4, offset=0):
"""Format result as json."""
string = json.dumps(result, indent=indent)
string = string.replace("\n", "\n" + " "*offset)
return string | 5,344,664 |
def run_test():
"""
Test run for checking a dataset.
"""
load_data() | 5,344,665 |
def delete_dkim(_domaine):
""" Generate DKIM"""
cmd_dkim = "/opt/zimbra/libexec/zmdkimkeyutil -r -d " + _domaine
try:
print(os.system(cmd_dkim))
print("\n[ok] Delete DKIM\n")
except os.error as e:
print(e) | 5,344,666 |
def rem():
"""Removes an item of arbitrary depth from the stack"""
try:
x = stack.pop()
del( stack[ int( x ) ] )
except:
print "Error: stack underflow!" | 5,344,667 |
def simple_http_get(url, port=80, headers=None):
"""Simple interface to make an HTTP GET request
Return the entire request (line,headers,body) as raw bytes
"""
client_socket = create_async_client_socket((url, port))
calling_session = Reactor.get_instance().get_current_session()
@types.corou... | 5,344,668 |
def _gumbel_softmax_sample(logits, temp=1, eps=1e-20):
"""
Draw a sample from the Gumbel-Softmax distribution
based on
https://github.com/ericjang/gumbel-softmax/blob/3c8584924603869e90ca74ac20a6a03d99a91ef9/Categorical%20VAE.ipynb
(MIT license)
"""
dims = logits.dim()
gumbel_noise = _sa... | 5,344,669 |
def test_cell_response(tmpdir):
"""Test CellResponse object."""
# Round-trip test
spike_times = [[2.3456, 7.89], [4.2812, 93.2]]
spike_gids = [[1, 3], [5, 7]]
spike_types = [['L2_pyramidal', 'L2_basket'],
['L5_pyramidal', 'L5_basket']]
tstart, tstop, fs = 0.1, 98.4, 1000.
... | 5,344,670 |
def interpolate_points(variable, variable_name, old_r, old_theta, new_r, new_theta):
"""Interpolate the old grid onto the new grid."""
grid = griddata(
(old_r, old_theta), variable, (new_r, new_theta), method=INTERPOLATION_LEVEL, fill_value=-1
)
n_error = 0
for i, element in enumerate(grid... | 5,344,671 |
def attitude(request):
"""
View configuration for discussion step, where we will ask the user for her attitude towards a statement.
Route: /discuss/{slug}/attitude/{position_id}
:param request: request of the web server
:return: dictionary
"""
LOG.debug("View attitude: %s", request.matchdic... | 5,344,672 |
def currentProgram():
"""currentProgram page."""
return render_template(
"currentProgram-index.j2.html",
title="currentProgram",
subtitle="Demonstration of Flask blueprints in action.",
template="currentProgram-template",
currentProgram=getCurrentProgr(),
timeStar... | 5,344,673 |
def checkIsMember(request):
"""
์ฌ์
์๋ฒํธ๋ฅผ ์กฐํํ์ฌ ์ฐ๋ํ์ ๊ฐ์
์ฌ๋ถ๋ฅผ ํ์ธํฉ๋๋ค.
- https://docs.popbill.com/statement/python/api#CheckIsMember
"""
try:
# ์กฐํํ ์ฌ์
์๋ฑ๋ก๋ฒํธ, '-' ์ ์ธ 10์๋ฆฌ
targetCorpNum = "1234567890"
response = statementService.checkIsMember(targetCorpNum)
return render(reques... | 5,344,674 |
def f1_score(y_true: List[List[str]], y_pred: List[List[str]],
*,
average: Optional[str] = 'micro',
suffix: bool = False,
mode: Optional[str] = None,
sample_weight: Optional[List[int]] = None,
zero_division: str = 'warn',
scheme:... | 5,344,675 |
def test_txt_to_triplets():
"""Test txt_to_triplets function"""
data_file = './tests/data.txt'
u_col = 0
i_col = 1
r_col = 2
sep = '\t'
triplet_data = Reader.read_uir_triplets(data_file, u_col, i_col, r_col, sep, skip_lines=0)
assert len(triplet_data) == 10
assert triplet_data[4][... | 5,344,676 |
def main():
""" One time script to simply update the business types in Historic Duns instead of reloading from the source """
sess = GlobalDB.db().session
for historic_duns in sess.query(HistoricDUNS).all():
historic_duns.business_types = [DUNS_BUSINESS_TYPE_DICT[type_code]
... | 5,344,677 |
def show_batch(ds: tf.data.Dataset,
classes: list,
rescale: bool = False,
size: tuple = (10, 10),
title: str = None):
"""
Function to show a batch of images including labels from tf.data object
Args:
ds: a (batched) tf.data.Dataset
... | 5,344,678 |
def calc_proportion_identical(lst: Any) -> float:
"""
Returns a value between 0 and 1 for the uniformity of the values
in LST, i.e. higher if they're all the same.
"""
def count_most_common(lst):
"""
Find the most common item in LST, and count how many times it occurs.
"""
... | 5,344,679 |
def _rolling_mad(arr, window):
"""Rolling window MAD outlier detection on 1d array."""
outliers = []
for i in range(window, len(arr)):
cur = arr[(i - window) : i]
med, cur_mad = _mad(cur)
cur_out = cur > (med + cur_mad * 3)
idx = list(np.arange((i - window), i)[cur_out])
... | 5,344,680 |
def test_setup_chunk_task_no_chunks(mock_import_chunk, batch, valid_user):
"""Assert that if a batch has no chunks, nothing happens."""
tasks.setup_chunk_task(batch, "PUBLISHED", valid_user.username)
mock_import_chunk.delay.assert_not_called() | 5,344,681 |
def compute_mean_and_cov(embeds, labels):
"""Computes class-specific means and shared covariance matrix of given embedding.
The computation follows Eq (1) in [1].
Args:
embeds: An np.array of size [n_train_sample, n_dim], where n_train_sample is
the sample size of training set, n_dim is the dimension ... | 5,344,682 |
def stackedensemble_multinomial_test():
"""This test check the following (for multinomial regression):
1) That H2OStackedEnsembleEstimator executes w/o errors on a 3-model manually constructed ensemble.
2) That .predict() works on a stack.
3) That .model_performance() works on a stack.
4) That test ... | 5,344,683 |
def wcenergy(seq: str, temperature: float, negate: bool = False) -> float:
"""Return the wc energy of seq binding to its complement."""
loop_energies = calculate_loop_energies_dict(temperature, negate)
return sum(loop_energies[seq[i:i + 2]] for i in range(len(seq) - 1)) | 5,344,684 |
def getDirectoriesInDir(directory):
"""
Returns all the directories in the specified directory.
"""
directories = {}
for d in os.listdir(directory):
path = os.path.join(directory, d)
if os.path.isdir(path):
directories[d] = path
return directories | 5,344,685 |
def upload_csv():
"""
Upload csv file
"""
upload_csv_form = UploadCSVForm()
if upload_csv_form.validate_on_submit():
file = upload_csv_form.csv.data
ClassCheck.process_csv_file(file)
flash('CSV file uploaded!', 'success')
return redirect('/') | 5,344,686 |
async def clean(request: Request) -> RedirectResponse:
"""Access this view (GET "/clean") to remove all session contents."""
request.session.clear()
return RedirectResponse("/") | 5,344,687 |
def svd(A):
"""
Singular Value Decomposition
Parameters
----------
A: af.Array
A 2 dimensional arrayfire array.
Returns
-------
(U,S,Vt): tuple of af.Arrays
- U - A unitary matrix
- S - An array containing the elements of diagonal matrix
- Vt - A... | 5,344,688 |
def parse_content_type_header(value):
""" maintype "/" subtype *( ";" parameter )
The maintype and substype are tokens. Theoretically they could
be checked against the official IANA list + x-token, but we
don't do that.
"""
ctype = ContentType()
recover = False
if not value:
ct... | 5,344,689 |
def check_analyzed_dependency(context, package, version):
"""Check for the existence of analyzed dependency for given package."""
jsondata = context.response.json()
assert jsondata is not None
path = "result/0/user_stack_info/analyzed_dependencies"
analyzed_dependencies = get_value_using_path(jsonda... | 5,344,690 |
def csr_matrix_multiply(S, x): # noqa
"""Multiplies a :class:`scipy.sparse.csr_matrix` S by an object-array vector x.
"""
h, w = S.shape
import numpy
result = numpy.empty_like(x)
for i in range(h):
result[i] = sum(S.data[idx]*x[S.indices[idx]] # noqa pylint:disable=unsupported-assign... | 5,344,691 |
def calculate_sem_IoU(pred_np, seg_np, num_classes):
"""Calculate the Intersection Over Union of the predicted classes and the ground truth
Args:
pred_np (array_like): List of predicted class labels
seg_np (array_like): List of ground truth labels
num_classes (int): Number of classes in... | 5,344,692 |
def create_mask(imaging, fileID, cleanup=2):
"""separate function to create masks which can be loaded in computrs with problem at masking images"""
imaging_folder = os.path.join(ROOTDIR, FILEDIR, 'preprocessed')
masks_folder = os.path.join(ROOTDIR, FILEDIR, 'masks')
for idx, image in enumerate(imaging)... | 5,344,693 |
def test_remove_with_list_and_set():
"""Testing remove with exclude as a set or list"""
assert remove("example", ['e', 'x']) == "ampl"
assert remove("example", set(['e', 'x'])) == "ampl" | 5,344,694 |
def _invert(M, eps):
"""
Invert matrices, with special fast handling of the 1x1 and 2x2 cases.
Will generate errors if the matrices are singular: user must handle this
through his own regularization schemes.
Parameters
----------
M: np.ndarray [shape=(..., nb_channels, nb_channels)]
... | 5,344,695 |
def read_densecsv_to_anndata(ds_file: Path):
"""Reads a dense text file in csv format into the AnnData format."""
return read_densemat_to_anndata(ds_file, sep=",") | 5,344,696 |
def get_original_date_jpeg(filepath):
"""
returns the DateTimeOriginal/DateTimeDigitized exif data from the given jpeg file
"""
try:
with Image.open(filepath) as image:
# NOTE: using old "private" method because new public method
# doesn't include this tag. It does ... | 5,344,697 |
def _singleton(name):
"""Returns a singleton object which represents itself as `name` when printed,
but is only comparable (via identity) to itself."""
return type(name, (), {'__repr__': lambda self: name})() | 5,344,698 |
def get_zone(*, zone_name: str):
""" Get zone with given zone name.
Args:
zone_name: zone name, e.g. "haomingyin.com"
Returns:
json: zone details
"""
params = dict(name=zone_name)
zones = _get("zones", params=params)
if not zones:
raise CloudflareAPIError(f"Unable to ... | 5,344,699 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.