content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def _check_allowed_to_manage_roles(self, context, protection, role=None, role_id=None):
"""Add a flag for the policy engine if the user is allowed to manage
the requested application.
"""
ref = {}
application_id = None
if role_id or (role and not 'application_id' in role):
role = self.r... | 5,323,000 |
def nextfig():
"""Return one greater than the largest-numbered figure currently
open. If no figures are open, return unity.
No inputs or options."""
# 2010-03-01 14:28 IJC: Created
figlist = getfigs()
if len(figlist)==0:
return 1
else:
return max(figlist)+1
retu... | 5,323,001 |
def test_distribution_param(matrix_name, gap_penalty, ref_lam, ref_k):
"""
Check if `EValueEstimator` estimates the extreme value distribution
parameters correctly by comparing them to the parameters described
in the original publication by Altschul *et al*.
"""
SAMPLE_LENGTH = 500
SAMPLE_SI... | 5,323,002 |
def load_laurent2016():
"""Model dataset for refolded fold
Returns
-------
tuple
pandas data frame with loopstructural dataset and numpy array for bounding box
"""
module_path = dirname(__file__)
data = pd.read_csv(join(module_path, Path('data/refolded_fold.csv')))
bb = np.loa... | 5,323,003 |
def test_matern_1_2_2():
"""
Test Matern kernel (nu=0.5) for 2-d input model
"""
cov = matern_kernel_1_2.c(points21, points22, hyperparameters2)
covariance_matrix2 = np.round(cov, 3)
expected_covariance_matrix2 = np.array([[2.866, 0.527, 0.541], [1.203, 1.472, 0.196], [0.428, 2.866, 0.069]])
... | 5,323,004 |
def get_user_best(key: str, user: int, mode: int = 0, limit: int = 10, type_: str = None, type_return: str = 'dict'):
"""Get the top scores for the specified user."""
params = {
'k': key,
'u': user,
'm': mode,
'limit': limit,
'type': type_}
r = req.get(urls['user_best'], params=params)
return from_json(r.text,... | 5,323,005 |
def _copy_fn(fn):
"""Create a deep copy of fn.
Args:
fn: a callable
Returns:
A `FunctionType`: a deep copy of fn.
Raises:
TypeError: if `fn` is not a callable.
"""
if not callable(fn):
raise TypeError("fn is not callable: %s" % fn)
# The blessed way to copy a function. copy.deepcopy fai... | 5,323,006 |
def ireport():
""" Incident Reports, RESTful controller """
resource = request.function
tablename = "%s_%s" % (module, resource)
table = db[tablename]
# Don't send the locations list to client (pulled by AJAX instead)
table.location_id.requires = IS_NULL_OR(IS_ONE_OF_EMPTY(db, "gis_location.i... | 5,323,007 |
def makenetbn(dims, softmax=True, single=True):
"""A batch-normalizing version of makenet. Experimental."""
ndims = len(dims)
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
# the weights must be set explicitly as attributes in the class
# (i.e., we can't collect the... | 5,323,008 |
def slack_showslackrealnames(bot, event, *args):
"""enable/disable display of realnames instead of usernames in messages synced from slack
(default: disabled)
usage: /bot slack_showslackrealnames <teamname> <channelid> {true|false}"""
if len(args) != 3:
bot.send_message_segments(event.conv, [h... | 5,323,009 |
def _ccsd_t_energy(output_str):
""" Reads the CCSD(T)/UCCSD(T) energy from the output file string.
Returns the energy in Hartrees.
:param output_str: string of the program's output file
:type output_str: str
:rtype: float
"""
ene = ar.energy.read(
output_str,
... | 5,323,010 |
def getMyPath():
"""returns path of current script"""
from miner_globals import getCurrentScriptPath
return getCurrentScriptPath() | 5,323,011 |
def _ResetWatcherDaemon():
"""Removes the watcher daemon's state file.
"""
path = \
qa_utils.MakeNodePath(qa_config.GetMasterNode(),
pathutils.WATCHER_GROUP_STATE_FILE % "*-*-*-*")
AssertCommand(["bash", "-c", "rm -vf %s" % path]) | 5,323,012 |
def get_codename():
"""Helper for generating a random codename to represent a voter
in the admin interface. To protect voting privacy of our voters,
we are using hashes to make it slightly more difficult to
reveal/infer who voted for who. On the admin interface, however,
instead of using a less huma... | 5,323,013 |
def load_paste_config(app_name, options, args):
"""
Looks for a config file to use for an app and returns the
config file path and a configuration mapping from a paste config file.
We search for the paste config file in the following order:
* If --config-file option is used, use that
* If args... | 5,323,014 |
def get_nearest_to_layers_mean_indicators(layers):
"""
Return indicators of weights in layers nearest
to layer weight mean.
This function, for every given layer, computes weights mean
and returns importance indicators for every weight
based on how close to it's layer mean it is.
Weights clo... | 5,323,015 |
def mach_wave_angle(mach: float):
"""Return the angle of the Mach wave given the Mach number after a turn
Notes
-----
Parameters
----------
mach : float
The mach number after a turn
Returns
-------
float
The angle of the mach wave in degrees
Examples
-... | 5,323,016 |
def parse(tokens, pop=False):
"""Parse a stream of :class:`Tokens<.Token>` into a stream of
:class:`Nodes<.Node>`.
:raises TemplateSyntaxError:
When an unexpected :class:`.Token` was encountered.
:param Iterator tokens:
The stream of :class:`Tokens<.Token>` to consume.
:param bool pop:
... | 5,323,017 |
def download_to_file(url, file, quiet=False):
"""Downloads a URL to file. Returns the file size.
Returns -1 if the downloaded file size does not match the expected file
size
Returns -2 if the download is skipped due to the file at the URL not
being newer than the local copy (identified by matching t... | 5,323,018 |
def peakfit(xvals, yvals, yerrors=None, model='Voight', background='slope',
initial_parameters=None, fix_parameters=None, method='leastsq', print_result=False, plot_result=False):
"""
Fit x,y data to a peak model using lmfit
E.G.:
res = peakfit(x, y, model='Gauss')
print(res.fit_repo... | 5,323,019 |
def error_027_mnemonic_codes(text):
"""Fix some cases and return (new_text, replacements_count) tuple."""
(text, ignored) = ignore(text, r"https?://\S+")
(text, count1) = re.subn(r"–", "–", text)
(text, count2) = re.subn(r" ", " ", text)
text = deignore(text, ignored)
return (te... | 5,323,020 |
def debug(_func, *, write=False):
"""Prints/writes debuging info for the decorated function
"""
def debug_decorator(func):
@functools.wraps(func)
def debug_decorator_wrapper(*args, **kwargs):
args_repr = [repr(arg) for arg in args]
kwargs_repr = [f"{k}={v!r}" for k, v... | 5,323,021 |
def memodict(f):
"""Memoization decorator for a function taking a single argument
http://code.activestate.com/recipes/578231-probably-the-fastest-memoization-decorator-in-the-/
"""
class memodict(dict):
def __missing__(self, key):
ret = self[key] = f(key)
return ret
... | 5,323,022 |
def unset(env_vars, verbose):
"""Unset environment variables - each of {ENV_VARS} must be of the form 'KEY'"""
set_verbosity(verbose)
hokusai.unset_env(KUBE_CONTEXT, env_vars) | 5,323,023 |
def denoise(sub):
"""
"""
ses = 1
#DATA_PATH = pkg_resources.resource_filename('brainnetworks', 'data/')
from src.data import subjects
subdir=subjects.preprocesseddir + '/sub-%s'%sub
assert os.path.exists(subdir)
sesdir=os.path.join(subdir,'ses-%d/func'%ses)
# get freesu... | 5,323,024 |
def xval(v):
"""Return the scalar x value of a single vector.
>>> xval(make(1, 2, 3))
1
"""
assert is_vec3(v)
assert v.shape[0] == 1
return v[0, 0] | 5,323,025 |
def payload_full():
"""full jwt payload"""
return {
"iss": "https://www.myapplication.com",
"aud": "https://www.myapplication.com",
"exp": datetime.datetime.utcnow() + datetime.timedelta(seconds=10),
"iat": datetime.datetime.utcnow(),
"nbf": datetime.datetime.utcnow(),
... | 5,323,026 |
async def create_accounts(source_kp: Keypair, account_kps: List[Keypair], channel_builders: List[Builder], horizon_endpoints: List[str], starting_balance: int):
"""Asynchronously create accounts and return a Keypair instance for each created account.
Accounts are created using given channel builders (as sequen... | 5,323,027 |
def run_single(i,threshold_area_fraction,death_to_birth_rate_ratio,domain_size_multiplier,return_history=False):
"""run a single voronoi tessellation model simulation"""
rates = (DEATH_RATE,DEATH_RATE/death_to_birth_rate_ratio)
rand = np.random.RandomState()
history = lib.run_simulation(simulation,L,TIM... | 5,323,028 |
def test_script_examples(tmp_path):
"""the script test_organization is responsible for all the schemas
in the root of the repository, under <schema>/examples.
A schema specific test is intended to run tests that
are specific to a schema. In this case, this is the "script"
folder. Invalid examples sh... | 5,323,029 |
def ensure_package(
requirement_str, error_level=None, error_msg=None, log_success=False
):
"""Verifies that the given package is installed.
This function uses ``pkg_resources.get_distribution`` to locate the package
by its pip name and does not actually import the module.
Therefore, unlike :meth:... | 5,323,030 |
def deliver_image_gif(): # type: () -> str
"""Return a minimal GIF image."""
return b64decode("""
R0lGODlhAQABAIABAP///wAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==
""") | 5,323,031 |
def build_bootstrap_likelihood(lex, sentence, ontology,
alpha=0.25, meaning_prior_smooth=1e-3):
"""
Prepare a likelihood function `p(meaning | syntax, sentence)` based on
syntactic bootstrapping.
Args:
lex:
sentence:
ontology:
alpha: Mixing parameter for bootstrap... | 5,323,032 |
def createDatabaseDir(outPrefix, kmers):
"""Creates the directory to write sketches to, removing old files if unnecessary
Args:
outPrefix (str)
output db prefix
kmers (list)
k-mer sizes in db
"""
# check for writing
if os.path.isdir(outPrefix):
# remo... | 5,323,033 |
def getTJstr(text, glyphs, simple, ordering):
""" Return a PDF string enclosed in [] brackets, suitable for the PDF TJ
operator.
Notes:
The input string is converted to either 2 or 4 hex digits per character.
Args:
simple: no glyphs: 2-chars, use char codes as the glyph
... | 5,323,034 |
def _sorckt_handler():
"""网络日志记录器"""
pass | 5,323,035 |
def predict_generate(csv_file_test_data, csv_file_test_label, csv_file_test_mask, dataset, generation_dataset, nnet_model, results_path, covar_module0, covar_module1, likelihoods, type_nnet, latent_dim, data_source_path, prediction_x, prediction_mu, zt_list, P, T, id_covariate, varying_T=False):
"""
Function to... | 5,323,036 |
def create_dest_group(glab, dest, src_group_tree):
"""Create destination group structure"""
if '/' in dest:
logging.error('SubGroup as destination not supported "%s"', dest)
sys.exit(1)
dest_group_tree = Tree()
logging.info('Attempting to create destination group at %s/%s', glab.url, des... | 5,323,037 |
def datetime_to_jd(date):
"""
Convert a `datetime.datetime` object to Julian Day.
Parameters
----------
date : `datetime.datetime` instance
Returns
-------
jd : float
Julian day.
Examples
--------
>>> d = datetime.datetime(1985,2,17,6)
>>> d
... | 5,323,038 |
def parse_channel_mention(part, message):
"""
If the message's given part is a channel mention, returns the respective channel.
Parameters
----------
part : `str`
A part of a message's content.
message : ``Message``
The respective message of the given content part.
... | 5,323,039 |
def keep_alive(headers, version, method):
""" return True if the connection should be kept alive"""
conn = set((v.lower() for v in headers.get_all('connection', ())))
if "close" in conn:
return False
elif 'upgrade' in conn:
headers['connection'] = 'upgrade'
return True
elif "... | 5,323,040 |
def cacheFile(*args, **kwargs):
"""
Creates one or more cache files on disk to store attribute data for a span of frames. The caches can be created for
either points on a geometry (using the pts/points flag) or for vectorArray output data (using the oa/outAttr flag). When
the ia/inAttr flag is used, con... | 5,323,041 |
def apply_dies_factory(have_dies, jones_type):
"""
Factory function returning a function that applies
Direction Independent Effects
"""
# We always "have visibilities", (the output array)
jones_mul = jones_mul_factory(have_dies, True, jones_type, False)
if have_dies:
def apply_dies... | 5,323,042 |
def check_skip(timestamp, filename):
"""
Checks if a timestamp has been given and whether the timestamp corresponds
to the given filename.
Returns True if this condition is met and False Otherwise"
"""
if ((len(timestamp) > 0) and not(timestamp in filename)):
return True
elif ((len(... | 5,323,043 |
def plot_lyapunov_1d(lyapunov, true_dynamics, legend=False):
"""Plot the lyapunov function of a 1D system
Parameters
----------
lyapunov : instance of `Lyapunov`
true_dynamics : callable
legend : bool, optional
"""
sess = tf.get_default_session()
feed_dict = get_feed_dict(sess.graph... | 5,323,044 |
def includeme(config):
"""
Инициализация хранилища изображений
Для активации данной настройки добавить ``config.include('stamper.imgstore')``.
"""
settings = config.get_settings()
# use pyramid_tm to hook the transaction lifecycle to the request
# config.include('pyramid_tm')
# use p... | 5,323,045 |
def extract_emoji(string: str, bot: Bot) -> Optional[Union[str, Emoji]]:
"""
Extracts a single emoji or custom emote from the input string.
:param string: Input string
:param bot: Discord bot object
:return: Either a string containing a unicode emoji, or a Discord
emoji object representing ... | 5,323,046 |
def get_bridge(driver):
"""Call this method to get a Bridge instead of a standalone accessory."""
bridge = Bridge(driver, 'Bridge')
light_1 = LightBulb(driver, 'Red Light', pin=LedPin1)
light_2 = LightBulb(driver, 'Blue Light', pin=LedPin2)
bridge.add_accessory(light_1)
bridge.add_accessory(ligh... | 5,323,047 |
def compute_gradient_penalty(D, real_samples, fake_samples):
"""Calculates the gradient penalty loss for WGAN GP"""
# Random weight term for interpolation between real and fake samples
alpha = Tensor(np.random.random((real_samples.size(0), 3, 1, 1)))
# Get random interpolation between real and fake samp... | 5,323,048 |
def is_tabledap(url):
"""
Identify a dataset as an ERDDAP TableDAP dataset.
Parameters
----------
url (str) : URL to dataset
Returns
-------
bool
"""
return "tabledap" in url | 5,323,049 |
def task_1(data_size, host):
"""
task_1:
before upgrade: create collection and insert data with flush, load and search
after upgrade: get collection, load, search, insert data with flush, create index, load, and search
"""
prefix = "task_1_"
connections.connect(host=host, port=19530,... | 5,323,050 |
def die(msg, exit_val=1):
"""warn() and sys.exit() with exit_val (default 1)"""
warn(msg)
sys.exit(exit_val) | 5,323,051 |
def parse_args(args):
"""Parse command line parameters
Args:
args ([str]): command line parameters as list of strings
Returns:
:obj:`argparse.Namespace`: command line parameters namespace
"""
parser = argparse.ArgumentParser(description="compare results from benchmarks")
parser.add... | 5,323,052 |
def downgrade():
"""
Downgrade Semantic Description:
ENTER DESCRIPTION HERE
"""
# ### commands auto generated by Alembic - please adjust! ###
with op.batch_alter_table('annotation', schema=None) as batch_op:
batch_op.drop_column('viewpoint')
batch_op.drop_column('content_guid... | 5,323,053 |
def generate_timestamp(time_to_use, stamp_type="default"):
""" Genrate a text timestamp """
new_stamp = time_to_use.strftime("%Y%m%d-%H%M%S")
return new_stamp | 5,323,054 |
def scr2idb(*args):
"""scr2idb(char name) -> char"""
return _idaapi.scr2idb(*args) | 5,323,055 |
def compute_local_nre_maps(
source_descriptors: torch.Tensor,
target_features: torch.Tensor,
prior_target_keypoints: torch.Tensor,
norm_coarse: torch.Tensor,
window_size: int,
):
"""Compute dense local correspondence maps.
Args:
* source_descriptors: The interpolated source keypoint ... | 5,323,056 |
def _strategies(min_difficulty=None, max_difficulty=None):
"""DOCUMENT ME!!!"""
return draw(one_of(
_global_strategy_lookup.items()[min_difficulty : max_difficulty]
)) | 5,323,057 |
def imag(z):
"""
Returns the imaginary part of z.
>>> imag(2+3j)
3.0
If the input is a number, a number is returned:
>>> isinstance(imag(2+3j), float)
True
Can be used with arrays, too:
>>> imag(np.array([1+10j, 2+20j, 3+30j]))
array([ 10., 20., 30.])
"""
return conte... | 5,323,058 |
async def test_blocked_by_execution_policy():
"""The credential should raise CredentialUnavailableError when execution policy blocks Get-AzAccessToken"""
stderr = r"""#< CLIXML
<Objs Version="1.1.0.1" xmlns="http://schemas.microsoft.com/powershell/2004/04"><S S="Error">Import-Module : Errors occurred while loa... | 5,323,059 |
def apply(f: Callable[[str], B_monoid], description: str) -> Parser[B_monoid]:
"""
A shortcut for ``item(description).apply(f)``.
In contrast to :py:meth:`Parser.apply`, this function spares ``f``
the trouble of outputting a :py:class:`Result<dollar_lambda.result.Result>` object.
Here is an example... | 5,323,060 |
def fit_normalized_gaussian_process(X, y, nu=1.5):
"""
We fit a gaussian process but first subtract the mean and divide by stddev.
To undo at prediction tim, call y_pred = gp.predict(X) * y_stddev + y_mean
"""
gp = gaussian.GaussianProcessRegressor(
kernel=gaussian.kernels.Matern(nu=... | 5,323,061 |
def reset_pkey(id_dir: Path) -> None:
"""Reset the the 'next_id' for the given directory by deleting
the pkey file ('next_id') if present."""
with lockfile.LockFile(id_dir/'.lockfile', timeout=1):
try:
(id_dir/PKEY_FN).unlink()
except OSError:
pass | 5,323,062 |
def choices_on_ballots(L, printing_wanted=False):
"""
Return a dict of the choices shown on ballot list L, with counts.
Args:
L (list): list of ballots
Returns:
C (dict): dict of distinct strings appearing in ballots in L,
each with count of number of occurren... | 5,323,063 |
def test_upsert_budget(lunch_money_obj: LunchMoney,
obscure_start_date: datetime.datetime):
"""
Test upserting some budgets
"""
# Ride Sharing
response = lunch_money_obj.upsert_budget(start_date=obscure_start_date,
category_id=22913... | 5,323,064 |
def test_number_violations():
"""This test validates the correct number of errors are found"""
hits = []
for d in pathlib.Path("test").iterdir():
if d.is_file():
if b.is_badfile(d).classification == "unsafe":
hits.append(b.is_badfile(d))
print("\n", *hits, sep="\n")
... | 5,323,065 |
def prime_mask(n: int) -> np.ndarray:
"""Generate boolean array of length N, where prime indices are True."""
primes = np.ones(n, dtype=bool)
primes[:2] = False
for i in range(2, n):
if primes[i]:
# Mark all multiples of i as composite
composite = 2 * i
while ... | 5,323,066 |
def _bulk_update_no_validation(model, values, conn, key_fds, upd_fds, ret_fds, where):
# type: (Type[Model], TUpdateValuesValid, TDatabase, Tuple[FieldDescriptor], Tuple[FieldDescriptor], Optional[Tuple[FieldDescriptor]], Tuple[str, tuple]) -> Union[int, 'ReturningQuerySet'] # noqa: F821
"""
Does bulk up... | 5,323,067 |
def dmm_exitcell(subidxs_ds, subuparea, subshape, shape, cellsize, mv=_mv):
"""Returns exit highres cell indices of lowres cells according to the
double maximum method (DMM).
Parameters
----------
subidxs_ds : 1D-array of int
highres linear indices of downstream cells
subuparea : 1D-arr... | 5,323,068 |
def cast_to_decimal(amount: str):
"""Cast the amount to either an instance of Decimal or None.
Args:
amount: A string of amount. The format may be '¥1,000.00', '5.20', '200'
Returns:
The corresponding Decimal of amount.
"""
if amount is None:
return None
amount = "".join... | 5,323,069 |
def test_csrf_exempt(csrf_app, csrf):
"""Test before CSRF protect decorator."""
# Test `exempt` as a function passing the name of the view as string
csrf.exempt('conftest.csrf_test')
with csrf_app.test_client() as client:
res = client.post(
'/csrf-protected',
data=json.d... | 5,323,070 |
def ITERATIVETEST_Variation_Of_Input_Parameter_inUseSecondPlane():
"""Tests variation of input value at field "inUseSecondPlane"."""
Logging.infoHTML( "<b>ToDo: Add more \"TestData\" objects to maximize variations!</b>" )
testDataVariations = {
"Variation_1" : __getTestDataVariation1_inUseSecondPlane(),
}
... | 5,323,071 |
def regweight_from_parbound(pst):
"""sets regularization weights from parameter bounds
which approximates the KL expansion. Called by
zero_order_tikhonov().
Parameters
----------
pst : pyemu.Pst
a control file instance
"""
pst.parameter_data.index = pst.parameter_data.parnme
... | 5,323,072 |
def wave_energy(F, df, rhow=1000, g=9.8):
"""Returns total wave energy."""
return rhow * g * np.sum(F * df) | 5,323,073 |
async def test_forgot_password_view_aiohttp_error(mock_cognito, cloud_client):
"""Test unknown error while logging out."""
mock_cognito.initiate_forgot_password.side_effect = aiohttp.ClientResponseError(
Mock(), Mock()
)
req = await cloud_client.post(
"/api/cloud/forgot_password", json={... | 5,323,074 |
def nav(context):
"""
Navigate to the customers page
"""
context.browser.get('http://localhost:5000/customers') | 5,323,075 |
def get_x_vector(N, K):
"""
Return x from given order of WH matrix and K
:param N: Order of WH matrix
:param K: Number of ones
:return: numpy.ndarray
"""
x = np.zeros(N)
random_pos = np.random.choice(
np.arange(0, N), K, replace=False
)
x[random_pos] = 1
return x | 5,323,076 |
def person_split(whole_data, train_names, valid_names, test_names):
"""Split data by person."""
random.seed(30)
random.shuffle(whole_data)
train_data = []
valid_data = []
test_data = []
for idx, data in enumerate(whole_data): # pylint: disable=unused-variable
if data["name"] in tr... | 5,323,077 |
def budget_delete(request, slug):
"""
Delete a budget object.
"""
budget = get_object_or_404(Budget.active.all(), slug=slug)
if request.POST:
if request.POST.get('confirmed'):
budget.delete()
return HttpResponseRedirect(reverse('budget:budget_budget_list'))
c... | 5,323,078 |
def get_connection_name(db_connection_id):
"""
To give data base connection name if data base exist.
Args:
db_connection_id(int):data base connection id.
Returns:
Returns data base name if exist or return message saying that db not
exist.
"""
if db_connection_id == APIM... | 5,323,079 |
def cal_area(group_xyz):
"""
Calculate Area of Triangle
:param group_xyz: [B, N, K, 3] / [B, N, G, K, 3]; K = 3
:return: [B, N, 1] / [B, N, G, 1]
"""
pad_shape = group_xyz[..., 0, None].shape
det_xy = torch.det(torch.cat([group_xyz[..., 0, None], group_xyz[..., 1, None], torch.ones(pad_shap... | 5,323,080 |
def detect_edges_better(img: Image, threshold: int) -> Image:
"""
Returns a copy of an image with the pixels changed to either black
or white based on the contrast of the pixel above, below, or to the right
based on the inputed threshold.
Author: Anita Ntomchukwu
>>>detect_edges(img, ... | 5,323,081 |
def lru_cache(timeout=10, maxsize=128, typed=False):
"""Least Recently Used Cache- cache the result of a function.
Args:
timeout
How many seconds to cache results for.
maxsize
The maximum size of the cache in bytes
typed
When `True` argument types ... | 5,323,082 |
def test_p_content():
"""make sure p-content (instead of the usual e-content) doesn't cause
us to throw an exception
"""
parsed = {"items": [{"properties": {"author": [{"properties": {"name": ["Kyle"],
"url": ["https://kylewm.com"]},
... | 5,323,083 |
def _mutator_plugins_bucket_name():
"""Mutator plugins bucket name."""
return environment.get_value('MUTATOR_PLUGINS_BUCKET') | 5,323,084 |
def densenet_imagenet_169(inputs, is_training=True, num_classes=1001):
"""DenseNet 121."""
depths = [6, 12, 32, 32]
growth_rate = 32
return densenet_imagenet_model(inputs, growth_rate, depths, num_classes,
is_training) | 5,323,085 |
def train(args):
"""Run Training """
global_step = 0
best_metric = None
best_model: Dict[str, torch.Tensor] = dict()
if not os.path.exists(args.output_dir):
os.makedirs(args.output_dir)
writer = SummaryWriter(log_dir=args.output_dir)
# We use flambe to do the data preprocessing
... | 5,323,086 |
def delete_todo(request, todo_id):
"""Delete one to_do task"""
logging.info(f'{os.getenv("ID_LOG", "")} Deleting the element with id={todo_id}')
TodoItem.objects.get(id=todo_id).delete()
logging.info(f'{os.getenv("ID_LOG", "")} Todo task with id={todo_id} successfully deleted')
# Redirect to the app... | 5,323,087 |
def save_sample_aminer_related(data_path):
"""Receive path to resource and save a list of related documents"""
# Analizer
analizer = get_default_analizer()
# Init variables and paths
nrand, doc_limit, fixed_seed = get_default_sample_init()
index_data_path = data_path + INDEX_DATA
index_data_... | 5,323,088 |
def get_jquery_min_js():
"""
Return the location of jquery.min.js. It's an entry point to adapt the path
when it changes in Django.
"""
return 'admin/js/vendor/jquery/jquery.min.js' | 5,323,089 |
def getLines_from_file(path, clean=False):
""" returns the table of lines from text file """
text = getText_from_file(path)
if not text:
return None
text = text.split("\n")
if clean:
text = [t.strip(' \t') for t in text]
return text | 5,323,090 |
def channel_shift(img, random_state):
"""
Adds random brightness to image.
Parameters
------
img: np.array
Image array [CWH].
random_state: np.random
Randomized state.
Returns
------
img: np.array
Image array [CWH].
"""
shift_val = in... | 5,323,091 |
def print_banner(text):
"""Prints the font in figlet style"""
print(Figlet(font='smslant').renderText(text)) | 5,323,092 |
def quicksort(inputArray):
"""input: array
output: new sorted array
features: stable
efficiency O(n^2) (worst case), O(n log(n)) (avg case), O(n) (best case):
space complexity: O(n)
method:
Pick the last element in the array as the pivot.
Separate values into arrays based on whether they... | 5,323,093 |
def get_paypal_currency_code(iso_currency_code):
"""
Function will map the currency code to paypal currency code
"""
if iso_currency_code == 124:
return 'CAD'
if iso_currency_code == 840:
return 'USD'
if iso_currency_code == 484:
return 'MXN'
return 'CAD' | 5,323,094 |
def draw_line(image, command):
"""
A function which draws a line on the given image.
:param dict image: The image on which to draw the line.
:param list command: The command given for the line to draw.
"""
# Get the color of the line
color = (int(command[1]), int(command[2]), int(command[3]... | 5,323,095 |
def rq3(ctx):
"""
RQ3: Feature Discrimination
Context: The map of elites can be a useful tool to gain insights about the combinations of feature values that
are likely to expose a failure. The regions of the map where there is a high probability of misbehaviours
indicate that the corresp... | 5,323,096 |
def get_num_audio_tracks(mpeg4_file, in_fh):
""" Returns the number of audio track in the input mpeg4 file. """
num_audio_tracks = 0
for element in mpeg4_file.moov_box.contents:
if (element.name == mpeg.constants.TAG_TRAK):
for sub_element in element.contents:
if (sub_ele... | 5,323,097 |
def test_karatsuba_1_2():
"""Test Karatsuba Multiplication 1x2"""
assert multiply(1, 2) == 2 | 5,323,098 |
def _get_paths(metadata_connection: metadata.Metadata,
executions: List[metadata_store_pb2.Execution],
output_dir: Text) -> Iterable[Tuple[Text, Text]]:
"""Yields tuple with source and destination artifact uris.
The destination artifact uris are located in the output_dir. The source
... | 5,323,099 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.