content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def handle_mpd_rm(bot, ievent):
""" arguments: <playlist> - remove playlist. """
handle_mpd_playlist_manipulation(bot, ievent, 'rm') | 5,336,600 |
def createOutputBuffer(file, encoding):
"""Create a libxml2 output buffer from a Python file """
ret = libxml2mod.xmlCreateOutputBuffer(file, encoding)
if ret is None:raise treeError('xmlCreateOutputBuffer() failed')
return outputBuffer(_obj=ret) | 5,336,601 |
def get_table_name(yaml_path):
"""gives how the yaml file name should be in the sql query"""
table_name = os.path.basename(yaml_path)
table_name = os.path.splitext(table_name)[0]
return table_name | 5,336,602 |
def wait_for_proof(node, proofid_hex, timeout=60, expect_orphan=None):
"""
Wait for the proof to be known by the node. If expect_orphan is set, the
proof should match the orphan state, otherwise it's a don't care parameter.
"""
def proof_found():
try:
wait_for_proof.is_orphan = n... | 5,336,603 |
def check(verbose=1):
"""
Runs a couple of functions to check the module is working.
:param verbose: 0 to hide the standout output
:return: list of dictionaries, result of each test
"""
return [] | 5,336,604 |
def cylinder_sideways():
"""
sideways cylinder for poster
"""
call_separator('cylinder sidweays')
T1 = .1
#gs = gridspec.GridSpec(nrows=2,ncols=3,wspace=-.1,hspace=.5)
fig = plt.figure(figsize=(5,4))
ax11 = fig.add_subplot(111,projection='3d')
#ax12 = fig.add_subplot(... | 5,336,605 |
def test(dir):
"""Discover and run unit tests."""
from unittest import TestLoader, TextTestRunner
testsuite = TestLoader().discover(f'./{dir}')
TextTestRunner(verbosity=2, buffer=True).run(testsuite) | 5,336,606 |
def get_generic_or_msg(intent, result):
""" The master method. This method takes in the
intent and the result dict structure
and calls the proper interface method. """
return Msg_Fn_Dict[intent](result) | 5,336,607 |
def s3_example_tile(gtiff_s3):
"""Example tile for fixture."""
return (5, 15, 32) | 5,336,608 |
def execute_list_of_commands(command_list):
"""
INPUT:
- ``command_list`` -- a list of strings or pairs
OUTPUT:
For each entry in command_list, we attempt to run the command.
If it is a string, we call ``os.system()``. If it is a pair [f, v],
we call f(v).
If the environment variable... | 5,336,609 |
def get_transceiver_diagnostics(baseurl, cookie_header, transceiver):
"""
Get the diagnostics of a given transceivers in the switch
:param baseurl: imported baseurl variable
:param cookie_header: Parse cookie resulting from successful loginOS.login_os(baseurl)
:param transceiver: data parsed to spec... | 5,336,610 |
def plot_cross_sections(obj, paths, xs_label_size=12, xs_color='black',
map_style='contour', scale='lin', n=101, x_labeling='distance',
show_max=True, fp_max=True, fp_text=True, cmap='viridis_r',
max_fig_width=12, max_fig_height=8, legend_padding=6, **kw):
"""Generate a map style plot (eithe... | 5,336,611 |
def mask_valid_boxes(boxes, return_mask=False):
"""
:param boxes: (cx, cy, w, h,*_)
:return: mask
"""
w = boxes[:,2]
h = boxes[:,3]
ar = np.maximum(w / (h + 1e-16), h / (w + 1e-16))
mask = (w > 2) & (h > 2) & (ar < 30)
if return_mask:
return mask
else:
return... | 5,336,612 |
def import_buffer_to_hst(buf):
"""Import content from buf and return an Hy AST."""
return tokenize(buf + "\n") | 5,336,613 |
def main():
"""Start web application."""
host = os.environ.get("HOST")
if not host:
host = "0.0.0.0" if os.getenv("DYNO") else "127.0.0.1" # noqa: S104
port = os.getenv("PORT", "")
port = int(port) if port.isdigit() else 5000
uvicorn.run("syndio_backend_test.api:API", host=host, port=po... | 5,336,614 |
def parse_args():
""" Parse command line arguments.
"""
parser = argparse.ArgumentParser(description="Deep SORT")
parser.add_argument(
"--sequence_dir", help="Path to MOTChallenge sequence directory",
default=None, required=False)
parser.add_argument(
"--detection_file", help... | 5,336,615 |
def load_lane_segments_from_xml(map_fpath: _PathLike) -> Mapping[int, LaneSegment]:
"""
Load lane segment object from xml file
Args:
map_fpath: path to xml file
Returns:
lane_objs: List of LaneSegment objects
"""
tree = ET.parse(os.fspath(map_fpath))
root = tree.getroot()
... | 5,336,616 |
def preprocess_input(x, **kwargs):
"""Preprocesses a numpy array encoding a batch of images.
# Arguments
x: a 4D numpy array consists of RGB values within [0, 255].
# Returns
Preprocessed array.
"""
return imagenet_utils.preprocess_input(x, mode='tf', **kwargs) | 5,336,617 |
def build_gauss_kernel(sigma_x, sigma_y, angle):
"""
Build the rotated anisotropic gaussian filter kernel
Parameters
----------
sigma_x : numpy.float64
sigma in x-direction
sigma_y: numpy.float64
sigma in y-direction
angle: int
angle in degrees of the nee... | 5,336,618 |
def parse_tle(fileobj):
"""Parse a file of TLE satellite element sets.
Builds an Earth satellite from each pair of adjacent lines in the
file that start with "1 " and "2 " and have 69 or more characters
each. If the preceding line is exactly 24 characters long, then it
is parsed as the satellite's... | 5,336,619 |
def kwargs_to_flags(**kwargs):
"""Convert `kwargs` to flags to pass on to CLI."""
flag_strings = []
for (key, val) in kwargs.items():
if isinstance(val, bool):
if val:
flag_strings.append(f"--{key}")
else:
flag_strings.append(f"--{key}={val}")
retu... | 5,336,620 |
def extractBananas(item):
"""
Parser for 'Bananas'
"""
badwords = [
'iya na kao manga chapters',
]
if any([bad in item['tags'] for bad in badwords]):
return None
vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
if not (chp or vol) or 'preview' in item['title'].lower():
r... | 5,336,621 |
def main():
"""Make a jazz noise here"""
args = get_args()
text = args.text
for line in args.text.splitlines():
print(' '.join(map(calc, line.split()))) | 5,336,622 |
def BuildSymbolToFileAddressMapping():
"""
Constructs a map of symbol-string -> [ (file_id, address), ... ] so that each
symbol is associated with all the files and addresses where it occurs.
"""
result = defaultdict(list)
# Iterate over all the extracted_symbols_*.txt files.
for filename in os.listdir(FL... | 5,336,623 |
def get_template_parameters_s3(template_key, s3_resource):
"""
Checks for existance of parameters object in S3 against supported suffixes and returns parameters file key if found
Args:
template_key: S3 key for template file. omit bucket.
s3_resource: a boto3 s3 resource
Returns:
filename of paramete... | 5,336,624 |
def cell_from_system(sdict):
"""
Function to obtain cell from namelist SYSTEM read from PW input.
Args:
sdict (dict): Dictinary generated from namelist SYSTEM of PW input.
Returns:
ndarray with shape (3,3):
Cell is 3x3 matrix with entries::
[[a_x... | 5,336,625 |
def _exit(msg):
""" Exits with red output """
exit(CFAIL + msg + CEND) | 5,336,626 |
def main():
"""Execute a rbpkg command.
The registered console script will call this when executing
:command:`rbpkg`. This will locate the appropriate command and execute it.
"""
parser = argparse.ArgumentParser(
prog='rbpkg',
usage='%(prog)s [--version] <command> [options] [<args>]... | 5,336,627 |
def A12_6_3_2(FAxial, eta, Pp, Pu, Muey , Muez, Muay, Muaz,
Ppls, Mby, Mbz, GammaRPa, GammaRPb):
"""
A.12.6.3.2 Interaction equation approach
where :
Pu is the applied axial force in a member due to factored actions,
determined in an analysis that includes Pu effects (see A.12.4);
... | 5,336,628 |
def gain_deploy_data():
"""
@api {get} /v1/deploy/new_data 获取当前deploy_id 的信息
@apiName deployNew_data
@apiGroup Deploy
@apiDescription 获取当前deploy_id 的信息
@apiParam {int} project_id 项目id
@apiParam {int} flow_id 流程id
@apiParam {int} deploy_id 部署id
@apiParamExample {json} Request-Example:... | 5,336,629 |
def topk_mask(score, k):
"""Efficient implementation of topk_mask for TPUs.
This is a more efficient implementation of the following snippet with support
for higher rank tensors. It has the limitation that it only supports float32
as element type. The mask only contains k elements even if other elements
have... | 5,336,630 |
def _generateGroundTruth(uids, COURSEDESCRIPTIONS):
"""Generate the ground truths from pre-stored bert model results given unique id lists
:param uids: list of unique ids
:type uids: list
:param COURSEDESCRIPTIONS: dictionary of course Descriptions
:type COURSEDESCRIPTIONS: dict
:return: a... | 5,336,631 |
def test_common_Generator():
"""Test Generator module class."""
scale = MajorScale('C')
chord_generator = Generator(
pitches = scale.getPitches('C','B')
)
generated_chords = set()
for chord in chord_generator.run():
generated_chords.add(
chordSymbolFigure(chord, inver... | 5,336,632 |
def test_get_option_env_var(os_env):
"""
If an option is given as an environment variable, then it should be
returned.
"""
os_env['DJANGO_ADMIN_USERNAME'] = 'foo'
assert createadmin.Command.get_option('username') == 'foo' | 5,336,633 |
def valueSearch(stat_type,op,value,**kwargs):
"""Quick function to designate a value, and the days or months where the
attribute of interest exceeded, equalled, or was less than the passed
value
valueSearch("attribute","operator",value,**{sortmonth=False})
* "attribute" must be in ["prcp","sno... | 5,336,634 |
def get_gnid(rec):
"""
Use geonames API (slow and quota limit for free accounts)
"""
if not any("http://www.geonames.org" in s for s in rec.get("sameAs")) and rec["geo"].get("latitude") and rec["geo"].get("longitude"):
changed = False
r = requests.get("http://api.geonames.org/findNearbyJ... | 5,336,635 |
def handle_message(message):
"""Handles every message and creates the reply"""
if re_vpncheck_short.search(message.body) or re_vpncheck_long.search(message.body):
"""Checks for VPN Connectivity"""
servername = None
protocol = None
if re_vpncheck_short.search(message.body):
... | 5,336,636 |
def test_list_g_month_enumeration_1_nistxml_sv_iv_list_g_month_enumeration_2_3(mode, save_output, output_format):
"""
Type list/gMonth is restricted by facet enumeration.
"""
assert_bindings(
schema="nistData/list/gMonth/Schema+Instance/NISTSchema-SV-IV-list-gMonth-enumeration-2.xsd",
in... | 5,336,637 |
def allowed_file(filename):
""" Is file extension allowed for upload"""
return '.' in filename and \
filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS | 5,336,638 |
def parse_tsv(filename, name_dict):
"""
"""
output_matrix = []
with open(filename, 'rU') as handle:
curr_protein = []
for line in handle:
if line[0] == "#" or line[0] == "-" or len(line.strip('\n')) < 1:
continue
if re.match("Protein", line):
... | 5,336,639 |
def get_orlist(site=DEFAULT_SITE, namespace="0|6|10|14|100|828", redirects="nonredirects"):
"""Get list of oldreviewed pages."""
request = Request(site=site,
action="query",
list="oldreviewedpages",
ornamespace=namespace,
or... | 5,336,640 |
def meshVolume(verts, norm, tri):
"""Compute the Volume of a mesh specified by vertices, their normals, and
indices of triangular faces
"""
# TEST
zeronorms = []
for i, n in enumerate(norm):
#if n == [0., 0., 0.] or n == (0., 0., 0.):
if n[0] == 0 and n[1] == 0 and n[2] == 0:
#print "norma... | 5,336,641 |
def _groupby_clause(uuid=None, owner=None, human_name=None, processing_name=None):
"""
Build the groupby clause. Simply detect which fields are set, and group by those.
Args:
uuid:
owner:
human_name:
processing_name:
Returns:
(str): "field, ..., field"
"""... | 5,336,642 |
async def test_response_body_can_be_missing(mock_app):
"""
The TestClient should allow for a response with no headers in the message
https://asgi.readthedocs.io/en/latest/specs/www.html#response-body-send-event
"""
async def custom_http_request(scope, receive, send, msg):
await send({"type"... | 5,336,643 |
def internalize_lexicon(mode, to_add):
"""Reads all entries from the lexicons specified in to_add
and puts them in sql. They may then be edited.
The ES index is not effected and this operation may hence
be run at any time
"""
ok = 0
es = conf_mgr.elastic(mode)
sql_bulk = None
for lex... | 5,336,644 |
def closeConn(client):
"""Remove client data and close connection with client"""
logMsg('Closing client connection')
# Clear client data
logout(client, False)
client.factory.clients.remove(client)
# Disconnect
client.abortConnection() | 5,336,645 |
def _coeff_mod_wfe_drift(self, wfe_drift, key='wfe_drift'):
"""
Modify PSF polynomial coefficients as a function of WFE drift.
"""
# Modify PSF coefficients based on WFE drift
if wfe_drift==0:
cf_mod = 0 # Don't modify coefficients
elif (self._psf_coeff_mod[key] is None):
_log.w... | 5,336,646 |
def get_transformed_webhook_payload(gh_payload, default_branch=None, lookup_user=None):
""" Returns the GitHub webhook JSON payload transformed into our own payload
format. If the gh_payload is not valid, returns None.
"""
try:
validate(gh_payload, GITHUB_WEBHOOK_PAYLOAD_SCHEMA)
except Exception as ex... | 5,336,647 |
def get_retweeted_tweet(tweet):
"""
Get the retweeted Tweet and return it as a dictionary
If the Tweet is not a Retweet, return None
Args:
tweet (Tweet or dict): A Tweet object or a dictionary
Returns:
dict: A dictionary representing the retweeted status
or None if there is... | 5,336,648 |
def listminus(c1, c2):
"""Return a list of all elements of C1 that are not in C2."""
s2 = {}
for delta in c2:
s2[delta] = 1
c = []
for delta in c1:
if not s2.has_key(delta):
c.append(delta)
return c | 5,336,649 |
def distribute_quantity_skew(batch_size, grouped_data, distributed_dataset, groupings, p=0.5, scalar=1.5):
"""
Adds quantity skew to the data distribution. If p=0. or scalar=1., no skew is applied and the data are divided
evenly among the workers in each label group.
:param batch_size: the batch siz... | 5,336,650 |
def xmkpy3_tpf_get_coordinates_v1():
"""Unit test"""
import numpy as np
import lightkurve as lk
print(lk.__version__, "=lk.__version__")
def msg(ok, tag_): # helper function
print("***" + tag_ + ": ", end="")
if ok:
print("PASS***")
else:
print("FAI... | 5,336,651 |
def __loadModule(modulePath):
# type: (str) -> module
""" Load module
Args:
modulePath (str): Full path to the python module
Return:
mod (module object): command module
None: if path doesn't exist
"""
# Create module names for import, for exapmle ...
#
# "rush/... | 5,336,652 |
def get_dtype(names, array_dtype=DEFAULT_FLOAT_DTYPE):
"""
Get a list of tuples containing the dtypes for the structured array
Parameters
----------
names : list of str
Names of parameters
array_dtype : optional
dtype to use
Returns
-------
list of tuple
Dty... | 5,336,653 |
def test_unhexlify():
"""
Ensure that we can get the script back out using unhexlify and that the
result is a properly decoded string.
"""
hexlified = uflash.hexlify(TEST_SCRIPT)
unhexlified = uflash.unhexlify(hexlified)
assert unhexlified == TEST_SCRIPT.decode('utf-8') | 5,336,654 |
def print_progress_table(col_headers, col_widths = None, col_init_data = None,
col_format_specs = None, skip_header=False):
""" Live updates on progress with NUPACK and Multistrand computations.
Note: This table has two rows. The
Args:
col_headers (list(str)): The header of the table.
col_widths (... | 5,336,655 |
def main():
"""
Centralized virtual environments.
""" | 5,336,656 |
def remove_stroke(settings):
"""Removes the stroke (i.e. border in Faint) from the settings object,
preserving fill.
"""
if settings.fillstyle == 'border':
settings.fillstyle = 'none'
elif settings.fillstyle == 'fill+border':
settings.fg = settings.bg
settings.fills... | 5,336,657 |
def if_analyser(string):
"""调用python的eval函数计算True false"""
trans = sign_transform(string.strip().lower())
# print('if_analyser>>', trans)
boool = eval(trans)
boool = 1 if boool else 0
return boool | 5,336,658 |
def zzX_trunc(f, p):
"""Reduce Z[X] polynomial modulo polynomial p. """
return zzX_strip([ zzX_rem(g, p) for g in f ]) | 5,336,659 |
def update_points_constellation(
points_in_range, new_constelation, point_to_constellation):
"""Update point_to_constellation mapping for points_in_range."""
for point_in_range in points_in_range:
point_to_constellation[point_in_range] = new_constelation | 5,336,660 |
def all_instances(clazz):
"""Return all subjects."""
logging.info(
"Starting aggregation for all AnVIL workspaces, this will take several minutes.")
print("Starting aggregation for all AnVIL workspaces, this will take several minutes.")
consortiums = (
('CMG', 'AnVIL_CMG_.*'),
(... | 5,336,661 |
def _format_bin_intervals(bins_arr: np.ndarray) -> List[str]:
"""
Auxillary function to format bin intervals in a histogram
Parameters
----------
bins_arr: np.ndarray
Bin endpoints to format into intervals
Returns
-------
List of formatted bin intervals
"""
bins_arr... | 5,336,662 |
def log(message, prefix_newline=False):
"""Logging function, provides a hook to suppress or redirect log messages."""
print(('\n' if prefix_newline else '') + '{0:.2f}'.format(time.time()) + ': ' + str(message)) | 5,336,663 |
def createDataset(businessIDs, dataset):
"""Writes a new json file containing subset of given Yelp dataset given a dictionary of business IDs to specify which businesses"""
writer = jsonlines.open(dataset + 'Dataset.json', mode='w')
with open(dataset + '.json', 'r', encoding='utf8') as dataJson:
... | 5,336,664 |
def main():
"""Zeigt den Link zum Repository in der Konsole an."""
print("Dieses Tool stellt übergreifende, grundlegende Funktionalitäten zur Verfügung.\n"
"Für weitergehende Informationen: https://github.com/MZH-bust/general_helpers") | 5,336,665 |
def get_embedder_functions(corpus: List[str]) -> Dict[str, Callable[[List[str]], List[float]]]:
"""
Returns a list of the available embedders.
#! If updated, update next function too
"""
embedders = {
# 'Bag of Words': bow_embedder(corpus),
'FastText (CBOW)': fasttext_embedder(corpu... | 5,336,666 |
def test_stimeit():
""" Test the stimeit function """
dummy_function = lambda x: x + 2
@vtime.stimeit(logging.info)
def stimeit_function(x):
return dummy_function(x)
assert dummy_function(42) == stimeit_function(42) | 5,336,667 |
def tag_dataset(client, short_name, tag, description, force=False):
"""Creates a new tag for a dataset."""
dataset_ = client.load_dataset(short_name)
if not dataset_:
raise ParameterError('Dataset not found.')
try:
dataset = client.add_dataset_tag(dataset_, tag, description, force)
... | 5,336,668 |
def main_aster(folder_name):
"""
@Input
folder_name : name of the folder where training data are stored.
@Output
trained parameters are stored in 'params' folder
"""
# arguments are stored in pred_params.py
from pred_params import Get_ocr_args
args = Get_ocr_args()
prin... | 5,336,669 |
def parse_thermal_properties(f):
"""thermal_properties.yaml parser."""
thermal_properties = {
"temperatures": [],
"free_energy": [],
"entropy": [],
"heat_capacity": [],
}
data = yaml.load(f, Loader=Loader)
for tp in data["thermal_properties"]:
thermal_properti... | 5,336,670 |
async def test_add_invalid_repository_file(coresys, store_manager):
"""Test add custom repository."""
current = coresys.config.addons_repositories
with patch("supervisor.store.repository.Repository.load", return_value=None), patch(
"pathlib.Path.read_text",
return_value=json.dumps({"name": "... | 5,336,671 |
def convert(ts, new_freq, include_partial=True, **kwargs):
"""
This function converts a timeseries to another frequency. Conversion only
works from a higher frequency to a lower frequency, for example daily to
monthly.
NOTE: add a gatekeeper for invalid kwargs.
"""
new_ts = ts.clone()
... | 5,336,672 |
def _get_image_info(name: str) -> versions.Image:
"""Retrieve an `Image` information by name from the versions listing."""
try:
return versions.CONTAINER_IMAGES_MAP[name]
except KeyError:
raise ValueError(
'Missing version for container image "{}"'.format(name)
) | 5,336,673 |
def _mother_proc_cpp_stat(
amplitude_distribution, t_stop, rate, t_start=0 * pq.ms):
"""
Generate the hidden ("mother") Poisson process for a Compound Poisson
Process (CPP).
Parameters
----------
amplitude_distribution : np.ndarray
CPP's amplitude distribution :math:`A`. `A[j]`... | 5,336,674 |
def main():
"""
Main execution flow.
"""
try:
args = process_arguments()
config = utilities.read(args.config_file)
manifest = utilities.read(args.manifest_file)
# TODO: Refactor
core.config = config
utilities.TOKENIZER = core.Tokenizer()
databas... | 5,336,675 |
def get_service(hass, config):
"""Get the Telegram notification service."""
import telegram
if not validate_config({DOMAIN: config},
{DOMAIN: [CONF_API_KEY, 'chat_id']},
_LOGGER):
return None
try:
bot = telegram.Bot(token=config[CON... | 5,336,676 |
def has_numbers(input_str: str):
""" Check if a string has a number character """
return any(char.isdigit() for char in input_str) | 5,336,677 |
def test_pyfs_delete_fail(pyfs, pyfs_testpath):
"""Test init of files."""
pyfs.save(BytesIO(b'somedata'))
os.rename(pyfs_testpath, join(dirname(pyfs_testpath), 'newname'))
pytest.raises(DirectoryNotEmpty, pyfs.delete) | 5,336,678 |
def _validate_LIMS_data(input, field_label, selectedTemplate, planObj):
"""
No validation but LIMS data with leading/trailing blanks in the input will be trimmed off
"""
errorMsg = None
if input:
data = input.strip()
try:
if planObj.get_planObj().metaData:
... | 5,336,679 |
def show(ctx, advisory, yaml, json):
""" Show RPMDiff failures for an advisory.
"""
runtime = ctx.obj # type: Runtime
if not advisory:
runtime.initialize()
advisory = runtime.group_config.advisories.get("rpm", 0)
if not advisory:
raise ElliottFatalError("No RPM advis... | 5,336,680 |
def get_report_permission(report: Report, user: User) -> Permission:
"""Get permission of given user for the report.
:param report: The report
:type report: Report
:param user: The user whose permissions are to be checked
:type user: User
:return: The user's permissions for the report
:rtyp... | 5,336,681 |
def peak_time_from_sxs(
sxs_format_waveform,
metadata,
extrapolation_order='Extrapolated_N2'):
"""Returns the time when the sum of the squared amplitudes of an
SXS-format waveform is largest. Note: this is not necessarily the time of
the peak of the l=m=2 mode."""
extrap = extrap... | 5,336,682 |
def create_trackhub_resource(project_dir, api_client, create_user_resource, create_genome_assembly_dump_resource):
"""
This fixture is used to create a temporary trackhub using POST API
The created trackhub will be used to test GET API
"""
_, token = create_user_resource
api_client.credentials(H... | 5,336,683 |
def create_node(x, y):
"""Create a node along the network.
Parameters
----------
x : {float, int}
The x coordinate of a point.
y : {float, int}
The y coordinate of a point.
Returns
-------
_node : shapely.geoemtry.Point
Instantiated node.
"""
_node = P... | 5,336,684 |
def get_matchroom_name(match: Match) -> str:
"""Get a new unique channel name corresponding to the match.
Parameters
----------
match: Match
The match whose info determines the name.
Returns
-------
str
The name of the channel.
"""
name_prefix = match.ma... | 5,336,685 |
def unidecode_name(uname):
"""
unidecode() of cjk ideograms can produce strings which contain spaces.
Strip leading and trailing spaces, and reduce double-spaces to single.
For some other ranges, unidecode returns all-lowercase names; fix these
up with capitalization.
"""
# Fix double spaci... | 5,336,686 |
def scnet50(**kwargs):
"""
SCNet-50 model from 'Improving Convolutional Networks with Self-Calibrated Convolutions,'
http://mftp.mmcheng.net/Papers/20cvprSCNet.pdf.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str,... | 5,336,687 |
def xception_block(inputs, depth_list, prefix, skip_connect_type, stride, rate=1,
depth_activation=False, return_skip=False):
"""用于构建xception,同样用到了残差结构,但是将卷积换成了 深度可分离卷积(depthwise + pointwise + conv 1x1)"""
residual = inputs
for i in range(3):
# depthwise + pointwise + conv2d
... | 5,336,688 |
def auth_test():
"""
Test's the endpoint authenticiation works.
:return:
"""
return "hello" | 5,336,689 |
def cnn_2x_lstm_siamese(voc_size, max_len, dropout=0.5):
"""Two siamese branches, each embedding a statement.
Binary classifier on top.
Args:
voc_size: size of the vocabulary for the input statements.
max_len: maximum length for the input statements.
dropout: Fraction of units to drop.
Returns:
... | 5,336,690 |
def play_throne_room(game):
"""
You may play an Action card from your hand twice.
"""
ps = game.player_state
if 'Action' not in set(c.Type for c in ps.hand):
print('ThroneRoom: No actions cards in hand')
return
card_name = game._respond(game.player, 'ThroneRoom')
card_class ... | 5,336,691 |
def SerialWrite(serialPort, Message):
""" Write message on serial port."""
serialPort.flushInput()
serialPort.write(Message)
time.sleep(3) | 5,336,692 |
def flatten_images_data(images, layer_path_segments=0, _test=False):
"""
Yield mapping for each layer of each image of an `images` list of Image.
This is a flat data structure for CSV and tabular output.
Keep only ``layer_path_segments`` trailing layer location segments (or keep
the locations unmodi... | 5,336,693 |
def roll_function(positions, I, angular_velocity):
"""
Due to how the simulations are generated where the first point of the simulation
is at the smallest x value and the subsequent positions are in a clockwise
(counterclockwise) direction when the vorticity is positive (negative), the first
point... | 5,336,694 |
def run_exkeys(hosts, capture=False):
"""
Runs gpssh-exkeys for the given list of hosts. If capture is True, the
(returncode, stdout, stderr) from the gpssh-exkeys run is returned;
otherwise an exception is thrown on failure and all stdout/err is untouched.
"""
host_opts = []
for host in hos... | 5,336,695 |
def ip_address(value):
"""
Validate whether or not the given string is a valid IP address.
Args:
value (str): the value to validate.
Raises:
`~serde.exceptions.ValidationError`: when the value is not a valid IP
address.
"""
if not validators.ipv4(value) and not vali... | 5,336,696 |
def top10():
"""Renders the top 10 page."""
top10_urls = ShortURL.query.order_by(ShortURL.hits.desc()).limit(10)
return render_template("top10.html", urls=top10_urls) | 5,336,697 |
def rename_group(str_group2=None):
"""
Rename OFF food group (pnns_group_2) to a standard name
Args:
str_group2 (str): OFF food group name
Returns:
conv_group (str): standard food group name
"""
#convert_group1 = {'Beverage':['Beverages'],
# 'Cereals':['Cerea... | 5,336,698 |
def save_png(fig: Figure, path: Union[None, str, pathlib.Path],
width: Union[int, float] = None, height: Union[int, float] = None, unit: str = 'px',
print_info: bool = False) -> Union[str, io.BytesIO]:
"""
Save PNG image of the figure.
:param fig: Figure to save.
:param... | 5,336,699 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.