content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def handler():
"""
This function puts into memcache and get from it.
Memcache is hosted using elasticache
"""
#r = redis.Redis(
#host='datanode-001.zumykb.0001.use2.cache.amazonaws.com',
#port=6379)
logging.info('created redis client')
queryuserid = sys.argv[1]
querylat = float(sys.argv[2])
querylong = flo... | 70,100 |
def init():
"""Initialize the challenge."""
if settings.DEBUG:
import logging
# logger = logging.getLogger('django.db.backends')
# logger.setLevel(logging.DEBUG)
# logger.addHandler(logging.StreamHandler())
logger = logging.getLogger('django_auth_ldap')
logger.addH... | 70,101 |
def a_view(request):
"""Regular unlocked view."""
return HttpResponse('A view.') | 70,102 |
def rotz(ang):
"""
Create a rotation matrix (3 x 3 np.array) in the 3D space with respect to z axis
:param ang: radians. If ang <(>) 0, rotation is (anti-)clockwise with respect to z.
:return: Rz: np.array of shape (3, 3) representing the rotation matrix
"""
Rz = np.array(
[
... | 70,103 |
def copy(source, destination, quiet=False):
""" Copy a file or folder.
"""
src = os.path.normpath(source)
dst = os.path.normpath(destination)
if not quiet:
pass
#verbose.print_('copy "%s" -> "%s"' %(src, dst))
try:
shutil.copyfile(src, dst)
return True, dst
except:
exc_type, exc_value, exc_traceback =... | 70,104 |
def check(c):
"""Check the code is ok by running flake8, black, isort and mypy."""
print("> check that code is formatted well")
c.run("black --check .")
c.run("isort --check-only .")
print("> lint with flake8")
c.run("flake8")
print("> typecheck")
c.run("mypy .") | 70,105 |
def fixture_vcf_dir(fixtures_dir: Path) -> Path:
"""Return the path to the vcf fixtures directory"""
return fixtures_dir / "vcfs" | 70,106 |
def save_as_netcdf(vars, varnames, formats, fname):
"""Save variables in a NetCDF4 file."""
rootgrp = nc.Dataset(fname, "w", format="NETCDF4")
for iv, v in enumerate(vars):
dims = {}
dimname = varnames[iv] + "dim"
dimspec = (varnames[iv] + "dim",)
if formats[iv] == "c32":
... | 70,107 |
def init_params(units, activations):
"""Initialize parameters of the model.
Arguments:
units (list): Each item in the list is the number of units
in the layer. units[0] is the number of input units and
units[len(units) - 1] is the number of output units.
activations (list): Each... | 70,108 |
def pos_features(df):
"""
Gets several part-of-speech features:
1) Percentage of nouns and proper nouns.
2) Percentage of proper nouns
3) Percentage of pronouns
4) Percentage of conjunctions
Needs features:
Tokens
N_words
Adds features
Noun_percent: percentage of no... | 70,109 |
def no_cache(func):
"""Decorator to disable proxy response caching."""
def wrapped_function(*args, **kwargs):
"""Wrapper function to add required headers."""
if flask.request.method == 'OPTIONS':
resp = flask.current_app.make_default_options_response()
else:
resp ... | 70,110 |
def test_stats_of_1_device_with_timestamp() -> None:
"""Tests retrieval & formatting of the stats of a
uniq devices when timestamps are somewhat ok"""
delete_all_collections_datas()
prep_db_if_not_exist()
add_fake_datas(12, 5, False, False)
query: List[str] = ["fake_device_stage1_3"]
iface_... | 70,111 |
def NDArrayEnd(builder):
"""This method is deprecated. Please switch to End."""
return End(builder) | 70,112 |
def _ScanModule(module):
"""Runs all the scan_hooks for a module."""
scanner_tags = getattr(module, _MODULE_SCANNED_TAG, None)
if scanner_tags is None:
# First scan, add the scanned marker set.
scanner_tags = set()
setattr(module, _MODULE_SCANNED_TAG, scanner_tags)
for scan in scan_hooks:
if sca... | 70,113 |
def calcularPVoto(tVoto, vJogador):
"""
-> Calcula o percentual de voto de cada jogador que recebeu voto
:param tVoto: Quantidade total de votos computados
:param vJogador: Quantidade de votos do jagador a ser calculado o percentual
Função criada por Jcvendrame
"""
return (vJogador / tVoto) ... | 70,114 |
def construct_SA1_wavefront(nx, ny, ekev, q, xoff = 0, yoff = 0, mx = 0, my = 0,
tiltX = 0, tiltY = 0,
xMin = -400e-06, xMax = 400e-06,
yMin = -400e-06, yMax = 400e-06):
"""
Construct a fully-coherent Gaussian source with proper... | 70,115 |
def check_sudoku_block(board, row, col):
"""
Check if the Sudoku board is valid.
"""
board_size = board.shape[0]
block_size = int(np.sqrt(board_size))
row_start = row - row % block_size
col_start = col - col % block_size
gt = set(range(1, board_size + 1))
r = set(board[row_start:(ro... | 70,116 |
def equalRankin(ranking, other):
"""Compare two rankings
Args:
ranking (List<CurrencyUsers>)
other (List<CurrencyUsers>)
Return:
Boolean. True if both ranking are equals.
"""
if not other or not ranking:
return False
if len(ranking) != len(other):
return ... | 70,117 |
def get_game_range_row_names(game_begin, game_end):
"""Get the row range containing the given games.
Sample row name:
g_0000000001_m001
To capture the range of all moves in the two given games,
the end row will need to go up to g_00..(N+1).
Args:
game_begin: an integer of the beginni... | 70,118 |
def calc_QIF(P, T):
"""
Quartz-Iron-Fayalite (QIF)
==========================
Define QIF buffer value at P
Parameters
----------
P: float
Pressure in GPa
T: float or numpy array
Temperature in degrees K
Returns
-------
float or numpy array
log_fO2
References
----------
B. R. Frost in Mineralogic... | 70,119 |
def score_word_count(count: int) -> float:
"""Score word frequency as log of count with min of 1.0"""
return max(1.0, math.log(count)) | 70,120 |
def test_select_backend_unknown():
"""
Test select_backend fails correctly when the `MESSAGE_BACKEND` env var is invalid.
"""
os.environ["MESSAGE_BACKEND"] = "unknown_env_name"
with pytest.raises(ValueError):
action.select_backend() | 70,121 |
def render(filename, variables):
"""
Grabs the jinja2 file and renders it
:param filename: the jinja2 file to render
:param variables:
:return:
"""
with open(filename, 'rt') as f:
filename = jinja2.Template(f.read())
return filename.render(**variables) | 70,122 |
def load_genomes(UTRfilestring, firstStopsCSV, twobitfile):
"""
make this a separate function so that these only need to be loaded a single time
"""
UTRdict= rph.readindict(open(UTRfilestring, "rU"))
utr3adj = pd.read_csv(firstStopsCSV, index_col=0)
genome= twobitreader.TwoBitFile(twobitfile) # do we actually nee... | 70,123 |
def calcTheta(wavelength, z1):
"""
Calculates the d spacing and the theta angle for a scattering
vector z1
@param wavelength
@param z1 A 3 component numpy array representing the scattering
vector
@param A tuple consisting of the d-value and the theta angle in
radians
... | 70,124 |
def octahedron():
"""Return the best integral embedding of the octahedral graph."""
v1 = (13 * root(1, 6, 1) - 2) / 3
v2 = -v1.conjugate()
omega = root(1, 3, 1)
v3 = v1 * omega
v4 = v2 * omega
v5 = v1 / omega
v6 = v2 / omega
vertices = (v1, v2, v3, v4, v5, v6)
edges = ((0, 1), (0... | 70,125 |
def symbols_for_inclusion(file: CheckFile, match) -> list:
""" Return a list of symbols for a match. """
line_number, column = file.line_number_at(match.end())
line = file.line_at(line_number)
include_suffix = line[column:]
if not is_symbol_list(include_suffix):
return []
listing = ... | 70,126 |
def sample_user(email="student@test.com",
password="password123",
name="some name"):
"""Create sample user for tests"""
return get_user_model().objects.create_user(email=email,
password=password,
... | 70,127 |
def reduce(l):
"""
Args:
Rangelist: generic list of tuples (can be either float or int tuple)
Return:
Reduced int list based on average value of every tuple in input tuple list
"""
result = []
for s in l:
midVal = abs(float(s[0]) - float(s[1])) / 2.0
result.append... | 70,128 |
def append_data_dir(proj_data_dir: str) -> None:
"""
Add an additional data directory for PROJ to use.
Parameters
----------
proj_data_dir: str
The path to the PROJ data directory.
"""
set_data_dir(os.pathsep.join([get_data_dir(), proj_data_dir])) | 70,129 |
def remove_osd_mounts(ctx):
"""
unmount any osd data mounts (scratch disks)
"""
ctx.cluster.run(
args=[
'grep',
'/var/lib/ceph/osd/',
'/etc/mtab',
run.Raw('|'),
'awk', '{print $2}', run.Raw('|'),
'xargs', '-r',
'... | 70,130 |
def test_config_absence(cluster: Cluster, provider: Provider):
"""Check that ADCM reacts adequate on passing config to bundle with no config"""
_expect_correct_fail_on_config(cluster, provider, {'oh_no': 'config is absent'}, CONFIG_NOT_FOUND) | 70,131 |
def polygon_iou(pts1, pts2):
"""
Intersection over union between two shapely polygons.
"""
poly1 = Polygon(pts1).convex_hull
poly2 = Polygon(pts2).convex_hull
# union_poly = np.concatenate((pts1, pts2))
if not poly1.intersects(poly2): # this test is fast and can accelerate calculation
... | 70,132 |
def diffusion(u, tempU, iterNum):
"""
Apply Numpy matrix for the Forward-Euler Approximation
"""
mu = .1
for n in range(iterNum):
tempU[1:-1, 1:-1] = u[1:-1, 1:-1] + mu * (
u[2:, 1:-1] - 2 * u[1:-1, 1:-1] + u[0:-2, 1:-1] +
u[1:-1, 2:] - 2 * u[1:-1, 1:-1] + u[1:-1, 0:... | 70,133 |
def choose_team_levels(num_teams, hackathon_level):
""" Calculates the average experience level per team and distributes any
remaining difference among some of the teams evenly
Returns a list of team_levels """
avg_team_level = math.floor(hackathon_level / num_teams)
team_levels = []
remainder ... | 70,134 |
def overall_random_accuracy_calc(item):
"""
Calculate overall random accuracy.
:param item: RACC or RACCU
:type item : dict
:return: overall random accuracy as float
"""
try:
return sum(item.values())
except Exception:
return "None" | 70,135 |
def awsloader() -> Generator[AWSLoader, None, None]:
"""Create a fixture to test with"""
loader = AWSLoader()
assert not loader.loaded_values
yield loader | 70,136 |
def infer_time_unit(time_seconds_arr):
"""
Determine the most appropriate time unit for an array of time durations
specified in seconds.
e.g. 5400 seconds => 'minutes', 36000 seconds => 'hours'
"""
if len(time_seconds_arr) == 0:
return 'hours'
max_time_seconds = max(time_seconds_arr... | 70,137 |
def user_is_author_of_snippet(user, snippet_type, snippet_id):
"""
Checks if the current user is
the author of the snippet provided
"""
snippet_models = {
"project": Project,
"skill": Skill,
"profile": Profile
}
snippet = get_object_or_404(snippet_models[snippet_type]... | 70,138 |
def test_roc_curve_multi():
"""roc_curve not applicable for multi-class problems"""
y_true, _, probas_pred = make_prediction(binary=False)
assert_raises(ValueError, roc_curve, y_true, probas_pred) | 70,139 |
def postorder_traversal(node):
"""
Do a postorder traversal of a tree.
This generator recursively yields nodes that it has visited in a postorder
fashion. That is, it descends through the tree depth-first to yield all of
a node's children's postorder traversal before yielding the node itself.
... | 70,140 |
def _batch_hard(query_features, positive_features, item_ids):
"""
Adapts the 'Batch Hard' triplet mining strategy of Hermans, Beyer, and Leibe.
This method differs from Batch Hard in that we don't search for the hardest positive
and just use the one positive example provided.
Args:
query_featur... | 70,141 |
def add_paper_grading_sheet(supervisor, modified_df):
"""Adding the Paper Grading sheet with all supervised student Papers and grading metrics"""
src_grading_wb = load_workbook('DataSources/Foik_GradingSheetSeminar.xlsx')
print("The available sheets in the xlsx file")
print(src_grading_wb.sheetnames)
... | 70,142 |
def _test_python_reader(basename):
"""Check that (test cells) and (test contents ==> cells) are the same."""
converted, expected = _test_reader(basename, 'python')
assert _remove_output(converted) == _remove_output(expected) | 70,143 |
def compare_gbp_cs_with_different_init_points():
"""Compare the optimization curves of GBP-CS with different
initialization points."""
init_strategy = ["Zero Init", "Rand Init", "MPInv Init"]
dist_info = {
"Zero Init": [0.123, 0.105, 0.075, 0.060, 0.047,
0.042, 0.036, 0.033... | 70,144 |
def getnuc(nuc = 430990001):
"""
This computes ORIGEN data based on ENSDF data.
FIXME: calculate B- and EC decays that end in metastable state after gamma transition
Parameters
----------
nid : nuc_id
a valid string or int that can be converted into a nuc_id
meta_t : float
... | 70,145 |
def addContraints(d, Ca):
""" Ajoute les conditions de Robinson qui ne sont pas encore satisfaites à Ca """
addedConstraints = False
precision=0.0001
nb=0
# print 'Contraintes ajoutees'
for i in range(d.n-2):
for j in range(i+2, d.n):
if (d[i,j] < d[i,j-1] - precision) and ([... | 70,146 |
def getTaxonomyKEGG() -> List[str]:
"""
Get KEGG taxonomy from KEGG BRITE.
Returns
-------
List[str]
Taxonomy of organisms in KEGG, in special text format, following KEGG's own scheme, line by line.
Raises
------
URLError
If connection to KEGG fails.
"""
... | 70,147 |
def fprint(prompt: str, question: bool=False, returnstr: bool=False):
"""
Fancy print function
"""
tags = {'[o]': '[\033[01;32m+\033[0m]',
'[ok]': '[\033[01;32m+\033[0m]',
'[+]': '[\033[01;32m+\033[0m]',
'[e]': '[\033[01;31m-\033[0m]',
'[er]': '[\033[01;31... | 70,148 |
def test_sort_ontology_unparseable_file(tmp_dir: "Path") -> None:
"""Ensure exceptions from RDFlib during parsing an unparseable Turtle file are
wrapped as Turtle Canon exceptions."""
import os
from turtle_canon.canon import sort_ontology
from turtle_canon.utils.exceptions import FailedParsingFile
... | 70,149 |
def test_text_multi_label_binarize():
"""Tests encoding.text_multi_label_binarize"""
# Should multi-label encode both specified columns, and not non-specified
df = pd.DataFrame()
df['a'] = ['aa,bb', 'aa', 'bb', 'bb,cc']
df['b'] = ['asdf,bb_r', 'haha', 'haha,asdf', 'asdf,asdf']
df['c'] = np.rand... | 70,150 |
def make_html(web_dir, title="Summary Pages", pages=None, stylesheets=[],
label=None):
"""Make the initial html page.
Parameters
----------
web_dir: str
path to the location where you would like the html file to be saved
title: str, optional
header title of html page
... | 70,151 |
def random_tuple_list(lst1, lst2, lb=1):
"""
Generate a random list of tuples (x,y) where x is in lst1 and y is in lst2;
"""
product = list(itertools.product(lst1, lst2))
if len(product) == 0:
k = 0
else:
k = random.randint(lb, len(product))
tups = random.sample(product,k)
... | 70,152 |
def head() :
"""official banner for PyStalker printed in yellow color"""
clear()
pystalker_banner = r"""
____ ____ _ _ _
| _ \ _ _/ ___|| |_ __ _| | | _____ _ __
| |_) | | | \___ \| __/ _` | | |/ / _ \ '__|
| __/| |_| |___) |... | 70,153 |
def tmp_img(tmpdir):
"""Get temp image fixture used by some test."""
img_path = tmpdir.join('image.jpg')
im = Image.new('RGB', (160, 160))
im.save(img_path.strpath)
return img_path | 70,154 |
def combine_stage1_stage2(df_1, df_2):
"""Combines the stage 1 and stage 2 submissions.
Replaces the positive class predictions in df_1 with those created in
df_2.
Args:
df_1 (pd.DataFrame): Stage 1 submission
df_2 (pd.DataFrame): Stage 2 submission
Return:
combined_df... | 70,155 |
def swap_status_iterator(uuids_list: list, node_proxy: MMProxy) -> dict:
"""Builds swaps statuses dictionary"""
swaps_d = dict.fromkeys(uuids_list, 'unknown')
while True:
work_d = {} # intermediate dictionary to iterate unfinished swaps
values_list = []
for key in swaps_d: # find u... | 70,156 |
def capture_exception(err: Exception, level: str = "error", extra_tags: dict = {}):
"""
Capture an exception. Optionally set the log level of the event. Extra tags accepted.
"""
with sentry_sdk.push_scope() as scope:
scope.set_level(level)
for k, v in extra_tags:
scope.set_t... | 70,157 |
def from_utc(utcTime, fmt="%Y-%m-%dT%H:%M:%SZ"):
"""
Convert UTC time string to time.struct_time
"""
return datetime.datetime.strptime(utcTime, fmt) | 70,158 |
def intersectGraphs(graph1={}, graph2={}):
"""Given two Graphs, create a new Graph that is their Relational Intersection
` Preconditions: Graph in Xaya Format
Postconditions: returns a graph in XAYA format with intersecting keys and values
Invariants: The input graphs do not change
... | 70,159 |
def airtable_message(request, instance, message="Airtable record updated", button_text="View record in Airtable", buttons_enabled=True) -> None:
"""
Common message handler for Wagtail hooks.
Supports a custom message, custom button text, and the ability to disable buttons entirely (use case: deleting a rec... | 70,160 |
def get_r2(reg, X, y):
"""Calculate the goodness of fit of regression model.
Arguments:
reg {model} -- regression model.
X {ndarray} -- 2d array object with int or float.
y {ndarray} -- 1d array object with int.
Returns:
float
"""
if isinstance(y, list):
y =... | 70,161 |
def test_cli_fix():
"""Test fix for ``cli``."""
assert Cli is ClFixHybridPressureCoord | 70,162 |
def h_m_emg_rvs(mu, sigma, *t_args,N_samples=1):
"""Draw random samples from negative skewed hyper-EMG probabaility density
Parameters
----------
mu : float
Nominal position of simulated peak (mean of underlying Gaussian).
sigma : float
Nominal standard deviation (of the und... | 70,163 |
def jupyter(no_build=False):
"""Run a jupyter with everything mapped (build if necessary)"""
d, config = get_anysnake()
if not no_build:
d.ensure()
else:
d.ensure_just_docker()
host_port = get_next_free_port(8888)
print("Starting notebook at %i" % host_port)
nbextensions_not... | 70,164 |
async def update_request(ctx):
"""
Function: update_request
Description: Help for command update_request
Inputs:
- ctx: Context of the function activation
Outputs: Result of !help update_request
"""
embed = Embed(title='update-request',
descri... | 70,165 |
def user_ajax_answer(request):
"""Submitting work to task (making Answer of it) is handled here.
Accepts only POST requests.
POST (ajax) params (all required):
wi: work id
ti: task id
ni: network id
a: action, (add or remove)
"""
if request.method !=... | 70,166 |
def get_diff(a, b):
"""比较图片差异"""
return get_match(a, b)[0] | 70,167 |
def get_image_metrics_for_samples(
real_images, generator, prior, data_processor, num_eval_samples):
"""Compute inception score and FID."""
max_classifier_batch = 10
num_batches = num_eval_samples // max_classifier_batch
def sample_fn(arg):
del arg
samples = generator(prior.sample(max_classifier_b... | 70,168 |
def load_data(
partition: int, num_clients: int
) -> Tuple[Tuple[np.ndarray, np.ndarray], Tuple[np.ndarray, np.ndarray]]:
"""Load partition of randomly shuffled Fashion-MNIST subset."""
# Load training and test data (ignoring the test data for now)
(x_train, y_train), (x_test, y_test) = tf.keras.dataset... | 70,169 |
def flip_y(im):
"""mirrors an image over the x axis."""
source_pix = im.load()
im = im.copy()
dest_pix = im.load()
width, height = im.size
for i in range(width):
for j in range(height):
dest_pix[i,j] = source_pix[i, height-j-1]
return im | 70,170 |
def augment_menpo_img_geom_dont_apply(img, p_geom=0):
"""geometric style image augmentation using random face deformations"""
if p_geom > 0.5:
lms_geom_warp = deform_face_geometric_style(img.landmarks['PTS'].points.copy(), p_scale=p_geom, p_shift=p_geom)
return img | 70,171 |
def lower_matrix_to_vector(lower: torch.Tensor) -> torch.Tensor:
"""Convert a lower triangular matrix to a vector.
Parameters
----------
lower : torch.Tensor
lower
Returns
-------
torch.Tensor
"""
shape = lower.shape
assert shape[-1] == shape[-2]
lower_idx = torch.... | 70,172 |
def PoStag(filepath, output, postProc=lambda w, tag: (w,tag), preProc=lambda w: w):
"""Pass tokenized file to tagger convert file to CoNLL and write to output"""
inpt = codecs.open(filepath, encoding="utf-8")
text = inpt.readlines()
inpt.close()
text = "\n".join([preProc(w.strip()) for w i... | 70,173 |
def unique(iterable, seen=None):
"""
Yields items from the given `iterable` of (hashable) items, once seen an
item is not yielded again.
:param seen:
An iterable specifying already 'seen' items which will be excluded
from the result.
.. versionadded:: 0.5
.. versionchanged:: ... | 70,174 |
def proxy_line(**kwargs):
"""
Generates a legend proxy for a line region.
Returns
----------
:class:`matplotlib.lines.Line2D`
"""
return matplotlib.lines.Line2D(range(1), range(1), **kwargs) | 70,175 |
def cluster_cr_conv(sources: Union[GalaxyCluster, ClusterSample], outer_radius: Union[str, Quantity],
inner_radius: Union[str, Quantity] = Quantity(0, 'arcsec'), sim_temp: Quantity = Quantity(3, 'keV'),
sim_met: Union[float, List] = 0.3, conv_en: Quantity = Quantity([[0.5, 2.0]],... | 70,176 |
def test_drawing():
"""Test circuit drawing"""
x = np.array(0.1, requires_grad=True)
y = np.array([0.2, 0.3], requires_grad=True)
z = np.array(0.4, requires_grad=True)
dev = qml.device("default.qubit", wires=2)
@qml.beta.qnode(dev, interface="autograd")
def circuit(p1, p2=y, **k... | 70,177 |
def test_indented_code_blocks_086a():
"""
Test case 086a: variation of 86 to include more spaces so extracted != left
"""
# Arrange
source_markdown = """ foo
bar"""
expected_tokens = [
"[icode-block(1,5): :\n ]",
"[text(1,5):foo\nbar: ]",
"[end-ico... | 70,178 |
def encrypt_vault_password(key: bytes, password: Union[str, bytes]) -> bytes:
"""Encrypt and return the given vault password.
:param key: The key to be used during the encryption
:param password: The password to encrypt
"""
if isinstance(password, str):
password = password.encode("utf-8")
... | 70,179 |
def t_to_col(t, tmin=6, tmax=11):
"""
Given a BPASS time bin, returns a value to input into the time colormap
Parameter
---------
t : float
BPASS log time bin between 6 and 11
Returns
-------
out : int
Input to tcmap to get the right color out
"""
co... | 70,180 |
def andorra(nsb, component_type, iasb, jasb, nc, cnew, csb, nelec, nsites, \
namesb, namec, sorption_group, chargesb, xnusb, nsites2, chargec, \
sorption_type, cap1, cap2, site_mass, site_area, totpsi, calcpsi, strionsb, \
surfacensb):
"""
andorra(nsb, component_type, iasb, jasb, nc, cnew, csb, nele... | 70,181 |
def create(user, request):
"""Create a new album for this user."""
# TODO validate the name in some manner?
# TODO also validate the permission ahem
album = model.Album(
name=request.POST['name'],
encapsulation=request.POST['privacy'],
)
user.albums.append(album)
model.sessio... | 70,182 |
def blockify(sudoku):
"""
Converts 9x9 sudoku list into a list containing lists of values in given sudoku's blocks
args:
-sudoku - 9x9 sudoku list
returns: List with lists of values of sudoku blocks
"""
i=0
block_row = []
while i<len(sudoku):
j=0
while j<7:
... | 70,183 |
def map_coords_to_scaled_float(coords, orig_size, new_size):
"""
maps coordinates relative to the original 3-D image to coordinates corresponding to the
re-scaled 3-D image, given the coordinates and the shapes of the original and "new" scaled
images. Returns a floating-point coordinate center where t... | 70,184 |
def residual_standard_unit(n, nout, s, newdepth=False):
"""
This creates the 'standard unit' shown on the left side of Figure 5.
"""
bottom = n.__dict__['tops'].keys()[-1] # find the last layer in netspec
stride = 2 if newdepth else 1
n[s + 'conv1'], n[s + 'bn1'] = conv_bn(n[bottom], ks=3, str... | 70,185 |
def getPosition(junctionID):
"""getPosition(string) -> (double, double)
Returns the coordinates of the center of the junction.
"""
return _getUniversal(tc.VAR_POSITION, junctionID) | 70,186 |
def warmer_errors_write_print(prefix):
"""
Print all the files with write errors to stdout, optionally prepending the supplied prefix
:param str prefix: Optional prefix to prepend to each name
"""
w = warmer_errors_write()
for fname in w:
print("{}{}".format(prefix,fname))
return | 70,187 |
def _structure_summary(structure):
"""
Extract messages from the structure.
Args:
structure: a Pymatgen Structure object
Returns:
dict of the following messages:
nsites (int): number of sites in the structure.
is_ordered (bool): whether the structure is ordered or not.
... | 70,188 |
def _mock_run(*args, **kwargs):
"""Placeholder logic for logging tests."""
logging.debug(args)
logging.debug(kwargs)
logging.warning("warning")
logging.error("error")
return True | 70,189 |
def id_type_dict(obj):
"""Creates dictionary with selected field from supplied object."""
if obj is None:
return None
return {
'id': str(obj.id),
'type': obj.type,
} | 70,190 |
def _split_selections_property_and_vertex(
selections: Sequence[Union[SelectionNode]],
# OrderedDict is unsubscriptable (pylint E1136)
) -> Tuple["OrderedDict[str, SelectionNode]", List[SelectionNode]]:
"""Split input selections into property fields and vertex fields/type coercions.
Args:
selec... | 70,191 |
def cached_path(
url_or_filename,
cache_dir=None,
force_download=False,
proxies=None,
resume_download=False,
user_agent: Union[Dict, str, None] = None,
extract_compressed_file=False,
force_extract=False,
local_files_only=False,
) -> Optional[str]:
"""
Given something that mig... | 70,192 |
def is_3d(mesh: Mesh) -> bool:
"""Check if a meshio mesh is 3-dimensional"""
for cell_block in mesh.cells:
# first 3D element type is enough.
if meshio_type_to_alpha[cell_block.type] in meshio_3d:
return True
return False | 70,193 |
def get_nginx_webserver_log(interval: float):
"""
A method to be used to generate logs based on supplied parameters and return them.
:param: interval: Time interval between two consecutive logs
:type: interval: int
"""
dt = datetime.utcnow()
while True:
yield Nginx.get_log_line(dt=... | 70,194 |
def fom_properties(fom, w):
"""Show properties of the full-order model.
Parameters
----------
fom
The full-order `Model` from :mod:`~pymor.models.iosys`.
w
Array of frequencies.
"""
from pymor.models.transfer_function import TransferFunction
if not isinstance(fom, Transf... | 70,195 |
def multiclass_nms(multi_bboxes,
multi_scores,
score_thr,
nms_cfg,
max_num=-1,
score_factors=None):
"""NMS for multi-class bboxes.
Args:
multi_bboxes (Tensor): shape (n, #class*4) or (n, 4)
multi_scor... | 70,196 |
def delete_case_study(case_study_id):
"""
Delete a case study
:param case_study_id:
:return:
"""
updater_json = validate_and_return_updater_request()
casestudy = CaseStudy.query.filter(
CaseStudy.id == case_study_id
).first_or_404()
audit = AuditEvent(
audit_type=A... | 70,197 |
def clustering_kmember(nec_set, k=25):
"""
group record accroding to QID distance. K-member
:param nec_set: natural EC
:param k: k
:return: grouped clusters
"""
clusters = [cluster for cluster in nec_set if len(cluster) >= k]
nec_set = [cluster for cluster in nec_set if len(cluster) < k]... | 70,198 |
def imports():
"""iter current loaded modules"""
for name, val in globals().items():
if isinstance(val, getattr(types, "ModuleType")):
yield val.__name__ | 70,199 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.