content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def merge_scenarios_with_paths(scenarios):
"""
This will merge ScenarioWithPaths objects and return a ScenarioWithPaths
objects which has the power generation vectors from all scenarios as well
as the paths from all scenarios. We assume independence across the
scenarios.
Args:
scenarios... | 60,200 |
def adaptive_threshold(image: np.ndarray) -> np.ndarray:
"""
Wrapper for OpenCV's adaptive threshold algorithm.
Parameters
----------
image : numpy.ndarray
Image as numpy array
Returns
-------
numpy.ndarray
Binarized image using adaptive threshold.
Contribute
-... | 60,201 |
def shuffle_permute_file(input_path, out_path, min_percent, max_percent):
"""
applies shuffle permutation to a file,
randomly selecting p percent of words to be shuffled, where min_percent < p < max_percent.
"""
output = open(out_path, "w")
for line in open(input_path):
words = line.spl... | 60,202 |
def quaternionInverse(*args):
"""
quaternionInverse(Quaternion pQua, Quaternion pQuaOut)
quaternionInverse(Quaternion pQua) -> Quaternion
"""
return _almath.quaternionInverse(*args) | 60,203 |
def crawl(params, update):
"""
Execute crawl operations using the specified parameters.
"""
# required configuration values
actions = params.get("crawl", "actions").split(",")
source = params.get("crawl", "input")
output = params.get("crawl", "output")
# optional configuration values
... | 60,204 |
def get_common_base(cls_list):
"""
Get the most derived common base class of classes in ``cls_list``.
"""
# MRO in which "object" will appear first
def rev_mro(cls):
return reversed(inspect.getmro(cls))
def common(cls1, cls2):
# Get the most derived class that is in common in th... | 60,205 |
def dispatch_repl_commands(command):
"""Execute system commands entered in the repl.
System commands are all commands starting with "!".
"""
if command.startswith('!'):
os.system(command[1:])
return True
return False | 60,206 |
def main(model_file, cppn_genome_path, seed=-1):
"""
Run simulation on given model and environment, and draw the location of stumble if the agent dies.
"""
info = run_simulation(model_file, cppn_genome_path, seed=seed)
if info['game_over']:
location_of_death = info['pos']
draw_terrai... | 60,207 |
def l_inverse(L, check=False, verbose=False):
"""invert L (lower triangular, 1 on diagonal)
"""
m, n = L.shape
assert m==n
L1 = identity(m)
# Work forwards
for i in range(m):
#u = L1[:, i]
assert L[i, i] == 1
for j in range(i+1, m):
#print("i=%d, j=%d"%(... | 60,208 |
def simplify_numpy_dtype(dtype):
"""Given a numpy dtype, write out the type as string
Args:
dtype (numpy.dtype): Type
Returns:
(string) name as a simple string
"""
kind = dtype.kind
if kind == "b":
return "boolean"
elif kind == "i" or kind == "u":
return "in... | 60,209 |
def model_predict(year, month, day, country, dev=DEV, verbose=True):
"""
make predictions
"""
## start timer for runtime
time_start = time.time()
## load data
datasets = engineer_features(training=False, dev=dev, verbose=verbose)
## load models
models = model_load(dev=... | 60,210 |
def form2(req, key, slug):
"""
Show the bookmarklet form.
"""
s = good_session(key)
if not s:
return redirect('bookmarklet:form1', slug=slug)
data = json.loads(s.data)
scholar_url = data['scholar_url']
doi = data['doi']
event = OAEvent.objects.get(id=data['event_id'])
c... | 60,211 |
def GetNetworkPerformanceConfig(args, client):
"""Get NetworkPerformanceConfig message for the instance."""
network_perf_args = getattr(args, 'network_performance_configs', [])
network_perf_configs = client.messages.NetworkPerformanceConfig()
for config in network_perf_args:
total_tier = config.get('total... | 60,212 |
def inv_lr_scheduler(param_lr, optimizer, iter_num, gamma=0.0001,
power=0.75, init_lr=0.001):
"""Decay learning rate by a factor of 0.1 every lr_decay_epoch epochs."""
lr = init_lr * (1 + gamma * iter_num) ** (- power)
i = 0
for param_group in optimizer.param_groups:
param_g... | 60,213 |
def OpenFace(openface_features, PID, EXP):
"""
Tidy up OpenFace features in pandas data.frame to be stored in sqlite
database:
- Participant and experiment identifiers are added as columns
- Underscores in column names are removed, because sqlite does not like
underscores in column names.
... | 60,214 |
def auth(function):
"""Wrapper checking if the user is logged in."""
@wraps(function)
def wrapper(*args, **kwargs):
testing = app.config.get('TESTING')
if (session.get('users') and session.get('logged_in')) or testing:
return function(*args, **kwargs)
return redirect(FLOW... | 60,215 |
def svd_solve(A, b=None, w_cut=1e-10):
"""
This function solves the system of equations Ax=b by calculating the
inverse of A using the SVD method: x=A^(-1)*b; A^(-1)=V*S^(-1)*U'
Inputs:
A: 2D array of dimensions nxm (n>=m)
b: 1D array of dimensions n
w_cut: cut-off frequency for ... | 60,216 |
def get_bootstrap_game(self, default_game='SamplesProject'):
"""
:param self: Context
:param default_game: Default game to set to if we cannot read bootstrap.cfg.
:return: Name of the game enabled in bootstrap.cfg
"""
game = default_game
project_folder_node = getattr(self,'... | 60,217 |
def check_issue(name, checks, controls):
"""
Checks if a certain RWT issue needs to be suggested.
Returns: list
"""
rwt = []
is_issue = False
total_reasons = []
total_offenders = []
for check in checks:
for control in controls:
if control != []:
f... | 60,218 |
def callback(hermes, intent_message):
"""
Makes an inference when the intent is to make a prediction.
"""
if hermes.skill.food.isOn:
result = hermes.skill.food.infer()
hermes.publish_end_session(intent_message.session_id, hermes.skill.message.get(result))
loop_new_question(hermes... | 60,219 |
def _write_keytab(keytab_entries, keytab, owner):
"""Write keytab file."""
try:
pwnam = pwd.getpwnam(owner)
except KeyError:
_LOGGER.error('Invalid user: %s', owner)
return
fs.write_safe(
keytab,
lambda f: f.write(keytab_entries),
owner=(pwnam.pw_uid, pw... | 60,220 |
def create_training_instances(all_tokens, vocab_words, max_seq_length, rng):
"""Create `TrainingInstance`s from raw text."""
rng.shuffle(all_tokens)
instances = []
print('Process of "create_training_instances"')
for tokens in all_tokens:
instances.append(create_instances_from_sentence(token... | 60,221 |
def get_binary_result(probs):
"""
将预测结果转化为二分类结果
Args:
probs: 预测结果
Return:
binary_result: 二分类结果
"""
binary_result = []
for i in range(len(probs)):
if float(probs[i][0]) > 0.5:
binary_result.append(1)
elif float(probs[i][0]) < 0.5:
binary... | 60,222 |
def _find_open_boundary_neighbors(neighbors, open_boundary_nodes):
"""Array of booleans that indicate if a neighbor is an open boundary."""
open_boundary_neighbors = neighbors[:, open_boundary_nodes]
is_open_boundary_neighbor = np.in1d(open_boundary_neighbors, open_boundary_nodes)
is_open_boundary_neigh... | 60,223 |
def _boto3_now():
"""Get a ``datetime`` that's compatible with :py:mod:`boto3`.
These are always UTC time, with time zone ``dateutil.tz.tzutc()``.
"""
if tzutc is None:
raise ImportError(
'You must install dateutil to get boto3-compatible datetimes')
return datetime.now(tzutc()) | 60,224 |
def pass_trigger(evt):
"""
# HLT_QuadJet40_IsoPFTau40
if (evt.run<165970 ) | ((evt.run>166782 & evt.run<171050)):
if evt.HLT_QuadJet40_IsoPFTau40 == 1:
return True
else:
return False
# HLT_QuadJet45_IsoPFTau45
elif ((evt.run>=165970) & (evt.run<=166782)) | ((... | 60,225 |
def ricker(t,ts,fsavg):
"""
Ricker Pulse
@param t time vector
@param ts temporal delay
@param fsavg pulse width parameter
@return Output signal vector
"""
a = fsavg*pi*(t-ts)
a2 = a*a
return ((1.0-2.0*a2)*np.exp(-a2)) | 60,226 |
def read_avgint(dismod_file):
"""Read average integrand cases, translating to locations and covariates."""
avgint = dismod_file.avgint
with_integrand = avgint.assign(integrand=avgint.integrand_id.apply(lambda x: IntegrandEnum(x).name))
with_location = with_integrand.merge(dismod_file.node, on="node_id",... | 60,227 |
def extendedMeasurementReport():
"""EXTENDED MEASUREMENT REPORT Section 9.1.52"""
a = TpPd(pd=0x6)
b = MessageType(mesType=0x36) # 00110110
c = ExtendedMeasurementResults()
packet = a / b / c
return packet | 60,228 |
def test_search_selection_update_invalid_400(session, client, jwt):
"""Assert that an invalid search selection update returns a 400 status."""
# setup missing required matchType
json_data = [
{
'baseRegistrationNumber': 'TEST0001',
'createDateTime': '2021-03-02T22:46:43+00:00... | 60,229 |
def part1(data):
"""
>>> part1(read_input())
6916
"""
twos = 0
threes = 0
for label in data:
if has_count(label, 2):
twos += 1
if has_count(label, 3):
threes += 1
return twos * threes | 60,230 |
def f_whist_jeu_real(request, record_id):
""" Saisie du réalisé 0 1 2 """
crudy = Crudy(request, APP_NAME)
obj = get_object_or_404(WhistJeu, id=record_id)
title = "Réalisé de %s" % (obj.participant.joueur.pseudo.upper())
if obj.pari > 1:
crudy.message = "**%s**, combien de plis as-tu réalisé... | 60,231 |
def expected_min(x, m):
"""Compute unbiased estimator of expected ``min(x[1:m])`` on a data set.
Parameters
----------
x : :class:`numpy:numpy.ndarray` of shape (n,)
Data set we would like expected ``min(x[1:m])`` on. Require ``len(x) >= 1``.
m : `int` or :class:`numpy:numpy.ndarray` with d... | 60,232 |
def execute_nosetests():
"""Execute nosetests"""
try:
load_entry_point('nose', 'console_scripts', 'nosetests')()
except SystemExit:
pass | 60,233 |
def _load_transforms():
"""
Load the transform pairs into the module level variable for later lookup.
Returns
-------
:class:`dict`
"""
return {
f: (globals().get(f), globals().get("inverse_{}".format(f)))
for f in globals().keys()
if "inverse_{}".format(f) in global... | 60,234 |
def scalarclip(polydata, arrayname, scalarvalue, insideout=True,
ispointdata=True):
"""Clip vtkPolyData returning regions with value of array above a
specified value."""
clipper = vtk.vtkClipPolyData()
clipper.SetInput(polydata)
if ispointdata: # array is pointdata
cli... | 60,235 |
def deep_merge_dict(base, priority):
"""Recursively merges the two given dicts into a single dict.
Treating base as the the initial point of the resulting merged dict,
and considering the nested dictionaries as trees, they are merged os:
1. Every path to every leaf in priority would be represented in t... | 60,236 |
def update_log_file(file_path: str, logs: List[dict]) -> None:
"""Update log file with logs.
Args:
filepath: Path to log file.
logs: Fetched logs.
Returns:
None
"""
stored_logs = get_logs_from_file(file_path)
if not stored_logs:
stored_logs = []
stored_logs.... | 60,237 |
def do_monitor_mss_check_list(client, args):
""" List monitor items """
kwargs = {}
if args.tenant:
kwargs['tenant'] = args.tenant
#if args.system:
# kwargs['is_system'] = True
monitors = client.msscheck.list(**kwargs)
utils.print_list(monitors, client.msscheck.columns) | 60,238 |
def balance():
"""
show your organization's credit balance
default format: autoretouch credits - corresponds to € cents excl. VAT
"""
click.echo(AutoRetouchAPIClient().get_balance()) | 60,239 |
def class_oneshot(X, y, clmod, testsize = .2, randomstate=2342, score_method = 'AUC'):
"""
Store test measures from one-shot classification methods.
Input: design matrix, X,
response vector, y,
a classification model, clmod,
size of test set, testsize,
random num... | 60,240 |
def _BuildUpgradeCandidateList(location_ref,
image_version_id,
python_version,
release_track=base.ReleaseTrack.GA):
"""Builds a list of eligible image version upgrades."""
image_version_service = image_version_api_util.Imag... | 60,241 |
def pointer_gamut_visual_response():
"""
Returns a *Pointer's Gamut* visual response.
Returns
-------
Response
*Pointer's Gamut* visual response.
"""
args = request.args
json_data = pointer_gamut_visual(
colourspace_model=args.get('colourspaceModel', COLOURSPACE_MODEL),... | 60,242 |
def change(new_input):
"""Translate the string."""
new = '' # final translation
extras = 'efmnoprt' # multi instance cases
valid_non_letters = f'{string.punctuation} '
fail = 'Invalid input.'
count = 0 # number length count
i = 0 # index for iterating through message
change_cases = {... | 60,243 |
def background_thread(dev):
"""Example of how to send server generated events to clients."""
tty_name = os.path.basename(dev)
tty_out = os.sep.join([
APP.config["wtty"]["roots"]["reader"], "%s.log" % tty_name
])
for chunk in tailf(tty_out):
payload = {'data': unicode(chunk, errors=... | 60,244 |
def save_history(loss_train, loss_test, error_3d_out, error_vae_out):
""" Save the error and lost history on files """
with open('./experiments/3d_vae/loss_train.npy', 'wb') as f:
np.save(f, np.array(loss_train))
with open('./experiments/3d_vae/loss_test.npy', 'wb') as f:
np.save(f, np.array... | 60,245 |
def max_pool(data_in, x, y):
"""Maxpool layer wrapper"""
return tf.nn.max_pool2d(data_in, ksize=[1, x, y, 1], strides=[1, x, y, 1], padding='SAME') | 60,246 |
def parse_proxy_line(line: bytes | bytearray) -> tuple[ProxyDict, int]:
"""
Parses the given line (string or sequence of bytes) for the client IP
and other fields passed through the proxy protocol.
This returns a tuple with elements as follows:
(1) Dictionary with the parsed IP addresses
(2) In... | 60,247 |
def overhead():
"""Run a macrospin example for 1 ps through ``mumax3c`` and directly and
return the difference in run times.
Returns
-------
float
The time difference (overhead) between running mumax3 though ``mumax3c``
and directly.
Examples
--------
1. Getting the overhe... | 60,248 |
def distinct_permutations_from_histogram(counts):
"""
iterate over all distinct permutations of sequences with symbol counts counts
Args:
* counts - (int vector) histogram of counts
Yields:
* (int tuple) sequence with histogram counts
"""
C = counts.copy()
n = ... | 60,249 |
def get_convert_label_fn(odgt):
"""
A function that converts labels to expected range [-1, num_classes-1] where -1 is ignored.
When using custom dataset, you might want to add your own function.
"""
def convert_ade_label(segm):
"Convert ADE labels to range [-1, 149]"
return segm - 1... | 60,250 |
def _get_span(s, pattern):
"""Return the span of the first group that matches the pattern."""
i, j = -1, -1
match = pattern.match(s)
if not match:
return i, j
for group_name in pattern.groupindex:
i, j = match.span(group_name)
if (i, j) != (-1, -1):
return i, j
... | 60,251 |
def GrabLocalPackageIndex(package_path):
"""Read a local packages file from disk into a PackageIndex() object.
Args:
package_path: Directory containing Packages file.
Returns:
A PackageIndex object.
"""
with open(os.path.join(package_path, 'Packages')) as f:
pkgindex = PackageIndex()
pkginde... | 60,252 |
def test_validate_schema(threedi_db):
"""Validate a correct schema version"""
schema = ModelSchema(threedi_db)
with mock.patch.object(
schema, "get_version", return_value=constants.MIN_SCHEMA_VERSION
):
assert schema.validate_schema() | 60,253 |
def plot_accuracy(accuracy: list):
"""Plot accuracy"""
plt.figure()
plt.plot(accuracy)
plt.xticks(
[i for i in range(0, len(accuracy))],
[i + 1 for i in range(0, len(accuracy))])
plt.ylabel('Accuracy')
plt.xlabel('Epoch')
plt.show() | 60,254 |
def chmod_writable(func, path, excinfo):
""" chmod +w file """
os.chmod(path, stat.S_IWRITE)
func(path) | 60,255 |
def random_prop(true_prop : np.ndarray,
niter : int = 1000,
loss_function : Callable = _rmse,
) -> Dict[str,float]:
"""Random Proportion performance
Samples proportion values from a
Z-dimensional (Z is number of types)
Dirichlet distribution with
conce... | 60,256 |
def guess_format(path):
"""Guess file format identifier from it's suffix. Default to DICOM."""
path = Path(path)
if path.is_file():
suffixes = [x.lower() for x in path.suffixes]
if suffixes[-1] in ['.h5', '.txt', '.zip']:
return suffixes[-1][1:]
if suffixes[-1] == '.nii' ... | 60,257 |
def execvp(file, args):
"""Execute a new program, replacing the current process.
:type file: bytes | unicode
:type args: collections.Iterable
:rtype: None
"""
pass | 60,258 |
def adjust(dev, value, newvalue=None):
"""Adjust the offset of the device.
There are two ways to call this function:
* with one value: the offset is adjusted so that `read()` then returns
the given value.
* with two values: the offset is adjusted so that the position that
previously had th... | 60,259 |
def cartesian_to_polar(u, v):
"""
Transforms U,V into r,theta, with theta being relative to north (instead of east, a.k.a. the x-axis).
Mainly for wind U,V to wind speed,direction transformations.
"""
c = u + v*1j
r = numpy.abs(c)
theta = numpy.angle(c, deg=True)
# Convert angle relative... | 60,260 |
def gkern(kernlen=3, nsig=3):
"""Returns a 2D Gaussian kernel."""
x = np.linspace(-nsig, nsig, kernlen + 1)
kern1d = np.diff(st.norm.cdf(x))
kern2d = np.outer(kern1d, kern1d)
return kern2d / kern2d.sum() | 60,261 |
def remove_duplicate_column_names(list_of_dict_of_header_info):
"""
No two columns of the table can have the same data
:param plot_options:
:return:
"""
list_of_column_names = []
list_of_dict_of_header_info_copy = copy.deepcopy(list_of_dict_of_header_info)
for index, dict_of_header_info ... | 60,262 |
def option(*param_decls, **attrs):
"""Attaches an option to the command. All positional arguments are
passed as parameter declarations to :class:`Option`, all keyword
arguments are forwarded unchanged. This is equivalent to creating an
:class:`Option` instance manually and attaching it to the
:att... | 60,263 |
def merge(line):
"""
Function that merges a single row or column in 2048.
"""
new_line = [x for x in line if x !=0]
while len(new_line) < len(line):
new_line.append(0)
for ind in range(len(new_line)-1):
if new_line[ind] == new_line[ind+1]:
new_line[ind] *= 2
... | 60,264 |
def axesvalues(roi, parameters):
"""
Args:
roi(list): y0,x0,ny,nx
parameters(dict)
Returns:
tuple(np.ndarray)
"""
x0 = roi[1]
y0 = roi[0]
nx = roi[3]
ny = roi[2]
# Sub region
if parameters["roi"] is not None:
ax = parameters["roi"][1][0]
b... | 60,265 |
def _urljoin(base, url):
"""
urljoin shim helper for Python2\3
"""
if (hasattr(urllib, 'parse')):
from urllib.parse import urljoin
else:
import urlparse
from urlparse import urljoin
return urljoin(base, url) | 60,266 |
def countdown():
"""Write a generator that counts from 100 to 1"""
yield from range(100, 0, -1) | 60,267 |
def scrape_profile(url):
"""
Scrape the user's profile to get user location and id.
"""
r = urllib.request.urlopen(url).read()
soup = BeautifulSoup(r, "lxml")
user_country = get_user_country(soup)
user_id = get_user_id(soup)
return user_country, user_id | 60,268 |
def make_new_aileenbox(options: dict) -> AileenBox:
""" make a new aileen_box """
aileen_box = None
if options["id"] is None:
options["id"] = uuid.uuid4()
try:
coordinates = [float(l) for l in options["location"].split(",")]
except Exception as e:
raise Exception("Location ca... | 60,269 |
def get_samples(profileDict):
"""
Returns the samples only for the metrics (i.e. does not return any
information from the activity timeline)
"""
return profileDict["samples"]["metrics"] | 60,270 |
def dobro(n):
"""
Dobrar número
:param n: número a ser dobrado
:return: resultado
"""
n = float(n)
n += n
return n | 60,271 |
def test_conll_dataloader(shared_datadir, dummy_vocabs):
"""Test the CoNLL dataset loader with batching and padding.
"""
token_vocab, char_vocab, label_vocab = dummy_vocabs
# Check on the <pad> and <unk> index
assert char_vocab.stoi["<pad>"] == 1
assert char_vocab.stoi["<unk>"] == 0
dataset ... | 60,272 |
def test_freeze_objects_archive_log_files(
session, freeze_objects, redis, museum_object_factory,
local_museum_package_factory, museum_packages_dir,
archive_dir):
"""
Test that freezing an object causes the log files to be archived
if the object directory with logs still exists
"... | 60,273 |
def add_user(username, password, first_name, last_name, email, session):
"""
Creates and saves a new user to the database
:param session:
:param username:
:param password:
:param first_name:
:param last_name:
:param email:
:return: id of the new user
"""
new_user = User(us... | 60,274 |
def cleanup_current():
"""Attempt to cleanup preview runs.
Currently this only scans for old processes.
"""
logging.info("reaping current micronet processes")
_cleanup_pids(True) | 60,275 |
def test_backslash_escapes_extra_9():
"""
Test case backslash extra 9: backslash before the first emphasis start
"""
# Arrange
source_markdown = """*\\*it's** me!"""
expected_tokens = [
"[para(1,1):]",
"[emphasis(1,1):1:*]",
"[text(1,2):\\\b*it's:]",
"[end-empha... | 60,276 |
def aoi_from_experiment_to_cairo(aoi):
"""Transform aoi from exp coordinates to cairo coordinates."""
width = round(aoi[1]-aoi[0], 2)
height = round(aoi[3]-aoi[2], 2)
return([aoi[0], aoi[2], width, height]) | 60,277 |
def lifecycle(sim_path,sol_path,par):
""" Simulate a panel along a transition path """
# unpack
p = sim_path.p
n = sim_path.n
m = sim_path.m
c = sim_path.c
d = sim_path.d
a = sim_path.a
discrete = sim_path.discrete
grid_p = par.grid_p
state = sim_path.state # Container for ... | 60,278 |
def nonzero_colmeans(array):
"""don't consider zeros when calculating mean
"""
value_sums = np.sum(array, axis=0)
presence_sums = np.sum(array!=0, axis=0)
distr = np.true_divide(
value_sums, presence_sums, where=presence_sums!=0)
return distr | 60,279 |
def liststats(ctx):
"""ListNodeStats enables you to view the high-level activity measurements for all nodes in a cluster."""
cli_utils.establish_connection(ctx)
ctx.logger.info(""": """+""";"""+"")
try:
_ListNodeStatsResult = ctx.element.list_node_stats()
except common.Api... | 60,280 |
def _find_paths(graph, start, end, paths, paths_so_far=""):
"""
Recursive helper function for finding paths.
Given graph, a start and an end, return all the path can be found.
This is done by tracking if the current path have the specified start
and end point, if not then keep looking.
This vers... | 60,281 |
def admin_remove_flag():
"""
In GET request
- Deletes the flag for the respective video ID.
"""
if request.method == 'GET':
if 'user' in session:
is_admin = (requests.get(url='http://127.0.0.1:8080/is-admin/{}'.format(session['user'])).content).decode("utf-8") # Done
... | 60,282 |
def test_strfield():
"""
StringField
"""
assert StringField("jan").is_default_valid() is True | 60,283 |
def rec_dfs_edges(graph):
""" recursive way for above
Note: a-b and b-a are different in this case..
"""
nodes = graph.nodes # type: dict
visited = set()
start = list(nodes.keys())[0]
edges = []
def _rec_dfs(graph, _start, _nodes):
for _node in nodes:
if _node in vi... | 60,284 |
def plot_comparison(linear_f: np.ndarray, constant_f: np.ndarray, linear_c: np.ndarray,
title: str, name: str):
"""
@param linear_f: (num_linears, num_evals)
@param constant_f: (num_constants, num_evals)
@param linear_c: (num_linears, num_evals)
@param name: Name to use for plot
... | 60,285 |
def _getitem(iterable_query: Query[Any], item: Any) -> Any:
"""calculate __getitem__ in terms of an iterable query object
that also has a slice() method.
"""
def _no_negative_indexes():
raise IndexError(
"negative indexes are not accepted by SQL "
"index / slice operato... | 60,286 |
def density_matrix(
N, z, l, dims=(32, 32, 32), sigma=0.5, dist=euclidean, label_frac=1.0, eps_frac=0.25
):
""" Compute density maps and species matrices """
a = l[0]
b = l[1]
c = l[2]
dx = (a + (2 * a * eps_frac)) / dims[0]
dy = (b + (2 * b * eps_frac)) / dims[1]
dz = (c + (2 * c * eps_... | 60,287 |
def acl_diff(file_a, file_b, output_file, input_dir, output_dir):
"""
The ACL Diffing Function
:param file_a: The name of file a
:param file_b: The name of file b
:param output_file: The name of the output file
:param input_dir: The name of the input directory
:param output_dir: The name of ... | 60,288 |
def train(model, train_loader, optimizer):
"""Train for one epoch."""
print('running train')
batch_time = AverageMeter()
data_time = AverageMeter()
losses = AverageMeter()
top1 = AverageMeter()
top5 = AverageMeter()
model.train()
end = time.time()
for i, (input, target) in enumer... | 60,289 |
def awl_data(word: str)->int:
"""returns all available awl data"""
result = 0
for pos in range(awl.nrows):
if (word == awl.cell(pos,0).value):
result = awl.cell(pos,1).value #AWL rating
break
pos += 1
return result | 60,290 |
def _js_compile_action(ctx, rule_kind, module_name, friend_paths=depset(), src_jars=[]):
"""Setup a kotlin js compile action.
Args:
ctx: The rule context.
Returns:
A JavaInfo struct for the output js file that this macro will build.
"""
# The main output js file
output_js = ctx.... | 60,291 |
def get_response(method: Callable,
url: str,
auth: AuthBase,
json: Optional[Dict]=frozenset()):
"""
Sends a request and checks the response for errors, and retries unless it's
a HTTP client error.
"""
headers = ({'If-None-Match': _RESPONSES[url].hea... | 60,292 |
def _points_in_convex_polygon_3d_jit(points, polygon_surfaces, normal_vec, d, num_surfaces=None):
"""
check points is in 3d convex polygons.
:param points: input points
:param polygon_surfaces: [num_polygon, max_num_surfaces, max_num_points_of_surface, 3] array.
all surfaces' normal vector mu... | 60,293 |
def psar_up(high, low, close, step=0.02, max_step=0.20):
"""Parabolic Stop and Reverse (Parabolic SAR)
Returns the PSAR series with non-N/A values for upward trends
https://school.stockcharts.com/doku.php?id=technical_indicators:parabolic_sar
Args:
high(pandas.Series): dataset 'High' column.
... | 60,294 |
def acons(x,v,seq):
"""Creates a fresh cons, the cdr of which is alist and the car of which is
another fresh cons, the car of which is key and the cdr of which is
datum. """
return lisptype.lispCons(lisptype.lispCons(x,v),seq) | 60,295 |
def run(username=None, password=None, period_minutes=None):
""" argument == 'None' will be replaced with the value from the configuration file """
printer = printlog.PrintLog('logger.log')
try:
if username == 'unittest':
job = session.Session(
local_settings.login_url(),
... | 60,296 |
def side_regress_loss(predict_side_deltas, tgt_deltas, tgt_cls_ids, anchor_indices_sampled):
"""侧边改善回归损失
Parameter:
predict_deltas: 预测的dx回归目标,[batch_num, anchors_num, 2]
tgt_deltas: 真实的回归目标,[batch_num, ctpn_train_anchor_num, (dy,dh,dx,padding_flag)]
tgt_cls_ids: 真实的类别目标,[batch_num, ctpn_... | 60,297 |
def palindromic(d):
"""Gets a palindromic number made from a product of two d-digit numbers"""
# Get the upper limit of d digits, e.g 3 digits is 999
a = 10 ** d - 1
b = a
# Get the lower limit of d digits, e.g. 3 digits is 100
limit = 10 ** (d - 1)
for x in range(a, limit - 1, -1):
... | 60,298 |
def db_session(app, database):
"""Create a new database session."""
connection = db.engine.connect()
transaction = connection.begin()
options = dict(bind=connection, binds={})
session = db.create_scoped_session(options=options)
db.session = session
db.app = app
yield session
tran... | 60,299 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.