content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def root():
"""
Landing page for PaperScraper, takes user input and run parameters
"""
if request.method == "GET":
return render_template("root.html")
elif request.method == "POST":
error = None
source = None
try:
source = get_source(request.form)
... | 2af8b4247b51afb86c71e61199c7d622996cb112 | 3,630,400 |
import os
def get_pkg_name_from_sxs_folder_name(path_folder):
"""
Get the name of the package from path
:param path_folder: path of the package
:return: string name of the package
"""
folder_name = os.path.basename(path_folder)
spited_name = folder_name.split("_")
if len(spited_name) <... | 8ebd35f0be590a19ea08ddcfdb129c0d9557098b | 3,630,401 |
from uncompyle6.scanner import get_scanner
import sys
def python_parser(version, co, out=sys.stdout, showasm=False,
parser_debug=PARSER_DEFAULT_DEBUG, is_pypy=False):
"""
Parse a code object to an abstract syntax tree representation.
:param version: The python version this code ... | 5b83e9bf75b22d17b9e44a552db7625b3bae7334 | 3,630,402 |
import sys
import ast
import configparser
def __parse_options(config_file, section, options):
""" Parse the section options
:type config_file: ConfigParser object
:param config_file: The config file object to use
:type section: str
:param section: Which section to read in the configuration file
... | 6a2813a336aee3e1696caeb148aaac98c7dd6621 | 3,630,403 |
from typing import Optional
def ArcSin(input_vertex: vertex_constructor_param_types, label: Optional[str]=None) -> Vertex:
"""
Takes the inverse sin of a vertex, Arcsin(vertex)
:param input_vertex: the vertex
"""
return Vertex(context.jvm_view().ArcSinVertex, label, cast_to_vertex(input_verte... | 68f80b459ae0b235463284cf8db237d3d15751a1 | 3,630,404 |
def LSFIR(H,N,tau,f,Fs,Wt=None):
""" Least-squares fit of a digital FIR filter to the reciprocal of a given frequency response.
Parameters
----------
H: np.ndarray
frequency response values
N: int
FIR filter order
tau: float
delay of filter
f: np.ndarray
frequencies
Fs: float
sampling frequ... | 025d3327b985eaf708a61f808e913256c91a911d | 3,630,405 |
import math
def DrawTextBar(value, max_value, max_width=53):
"""Return a simple ASCII bar graph, making sure it fits within max_width.
Args:
value: integer or float representing the value of this bar.
max_value: integer or float representing the largest bar.
max_width: How many characters this graph ... | 7f4b267527317cbceddadc9f7a0307f8ec430bb4 | 3,630,406 |
def dpAdvisorTime():
"""
runs dpAdvisor and measures the time required to compute an answer.
"""
res = {}
length = len(subjects)
start_time = time.time()
res = dpAdvisor(subjects, 24)
end_time = time.time()
total_time = end_time - start_time
print 'It took', total_time, 'to compu... | edd26cb9840de04ea3bca8504ab3a27f0dd4b93b | 3,630,407 |
import os
import json
from datetime import datetime
def expire_batch(
client,
batch_dir):
"""Expire all the (unanswered) HITs in the batch.
Parameters
----------
client : MTurk.Client
a boto3 client for MTurk.
batch_dir : str
the path to the directory for the batch... | f63129c66ca6c5e58b48190dd64e062577df31ec | 3,630,408 |
import os
def googlenet(path = ""):
"""
returns info of each layer of the googlenet model with layer image path
"""
lr='0.001'
model = create_googlenet(48, 0.5)
files = os.listdir(path)
layer_name=[]
for layer in model.layers:
check = path + "/" + layer.name + ".png"
if... | 83849cd5f39efb9a2a1ac19ec1126e699731db54 | 3,630,409 |
import ctypes
def get_size(ctype, num, il_code):
"""Return ILValue representing total size of `num` objects of given ctype.
ctype - CType of object to count
num - Integral ILValue representing number of these objects
"""
long_num = set_type(num, ctypes.longint, il_code)
total = ILValue(ctype... | 14a405edb55a14ec408094c5d27995a4c0906ce2 | 3,630,410 |
def pe_17():
"""Sum the number of characters in the UK words representing the
integers from 1 to 1,000. Exclude dashes and spaces.
"""
total = 0
for number_word in range(1, 1001):
number_word = lpe.number_to_word(number_word)
number_word = number_word.replace('-', '')
number_... | fb55ff73072c50c6b272a2c7f9c9228d5c406b40 | 3,630,411 |
def metrics_detection(scores, labels, pos_label=1, max_fpr=FPR_MAX_PAUC, verbose=True):
"""
Wrapper function that calculates a bunch of performance metrics for anomaly detection.
:param scores: numpy array with the anomaly scores. Larger values correspond to higher probability of a
point... | 854c9a74518bdd09520a47173077bcd7865bef87 | 3,630,412 |
def bias_init(shape, name=None, constant=0.0):
"""Bias Initialization
Args:
shape : Shape of the variable
name : Name of the variable
constant: Value of constant to initialize
Returns:
Initialized bias tensor
"""
if name is None:
name = 'b'
b = tf.... | a9f9314a3ba896f036e6cd30c88951ec08bbeb68 | 3,630,413 |
def _FindBinmanNode(dtb):
"""Find the 'binman' node in the device tree
Args:
dtb: Fdt object to scan
Returns:
Node object of /binman node, or None if not found
"""
for node in dtb.GetRoot().subnodes:
if node.name == 'binman':
return node
return None | bf924d173a1adf81c1705ad1ea1fae490567a317 | 3,630,414 |
def replace_escape_chars(text, which_ones=('\n', '\t', '\r'), replace_by=u'', \
encoding=None):
"""Remove escape characters.
`which_ones` is a tuple of which escape characters we want to remove.
By default removes ``\\n``, ``\\t``, ``\\r``.
`replace_by` is the string to replace the escape char... | 3742e08ed8b657ce1f9379b4e751fae413c19786 | 3,630,415 |
def purge_report_from_mobile_ucr(report_config):
"""
Called when a report is deleted, this will remove any references to it in
mobile UCR modules.
"""
if not toggles.MOBILE_UCR.enabled(report_config.domain):
return False
did_purge_something = False
for app in get_apps_in_domain(repo... | cf9a744772514868a5e0c6a7ec890ca55ecaa82c | 3,630,416 |
def image_color_cluster(image, k=5):
"""
:param image(numpy array): 추출된 옷
:param k(int) : 군집화할 개수
:return c_list(list) : 각 색의 rgb 값이 담긴 리스트
:return p_list(list) : 각 색의 분포도가 담긴 리스트
"""
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
image = image.reshape((image.shape[0] * image.shape[1], 3... | d0fc166cd3465b9f26b4a7bd2e290b1565c77488 | 3,630,417 |
def _get_auth_service(app):
"""Returns an _AuthService instance for an App.
If the App already has an _AuthService associated with it, simply returns
it. Otherwise creates a new _AuthService, and adds it to the App before
returning it.
Args:
app: A Firebase App instance (or None to use the... | 75b6890fb8650e621bd3d668d8704b6c38a76807 | 3,630,418 |
def winner_distance(r1, r2, reverse=False):
""" Asymmetrical winner distance.
This distance is the rank of the winner of r1 in r2, normalized by the number of candidates.
(rank(r1 winner)) - 1 / (n - 1)
Assuming no ties.
Args:
r1: 1D vector representing a judge.
... | 4f8912165905360aeecd355c68da19a11adf3600 | 3,630,419 |
def make_list_accos():
"""Return the acco numbers as list
Returns:
list: List with acco numbers
"""
list_saharas= list(range(1,23))
list_kalaharis =list(range (637,656))
list_balis = list(range (621,627))
list_waikikis = list(range(627,637))
list_serengeti = list(range(659,668))... | 9f2ac7aa4f78588013160f94374e602832b61771 | 3,630,420 |
def load_manifest(url, version, manifest_name):
"""Download and parse manifest."""
manifest_raw = do_curl(f"{url}/{version}/Manifest.{manifest_name}")
manifest = {}
if not manifest_raw:
raise Exception(f"Unable to load manifest {manifest_name}")
try:
lines = manifest_raw.splitlines(... | f2eb6bb8a9fb3e86a7a87293873f32ae73e2ae62 | 3,630,421 |
from typing import List
def create_intrusion_set_from_name(
name: str,
author: Identity,
external_references: List[ExternalReference],
object_marking_refs: List[MarkingDefinition],
) -> IntrusionSet:
"""Create intrusion set with given name."""
aliases: List[str] = []
alias = name.replace(... | 9e545b78af90acf4ab7e9ab556bd0f66989b5f9a | 3,630,422 |
from typing import Any
def get_clients(
*,
db: Session = Depends(deps.get_db),
current_user: models.User = Security(
deps.get_current_active_user,
scopes=[Role.ADMIN["name"], Role.SUPER_ADMIN["name"]],
),
) -> Any:
"""
Retrieve all clients.
"""
# TODO redundant check
... | e292986d88dbc07e931e0656eefc0b86e75a7575 | 3,630,423 |
import os
import re
def find_files(directory='.', pattern='.*', recursive=True):
"""Search recursively for files matching a pattern"""
if recursive:
return (os.path.join(directory, filename)
for directory, subdirectories, filenames in os.walk(directory)
for filename in filename... | a725a30df0783badd90357e5ce917dd37cf99426 | 3,630,424 |
def _host_is_same(host1: str, host2: str) -> bool:
"""Check if host1 and host2 are the same."""
return host1.split(":")[0] == host2.split(":")[0] | 0bd9393786801d0f69d4982fc9f8edce378e9656 | 3,630,425 |
from typing import List
def check_chan_xt_three_bi(kline, bi_list: List[ChanObject]):
"""
获取指定3分笔得形态
(含有三笔)
:param kline: ctaLineBar对象
:param bi_list: 笔列表
:return:
"""
v = ChanSignals.Other.value
if len(bi_list) != 3:
return v
bi_1, bi_2, bi_3 = bi_list
# 最后一笔是下跌... | cf4e9b88abb604ff0646b6513a0cec62e15660dc | 3,630,426 |
def get_filter_type_choices():
"""
Get a tuple of filter types
:return: tuple with filter types
"""
return ('', 'Select one'), ('Filter Types', [('storlet', 'Storlet'), ('native', 'Native')]) | 21f4173b1aafa35b4c877d6f844349c2907932a8 | 3,630,427 |
from typing import Optional
def get_connected_devices() -> ConnectedDevices:
"""Returns Mbed Devices connected to host computer.
Connected devices which have been identified as Mbed Boards and also connected devices which are potentially
Mbed Boards (but not could not be identified in the database) are r... | cb9a3565c7b62f99858ed90e85dd9686c9db9e00 | 3,630,428 |
from typing import Union
from typing import Optional
def my_sqrt_with_local_types(x: Union[int, float]) -> float:
"""Computes the square root of x, using the Newton-Raphson method"""
approx: Optional[float] = None
guess: float = x / 2
while approx != guess:
approx = guess
guess = (appr... | 61263b7722ea6becc536e6ccac69063ded41aa92 | 3,630,429 |
def get_tempo(h5,songidx=0):
"""
Get release year from a HDF5 song file, by default the first song in it
"""
return h5.root.musicbrainz.songs.cols.tempo[songidx] | 155d690eb6773cbaf0d06e2cb83ea8976cb0f1d8 | 3,630,430 |
def boolstr(value):
"""Value to bool handling True/False strings."""
if isinstance(value, basestring):
if value.lower() == 'false':
return False
try:
value = float(value)
except ValueError:
pass
return bool(value) | ccfaa56e3f5694fad2f94ea53f90379890148181 | 3,630,431 |
import math
def round_half_up(n: float, decimals: float = 0) -> float:
"""This function rounds to the nearest integer number (e.g 2.4 becomes 2.0 and 2.6 becomes 3);
in case of tie, it rounds up (e.g. 1.5 becomes 2.0 and not 1.0)
Args:
n (float): number to round
decimals (int): number of ... | e0aab5cba456b4ffe6fab11a21b97fe4e17b045a | 3,630,432 |
from typing import Set
def _possible_edges(n1: Set, n2: Set, directed: bool, self_loops: bool = False):
"""Compute the number of possible edges between two sets."""
a = n1.intersection(n2)
e = (len(n1) - len(a)) * (len(n2) - len(a))
if directed:
e *= 2
if self_loops:
e += len(n1) +... | 4cf21d9521c3d071d7d1376bd917f2ec39435108 | 3,630,433 |
import math
def compute_backbone_shapes(config, image_shape):
"""Computes the width and height of each stage of the backbone network.
Returns:
[N, (height, width)]. Where N is the number of stages
"""
if callable(config.BACKBONE):
return config.COMPUTE_BACKBONE_SHAPE(image_shape)
... | 9af0a10393bf3297a1ac239682d493c0670fcbbd | 3,630,434 |
def coherency_phase_delay_bavg(time_series,lb=0,ub=None,csd_method=None):
"""
Band-averaged phase delay between time-series
Parameters
----------
time_series: float array
The time-series data
lb,ub : float, optional
Lower and upper bounds on the frequency range over which the ph... | 62b689d9513c94ab6ad411e485d4e5f3cb9ca125 | 3,630,435 |
def write_sale_table(
df: DataFrame, output_path: str, filename: str = "sale.csv",
) -> DataFrame:
"""
Extract a sale transaction (fact) table from the staging data and save it in the csv format.
Args:
df: Staging dataframe containing source data.
output_path: Path to where the resulting... | c567c2a929bbe2676e8ff544398954c0a2926d93 | 3,630,436 |
def is_equal_tf(x: tf.Tensor, y: tf.Tensor) -> bool:
"""return true if two tf tensors are nearly equal"""
x = tf.cast(x, dtype=tf.float32)
y = tf.cast(y, dtype=tf.float32)
return tf.reduce_max(tf.abs(x - y)).numpy() < EPS | f9816cc393689c14e20381f9b0b3651235d40eab | 3,630,437 |
from typing import List
def align_dtw_scale(
reference: Trace, *traces: Trace, radius: int = 1, fast: bool = True
) -> List[Trace]:
"""
Align :paramref:`~.align_correlation.traces` to the :paramref:`~.align_correlation.reference` trace.
Use fastdtw (Dynamic Time Warping) with scaling as per:
Jas... | 628e458ce88bebd6b2919fca35b9c4d5cc0782a1 | 3,630,438 |
import tensorflow as tf # wanted to circumvent this, but parsing the serialized data cleanly was difficult
import sqlite3
import collections
def load_stackoverflow_tff(cache_dir="~/data", user_idx=0, split="train"):
"""Load the tensorflow federated stackoverflow dataset into pytorch."""
if split == "validati... | 91c0defba1081c5871c20d09e2ad9e758617906f | 3,630,439 |
def format_string(current_size, total_length, elapsed_time):
"""
Consistent format to be displayed on the screen.
:param current_size: Number of finished object size
:param total_length: Total object size
:param elapsed_time: number of seconds passed since start
"""
n_to_mb = current_size /... | 8e9df1ede4bcc42aa97c46139453d677703e77dc | 3,630,440 |
import os
import time
def get_file (queue):
"""Get file from queue after making sure it arrived completely; None
is returned if the file is not a fits file or still having trouble
reading the fits file even after waiting for 60s; otherwise the
filename is returned.
"""
# get event from queu... | 5a81f5026b55ac4359bf119c67271d935057545b | 3,630,441 |
import logging
def upload_file(src_local_path, dest_s3_path):
"""
upload file
:param src_local_path:
:param dest_s3_path:
:return:
"""
try:
with open(src_local_path, 'rb') as f:
s3.upload_fileobj(f, BUCKET_NAME, dest_s3_path)
except Exception as e:
logging.e... | bf4f324fc3246d50e41a956e5bed4c2888276dee | 3,630,442 |
import torch
def labels_from(distribution):
"""Takes a distribution tensor and returns a labels tensor."""
nclasses = distribution.shape[0]
llist = [[i] * n for i, n in zip(range(nclasses), distribution)]
# labels = [l for cl in llist for l in cl] # flatten the list of lists
labels = list(chain(*... | 7f1cc3fec0b3fe4f2cef963da40087e33c974996 | 3,630,443 |
import argparse
def get_raygen_argparser():
"""
Get the command line input/output arguments passed in to `raygen`.
"""
parser = argparse.ArgumentParser(
description='A simple static site generator, for those who want to fully the generation of blog.'
)
parser.add_argument(
'--... | da3993c1d98be1a3ecf5cec2942b4cda5edb3a8d | 3,630,444 |
def import_ham_dataset(dataset_root, outf, training=True):
"""
Returns dataset class instance for DataLoader. Downloads dataset if not present in dataset_root.
Args:
dataset_root (str): root directory of dataset.
outf (str): path to working directory.
training (bool): return trainin... | 1f9a659a1c13d862fbd32edad2e5ea03860bc3ad | 3,630,445 |
def truncatechars(value, arg):
"""
Truncates a string after a certain number of letters
Argument: Number of letters to truncate after
"""
def truncate_chars(s, num):
"Truncates a string after a certain number of letters."
length = int(num)
letters = [l for l in s]
if... | 1a1542504261fcf859edfac01048c8fa817a314b | 3,630,446 |
def default_category_orders() -> dict:
"""Returns the default dictionary of category orders"""
day_order = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
weekend_order = ["Weekday", "Weekend"]
season_order = ["Spring", "Summer", "Autumn", "Winter"]
month_order = [
"January",
"Febr... | 4110287bc30445f27c7c3d0c38cb662d769a5217 | 3,630,447 |
def argsort(seq, key=None, cmp=None, reverse=False):
"""Returns the indices corresponding to a sort of the given `seq`.
Can optionally pass in `cmp` and `reverse` just as you would to :func:`sorted()`.
"""
if not seq: return ()
ukey = key
iseq = sorted([(v, i) for i, v in enumerate(seq)], key=la... | eb56870506642928c35e434b2a859d8d4f0bf08a | 3,630,448 |
def new_category():
""" Add new category """
# Check if the user is loged in
if 'username' not in login_session:
return redirect('/login')
if request.method == 'POST':
# Get data from the front-end
name = request.form['name']
description = request.form['description']
... | 0c108ff1d9cf86ef072ed723c067d94b11b82ddd | 3,630,449 |
def create_densenet(hidden_units, idx_to_cat):
"""Create a flowernet model based on the Densenet-121 architecture.
Args:
hidden_units: The number of hidden units in the flowernet classifier.
idx_to_cat: A dictionary mapping the internal index numbers provided by
the classifier to ... | 86643b9ca3b85d1aa940917c8c0fbe8467100ee6 | 3,630,450 |
import functools
import uuid
def log_event(func):
"""Decorator function to log events."""
@functools.wraps(func)
def wrapper(*args, **kwargs):
logger = get_logger()
result = func(*args, **kwargs)
_uuid = uuid.uuid4()
logger.info("[%s] Request: %s %s" % (_uuid, result['re... | cbae86724756451b9e484e6d16141c5e8f06e278 | 3,630,451 |
import tokenize
def cleanup_string(string, already_lowercase=False):
""" Do the following cleanup steps on the provided string:
1. Case Folding
2. Tokenization
3. Give it to cleanup_list()
"""
if not already_lowercase: # Case folding ... | 5e3dccec9306097c5e952f69d883a78507991779 | 3,630,452 |
def fscore(mesh1,
mesh2,
sample_count=100000,
tau=1e-04,
points1=None,
points2=None):
"""Computes the F-Score at tau between two meshes."""
points1, points2 = get_points(mesh1, mesh2, points1, points2, sample_count)
dist12, _ = pointcloud_neighbor_dista... | 07707b4ae58d3aa4f559ceb7f2b5f82c9d7fe8a7 | 3,630,453 |
def jsonp_ize(dep):
"""Parse dep as :term:`jsonp` (unless it has been modified with ``jsnop=False``). """
return modify(dep) if "/" in dep and type(dep) is str else dep | 0e5ff172a732a9319e7486a67cfd1db6520c8cf1 | 3,630,454 |
import re
def is_guid(techfin_tenant):
"""Validate guid arg
Args:
tenant (str): techfin tenant id
Returns:
bool: true if is valid guid value
"""
c = re.compile('[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}', re.I)
res = c.match(techfin_tenant)
r... | 7242f0da279375ab5873670ffef1fd4aa8749546 | 3,630,455 |
from typing import Callable
def register(name: ServiceKey, version: ServiceVersion) -> Callable:
"""Maps a service with a callable
Basically "glues" the implementation to a function node
"""
key: _ServiceKeyVersionPair = (name, version)
if key not in FUNCTION_SERVICES_CATALOG.keys():
rai... | 0dc38ca605c4d55fde9019fd473ab58bd7225357 | 3,630,456 |
import re
def get_pd_metrics(data):
"""Function for create physical disks metrics files."""
create_dir(LLD_METRICS_PATH)
for ctrl, ctrl_value in data.items():
if isinstance(ctrl_value, dict):
for ar_key, ar_value in ctrl_value.items():
match = re.search(ARRAY_NAME_PATT... | 5b073b0ec045ac3df5de74c6d2454b6775ffac78 | 3,630,457 |
def svn_stream_read(*args):
"""svn_stream_read(svn_stream_t stream, char buffer) -> svn_error_t"""
return _core.svn_stream_read(*args) | 1c9657c2b65b8b30fc20bc62f9002f8f6578cc63 | 3,630,458 |
import random
def create_pipes(pipes, pipe_assets):
"""
Creates the pipes. Generates them randomly and appends them to the pipe list.
Args:
pipes(list): A list containing the pipe rects
pipe_assets(list): A list containing the pipe images images (rotated and non-rotated)
Returns:
... | f5740d13b8524063c736de38cabaf0132d8d0f6d | 3,630,459 |
def shell_short(unordered, ordered):
"""
Startig at the bottom of the stack:
1 - If the name is in the correct position move to the next
2 - If it is not in the position remove it, move all other names
one positions down and got to 1
sort all the removed positions, these nam... | df57eb0bee03159ac6b698bf0377efec48355e76 | 3,630,460 |
def render_latest_entries_links(context, request=None):
"""
Renders the links to the 5 latest entries.
"""
qs = NewsEntry.objects.published()
context.update({
'entries': qs[:5]
})
return context | ea5afb238162d565bf00977c146ddd79a59fb3b4 | 3,630,461 |
def __standard_cand_fun(candidates):
"""
Convert candidates from the forms accepted by :py:fun:`recommend` into
a standard form, a function that takes a user and returns a candidate
list.
"""
if isinstance(candidates, dict):
return candidates.get
elif candidates is None:
retu... | ad206802bfbcd0ec8f4601ebc043f8d468709c75 | 3,630,462 |
import subprocess
def run_pwsh(code):
"""
:param code: powershell code to run
//TODO 16: add creation flags to make hidden, but still get stdout.
"""
p = subprocess.run(['powershell', code], stdout=subprocess.PIPE, stderr=subprocess.STDOUT, shell=True)
return p.stdout.decode() | eb78bfc2b6cc9611e0b6f550ebd7e318555088d6 | 3,630,463 |
def diff(obj1, obj2):
"""Prints a simple human-readable difference between two Python objects."""
result = []
diffAny(obj1, obj2, result)
return '\n'.join(result) | 9f898a17ee6e447e5aca9edcba8b4b6151aa6e3c | 3,630,464 |
import torch
def get_static_features(
inputs,
num_windows,
stream_sizes=None,
has_dynamic_features=None,
streams=None,
):
"""Get static features from static+dynamic features."""
if stream_sizes is None:
stream_sizes = [180, 3, 1, 15]
if has_dynamic_features is None:
has... | 4767c0a480b04047b16d01d7e994fb09c61b543c | 3,630,465 |
def _l4_parameterize_ ( l4 ,
tree ,
xvar ,
yvar ,
zvar ,
uvar ,
cut = '' , first = 0 , last = _large ) :
"""Parameterize 4D unbinned ddistribuition from TTree in terms of... | 6e4448450feb7063fb8ef8bb540a6b2af3fcfd5f | 3,630,466 |
import textwrap
def welcome():
"""
Welcomes the player, brief intro to the game, and returns hand size as integer
ranging from 4 to 9
"""
version = '0.1'
m01 = "Welcome to the MIT 6.00.1x Wordgame (etherwar's mod)"
m02 = "Build " + version
m03 = "The Game: "
m04 = "First, you must ... | 0a89b38c1b9636e78d7299b8d3c6051717ab7fd7 | 3,630,467 |
def look_up_annotation_set(p_load_list, p_type=''):
"""
Looks up an set of annotations in the database and finds the Ids of nodes containing SWISSPROT
proteins linked to by annotations
:param p_load_list: list of payloads
:param p_type: expected type of payloads
:return: list of tags for which ... | d1480a77472fd0c1e1a3d957fb7286da5360d4e8 | 3,630,468 |
def check():
"""Do the database check."""
icursor.execute("""
SELECT datname, age(datfrozenxid) FROM pg_database
ORDER by age DESC LIMIT 1
""")
row = icursor.fetchone()
return row | cc2584d2d049aa25745c67ccc90a65f4dbb227ec | 3,630,469 |
import random
def sample_multi_ellipsoid(key, mu, radii, rotation, unit_cube_constraint=True):
"""
Sample from a set of overlapping ellipsoids.
When unit_cube_constraint=True then during the sampling when a random radius is chosen, the radius is constrained.
u(t) = R @ (x + t * n) + c
u(t) == 1
... | 9b507adc2d485dc036718879e2de1a174e9713eb | 3,630,470 |
def auto_dataset(dataset, label) -> pd.DataFrame:
"""Prepares a dataset object."""
semantics = infer_semantic_from_dataframe(dataset)
def extract_by_semantic(semantic):
return [k for k, s in semantics.items() if s == semantic and k != label]
categorical_features = extract_by_semantic(Semantic.CATEGORICAL... | c58d1f6a7ca0a9aa36b93531c26b20deb23c7974 | 3,630,471 |
def chuz_top(input):
"""
:type input: ndarray
:return:
"""
return K.argmax(input, 1) | 009bea44ccb6a26e39fe9eb9bcd79afab1174fd7 | 3,630,472 |
import limix_legacy.modules.varianceDecomposition as VAR
import time
def _estimateKronCovariances(
phenos,
K1r=None,
K1c=None,
K2r=None,
K2c=None,
covs=None,
Acovs=None,
trait_covar_type="freeform",
rank=1,
lambd=None,
verbose=True,
init_method="random",
old_opt=Tru... | 8b29d0b2c6a967153e3a1717eaff9715de5eea26 | 3,630,473 |
def dBrickId(brickId):
"""Return box id if valid, raise an exception in other case"""
if brickId >= 0 and brickId <= 15:
return brickId
else:
raise ValueError(
'{} is not a valid Brick Id, Brick Id must be between 0-15'.format(
brickId)) | 10e0f27f179dcd54c5cc4967ea960b77a4c5a924 | 3,630,474 |
def vibrational_density_state(path_to_mass_weighted_hessian: str, eps_o: float = 3e12, nq: int = 2e4):
"""
Compute the vibrational density of state from hessian matrix
:arg
path_to_mass_weighted_hessian: str
Point to the mass weighted hessian file
eps_o: float
Th... | 4fbb92ad08174ab77d6df078876bcbdfc6786a92 | 3,630,475 |
import hashlib
def hash(text, digest_alg = 'md5'):
"""
Generates hash with the given text using the specified
digest hashing algorithm
"""
if not isinstance(digest_alg,str):
h = digest_alg(text)
else:
h = hashlib.new(digest_alg)
h.update(text)
return h.hexdigest() | 386268086a55b8e622c00b407cabd3207bb94ffb | 3,630,476 |
def box2d_iou(box1, box2):
"""Compute 2D bounding box IoU.
Input:
box1: tuple of (xmin,ymin,xmax,ymax)
box2: tuple of (xmin,ymin,xmax,ymax)
Output:
iou: 2D IoU scalar
"""
return get_iou(
{"x1": box1[0], "y1": box1[1], "x2": box1[2], "y2": box1[3]},
{"x1": box... | 8f291f5a1dd9d6c2278a0ecb00d7b6b3d581e028 | 3,630,477 |
from lxml import etree
from . import mavgen_python
from . import mavgen_c
from . import mavgen_wlua
from . import mavgen_cs
from . import mavgen_javascript
from . import mavgen_objc
from . import mavgen_swift
from . import mavgen_java
from . import mavgen_cpp11
import sys
import re
import os
def mavgen(opts, args):
... | a07a208252905a38eb4d1c91a9d457c3d5748264 | 3,630,478 |
def merge_params(params, config):
"""Merge CLI params with configuration file params. Configuration params
will overwrite the CLI params.
"""
return {**params, **config} | a1dc002a900968e6cf7c5ba401519759e6ef485e | 3,630,479 |
def init_rate():
""" This rate indicates the recorded positions' intervals. """
rate = float(0.1) # (Hz)
return rate | e6e9c6439fe4288c24be18bb098f1844aed9fc64 | 3,630,480 |
import time
import json
import base64
import requests
def doge_response(event, context):
""" Background Cloud Function to be triggered by Pub/Sub.
Takes the image URL passed in a Slack request and dogeifies it
by overlaying text generated by Cloud Vision.
Args:
event (dict): The data associate... | bc4120633ac278dbbdd11f6577bb72b3e953266e | 3,630,481 |
def get_gamma(y1, y2, gamma1, gamma2):
"""一般部位及び大部分がガラスで構成されていないドア等の開口部における日除けの効果係数 (-)
Args:
y1(float): 日除け下端から一般部及び大部分がガラスで構成されていないドア等の開口部の上端までの垂直方向距離 (mm)
y2(float): 一般部及び大部分がガラスで構成されていないドア等の開口部の高さ寸法 (mm)
gamma1(float): データ「日除けの効果係数」より算出した値
gamma2(float): データ「日除けの効果係数」より算出した値
Re... | 6503a957bc7d5daee1926aaa23694b4550733f6d | 3,630,482 |
import io
import pprint
def show(files, repo):
"""Show the commit dialog.
Args:
files: files for pre-populating the dialog.
repo: the repository.
Returns:
The commit msg.
"""
if IS_PY2:
# wb because we use pprint to write
cf = io.open(_commit_file(repo), mode='wb')
else:
cf = io.... | 48a6e77c40ebbe87870a425613a01f3376232230 | 3,630,483 |
def download_clip_wrapper(row, output_filename):
"""Wrapper for parallel processing purposes. label_to_dir"""
#print(row, type(row))
#print(output_filename)
downloaded, log = download_clip(row['video-id'], output_filename, row['start-time'], row['end-time'])
status = tuple([str(downloaded), out... | f7715c075b2f59078c2af3e17928ddd9591f00fd | 3,630,484 |
def staff_user_id():
"""Creates a staff user and returns its ID."""
staff = factories.UserStaff()
return staff.pk | 57e582056f130a91c1cbdaabaf0744d6959bc5ab | 3,630,485 |
def shift_combine(images, offsets, stat='mean', extend=False):
"""
Statistics on image stack each being offset by some xy-distance
Parameters
----------
images
offsets
stat
extend
Returns
-------
"""
# convert to (masked) array
images = np.asanyarray(images)
of... | 2d6d3b721a2dc47a52b656256fdb5d42793511dc | 3,630,486 |
from .wrapper import tf2onnx, tf2onnx_builtin_conversion
import logging
def convert_tensorflow(frozen_graph_def,
name=None, input_names=None, output_names=None,
doc_string='',
target_opset=None,
channel_first_inputs=None,
... | 2348498cfa54879fc30c3227f7ce80fdd48e0271 | 3,630,487 |
def isNumber(s):
"""returns True if string s can be cast to a number, False otherwise"""
try:
float(s)
return True
except ValueError:
return False | fdee7992541ce42fb05e3202e63fc5bac04d43bc | 3,630,488 |
def tasks(tmpdir):
"""
Set up a project with some tasks that we can test displaying
"""
task_l = [
"",
" ^ this is the first task (released)",
" and it has a second line",
" > this is the second task (committed)",
" . this is the third task (changed, not yet com... | 64104bde2aab55021cf0d49fbb1d47670d0e4e0d | 3,630,489 |
def user_login(username, password):
"""
用户登录api(手机登录)
Args:
username: 用户账号,手机号
password: 密码
Returns:
result: a json obj of user data
"""
base_url = 'https://music.163.com/weapi/login/cellphone'
login_url = 'https://music.163.com/weapi/login/'
password = hashlib.m... | d4e8ff4cce3e5606c59ebddb6c3ee2ec5275e4a4 | 3,630,490 |
import os
def get_input_source_directory(config):
"""
Given a configuration object, returns the directory of the input file(s).
"""
options = config.commandline
if options.multilocus:
# multilocus dataset: assume directory is given as input source
return os.path.abspath(options.inp... | 28f1b7d90ba45c812a36e8d16dde4813d5b4090d | 3,630,491 |
def validate_search_string(cls, value):
"""Strip search_field for evil chars used in XSS/SQL injection."""
return escape(value, quote=True) if value is not None else value | 4b77aea29d75d7ecc180514e44b1156c202be172 | 3,630,492 |
import torch
def get_topo(logbook):
"""Return a network for the experiment and the loss function for training."""
# create the network
net_config = logbook.config['indiv']['net']
if net_config['class'] not in logbook.module.__dict__:
raise ValueError('Network topology {} is not defined for pro... | 03977bb5d3520c913245b0e5bda56f6cad91a4bc | 3,630,493 |
def contact_length(roll_pass: RollPass, roll: Roll):
"""
Contact length between rolls and stock calculated using Siebel's approach
"""
height_change = roll_pass.in_profile.height - roll_pass.height
return np.sqrt(roll.min_radius * height_change - height_change ** 2 / 4) | 230914ec015ee84f6d3e4ece57d39357396b57f7 | 3,630,494 |
def swagger_url(self):
"""Patch for HTTPS"""
return url_for(self.endpoint('specs'), _external=True, _scheme='https') | 827ce733aef5a62ceb80a0ceb1fac7fd2d4a7b44 | 3,630,495 |
def read_matrix_as_image(path):
"""Read every channel of a fusion npy matrix.
Args
path: Path to the image.
"""
image = np.load(path)
#img = np.zeros((image.shape[0], image.shape[1],6))
#img[:,:,:5] = image
#return img[:, :, ::-1].copy()
return image[:, :, ::-1].copy() | 00ab043e5aff02f6e6de6aa1e1ac8aa52a6ddbc3 | 3,630,496 |
def home(request):
"""Mock home view"""
return HttpResponse('home') | 017be5073942202030c627a8a62393f49ef7d526 | 3,630,497 |
async def async_setup(hass: HomeAssistant, config: dict):
"""Set up the bpost component."""
hass.data.setdefault(DOMAIN, {})
return True | 69e7ea1d542f5aca3b7a6685b49761bc989b6985 | 3,630,498 |
from typing import List
def merge_subgroups(subgroup_list: List[Subgroup]) -> List[Subgroup]:
"""Post-processing the clusters by merging long names with short sub-name.
For example, `male canadian lynx` is merged with `canadian lynx`"""
if len(subgroup_list) <= 1:
return subgroup_list
# sort... | 01fdfcd7c89a0e65eb9118d0b97748298a0c8f70 | 3,630,499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.