content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def update_resnet(model, debug=False):
"""
Update a ResNet model to use :class:`EltwiseSum` for the skip
connection.
Args:
model (:class:`torchvision.models.resnet.ResNet`): ResNet model.
debug (bool): If True, print debug statements.
Returns:
model (:class:`torchvision.mod... | 16,600 |
def docker(cmd='--help'):
"""
Wrapper for docker
"""
set_env()
template = 'docker {cmd}'.format(cmd=cmd)
run(template) | 16,601 |
def sameSize(arguments) -> bool:
"""Checks whether given vectors are the same size or not"""
sameLength = True
initialSize = len(vectors[arguments[0]])
for vector in arguments:
if len(vectors[vector]) != initialSize:
sameLength = False
return sameLength | 16,602 |
def write_bed_file(
simulated_individuals,
bim_SNP_names,
output_name,
bim_SNP_complete_pos,
bim_SNP_nucleotides,
population_ID,
test_functionality,
):
"""
Purpose
-------
to write the simulated data into realistic (bed, bim, fam) filesets. Does not include phenotypes at th... | 16,603 |
def db_read(src_path, read_type=set, read_int=False):
"""Read string data from a file into a variable of given type.
Read from the file at 'src_path', line by line, skipping certain lines and
removing trailing whitespace.
If 'read_int' is True, convert the resulting string to int.
Return r... | 16,604 |
def get_config_keys():
"""Parses Keys.java to extract keys to be used in configuration files
Args: None
Returns:
list: A list of dict containing the following keys -
'key': A dot separated name of the config key
'description': A list of str
"""
desc_re = re.compile(... | 16,605 |
def tick_update_position(tick, tickxs, tickys, labelpos):
"""Update tick line and label position and style."""
tick.label1.set_position(labelpos)
tick.label2.set_position(labelpos)
tick.tick1line.set_visible(True)
tick.tick2line.set_visible(False)
tick.tick1line.set_linestyle('-')
tick.tick... | 16,606 |
def new():
"""Create a new community."""
return render_template('invenio_communities/new.html') | 16,607 |
def interpolate(results_t, results_tp1, dt, K, c2w, img_wh):
"""
Interpolate between two results t and t+1 to produce t+dt, dt in (0, 1).
For each sample on the ray (the sample points lie on the same distances, so they
actually form planes), compute the optical flow on this plane, then use softsplat
... | 16,608 |
def divisor(baudrate):
"""Calculate the divisor for generating a given baudrate"""
CLOCK_HZ = 50e6
return round(CLOCK_HZ / baudrate) | 16,609 |
def test_Preprocess_undefined_variable():
"""Test that an undefined variable does not cause an error."""
assert (
clang.Preprocess(
"""
int main(int argc, char** argv) { return UNDEFINED_VARIABLE; }
""",
[],
)
== """
int main(int argc, char** argv) { return UNDEFINED_VARIABLE; }
"""
) | 16,610 |
def scm_get_active_branch(*args, **kwargs):
"""
Get the active named branch of an existing SCM repository.
:param str path: Path on the file system where the repository resides. If not specified, it defaults to the
current work directory.
:return: Name of the activ... | 16,611 |
def search_evaluations(campus, **kwargs):
"""
year (required)
term_name (required): Winter|Spring|Summer|Autumn
curriculum_abbreviation
course_number
section_id
student_id (student number)
"""
url = "%s?%s" % (IAS_PREFIX, urlencode(kwargs))
data = get_resource_by_campus(url, cam... | 16,612 |
async def get_user(username: str, session: AsyncSession) -> Optional[User]:
"""
Returns a user with the given username
"""
return (
(await session.execute(select(User).where(User.name == username)))
.scalars()
.first()
) | 16,613 |
def convert_modtime_to_date(path):
"""
Formats last modification date of a file into m/d/y form.
Params:
path (file path): the file to be documented
Example:
convert_modtime_to_date(/users/.../last_minute_submission.pdf)
"""
fileStatsObj = os.stat(path)
modificationTime = ... | 16,614 |
def compute_balances(flows):
"""
Balances by currency.
:param flows:
:return:
"""
flows = flows.set_index('date')
flows_by_asset = flows.pivot(columns='asset', values='amount').apply(pandas.to_numeric)
balances = flows_by_asset.fillna(0).cumsum()
return balances | 16,615 |
def unjsonify(json_data):
"""
Converts the inputted JSON data to Python format.
:param json_data | <variant>
"""
return json.loads(json_data, object_hook=json2py) | 16,616 |
def comp_state_dist(table: np.ndarray) -> Tuple[np.ndarray, List[str]]:
"""Compute the distribution of distinct states/diagnoses from a table of
individual diagnoses detailing the patterns of lymphatic progression per
patient.
Args:
table: Rows of patients and columns of LNLs, reporting which L... | 16,617 |
def polyConvert(coeffs, trans=(0, 1), backward=False):
"""
Converts polynomial coeffs for x (P = a0 + a1*x + a2*x**2 + ...) in
polynomial coeffs for x~:=a+b*x (P~ = a0~ + a1~*x~ + a2~*x~**2 +
...). Therefore, (a,b)=(0,1) makes nothing. If backward, makes the
opposite transformation.
Note: backw... | 16,618 |
def uniform(_data, weights):
"""
Randomly initialize the weights with values between 0 and 1.
Parameters
----------
_data: ndarray
Data to pick to initialize weights.
weights: ndarray
Previous weight values.
Returns
-------
weights: ndarray
New weight values... | 16,619 |
def ingresar_datos():
"""Ingresa los datos de las secciones"""
datos = {}
while True:
codigo = int_input('Ingrese el código de la sección: ')
if codigo < 0:
break
cantidad = int_input(
'Ingrese la cantidad de alumnos: ', min=MIN, max=MAX
)
dato... | 16,620 |
def fetch_credentials() -> Credentials:
"""Produces a Credentials object based on the contents of the
CONFIG_FILE or, alternatively, interactively.
"""
if CONFIG_FILE_EXISTS:
return parse_config_file(CONFIG_FILE)
else:
return get_credentials_interactively() | 16,621 |
def pool_adjacency_mat_reference_wrapper(
adj: sparse.spmatrix, kernel_size=4, stride=2, padding=1
) -> sparse.spmatrix:
"""Wraps `pool_adjacency_mat_reference` to provide the same API as `pool_adjacency_mat`"""
adj = Variable(to_sparse_tensor(adj).to_dense())
adj_conv = pool_adjacency_mat_reference(adj... | 16,622 |
def send(socket, obj, flags=0, protocol=-1):
"""stringify an object, and then send it"""
s = str(obj)
return socket.send_string(s) | 16,623 |
def arraystr(A: Array) -> str:
"""Pretty print array"""
B = np.asarray(A).ravel()
if len(B) <= 3:
return " ".join([itemstr(v) for v in B])
return " ".join([itemstr(B[0]), itemstr(B[1]), "...", itemstr(B[-1])]) | 16,624 |
def dist2_test(v1, v2, idx1, idx2, len2):
"""Square of distance equal"""
return (v1-v2).mag2() == len2 | 16,625 |
def extract_grid_cells(browser, grid_id):
"""
Given the ID of a legistar table, returns a list of dictionaries
for each row mapping column headers to td elements.
"""
table = browser.find_element_by_id(grid_id)
header_cells = table.find_elements_by_css_selector(
'thead:nth-child(2) ... | 16,626 |
def gatherAllParameters(a, keep_orig=True):
"""Gather all parameters in the tree. Names are returned along
with their original names (which are used in variable mapping)"""
if type(a) == list:
allIds = set()
for line in a:
allIds |= gatherAllVariables(line)
return allIds
if not isinstance(a, ast.AST):
r... | 16,627 |
def average_link_euclidian(X,verbose=0):
"""
Average link clustering based on data matrix.
Parameters
----------
X array of shape (nbitem,dim): data matrix
from which an Euclidian distance matrix is computed
verbose=0, verbosity level
Returns
-------
t a weightForest structur... | 16,628 |
def cached(func):
"""Decorator cached makes the function to cache its result and return it in duplicate calls."""
prop_name = '__cached_' + func.__name__
@functools.wraps(func)
def _cached_func(self):
try:
return getattr(self, prop_name)
except AttributeError:
va... | 16,629 |
def SX_inf(*args):
"""
create a matrix with all inf
inf(int nrow, int ncol) -> SX
inf((int,int) rc) -> SX
inf(Sparsity sp) -> SX
"""
return _casadi.SX_inf(*args) | 16,630 |
def test_book_id_put_missing_auth_gets_400_status_code(testapp, testapp_session, one_user):
"""Test that PUT to book-id route gets 400 status code for missing auth."""
res = testapp.put('/books/1', status=400)
assert res.status_code == 400 | 16,631 |
def many_body_collide(
MAX_TIMER=600, VB=1000, TSTEP=0.0001, EP=0.01, recalculate=True, algorithm="vv"
):
"""
Runs a multi body collision to look check other functions.
"""
particles = []
sub = str(MAX_TIMER) + "t_" + str(EP) + "e"
co = scl.Controls(
MAXTIMER=MAX_TIMER,
TSTEP... | 16,632 |
async def live_pusher(bot: Bot, config: Config):
"""直播推送"""
uids = config.get_live_uid_list()
if not uids:
return
log.debug(f'爬取直播列表,目前开播{sum(status.values())}人,总共{len(uids)}人')
br = BiliReq()
res = await br.get_live_list(uids)
if not res:
return
for uid, info in res.it... | 16,633 |
def aes_encrypt(mode, aes_key, aes_iv, *data):
"""
Encrypt data with AES in specified mode.
:param aes_key: aes_key to use
:param aes_iv: initialization vector
"""
encryptor = Cipher(algorithms.AES(aes_key), mode(aes_iv), backend=default_backend()).encryptor()
result = None
for value in... | 16,634 |
def _ebpm_gamma_update_a(init, b, plm, step=1, c=0.5, tau=0.5, max_iters=30):
"""Backtracking line search to select step size for Newton-Raphson update of
a"""
def loss(a):
return -(a * np.log(b) + a * plm - sp.gammaln(a)).sum()
obj = loss(init)
d = (np.log(b) - sp.digamma(init) + plm).mean() / sp.polygamma... | 16,635 |
def edge_distance_mapping(graph : Graph,
iterations : int,
lrgen : LearningRateGen,
verbose : bool = True,
reset_locations : bool = True):
"""
Stochastic Gradient Descent algorithm for performing ... | 16,636 |
def prec_solvefn(t, y, r, z, gamma, delta, lr):
"""Solve the preconditioning system I - gamma * J except
for a constant factor."""
z[0] = r[0] + gamma * r[1]
z[1] = - gamma*k/m * r[0] + r[1] | 16,637 |
def plot_n_images(image_array, n):
""" plot first n images
n has to be a square number
"""
first_n_images = image_array[:n, :]
grid_size = int(np.sqrt(n))
fig, ax_array = plt.subplots(nrows=grid_size, ncols=grid_size, sharex=True, sharey=True, figsize=(8, 8))
for r in range(grid_size):
... | 16,638 |
def strip_extension(name: str) -> str:
"""
Remove a single extension from a file name, if present.
"""
last_dot = name.rfind(".")
if last_dot > -1:
return name[:last_dot]
else:
return name | 16,639 |
def next_joystick_device():
"""Finds the next available js device name."""
for i in range(100):
dev = "/dev/input/js{0}".format(i)
if not os.path.exists(dev):
return dev | 16,640 |
def test_notimplemented():
"""
Function testing raising not implemented error for higher order
"""
x = fwd.Variable()
y = fwd.Variable()
with pytest.raises(NotImplementedError):
f = x * y
f.derivative_at(x, {x:0.5, y:0.5}, order=3)
with pytest.raises(NotImplementedError)... | 16,641 |
def validatePullRequest(data):
"""Validate pull request by action."""
if 'action' not in data:
raise BadRequest('no event supplied')
if 'pull_request' not in data or 'html_url' not in data.get('pull_request'):
raise BadRequest('payload.pull_request.html_url missing')
return True | 16,642 |
def assert_json_roundtrip_works(obj, text_should_be=None, resolvers=None):
"""Tests that the given object can serialized and de-serialized
Args:
obj: The object to test round-tripping for.
text_should_be: An optional argument to assert the JSON serialized
output.
resolvers: ... | 16,643 |
def _test(fonts, phase, extra_styles):
"""Build name info from font_paths and dump the names for them."""
family_to_name_info = create_family_to_name_info(fonts, phase, extra_styles)
print(write_family_name_info(family_to_name_info, pretty=True))
_dump_family_names(fonts, family_to_name_info, phase) | 16,644 |
def __adjust_data_for_log_scale(dataframe: pd.DataFrame) -> pd.DataFrame:
"""
This will clean and adjust some of the data so that Altair can plot it using a logarithmic scale. Altair does not
allow zero values on the Y axis when plotting with a logarithmic scale, as log(0) is undefined.
Args:
d... | 16,645 |
def predict_sentence(model,vocab,sentence):
"""Predicts the section value of a given sentence
INPUT: Trained model, Model vocab, Sentence to predict
OUTPUT: Assigned section to the sentence"""
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
nlp=spacy.load('en_core_sci_md')... | 16,646 |
def ne_offsets_by_sent(
text_nest_list=[],
model='de_core_news_sm',
):
""" extracts offsets of NEs and the NE-type grouped by sents
:param text_nest_list: A list of list with following structure:\
[{"text": "Wien ist schön", "ner_dicts": [{"text": "Wien", "ne_type": "LOC"}]}]
:param model: The ... | 16,647 |
def write_build_info(filename, is_config_cuda, is_config_rocm, key_value_list):
"""Writes a Python that describes the build.
Args:
filename: filename to write to.
build_config: A string that represents the config used in this build (e.g.
"cuda").
key_value_list: A list of "key=value" strings that... | 16,648 |
def clone_repo(
url: str,
path: str,
branch: Optional[str] = None,
) -> bool:
"""Clone repo from URL (at branch if specified) to given path."""
cmd = ['git', 'clone', url, path]
if branch:
cmd += ['--branch', branch]
return run(cmd)[0].returncode == 0 | 16,649 |
def get_inputtype(name, object_type):
"""Get an input type based on the object type"""
if object_type in _input_registry:
return _input_registry[object_type]
inputtype = type(
name,
(graphene.InputObjectType,),
_get_input_attrs(object_type),
)
_input_registry[object... | 16,650 |
def normalize_df_(df_train, *, other_dfs=None, skip_column=None):
"""
Normalizes all columns of `df_train` to zero mean unit variance in place.
Optionally performs same transformation to `other_dfs`
# Parameters
other_dfs [pd.DataFrame]: List of other DataFrames to apply transformation to
skip_... | 16,651 |
def res_ex_response(e, original=False):
"""异常响应,结果必须可以作json序列化
参数: e # 原始错误信息
original # 是否返回原始错误信息,默认flase
"""
from src.common import lang
if os.getenv('ENV') != 'UnitTest':
current_app.logger.error(e)
msg = lang.resp('L_OPER_FAILED')
if original:
msg = st... | 16,652 |
def transform_mappings(queryables, typename, reverse=False):
"""transform metadata model mappings"""
if reverse: # from csw:Record
for qbl in queryables.keys():
if qbl in typename.values():
tmp = [k for k, v in typename.items() if v == qbl][0]
val = queryable... | 16,653 |
def get_engine_status(engine=None):
"""Return a report of the current engine status"""
if engine is None:
engine = crawler.engine
global_tests = [
"time()-engine.start_time",
"engine.is_idle()",
"engine.has_capacity()",
"engine.scheduler.is_idle()",
"len(engi... | 16,654 |
def stock_em_jgdy_tj():
"""
东方财富网-数据中心-特色数据-机构调研-机构调研统计
http://data.eastmoney.com/jgdy/tj.html
:return: pandas.DataFrame
"""
url = "http://data.eastmoney.com/DataCenter_V3/jgdy/gsjsdy.ashx"
page_num = _get_page_num_tj()
temp_df = pd.DataFrame()
for page in tqdm(range(1, page_num+1)):... | 16,655 |
def storage():
"""Create managed bare-database repository storage."""
with tempfile.TemporaryDirectory(prefix="representations-") as temporary:
yield RepoStorage(directory=temporary) | 16,656 |
def hpdi(x, prob=0.90, axis=0):
"""
Computes "highest posterior density interval" (HPDI) which is the narrowest
interval with probability mass ``prob``.
:param numpy.ndarray x: the input array.
:param float prob: the probability mass of samples within the interval.
:param int axis: the dimensio... | 16,657 |
def a(n, k):
"""calculates maximum power of p(n) needed
>>> a(0, 20)
4
>>> a(1, 20)
2
>>> a(2, 20)
1
"""
return floor(log(k) / log(p(n))) | 16,658 |
def do_train(
train_path: typing.Union[str, Path],
model_path: typing.Union[str, Path],
max_iterations: int = 100,
**kwargs,
):
"""CLI method for train_model"""
train_model(train_path, model_path, max_iterations=max_iterations) | 16,659 |
def is_windows():
""" détermine si le système actuel est windows """
return platform.system().lower() == "windows" | 16,660 |
def WTfilt_1d(sig):
"""
# 使用小波变换对单导联ECG滤波
# 参考:Martis R J, Acharya U R, Min L C. ECG beat classification using PCA, LDA, ICA and discrete
wavelet transform[J].Biomedical Signal Processing and Control, 2013, 8(5): 437-448.
:param sig: 1-D numpy Array,单导联ECG
:return: 1-D numpy Array,滤波后信号
... | 16,661 |
def discount_rewards(r):
""" take 1D float array of rewards and compute discounted reward """
gamma = 0.99
discounted_r = np.zeros_like(r)
running_add = 0
for t in reversed(range(0, r.size)):
running_add = running_add * gamma + r[t]
discounted_r[t] = running_add
return discounted... | 16,662 |
def mvn(tensor):
"""Per row mean-variance normalization."""
epsilon = 1e-6
mean = K.mean(tensor, axis=1, keepdims=True)
std = K.std(tensor, axis=1, keepdims=True)
mvn = (tensor - mean) / (std + epsilon)
return mvn | 16,663 |
def grapheme_to_phoneme(text, g2p, lexicon=None):
"""Converts grapheme to phoneme"""
phones = []
words = filter(None, re.split(r"(['(),:;.\-\?\!\s+])", text))
for w in words:
if lexicon is not None and w.lower() in lexicon:
phones += lexicon[w.lower()]
else:
phone... | 16,664 |
def mean_log_cosh_error(pred, target):
"""
Determine mean log cosh error.
f(y_t, y) = sum(log(cosh(y_t-y)))/n
where, y_t = predicted value
y = target value
n = number of values
:param pred: {array}, shape(n_samples,)
predicted values.
:... | 16,665 |
def plot_abctraces(pools, surveypath=''):
""" Input: a list of pools in the abc format
Generates trace plots of the thetas,eps and metrics """
sns.set_style("white")
matplotlib.rc("font", size=30)
""" Plot Metric-Distances """
distances = np.array([pool.dists for pool in pools])
... | 16,666 |
def initialize_runtime_commands():
"""
Creates all runtimeCommands that are depended to the Maya GUI.
"""
main_category = 'FG-Tools'
category = main_category + '.Display'
fg_tools.maya_runtime_command.create_runtime_command(command_name='fgToggleSmoothShaded',
... | 16,667 |
def set_cookie(cookiejar, kaka):
"""
Place a cookie (a http_cookielib.Cookie based on a set-cookie header line) in the cookie jar.
Always chose the shortest expires time.
:param cookiejar:
:param kaka: Cookie
"""
# default rfc2109=False
# max-age, httponly
for cookie_name, morsel i... | 16,668 |
def init_configuration(config_file):
"""
config_file -- configuration file of SFT module.
raises ConfigError in case of problems.
"""
sft_globals.config = configuration.Config(config_file) | 16,669 |
def main():
"""Run experiments"""
parser = argparse.ArgumentParser(
description="Run experiments for WAFR 2016 paper")
parser.add_argument('jobs', help='job file to run')
args = parser.parse_args()
with open(args.jobs, 'r') as job_file:
jobs = yaml.load(job_file)
print "Startin... | 16,670 |
def context(profile, mock_admin_connection, message):
"""RequestContext fixture."""
context = RequestContext(profile)
context.connection_record = mock_admin_connection
context.connection_ready = True
context.message = message
yield context | 16,671 |
def check_columns(board: list):
"""
Check column-wise compliance of the board for uniqueness (buildings of unique height)
and visibility (top-bottom and vice versa).
Same as for horizontal cases, but aggregated in one function for vertical case, i.e. columns.
>>> check_columns(['***21**', '412453*... | 16,672 |
def extract_header(mjds, path, keywords, dtypes=None, split_dbs=False, is_range=False):
"""Returns a `~pandas.DataFrame` with header information.
For a list or range of MJDs, collects a series of header keywords for
database files and organises them in a `~pandas.DataFrame` sorted by
MJD and frame numb... | 16,673 |
async def get_time():
"""获取服务器时间
"""
tz = pytz.timezone('Asia/Shanghai')
return {
'nowtime': datetime.now(),
'utctime': datetime.utcnow(),
'localtime': datetime.now(tz)
} | 16,674 |
def health_check():
"""Attempt to ping the database and respond with a status code 200.
This endpoint is verify that the server is running and that the database is
accessible.
"""
response = {"service": "OK"}
try:
postgres.session.query(text("1")).from_statement(text("SELECT 1")).all()... | 16,675 |
def find_ad_adapter(bus):
"""Find the advertising manager interface.
:param bus: D-Bus bus object that is searched.
"""
remote_om = dbus.Interface(
bus.get_object(constants.BLUEZ_SERVICE_NAME, '/'),
constants.DBUS_OM_IFACE)
objects = remote_om.GetManagedObjects()
for o, props... | 16,676 |
def leaky_relu(x, slope=0.2):
"""Leaky Rectified Linear Unit function.
This function is expressed as :math:`f(x) = \max(x, ax)`, where :math:`a`
is a configurable slope value.
Args:
x (~chainer.Variable): Input variable.
slope (float): Slope value :math:`a`.
Returns:
~chai... | 16,677 |
def test_check_whitespace_ink():
""" Whitespace glyphs have ink? """
check = CheckTester(universal_profile,
"com.google.fonts/check/whitespace_ink")
test_font = TTFont(TEST_FILE("nunito/Nunito-Regular.ttf"))
assert_PASS(check(test_font))
test_font["cmap"].tables[0].cmap[0x1... | 16,678 |
def GetConfig(user_config):
"""Decide number of vms needed to run oldisim."""
config = configs.LoadConfig(BENCHMARK_CONFIG, user_config, BENCHMARK_NAME)
config['vm_groups']['default']['vm_count'] = (FLAGS.oldisim_num_leaves
+ NUM_DRIVERS + NUM_ROOTS)
return config | 16,679 |
def build_tstuser_dir(username):
"""
Create a directory with files and return its structure
in a list.
:param username: str
:return: tuple
"""
# md5("foo") = "acbd18db4cc2f85cedef654fccc4a4d8"
# md5("bar") = "37b51d194a7513e45b56f6524f2d51f2"
# md5("spam") = "e09f6a7593f8ae3994ea57e1... | 16,680 |
def gen_answer(question, passages):
"""由于是MLM模型,所以可以直接argmax解码。
"""
all_p_token_ids, token_ids, segment_ids = [], [], []
for passage in passages:
passage = re.sub(u' |、|;|,', ',', passage)
p_token_ids, _ = tokenizer.encode(passage, maxlen=max_p_len + 1)
q_token_ids, _ = tokenizer... | 16,681 |
def compile(function_or_sdfg, *args, **kwargs):
""" Obtain a runnable binary from a Python (@dace.program) function. """
if isinstance(function_or_sdfg, dace.frontend.python.parser.DaceProgram):
sdfg = dace.frontend.python.parser.parse_from_function(
function_or_sdfg, *args, **kwargs)
el... | 16,682 |
def show_bgr(bgr, caption="image"):
"""指定BGRイメージをウィンドウへ表示する.
# Args:
bgr: BGRイメージ.
"""
cv2.imshow(caption, bgr)
cv2.waitKey(0) | 16,683 |
def is_untweeable(html):
"""
I'm not sure at the moment what constitutes untweeable HTML, but if we don't find DVIS in tiddlywiki,
that is a blocker
"""
# the same regex used in tiddlywiki
divs_re = re.compile(
r'<div id="storeArea"(.*)</html>',
re.DOTALL
)
return bool(divs_re.search(html)) | 16,684 |
def create_1m_cnn_model(only_digits: bool = False, seed: Optional[int] = 0):
"""A CNN model with slightly under 2^20 (roughly 1 million) params.
A simple CNN model for the EMNIST character recognition task that is very
similar to the default recommended model from `create_conv_dropout_model`
but has slightly u... | 16,685 |
def _check_index(target_expr, index_expr):
"""
helper function for making sure that an index is valid
:param target_expr: the target tensor
:param index_expr: the index
:return: the index, wrapped as an expression if necessary
"""
if issubclass(index_expr.__class__, _Expression):
in... | 16,686 |
def create_access_token(user: UserModel, expires_delta: timedelta = None) -> str:
"""
Create an access token for a user
:param user: CTSUser -> The user
:param expires_delta: timedelta -> The expiration of the token. If not given a default will be used
:return: str -> A token
"""
load_all_co... | 16,687 |
def is_async_mode():
"""Tests if we're in the async part of the code or not."""
async def f():
"""Unasync transforms async functions in sync functions."""
return None
obj = f()
if obj is None:
return False
obj.close() # prevent unawaited coroutine warning
return True | 16,688 |
def remove_arm(frame):
"""
Removes the human arm portion from the image.
"""
##print("Removing arm...")
# Cropping 15 pixels from the bottom.
height, width = frame.shape[:2]
frame = frame[:height - 15, :]
##print("Done!")
return frame | 16,689 |
def _DeleteCheckout(path, dry_run):
"""Deletes the checkout in |path|. Only actually deletes the checkout if
|dry_run| is False.
"""
_LOGGER.info('Deleting checkout directory: %s', path)
if dry_run:
return
_Shell('rmdir', '/S', '/Q', path, dry_run=False) | 16,690 |
def test_initialize_variants():
"""Test NNDSVD variants correctness
Test that the variants 'a' and 'ar' differ from basic NNDSVD only where
the basic version has zeros.
"""
data = np.abs(random_state.randn(10, 10))
W0, H0 = nmf._initialize_nmf(data, 10, variant=None)
Wa, Ha = nmf._initializ... | 16,691 |
def cumulative_spread(array, x):
"""
>>> import numpy as np
>>> a = np.array([1., 2., 3., 4.])
>>> cumulative_spread(a, 0.)
array([0., 0., 0., 0.])
>>> cumulative_spread(a, 5.)
array([1., 2., 2., 0.])
>>> cumulative_spread(a, 6.)
array([1., 2., 3., 0.])
>>> cumulative_spread(a, 1... | 16,692 |
def GetIdentifierStart(token):
"""Returns the first token in an identifier.
Given a token which is part of an identifier, returns the token at the start
of the identifier.
Args:
token: A token which is part of an identifier.
Returns:
The token at the start of the identifier or None if... | 16,693 |
def search_Language_Binding_Spec(stmt, node, config, gentype=None):
""" Identifying a name in Language_Binding_Spec node"""
# No need to resolve exteranl c library routines
pass | 16,694 |
def load_spec(filename):
"""
loads the IDL spec from the given file object or filename, returning a
Service object
"""
service = Service.from_file(filename)
service.resolve()
return service | 16,695 |
def connect(db_config_name):
"""
Check the current environment to determine which database
parameters to use, then connect to the target database on the
specified host.
:return: A database connection object.
"""
config_path = os.path.join(
os.path.dirname(os.path.dirname(os.path.rea... | 16,696 |
def load_model(file_path, *, epoch, model, likelihood, mll, optimizer, loss):
"""モデルの保存関数
Parameters
----------
file_path : str
モデルの保存先のパスとファイル名
epoch : int
現在のエポック数
model : :obj:`gpytorch.models`
学習済みのモデルのオブジェクト
likelihood : :obj:`gpytorch.likelihoods`
... | 16,697 |
def valid_account_id(log, account_id):
"""Validate account Id is a 12 digit string"""
if not isinstance(account_id, str):
log.error("supplied account id {} is not a string".format(account_id))
return False
id_re = re.compile(r'^\d{12}$')
if not id_re.match(account_id):
log.error(... | 16,698 |
def R_2(opc):
"""2 ops: src1/src2"""
# REG_OPC(opc)
M3(opc) | 16,699 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.