content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def col2im(input, kernel_size, stride, padding):
"""Converts columns back to NCHW format.
This is used in backward wrt inputs in GEMM-based convolution.
"""
return Col2Im(kernel_size, stride, padding)(input) | 4980fbcb4e8a6fed1f355cb27efe27f856504b13 | 60,300 |
import collections
def _create_p13n_fn_dict(learning_rate):
"""Creates a dictionary containing two personalization strategies."""
p13n_fn_dict = collections.OrderedDict()
opt_fn = lambda: tf.keras.optimizers.SGD(learning_rate=learning_rate)
# The two personalization strategies use different training batch si... | 1127d172e08654af35fe2dfeee47c22aec328494 | 60,301 |
def _es_documents_for(locale, topics=None, products=None):
"""ES implementation of documents_for."""
s = (Document.search()
.values_dict('id', 'document_title', 'url', 'document_parent_id',
'document_summary')
.filter(document_locale=locale, document_is_archived=False,
... | a4ff9a6cddcf25174ff2ec88e5154b426acc16c4 | 60,302 |
from typing import Dict
def output(jobId : str = '', **params) -> Dict:
"""
Displays results for a job in the current Azure Quantum workspace.
See https://docs.microsoft.com/qsharp/api/iqsharp-magic/azure.output for more details.
"""
result = qsharp.client._execute_magic(f"azure.output {jobId}", r... | f8f5c3235c09ce94dfb6f593485a164ce802c51b | 60,303 |
import torch
def calc_displacement(displacement, n_iter = 1000):
"""
Calculates the displacement estimate given the displacement matrix (decentralized registration)
"""
p = torch.zeros(displacement.shape[0]).cuda()
displacement = torch.from_numpy(displacement).cuda().float()
n_batch = displac... | bbaa51463b0a9f606a2c179ef48f07e244cc772c | 60,304 |
import time
def monitor_inference_service(name: str):
"""Waits for an InferenceService to become ready.
An InferenceService is considered ready when two conditions are met:
1. the ``status.conditions`` field of the CR contains a condition of
type ``Ready`` with a ``True`` status.
2. The... | 0a101a14fb31ecea0162c5b82faf747aec635725 | 60,305 |
def explained_var(y_true, y_pred):
"""
Custom metric for Keras, explained variance.
"""
return 1 - K.mean((y_true - y_pred) ** 2) / K.var(y_true) | 529cbf7665ab4aa996ff534111005e28859443c6 | 60,306 |
def is_registered(label):
"""
Checks whether a specific label has already been registered.
Args:
label (str): Label to check for.
Return:
bool: True if registered, False if not.
"""
if not isinstance(label, (str, bytes)):
raise TypeError("Only strings allowed as labels!")
... | c6c7d76791f77bc77bebe0f29fbc24a0d898f678 | 60,307 |
def load_saved_json(concepts_file):
"""
Read a saved termset as a JSON to format it as a dataframe.
"""
df = pd.read_json(concepts_file, orient="index")
df = df.reset_index().rename(columns={"index": "concept"})
df = df.melt(id_vars=["concept"], value_vars=df.columns[1:], value_name="term")
... | 96157391f5d9ccf39dfb3905e235e211012201aa | 60,308 |
import zlib
def deflate_encode(data, level=6, raw=False, out=None):
"""Compress Deflate/Zlib."""
if raw:
raise NotImplementedError
return zlib.compress(data, level) | 2b7b369c4d2e837dfcab00a1dfa60f6f0ef8775a | 60,309 |
def _component_display_name(
component_type: StackComponentType, plural: bool = False
) -> str:
"""Human-readable name for a stack component."""
name = component_type.plural if plural else component_type.value
return name.replace("_", " ") | 1c4f137b9efadb4b516d99e99d25b53680bd1f90 | 60,310 |
import sys
import warnings
import pkgutil
def _get_template():
"""Returns the content of user_template_reader.py as a utf-8 string."""
# pkgutil.get_data triggers a ResourceWarnin'g on Python 3.2
if sys.version_info[:2] == (3, 2):
warnings.simplefilter('ignore', ResourceWarning)
bytes = pkguti... | 9afe5fa9f7d94d38222a380347209dd997f3373a | 60,311 |
def build_add_user_to_group_request(
hub, # type: str
group, # type: str
user_id, # type: str
**kwargs # type: Any
):
# type: (...) -> HttpRequest
"""Add a user to the target group.
Add a user to the target group.
See https://aka.ms/azsdk/python/llcwiki for how to incorporate this ... | 32ed15fd35f84bb3af830496f60b22bcc99de331 | 60,312 |
import click
def n_protocols_option(required=True, **kwargs):
"""Get option for number of protocols."""
def custom_n_protocols_option(func):
def callback(ctx, param, value):
value = abs(value)
ctx.meta["protocols_number"] = value
return value
return click.... | bcdd204ea9b9cd7d09e159ba45ea54b349c648b6 | 60,313 |
def copy_fields(model):
"""
Creates copies of the model's original fields, returning
a dictionary mapping field name to copied field object.
"""
fields = {
PK: AutoField(verbose_name=PK,
primary_key=True,
auto_created=True),
CU: create_user... | e13a76099f80559e3047cdf16535b907b5d5ae3e | 60,314 |
def fibonacci(number: int) -> int:
"""Returns fibonacci number.
Args:
number: number to count fibonacci sequence
"""
counter, handler = 1, 1
for next_number in range(number - 1): # type: int
counter, handler = handler, counter + handler
return counter | 88931af6f1d22ea4d01fe77a46eaec504eff9020 | 60,315 |
def next_bound_var(bound_vars, type):
"""
Helper function: generate the next bound variable in a context where there
are currently the bound variables `bound_vars` (assumed to be generated by
this function).
"""
name_length = 1 + len(bound_vars) // 26
name_id = len(bound_vars) % 26
name = chr(97 + name_... | bd9a6027ecce2b2ea1e7980a72ed8768ab465c0f | 60,316 |
def _estimate_covar(cweights, proppts, mean, covmat):
"""See BFaS; p. 88.
Parameters
----------
cweights: np.ndarray, shape (2*dimension + 1,)
Constant kernels weights for unscented transform.
proppts: np.ndarray, shape (2*dimension + 1, dimension)
Propagated sigma points
mean: ... | 514d892c25bac16853e98c31d4b47ab20d99800f | 60,317 |
def profile(request, username):
"""Возвращение информации об авторе и его постов"""
user = get_object_or_404(User, username=username)
post_list = user.posts.all()
paginator = Paginator(post_list, 10)
page_number = request.GET.get('page')
page = paginator.get_page(page_number)
return render(... | 84fd19e3d80a3f13bdac749c8e8bc3835daae038 | 60,318 |
from typing import List
from typing import Tuple
def update_comment_segments(comment_segments: List[Tuple[int, int]], pos: int, offset: int) -> List[Tuple[int, int]]:
"""
Update comment segments with an offset
"""
new_comment_segments = []
for begin, end in comment_segments:
if end >= pos... | 79a1d748b2672f675b85e2fb180645bf99e269c3 | 60,319 |
from operator import add
def identity_block(input_tensor, kernel_size, filters, stage, block):
"""The identity block is the block that has no conv layer at shortcut.
# Arguments
input_tensor: input tensor
kernel_size: default 3, the kernel size of
middle conv layer at main path
... | b0831023dff5cbe895f193fcc161b70612336800 | 60,320 |
import sys
import os
import signal
import time
import logging
import json
def test_master_shuts_down_busy_process_workers():
"""
Test managing process properly cleans up busy Process Workers
"""
# For debugging test
logger = logging.getLogger("pyqs")
logger.setLevel(logging.DEBUG)
stdout_h... | 3543205e7fa8a8cb9e03de6aeb3ecea9ea83fcfe | 60,321 |
def gyromagnetic_ratio(elem="mu", iso=None):
"""Return the gyromagnetic ratio of a given particle
Return the gyromagnetic ratio of either an atomic nucleus,
an electron or a muon. The value returned is in MHz/T. It
corresponds to a frequency, not a pulsation (so it's gamma,
not gammabar = 2*pi*gamm... | 89e241c26cd295e3dc4d4e7883f15b3c10728179 | 60,322 |
def load_trace(logfile, root_dir, api, blacklist):
"""Loads a trace file and returns the Results instance.
Arguments:
- logfile: File to load.
- root_dir: Root directory to use to determine if a file is relevant to the
trace or not.
- api: A tracing api instance.
- blacklist: Optional blackli... | e51ad3e61ee4206e74800f1c24b14fd20f51e477 | 60,323 |
def geez_alpha(s1, s2, pos1 = 0, pos2 = 0):
"""Comparator function for two strings or lists using Geez order."""
if s1 == s2:
return 0
elif pos1 >= len(s1):
return -1
elif pos2 >= len(s2):
return 1
else:
seg1 = s1[pos1]
seg2 = s2[pos2]
if seg1 == seg2:... | 0d713f8438c72c4471f621c296472e0fff0d8f05 | 60,324 |
def to_bob(img):
"""Returns a view of the image from matplotlib format to Bob format.
This function works with images, batches of images, videos, and higher
dimensional arrays that contain images.
Parameters
----------
img : numpy.ndarray
An image in matplotlib format (channels last): F... | 93b528f5ce84080b85d70a9d7b2c4d54519b7386 | 60,325 |
def mean(series):
"""
"""
avg = 0
for i in series:
avg += i
avg /= len(series)
return avg | 3795938f0cb3ebe3d1d1fed7b90980e2fd02690b | 60,326 |
def user_sign_up(request):
"""User Sign up view"""
if request.method == 'GET': # open sign up page
return render(request, 'image_repo/user_sign_up.html', {'form': UserCreationForm()})
else:
# create a new user with a built-in model
if request.POST.get('password1') == request.POST.ge... | 9d88d378fc211b86158e0acc49841f5341958fce | 60,327 |
def Endnote_text_split(f):
"""Parse the EndNote output in Text format
split into records
"""
records = []
blocks = []
with open(f, 'rt') as fi:
for line in fi:
line = line.strip()
if line.startswith('#') or not line:
continue # skip '#' and blank l... | 2aa63e222d23a3827828cf838dbc96dd60fb5f3e | 60,328 |
def get_evidence_fields_for_variant(genome_build: GenomeBuild, variant: Variant,
refseq_transcript_accession, ensembl_transcript_accession,
evidence_keys_list: list, annotation_version: AnnotationVersion) -> AutopopulateData:
""" annotation_ver... | 0125e2a2575aee968eb20cf5802f7ecc16a20fd7 | 60,329 |
def from_csv(*args, **kwargs):
"""Read from csv."""
gen = kwargs.pop("gen", True)
iterator = _csv_gen(*args, **kwargs)
return iterator if gen else _fix_and_split(iterator) | 64878e468fe3945f0d7c32281365cd1f9c30a235 | 60,330 |
import os
def get_immediate_subdirectories(path_base_dir):
"""
Args:
path_base_dir:
Returns:
"""
return [name for name in os.listdir(path_base_dir)
if os.path.isdir(os.path.join(path_base_dir, name))] | 19e73a71407ecac89ed763b19a9bcef3e53cd280 | 60,331 |
def csvSplit(line, delim=',', allowEol=True):
""" Take a string as input (e.g. a line in a csv text file), and break
it into tokens separated by commas while ignoring commas embedded inside
quoted sections. This is exactly what the 'csv' module is meant for, so
we *should* be using it, save that it has... | 09c423e97032214c9f01b92a03127b01a225c805 | 60,332 |
def sendMail(weekday):
"""This is a page which cron job requests to send an email.
If 'today' is defined in config.ini, and call was made from cron,
get the current forecast and send an email. Otherwise redirect.
Args:
weekday from url
Returns:
A message content of the email or redirection to Google
... | 828dd2334b149a98e12e16876ccb12ee7e98383f | 60,333 |
def splitUIAElementAttribs(attribsString):
"""Split an UIA Element attributes string into a dict of attribute keys and values.
An invalid attributes string does not cause an error, but strange results may be returned.
@param attribsString: The UIA Element attributes string to convert.
@type attribsString: str
@ret... | db472d90b2dacdda4606b39e2e1f1d959ae056ca | 60,334 |
def get_ident():
"""
Return a unique number for the current greenlet in the current thread.
"""
return hash((get_current_thread(), get_current_greenlet())) | 2c6361805acc1b13921f467d3f6e6b575ed9ff70 | 60,335 |
def apply_filter_include_exclude(
filename, include_filters, exclude_filters):
"""Apply inclusion/exclusion filters to filename
The include_filters are tested against
the given (relative) filename.
The exclude_filters are tested against
the stripped, given (relative), and absolute filenames... | 12d1f56436bfbee606d5a75f8aab5ad34e930981 | 60,336 |
def gen_indx(x_locs):
"""
Return the indexes for each node to be iterated over.
Uses the x_locs array as an array to mimic.
"""
n_elem = x_locs.shape[0] * x_locs.shape[1]
indx = np.arange(n_elem).reshape(x_locs.shape[0], x_locs.shape[1])
pindx = np.zeros_like(indx)
pindx[:] = -1
ret... | dfa66fd62465f1938deb8d14c22e91aef731cd1a | 60,337 |
import sympy
def differential (F, X):
"""
Computes the differential of the given [possibly tensor-valued] symbolic function F with respect to the
[possibly tensor-valued] symbolic argument X. If the shape of F is (f_1, f_2, ..., f_m,) and the shape of
X is (x_1, x_2, ..., x_n,), then the shape of the... | 46d9dd1ab2aab8c472bb98764c059656b820be9d | 60,338 |
import json
def setup_scanner(hass, config, see):
"""Setup an OwnTracks tracker."""
max_gps_accuracy = config.get(CONF_MAX_GPS_ACCURACY)
def validate_payload(payload, data_type):
"""Validate OwnTracks payload."""
try:
data = json.loads(payload)
except ValueError:
... | e01d01397647357f5dc1e17a7d9ab0a2aa94ba04 | 60,339 |
def getNbtestOk(results):
"""
based on default value (PASS) count the number of test OK
"""
nb_test_ok = 0
for my_result in results:
for res_k, res_v in my_result.iteritems():
try:
if "PASS" in res_v:
nb_test_ok += 1
except TypeErro... | 6cac82e138ac17b1cc70bda0d892542db6fdecf0 | 60,340 |
def format_time(start, end):
"""Format length of time between ``start`` and ``end``.
Args:
start (:class:`time.time`): The start time.
end (:class:`time.time`): The end time.
Returns:
str: A formatted string of hours, minutes, and seconds.
"""
hours, rem = divmod(end - sta... | 5650fe13f51821056b2e0be3be04ddcfa35bb1c6 | 60,341 |
import scipy
def calc_fft(feature_vec, smooth = False):
"""
takes in feature vector, splits it into its 3 components, and does the fft of each
returns magnitude of fft for each component
"""
# separate components
xline = feature_vec[0::3]
yline = feature_vec[1::3]
zline = feature_vec[... | d30433a0758dbdee590b89edf8a9851c94a915e2 | 60,342 |
def suggest_box():
"""Custom commands.guild_only with different error checking."""
def pred(ctx):
if ctx.guild is None:
raise UnavailableTagCommand()
return True
return commands.check(pred) | 5772fd7c279f844644eebc40cb7270269863719a | 60,343 |
def shadow_model():
"""The architecture of the shadow model is same as target model, because the attack is white-box,
hence the attacker is assumed to know this architecture too.
:return: shadow model
"""
classifier = Sequential()
classifier.add(Conv1D(num_kernels,
ke... | 17b0d6df8046a1cda0e85c84d29102af019b8e72 | 60,344 |
def coins(change):
""" 8.11 Coins: Given an infinite number of quarters (25 cents),
dimes (10 cents), nickels (5 cents), and pennies (1 cent), write
code to calculate the number of ways of representing n cents.
Using dynamic programming.
The recursivity is:
t(n, c) = t(n, sc), where sc is ... | aba4838d8767c31218406e9f756f17162a2b485d | 60,345 |
def validate_armada_documents(documents):
"""Validates multiple Armada documents.
:param documents: List of Armada manifests to validate.
:type documents: :func:`list[dict]`.
:returns: A tuple of bool, list[dict] where the first value is whether
the full set of documents is valid or not and th... | 91e20288322c01ace613aafba98a3f19f96ee538 | 60,346 |
def retrieve_runinfo(sra_accession):
"""Retrieve a SRA runinfo using search and efetch utilities"""
esearch_proc = Popen(['esearch', '-db', 'sra', '-query', sra_accession], stdout=PIPE)
runinfo_data = check_output(['efetch', '-format', 'runinfo'], universal_newlines=True, stdin=esearch_proc.stdout)
if n... | e57bb46ec4a969d9c03901ad321fcd1b3b388957 | 60,347 |
def fetch_all_metadata(client):
"""Fetches all the files.
Args:
client: Authorized drive api client.
Returns:
"""
results = []
page = ended = None
while not ended:
resp = client.files().list(pageToken=page, maxResults=100,
q='trashed=false',
fields='nextPageToken,items(id,md5Check... | 11fff0cbaa3ceecb57aa7ebefaaf7a52811fa9c4 | 60,348 |
from typing import Optional
from typing import Iterable
from typing import List
def extract_bounding_boxes(
diff_image: np.ndarray,
page_number: int,
hue: float,
masks: Optional[Iterable[FloatRectangle]] = None,
) -> List[BoundingBox]:
"""
See 'PixelMerger' for description of how bounding boxe... | fc3f95d56019a52ea44d2bb3594f69151dbbf996 | 60,349 |
def size(current):
"""Fuzz image size header field."""
constraints = UINT64_V
return selector(current, constraints) | b6ed4c5da118e1f2a74cab0dd8012c96ed6a9779 | 60,350 |
import torch
import torchvision
def _adjust_brightness(video: torch.Tensor, factor: float, **kwargs) -> torch.Tensor:
"""
Adjust brightness of a video.
Args:
video (torch.Tensor): Video tensor with shape (T, C, H, W).
sharpness_factor (float): How much to adjust the sharpness. Can be any
... | 9234167077968c1e36ee799eeb0c5918aacb32c7 | 60,351 |
def get_stationary_distribution(f_rate, f_noise, x_view, x_points, iters=100):
"""
Get the stationary distribution with a particular rate and noise function.
:param f_rate f(x): rate function
:param f_noise f(x): density function of noise (integral 1)
:param x_view (float, float): range of paramete... | 079489c0fd25440fac02526bcd586eb912a445f4 | 60,352 |
def getHostWhiteboard():
"""
:rtype: list<Host>
:return: NestedHost """
nestedHostSeq = Cuebot.getStub('host').GetHostWhiteboard(
host_pb2.HostGetHostWhiteboardRequest(),
timeout=Cuebot.Timeout).nested_hosts
return [NestedHost(nh) for nh in nestedHostSeq.nested_hosts] | c294c1378e2fb225825d91fff53d366a89bdff3f | 60,353 |
def get_fuzzy_points(discretize_method, df_numerical_columns, X, y=None, sets=0,
point_variables=None, debug=False):
"""Obtain the peak of the fuzzy triangles of
the continuous variables of a DataFrame
Parameters
----------
discretize_method : string
Function used to ge... | d526eebe93e4e1016b8c6553c5b2c47792e4676d | 60,354 |
def keep_login_url(func):
"""
Adds attribute g.keep_login_url in order to pass the current
login URL to login/signup links.
"""
@wraps(func)
def wrapper(*args, **kwargs):
g.keep_login_url = True
return func(*args, **kwargs)
return wrapper | 1d785680846cfe2272d3ec6803d5c2434d44a21c | 60,355 |
from typing import Tuple
from typing import Sequence
import builtins
def builtin_lookup(name: str) -> Tuple["nodes.Module", Sequence["nodes.NodeNG"]]:
"""Lookup a name in the builtin module.
Return the list of matching statements and the ast for the builtin module
"""
# pylint: disable-next=global-st... | 2caf57dc6d3d335d2b59e9740df0d243d6a7edd2 | 60,356 |
def toggle_article_hidden():
"""
Method POST
Form:
- aid int
- hidden bool
"""
aid = get_int_field('aid')
hidden = get_bool_field('hidden')
a = Article.query.get(aid)
if a is None:
raise RequestArgumentError("Article %d is not found" % aid)
if a.h... | 2fa58070625ba1aef96249e45d6f5cf05010d2f3 | 60,357 |
def is_reviewed(protein_id):
"""Return True if the UniProt ID corresponds to a reviewed entry.
Parameters
----------
protein_id : str
The UniProt ID to check.
Returns
-------
True if it is a reviewed entry, False otherwise.
"""
return _strip_isoform(protein_id) in um.unipro... | 684c22dedc79282fd7a6b58a2c6175079f508ab9 | 60,358 |
def matrix_compile(main: list, sub: list, pos: int):
"""
Compile sub-matrices into a main matrix.
"""
n = len(sub)
total = len(main)
if len(main) != 2 * n:
print("ERROR: Cannot merge matrices of incompatible dimension. Stop.")
return None
results = []
if pos == 0:
... | 0ee10948b1e4597dcf34176942b20d119aa12396 | 60,359 |
import logging
def good_from(station: int, missing_days: int = 4, tabname: str = "readings", data: tuple = None) -> dict:
"""
Determines from which year we have almost consecutive data for each value. "Almost" will be assessed by the number
of days where thae value is not available. A year is almost compl... | 84d618b829efe0bb9d9ea6c82c1bd0230e820b36 | 60,360 |
def getGroups(datestring):
"""Utility function to get the parts of the datestring as a dict."""
if not isinstance(datestring, basestring):
raise ParseError("Expecting a string %r" % datestring)
m = ISO8601_REGEX.match(datestring)
if not m:
raise ParseError("Unable to parse date string %r" % datestring)
... | 6d659ec4ba039b2efdb3b2bdecfb7244e91da5e8 | 60,361 |
import math
def get_news(n: int = 100) -> pd.DataFrame:
"""Scrapes news from "https://www.coingecko.com/en/news?page={}" [Source: CoinGecko]
Parameters
----------
n: int
Number of news, by default n=100, one page has 25 news, so 4 pages are scraped.
Returns
-------
pandas.DataFram... | 541f975ea37f9c92875395043481d567cdf9c041 | 60,362 |
def get_variables(hoc, obj, vartype=int(0)):
"""Get the variables associated with an object.
:param hoc: is a hoc object such as would be obtained
when importing neuron.
:param obj: is the object from which to retrieve
its variable names. This can be a Section, Segm... | 9d304031bb0cf8bc553b12f688435220aaf842d3 | 60,363 |
def wtype():
"""Returns the "window type" of $w.
Important notes:
* "window type" is not a tk concept;
rather, Tk refers to a window's "class";
see "winfo class" for more on this context
* "window type" is made up by me, and consists of a matching symbol;
presently (2021-10-09), I... | 31b97f3247f5e32fca761d14decb94a6ed3e7aeb | 60,364 |
from re import I
def compute_matrix_from_ops_two_qubit(ops, wire_order):
"""Given a list of two-qubit operations, construct its matrix representation."""
mat = qml.math.kron(I, I)
for op in ops:
if len(op.wires) == 1:
if op.wires == qml.wires.Wires(wire_order[0]):
mat... | 3b326d0af015559a0112f31735c8208f632ddc28 | 60,365 |
def get_attribute_by_name(cls, group_name, attr_name, verbose_name=False, case_insensitive=False):
""" Return the attribute of :obj:`Model` class :obj:`cls` with name :obj:`name`
Args:
cls (:obj:`class`): Model class
group_name (:obj:`str`): name of attribute group
attr_name (:obj:`str`... | 9f0addc5ca0019366b934c9b88ba3bca11d3d082 | 60,366 |
def interface_r(polarization, n_i, n_f, th_i, th_f):
"""
reflection amplitude (from Fresnel equations)
polarization is either "s" or "p" for polarization
n_i, n_f are (complex) refractive index for incident and final
th_i, th_f are (complex) propegation angle for incident and final
(in radian... | baeaed3438725ac6492714bfca4221249476d226 | 60,367 |
def alignUnalignedSeqsFromFile(filename,WorkingDir=None,SuppressStderr=None,\
SuppressStdout=None):
"""Aligns unaligned sequences from some file (file should be right format)
filename: string, the filename of the file containing the sequences
to be aligned in a valid format.
"""
app = Clust... | 60b3079a775597638cb47bd70993569f87d8657f | 60,368 |
from sys import path
def get_baked_files():
"""
A helper to retrieve the baked files included with this package. This is
to assist with building from source, where baked files may not be present
on a fresh clone
"""
data_files = []
if path.isfile("linode-cli.sh"):
data_files.appe... | 771a2d4022f852bed0a9755ad3aa015ecc167caf | 60,369 |
import math
def C_26Al(depth, erosion, exposure, density, inheritance,
P_0=35.):
"""
A model for profiles of 26Al concentration vs. depth.
Notes
-----
The following parameters are used
(Braucher et al. 2003)
26Al radioactive decay: log(2) / 0.72e6
Contribution... | e15450f301c3e24a66337b87a48fbf90f350dc73 | 60,370 |
import os
def default_list_paths():
"""List the real path to dcos executable
:returns: list dcos program path
:rtype: str
"""
# Let's get all the default subcommands
binpath = util.dcos_bin_path()
return os.path.join(binpath, "dcos") | 5d47a0770ee38abc7f5473797ecf53af62acb7d9 | 60,371 |
import time
def Subdue(params, graph):
"""
Top-level function for Subdue that discovers best pattern in graph.
Optionally, Subdue can then compress the graph with the best pattern, and iterate.
:param graph: instance of Subdue.Graph
:param params: instance of Subdue.Parameters
:return: patter... | 635be5cab9fcccaec040b268b0a21042dd07ca52 | 60,372 |
def func_proDATA(inlist):
"""
Pre-process input DATA list
Parameter:
inlist: 2D nested list
sublist in an array
[ symbol deltaTbM deltaTM deltaPM deltaVM nickName(as many as you can) ]
Return:
3D nested list
in a format,
[
... | 2221a5399db0d6896ef8f7fb303834f91f654aed | 60,373 |
import ibeis
def find_installed_tomcat(check_unpacked=True, strict=True):
"""
Asserts that tomcat was properly installed
Args:
check_unpacked (bool): (default = True)
Returns:
str: tomcat_dpath
CommandLine:
python -m ibeis find_installed_tomcat
Example:
>>> ... | 1c5488bc528207641826dc14f277ea0604357cbd | 60,374 |
def get_tokens_of_doc(doc):
"""分词获得token"""
sent_list = split_doc(doc)
tokens = []
for sent in sent_list:
tmp_tokens = tokenizer.segment(sent.strip())
for token in tmp_tokens:
tokens.append(str(token).split('/')[0].strip())
return tokens | 82b854411f56435634241fec3b76bb9e124ad58a | 60,375 |
def normalize(img: np.ndarray, div255=True, mean=[0.485, 0.456, 0.406],
std=[0.229, 0.224, 0.225]) -> np.ndarray:
"""
normalize using standard pytorch model normalization parameters
expects RGB image with 0-255 pixels as input
returns float type
"""
img = img.astype(float)
if d... | 6a835950494b824b918cb4b9bd4bf85e2f9723d9 | 60,376 |
def upper_case(string, **kwargs):
"""
大写命名法
eg:USER_NAME
"""
return case_convert.upper_case(string, **kwargs) | 1539031c0626d11b42ebc5583e84cf6e18f108f5 | 60,377 |
def response_for_courses_list(all_courses):
"""
Return the response for when courses are requested by the user.
:param courses:
:return:
"""
return make_response(jsonify({
'status': 'success',
'courses': all_courses
})) | a5af95a709dfe8dd3e7b19dfddbcf3aa99ecb3de | 60,378 |
def move_ara_files(source_dir, dest_dir):
""" old name of the collect_text_files function;
renamed because the name does not reflect what function does;
old name kept for backward compatibility
"""
return collect_text_files(source_dir, dest_dir) | 7730715d1d77d1ed93b574f131bd5e114a09dad8 | 60,379 |
def normalize_and_dedupe_with_counts(dirty_urls):
""" Takes a list of URLs, takes a count of them, sanitises them and
returns a count of the sanitised URLs. Output is namedtuple of count
pre-cleaning, count post-cleaning, and then the list of URLs.
"""
urls_entered = len(dirty_urls)
cl... | 02ab7c2365f8f3e5329baa8f4f9628003665b60f | 60,380 |
def get_country_code(country_name):
"""根据指定的国家,返回pygal使用的两个字母的国别码"""
for code, name in COUNTRIES.items():
if name == country_name:
return code
if country_name == "Hong Kong SAR, China":
return 'hk'
if country_name == "Korea, Dem. People’s Rep.":
retur... | 4f0b5c28027f409638004464b8af3a1c304c7a66 | 60,381 |
from typing import Dict
import atexit
from typing import Optional
from re import VERBOSE
from re import DEBUG
def bootstrap_window_discovery(bus: EventBus, listeners: ListenerSet, hooks: WindowsHookEvent) -> None:
"""
Startup the window code. NOte that this does not need to be aware of
windows created by... | 2fd5d8257a1c00181ec25a41cefa2b30bf9e263b | 60,382 |
from fsspec import get_filesystem_class
def can_be_local(path):
"""Can the given URL be used wih open_local?"""
try:
return getattr(get_filesystem_class(get_protocol(path)), "local_file", False)
except (ValueError, ImportError):
# not in registry or import failed
return False | 918646e65907d59bad1d40e8b5238865356e9fdf | 60,383 |
def create_hdmedians_multiple_band_mosaic(dataset_in,
clean_mask=None,
no_data=-9999,
dtype=None,
intermediate_product=None,
... | 3d9697325169693cebdc1a7c8f15d0d9e2080c3b | 60,384 |
def get_ti16_config():
"""Returns the ViT-S/16 configuration."""
config = get_base_config()
config.update(dict(
patch_size=(16, 16),
hidden_size=192,
intermediate_size=768,
num_attention_heads=3,
representation_size=192
))
return config | 9ba8c89d858e4960944ef06cba1e81dfe04e3f8a | 60,385 |
def lookup_unique_task_from_func(task_func, default_pipeline_name="main"):
"""
Go through all pipelines and match task_func to find a unique task
Throw exception if ambiguous
"""
def unique_task_from_func_in_pipeline(task_func, pipeline):
if task_func in pipeline.lookup:
if len(... | 39b70af87e019fc948563fcda20597b57e3bb292 | 60,386 |
import os
def get_dir_for_run(task_run: "TaskRun", project_name: str = NO_PROJECT_NAME) -> str:
"""
Return the directory where the mephisto run data is expected to go
"""
run_id = task_run.db_id
root_dir = task_run.db.db_root
return os.path.join(get_data_dir(root_dir), "runs", project_name, ru... | 25e66d7dfb920196fb8d4ddd5f55764928bfacd4 | 60,387 |
def data_to_nameCat(LOC, quota, rank, CCA):
"""
Returns a dictionary of the category of a CCA
"""
final_dic = {}
dic_quota = quota.dic #dictionary
cat = ""
for category, dic_CCAs in dic_quota.items(): #for each category
for cca, quota in dic_CCAs.items(): #for each cca
... | 96de92f435f8257425887d21c42d6b2a1359d747 | 60,388 |
import logging
from pathlib import Path
def get_system_library_path():
""" return the path to the system Photos library as string """
""" only works on MacOS 10.15+ """
""" on earlier versions, returns None """
_, major, _ = _get_os_version()
if int(major) < 15:
logging.debug(
... | 1db9ba2b9e304c88486ed7795ddbce4db40e6d4a | 60,389 |
def GenerateRSAKey(passphrase=None, key_length=2048):
"""Generate an RSA key and return tuple of pem strings for (priv,pub) keys."""
if passphrase is not None:
passphrase_cb = lambda: passphrase
else:
passphrase_cb = None
key = RSA.gen_key(key_length, 65537)
priv_key = key.as_pem(passphrase_cb)
bio ... | c40b0879f998875e3bea17af864daa37f98c27d5 | 60,390 |
def get_parsed_url(test_item):
# type: (AnyMagpieTestItemType) -> ParseResult
"""
Obtains the parsed URL result from the test class web application implementation.
"""
app_or_url = get_app_or_url(test_item)
if isinstance(app_or_url, TestApp):
app_or_url = get_magpie_url(app_or_url.app.re... | ea57174e89349b43b66bebd0068f8e13e1173d82 | 60,391 |
def transformer_revnet_encoder(encoder_input,
encoder_self_attention_bias,
hparams,
name="encoder"):
"""A stack of transformer layers.
Args:
encoder_input: a Tensor
encoder_self_attention_bias: bias Tensor for self... | b049e40bf3cdd08e476663e7494f426fa3339ea0 | 60,392 |
import utool as ut
def inverable_unique_two_lists(item1_list, item2_list):
"""
item1_list = aid1_list
item2_list = aid2_list
"""
unique_list1, inverse1 = np.unique(item1_list, return_inverse=True)
unique_list2, inverse2 = np.unique(item2_list, return_inverse=True)
flat_stacked, cumsum = ... | 85b032e927be2615e3927f6f14b2bfa1ea5842f5 | 60,393 |
def sanitize_host(host):
"""Return the hostname or ip address out of a URL"""
for prefix in ['https://', 'http://']:
host = host.replace(prefix, '')
host = host.split('/')[0]
host = host.split(':')[0]
return host | f00a79804624076c75e9b90c0da5b03888067a42 | 60,394 |
def compute_CCC(matrix, CCC_params):
"""
Compute causal complexity estimates for all pairs of rows of input matrix
Estimates are derived as per 4 models: ETCP, ETCE, LZP and CCC
Parameters
----------
matrix : np.ndarray, 2d, uint32
MxN matrix, C(M,2) rowpairs, with each row of length N... | 28f3c3135cd354007e6d12979277528d6257fdcf | 60,395 |
def team_user_names_query(after_cursor=None, team_name=None) -> gql:
"""A GraphQL query to get the list of user names within each organisation team.
Args:
after_cursor ([type], optional): Is the pagination offset value gathered from the previous API request. Defaults to None.
team_name ([type],... | ab9a02b498c9f194002b03c28f45cf3f0545414b | 60,396 |
def cut_rod_extend(p, n):
"""重构解"""
r = [0]
s = [0]
for i in range(1, n + 1):
res_r = 0 # 收益的最大值
res_s = 0 # 收益最大时对应方案的左边不切割部分的长度
for j in range(1, i + 1):
if p[j] + r[i - j] > res_r:
res_r = p[j] + r[i - j]
res_s = j
r.append... | e37d3300d2b79b1542dac46a723b0bff9668de09 | 60,397 |
def create_regions(algorithms: str, hash_file: HashFile):
"""
:param algorithms: the type of the algorithm to create the region
:param hash_file: the hash file object
"""
if algorithms == "FIXED-SIZE":
return create_fixed_regions(hash_file, 4)
if algorithms == "CONTENT-DEFINED":
... | ae942c80c4fd22e9bb1addd49525542c41831f83 | 60,398 |
def _get_one_dimensional_median_and_error_bar(
posterior, key, fmt=".2f", quantiles=(0.16, 0.84)
):
"""Calculate the median and error bar for a given key
Parameters
----------
key: str
The parameter key for which to calculate the median and error bar
fmt: str, ('.2f')
A format s... | 11a2630720c0968e16e484388ebb48c9b8c0ec35 | 60,399 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.