content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import six
def parse_fetch_response(text, normalise_times=True, uid_is_key=True):
"""Pull apart IMAP FETCH responses as returned by imaplib.
Returns a dictionary, keyed by message ID. Each value a dictionary
keyed by FETCH field type (eg."RFC822").
"""
if text == [None]:
return {}
res... | 3d629cb318ccf48f36a276a26caf7526e23aa4ea | 52,526 |
def compute_result(result_parameter, inputs, env, fix_point):
"""
Funciton to generate the expected result of the testcase.
Arguments
---------
result_parameter: Either OutputArgument or ReturnValue (see pulp_dsp_test.py)
inputs: Dict mapping name to the Argument, with arg.value, arg.ctype (and... | cb8798f79ae641f7223b5597c51f37e87f1f3bfe | 52,527 |
import re
def read_mp_feat(pred_path):
"""
if no prediction was done take mp_feat_norm
"""
header = []
temp = {}
test = makehash()
for line in open(pred_path, "r"):
line = line.rstrip("\n")
if line.startswith(str("ID") + "\t"):
header = re.split(r"\t+", line)
... | 54e70de2d34c4f8cbee5cec638ff22f5a4e6afa3 | 52,528 |
from typing import Any
def netconf_capabilities(task: Task, **kwargs: Any) -> Result:
"""nornir get netconf capabilities
:params task: type object
:returns: nornir result object
"""
conn = task.host.get_connection(
connection="netconf", configuration=task.nornir.config
)
results =... | 95119f081e9d06b43c8da36550b3e47aa7731eae | 52,529 |
def objective_fun(beta, lam, K, y):
"""Dual objective of binary kernel SVMs with intercept."""
# The dual objective is:
# fun(beta) = 0.5 beta^T K beta - beta^T y
# subject to
# sum(beta) = 0
# 0 <= beta_i <= C if y_i = 1
# -C <= beta_i <= 0 if y_i = -1
# where C = 1.0 / lam
return 0.5 * jnp.dot(beta,... | b72cecabdaf6f07fdba4f02f63b7e3923bdf7160 | 52,530 |
def is_unquoted_text(token):
"""
:param token: Token
:return: boolean
"""
return isinstance(token, UnquotedText) | 5f3a95c855885a7c607b5ab8889eac821fef50a2 | 52,531 |
def gallery(request):
"""renders the gallery for all images
"""
if request.user.is_authenticated():
return render(request, 'gallery.html')
return HttpResponseRedirect("/") | cdf17f2fb01444a2532457a775276dc77af0cd49 | 52,532 |
def rel_rmse(obs, mod):
"""returns RMSE of model results given observations"""
arg = ((mod - obs) / obs) ** 2
return sqrt(nanmean(arg)) | e5f99281123e255a47e949ee39380b194f180b15 | 52,533 |
import json
import logging
def spell_check(request):
"""
Returns a HttpResponse that implements the TinyMCE spellchecker protocol.
"""
try:
if not enchant:
raise RuntimeError("install pyenchant for spellchecker functionality")
raw = force_text(request.body)
input =... | 969cd2bc685c6ca9aef0e9eef850a4fb38dbe2ff | 52,534 |
def initialize_firebase():
"""Initialize Firebase, unless already initialized.
Returns:
(Firestore client): A Firestore database instance.
"""
try:
initialize_app()
except ValueError:
pass
return firestore.client() | 93c6e263bf94e9a9133605b2e7da730fcb5acccf | 52,535 |
def evaluate_(batch_iter, model):
""" To evaluate the model in EDU segmentation.
因内存原因,我们依旧选择批量运算的方式
不同的解码评测,不同的是,这个模式下只要一句一句进行,因为边界是未知
的,所以模型要做完边界预测才知道下一步做什么。
"""
c_b, g_b, h_b = 0., 0., 0.
for n_batch, (inputs, target) in enumerate(batch_iter, start=1):
word_ids, word_e... | 972758d49c81a176f1c50458757c8da59aebf70f | 52,536 |
from typing import Tuple
from pathlib import Path
def saved_model(od_detection_learner, tiny_od_data_path) -> Tuple[str, Path]:
""" A saved model so that loading functions can reuse. """
model_name = "test_fixture_model"
od_detection_learner.save(model_name)
assert (Path(tiny_od_data_path) / "models" ... | 383cd80905992775814be6f0024c836ec0c73c3d | 52,537 |
import itertools
def build_instance(ξ, n, m, r, D):
"""The graph generation algorithm."""
assert n <= m <= n * (n - 1), f"invalid number of arcs {m=}"
network = Network(nodes=range(n))
# Create optimal shortest path tree
m_neg = nb_neg_arcs(n, m, r)
m_neg_tree = nb_neg_tree_arcs(ξ, n, m, m_neg... | 1dd063a086304892fd6e8e88d0ca72ec4fd3265f | 52,538 |
import pathlib
def _check_if_python_module_exists(path: str) -> bool:
"""Check if an Earth Engine python module has been created from a JavaScript module in ee_extra.
Args:
path: str
Returns:
Whether the python module has been created.
"""
return pathlib.Path(_convert_path_to_ee_... | d5d57c63dff84a5d62945b64ece8ac7d6ba18804 | 52,539 |
def conv2d_bn(x,
filters,
num_row,
num_col,
padding='same',
strides=(1, 1),
name=None):
"""Utility function to apply conv + BN.
Arguments:
x: input tensor.
filters: filters in `Conv2D`.
num_row: height o... | fd317404f3625ea54e27ad15b64ae253b79374b4 | 52,540 |
def rho_basis(qubits):
"""
Generates a complete orthonormal basis composed of pure
states for the n-qubit density matrix.
:param qubits: number of qubits
:type qubits: int
:return: pure state spectral decomposition
:rtype: np.ndarray, float
"""
return np.array([i*np.conjugate(j).... | 3755613dcb3776e547d9219fde1652470e7c7f3d | 52,541 |
def formatted_value(value, array=True):
"""Format a given input value to be compliant for USD
Args:
array (bool): If provided, will treat iterables as an array rather than a tuple
"""
if isinstance(value, str):
value = '"{}"'.format(value.replace('"', '\\"'))
elif isinstance(value,... | 915e3b2952d43f45a7a75ab266802e22702600c8 | 52,542 |
import math
def estimate_highest_divisor(method, divisor, populations, seats):
"""
Calculates the estimated highest possible divisor.
:param method: The method used.
:type method: str
:param divisor: A working divisor in calculating fair shares.
:type divisor: float
:param populations: ... | e8b06564ed8bd13d1992cb8f498f5180cf27b5bd | 52,543 |
def growth_rate(x, steps=1):
""" calculates first differences"""
return x[steps:]-x[:-steps] | aebb957d53936b2d5a81754a505d3f9b42c7fdd4 | 52,544 |
def vit_base_patch16_224_in21k(num_classes: int = 21843, has_logits: bool = True):
"""
ViT-Base model (ViT-B/16) from original paper (https://arxiv.org/abs/2010.11929).
ImageNet-21k weights @ 224x224, source https://github.com/google-research/vision_transformer.
weights ported from official Google JAX i... | fe9ff82fad38ce04026f84322ec57689c97d24d2 | 52,545 |
def rigidbodies(traj,pdb_output=None,pdb_keep_all=False,pdb_filter=False,cluster_output=False,cutoff=None,ndomains=2,similarity_type='distance_fluctuation',similarity_binarize=None):
"""rigidbodies
Description
-----------
Rigid body decomposition through Ward clustering of a pariwise atom similarity ma... | 754af9f260d62d117425b4bb84994f52e58b4402 | 52,546 |
def swinnet50ts_256(pretrained=False, **kwargs):
"""
"""
kwargs.setdefault('img_size', 256)
return _create_byoanet('swinnet50ts_256', 'swinnet50ts', pretrained=pretrained, **kwargs) | 88c5d1a5be9f1da2cbf9a846b8b298beb003a557 | 52,547 |
import logging
def produce_segmentation(mtx, gamma, good_bins='default', method='modularity', max_intertad_size=3, max_tad_size=10000):
"""
Produces single segmentation (TADs or CDs calling) of mtx with one gamma with the algorithm provided.
:param mtx: input numpy matrix
:param gamma: parameter for s... | e78b56eba6e54e83f7cb45f92749cf92aa3bd58b | 52,548 |
def role_required(*roles):
"""Ensure that logged in user has one of the required roles.
Return 403 if the user doesn't have a required role.
Should be applied before the `@login_required` decorator:
@login_required
@role_required('admin', 'admin-ccs-category')
def view():
... | 7e739e4883ceb5083ec0d9958f197eded45fdc0a | 52,549 |
def ResNet50(inputs):
"""
Implementation of the popular ResNet50 the following architecture:
CONV2D -> BATCHNORM -> RELU -> MAXPOOL -> CONVBLOCK -> IDBLOCK*2 -> CONVBLOCK -> IDBLOCK*3
-> CONVBLOCK -> IDBLOCK*5 -> CONVBLOCK -> IDBLOCK*2 -> AVGPOOL -> TOPLAYER
Arguments:
input_shape -- shape of th... | 15982f1d6cbbfababcd65afb9b6458aea99336da | 52,550 |
import csv
def readCSV(path, datatype=float, realVal=True):
"""
Function to read from a CSV file in the given path. Rows of the CSV file are read in as list into an arrays.
Parameters
----------
path : str
path to the CSV file
Returns
-------
list
list containing the ... | f23f780a54af648deaece10bb5e2167d70411db4 | 52,551 |
import torch
def build_lm_1(state_dict_path):
"""
:meta private:
"""
model = SkipLSTM(21, 100, 1024, 3)
state_dict = torch.load(state_dict_path)
model.load_state_dict(state_dict)
model.eval()
return model | 157dc2c35520cfbc159324ea3f1594f55c550bc3 | 52,553 |
from typing import Union
from pathlib import Path
def _filename(path: Union[str, Path]) -> str:
"""Get filename and extension from the full path."""
if isinstance(path, str):
return Path(path).name
return path.name | 552655ff66ec6cd42b57ada6080df9dc34db1bd0 | 52,554 |
def stitch(probs, positions, decode_consensus_func):
"""Stitch predictions on chunks into a contiguous sequence.
Args:
probs: 3D array of predicted probabilities. no. of chunks X no. of positions in chunk X no. of bases.
positions: Corresponding list of position array for each chunk in probs.
... | 26773439bb7f1e8109791a2536bc075ed34e3387 | 52,555 |
from typing import Optional
from typing import Union
def sync(
*,
client: AuthenticatedClient,
form_data: FormBody,
multipart_data: MultiPartBody,
json_body: Json,
) -> Optional[Union[str, int]]:
""" POST endpoint """
return sync_detailed(
client=client,
form_data=form_dat... | 713a42fb1da92ce0fd25126701ae910cf4167018 | 52,556 |
def O2_sat(P_air, temp):
"""This equation returns saturaed oxygen concentration in mg/L. It is valid
for 278 K < T < 318 K
Parameters
----------
Pressure_air : float
air pressure with appropriate units.
Temperature :
water temperature with appropriate units
Returns
----... | 99014fee424140f01cecb38d742b97574e61ebd9 | 52,557 |
def new_version_available():
"""
Checks this version and checks the download site for a new version.
"""
return current_version() < available_version() | 5b42d7b8182a346783f27efad6e9ee45709d8eae | 52,558 |
def getAppModuleFromProcessID(processID: int) -> AppModule:
"""Finds the appModule that is for the given process ID. The module is also cached for later retreavals.
@param processID: The ID of the process for which you wish to find the appModule.
@returns: the appModule
"""
with _getAppModuleLock:
mod=runningTab... | a999667ecd79c38d3defe8ebf2f23f0ae13700cb | 52,559 |
import logging
def new_algo_logger():
"""
Create and return a logger for the simulation algorithms.
:return: Logger object from the logging library
"""
algo_logger = logging.getLogger("algo_logger")
algo_logger.propagate = False
formatter = logging.Formatter(ALGO_LOGGER_FORMAT)
strea... | b0d86d5c528702d624e68bd0cd27483e5c4bc41f | 52,560 |
def device(request):
"""Run a test case for all available devices."""
return request.param | 7547dae12266fbe6c2b9d3ec87dea20118f5e1e2 | 52,561 |
def _xls_eval_ir_test_impl(ctx):
"""The implementation of the 'xls_eval_ir_test' rule.
Executes the IR Interpreter on an IR file.
Args:
ctx: The current rule's context object.
Returns:
DefaultInfo provider
"""
src = ctx.file.src
runfiles, cmd = get_eval_ir_test_cmd(ctx, src)
... | 415eeebb78e21e2c8f2f9c4e14d968fbde317c00 | 52,562 |
def map_dimensions_to_integers(dimensions):
"""
FragmentSelector requires percentages expressed as integers.
https://www.w3.org/TR/media-frags/#naming-space
"""
int_dimensions = {}
for k, v in dimensions.items():
int_dimensions[k] = round(v)
return int_dimensions | e265e71912c6d582cf21d331767acca3511452f2 | 52,563 |
def get_source_title(meta_data):
"""
get source title for cards on web app
:return: string
"""
if 'source_title' in meta_data:
return meta_data['source_title']
crawler_used = meta_data["crawler_used"]
display_source = CRAWLER_TO_SOURCE_TITLE_LOOKUP[crawler_used]
return display_... | fbc8e8ac9d4c8c8c30f66d1f47d39f28c6724e36 | 52,564 |
from typing import Union
from typing import List
from typing import Tuple
def write_LUT_SonySPI3D(
LUT: Union[LUT3D, LUTSequence], path: str, decimals: Integer = 7
) -> Boolean:
"""
Writes given *LUT* to given *Sony* *.spi3d* *LUT* file.
Parameters
----------
LUT
:class:`LUT3D` or :cl... | 2702326cb92f487dced3c18c839be2ffdeeaf377 | 52,565 |
def padstr(x, align=8):
"""Pad string x with null bytes so it's a multiple of align bytes long.
Return bytes object"""
nbytes = len(x)
rem = nbytes % align
npadbytes = align - rem if rem else 0 # nbytes to pad with for 8 byte alignment
x = x.encode('ascii') # ensure it's pure ASCII, where each c... | ef23c8669c05afe333e524eae3969146a109e734 | 52,567 |
def rmsprop(step_size, gamma=0.9, eps=1e-8):
"""Construct optimizer triple for RMSProp.
Args:
step_size: positive scalar, or a callable representing a step size schedule
that maps the iteration index to positive scalar.
Returns:
An (init_fun, update_fun, get_params) triple.
"""
step_size = mak... | 23de7cda1335ca83917a7b66a716a02cd2b7cb03 | 52,568 |
def get_mail(monitoring: Monitoring):
"""
メールを取得する
Params
------
monitoring: Monitoring
監視設定オブジェクト
"""
config = Config()
run_time = RunTime(monitoring.search_word)
# メールボックスへの接続
credentials = (config.client_id, config.client_secret)
token_backend = FileSystemTokenBa... | 86c6793961dd7e62de6b8262b9f2630a60054027 | 52,569 |
def grpdelay(b, a=1, nfft=512, whole='none', analog=False, Fs=2.*pi):
#==================================================================
"""
Calculate group delay of a discrete time filter, specified by
numerator coefficients `b` and denominator coefficients `a` of the system
function `H` ( `z`).
... | af20fe32ab6e08480d35efbb7213cff2a12cba19 | 52,570 |
def request_recognizer(user_id, message):
"""
Выделяет команду из сообщения и передает на выполнение ответственному модулю
:param user_id: str or int
:param message: str
:return: tuple(str, tuple(str, bool))
"""
answer = "Не понял вас. Напиши 'помощь', чтобы узнать мои команды", ('text',)
... | 80b54303dde4576b286f4d81c82f5a46c581ec97 | 52,571 |
def unbox(boxed_pixels):
""" assumes the pixels came from box
and unboxes them!
"""
flat_pixels = []
for boxed_row in boxed_pixels:
flat_row = []
for pixel in boxed_row:
flat_row.extend(pixel)
flat_pixels.append(flat_row)
return flat_pixels | d74741a206448273330b866d8ec045d59dea02fb | 52,572 |
from re import T
def log_multinomial(x, p, eps=0.0):
"""
Compute log pdf of multinomial distribution
.. math:: \log p(x; p) = \sum_x p(x) \log q(x)
where p is the true class probability and q is the predicted class
probability.
Parameters
----------
x : Theano tensor
Va... | 8041827ca49bbebc7c3e68bc714695884d28a6c5 | 52,573 |
import re
def parse_human_input(file_size):
"""Parse an input in human-readable format and return a number of bytes."""
multipliers = {
"K": 10 ** 3,
"M": 10 ** 6,
"G": 10 ** 9,
"T": 10 ** 12,
"Ki": 2 ** 10,
"Mi": 2 ** 20,
"Gi": 2 ** 30,
"Ti": 2 ... | e88ed389d2a71f642f12438caabc14d8c7b21e81 | 52,574 |
def check_internet_connection(ad, ping_addr):
"""Validate internet connection by pinging the address provided.
Args:
ad: android_device object.
ping_addr: address on internet for pinging.
Returns:
True, if address ping successful
"""
droid, ed = ad.droid, ad.ed
ping = d... | b63d4e2e2dcaa57afa90163edca2aff8552a97b6 | 52,575 |
def create_frozen_request(sheet_id, rows=None, cols=None):
"""
Create v4 API request to freeze rows and/or columns for a
given worksheet.
"""
grid_properties = {}
if rows is not None and rows >= 0:
grid_properties["frozen_row_count"] = rows
if cols is not None and cols >= 0:
... | 0eeeebd636ff31cd5a0a31aee81701243edbbd3e | 52,576 |
from pathlib import Path
def create_path():
"""function to create traffic monitor directory"""
data_store_path = '~/Documents/TrafficMonitor'
path = Path(data_store_path).expanduser()
path.mkdir(parents=True, exist_ok=True)
return str(path) | 2aef318d62a2f4a19879ef87d62af48247afdcf7 | 52,577 |
def search(request):
"""
Search page view
"""
try:
query = request.GET.get('query')
if len(query) < 3:
messages.warning(request, "Search query must be at least 4 characters.")
query = "NONE"
except:
query = "NONE"
cards = Card.objects.filter(nam... | 0589ec1fe62b624221eb1db4b82ece3e79159167 | 52,578 |
def gauss_function(x, a, x0, sigma):
"""
Gaussian
_________
Arguments:
x (float or float array) - argument
a (float) - amplitude
x0 (float) - mathematical expectation
sigma (float) - standard deviation
__________________________________
Returns:
Gauss function by formula
... | 3178d2e187a8f0c0c5dcbc2c79ab83c368251f76 | 52,579 |
import requests
import random
def bingimage(text, bot):
"""<query> - returns the first bing image search result for <query>"""
api_key = bot.config.get("api_keys", {}).get("bing_azure")
# handle NSFW
show_nsfw = text.endswith(" nsfw")
# remove "nsfw" from the input string after checking for it
... | 372bbb2192c547405f96b1c2b7393600ff2e30e1 | 52,580 |
def convert_to_axes(axes, container=tuple):
"""Convert `obs` to the list of obs, also if it is a
:py:class:`~ZfitSpace`. Return None if axes is None.
Raises
TypeError: if the axes are not int
"""
if axes is None:
return axes
axes = convert_to_container(value=axes, container=cont... | 12cdcda5d989ec2ce53e71d8a1b6a93a218d0a7d | 52,581 |
def aumentar(n=0, p=0, formato=False):
"""
Somar porcentagem
:param n: número a ser somado
:param p: porcentagem a ser somada
:param formato: (opicional) mostrar o moeda
:return: resultado
"""
n = float(n)
resultado = n + (n * p / 100)
return moeda(resultado) if formato else resu... | 65af169a0ab7d33450e698e4d303e09e0f09dadf | 52,582 |
import math
def calculate_threshold_value(q: int,
t: int,
p: int,
lmbda: int,
w: float,
lower_val: float,
upper_val: float,
... | 0fc60fb8308b8f75a80eb2b6a2940a61f6e421d6 | 52,583 |
import pandas as pd
import pbio.misc.parallel as parallel
def _parse_gtf_group(rows):
""" This is a helper function for parsing GTF attributes from a data frame.
It is not intended for external use.
"""
res = parallel.apply_df_simple(rows, parse_gtf_attributes)
res = pd.DataFrame(res)
retu... | 24486ec6249714bf736258b4acbc59f11667b1a8 | 52,584 |
def z_levels(fid, x, y, variable, n_levels, n_frames, t_idx,
symflag, n_lev_auto, n_dec, n_seg, avleng):
"""
list(float) = zlevels(fid, variable, n_levels, n_frames, t_idx,
symflag, n_lev_auto, n_dec, n_seg, avleng)
"""
z_levs_auto = auto_z_levels(fid, x, y, variab... | b9cd63defbe776d2ab451d3ceec557c88c7913d1 | 52,585 |
from typing import Union
import io
from typing import Optional
def getint(
string: Union[io.StringIO, str], key: str, section: Optional[str] = None
) -> Union[int, None]:
"""get option's value in `int` type"""
val = get(string, key, section)
if val:
return int(val) | 6127e5fbaefb753ddac6312d8badc18815e1c7e1 | 52,586 |
def fec_old_patch():
"""
Further Education College UK RSF patch generated with the old
`rsfcreate.py` script.
"""
with open("tests/fixtures/fec_old_patch.rsf") as handle:
return handle.read().splitlines() | 41f382e1b31be2633a0d2c352e352f8926a8bae0 | 52,587 |
def get_n_pixels(bad_bin_mask, window=10, ignore_diags=2):
"""
Calculate the number of "good" pixels in a diamond at each bin.
"""
N = len(bad_bin_mask)
n_pixels = np.zeros(N)
loc_bad_bin_mask = np.zeros(N, dtype=bool)
for i_shift in range(0, window):
for j_shift in range(0, window)... | 564d1e40cbd3053bcb170e90496e2efc5418808e | 52,588 |
def ruleset_refresh(p_engine, p_username, rulesetname, envname):
"""
Refresh ruleset on the Masking engine
param1: p_engine: engine name from configuration
param2: rulesetname: ruleset name
param3: envname: environment name
return 0 if added, non 0 for error
"""
return ruleset_worker(p_... | 97d053a3164bde44384e55e99108a901bdf83b04 | 52,590 |
from typing import Any
def str_or_raise(value: Any) -> str:
"""Return string or raise exception."""
return enforce_type(str_or_none(value), str) | 63b77bb8d75879ab45d9182aef02ebf8785d8a17 | 52,591 |
def trima(close, timeperiod=30):
"""Triangular Moving Average 三角移动平均线
the triangular moving average (TMA) is a technical indicator that
is similar to other moving averages. The TMA shows the average
(or mean) price of an asset over a specified number of data
points—usually a number of price bars. H... | ecf64f24db7f09070c549528d78e33122507a1f7 | 52,592 |
def CheckCardinalities(*cardinality):
"""Checks cardinality values for compatibility. None is treated as a wild
card that matches all cardinalities. It returns the resulting cardinality,
or None if all are wild cards. If they don't match then a ProcessingError
is raised."""
cReturn = None
for... | a320312eb117749133045787364b9cb388137088 | 52,593 |
async def index_route(request):
""" Redirect to the dashboard. """
return response.redirect('/jobs') | ba5f1a341fe5afef5247e0feb473e8a4c2405680 | 52,594 |
def make_format_plugin_table(group="waveform", method="read", numspaces=4,
unindent_first_line=True):
"""
Returns a markdown formatted table with read waveform plugins to insert
in docstrings.
>>> table = make_format_plugin_table("event", "write", 4, True)
>>> print(tab... | 74614844b0f7445af42d0eb2978599a36b79ed85 | 52,595 |
def create_gsheet(gc, eid, program_db):
"""
Creates a Google sheet for the program.
:param gc: The `gspread.Client` object. Should have called
`gc = authorize_google_sheets()` before passing into this function.
:type gc: `gspread.Client` object
:param eid: The eid of the program.
:type... | 6134250dd2247a8abbcec6fa72363c1f0c6634cf | 52,596 |
def probability_of_selection(spt, snr):
"""
probablity of selection for a given snr and spt
"""
ref_df=SELECTION_FUNCTION.dropna()
#self.data['spt']=self.data.spt.apply(splat.typeToNum)
interpoints=np.array([ref_df.spt.values, ref_df.logsnr.values]).T
return griddata(interpoints, ref_df.tot_... | 562ffbe0dc280e4544af32daa94a07b3320c7207 | 52,597 |
def entryPoint(coursesCompleted, coursesDesired, startSem):
"""
This is the entry point function for the ILP scheduler.
coursesCompleted: a list of courses that the person already has credits for
coursesDesired: a list of courses that the person wants to take.
startSem: either 0 or 1 indicating wet... | 96a766f7ea756e90b289ef2c14cc7b78ae0363d0 | 52,598 |
def render(template, context=None, **kwargs):
"""
Return the given template string rendered using the given context.
"""
renderer = Renderer()
return renderer.render(template, context, **kwargs) | b5220cdc10cc55346bb0593e60bd5d7e80b63883 | 52,599 |
def deserialize_graph(data):
"""De-serialize from the given json data."""
graph = import_class(data['module'], data['cls'])()
graph._nodes = []
for node in data['nodes']:
graph._nodes.append(deserialize_node(node))
nodes = {n.identifier: n for n in graph.nodes}
for node in data['nodes']:... | 277d34e6342b02f3794226a82a58e9b5442e0162 | 52,600 |
def normalCdf(x,mu=0.0,sigma=1.0):
"""
Computation of normal cdf
@ In, x, list or np.array, x values
@ In, mu, float, optional, mean
@ In, sigma, float, optional, sigma
@ Out, cdfReturn, list or np.array, cdf
"""
return stats.norm.cdf(x,mu,sigma) | 89c55615ef280019ad9b0c22b0b782895625301b | 52,601 |
def transform(codec):
"""
transform post
"""
if codec not in CODECS:
return abort(404)
return run(codec, request.get_data()) | 9a65c9b5ed2e8ee6e8bd6b6c0e6fbd9f164709c5 | 52,602 |
def largest_connected_component(H):
"""
A function to find the largest connected component of a hypergraph.
Parameters
----------
H: Hypergraph object
The hypergraph of interest
Returns
-------
set
The largest connected component (a set of nodes) of the hypergraph.
... | cf5276958cb07e2280a170f7d7b570984a3ff670 | 52,603 |
import time
def log_str(proc_str, start):
"""Create a preamble string for stdout."""
former = "[{:>4}".format(proc_str)
latter = "] {:.2f}".format(round(time.time() - start, 3))
return former + latter | 5f4f82e758cf87ff643a20928e5c0f7368ef537f | 52,605 |
def authenticate_user_from_request(request):
"""
Given a request, attempt to authenticate based on Auth Header Scheme/Credentials
Called via the middleware, etc
"""
# Step 1: Detect if we have an Auth Header
raw_auth_header_val = request.headers.get('Authorization', None)
if not raw_auth_he... | 37f7c093bccd1380219e7cebef0fbefd1868a8c0 | 52,606 |
def linear_kernel(X, Y=None):
"""Compute linear Gram matrix between X and Y (or X)
Parameters
----------
X: torch.Tensor of shape (n_samples_1, n_features)
First input on which Gram matrix is computed
Y: torch.Tensor of shape (n_samples_2, n_features), default None
Second input on whic... | b1389059e755fa19bb26c88cf8c9f6ab39d51aec | 52,607 |
def split_to_pieces(number, name, lang, doc_path):
"""
:param number: id number of document
:param name: file name
:param lang: language one of ENG, RUS, ESP, JAP, etc.
:param doc_path: document path
:return: pieces ids
:structure: list(ObjectId Bson)
"""
if len(doc... | dd83163dfa19d1c1c74fbec581fd8677e42fd512 | 52,608 |
def hit(health):
"""Hits health for a random number between 1 and 10"""
hit_value = random.randint(1, 10)
print "hits for:", hit_value
health = health - hit_value
print "health now:", health
return health | 606a6b224eb2348b222623b1eddd5d8691648a91 | 52,609 |
from joblib import Parallel, delayed
def parallel_func(func, n_jobs):
"""Return parallel instance with delayed function
Util function to use joblib only if available
Parameters
----------
func: callable
A function
n_jobs: int
Number of jobs to run in parallel
Returns
... | fcbe721ed91c49c12d4af534e75522c1ebe36688 | 52,610 |
def evaluate_task_accuracy(scenario, prediction_results, subclasses, null_label=NULL_LABEL):
"""
Evaluates the accuracy of the predictor for each task, where we consider the best possible performance as
the ground truth. The best possible is the perfect labeling for current iteration.
:param scenario:
... | 3d704f25bef263a3c02f05fdc77b2f49c41d3fd6 | 52,611 |
def _graycode(bqm):
"""Get a numpy array containing all possible samples in a gray-code order"""
# developer note: there are better/faster ways to do this, but because
# we're limited in performance by the energy calculation, this is probably
# more readable and easier.
n = len(bqm.variables)
ns... | 7d8fc2c5d4ff71f98bd27869616af3a1f677b51c | 52,612 |
def get_indices_of_line(l, angle, dist):
"""
Return indices in square matrix of <l>x<l> for Hough line defined by <angle> and <dist>
"""
# Get start and end points of line to traverse from angle and dist
x0, y0, x1, y1 = get_extremes(angle, dist, l)
# To ensure no lines are defined outside th... | a2ce1e5a000f59ff7cbc2ad92ca0796e705e7c19 | 52,613 |
def get_oaa_connection(agent):
"""return the LibOaa OAA connection for the specified agent,
or None if none exists"""
if _AGENT_OAA.has_key(agent):
return _AGENT_OAA[agent]
return None | 58733faf0e64e96b4d116147d129773330e28346 | 52,614 |
def diaresnet18(**kwargs):
"""
DIA-ResNet-18 model 'DIANet: Dense-and-Implicit Attention Network,' https://arxiv.org/abs/1905.10671.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.chainer/models'
... | 25ef3967cbfcf0b15b580a21cea83eca3445d348 | 52,615 |
def mc_indices(context_vector, fns, mc = 50):
"""Return the indices of the @mc highest values of context_vector.
@fns is just for reference. Not really optimized.
"""
# If the context vector has more nonzero elements than mc, only take the mc occurrences!
if len(np.flatnonzero(context_vector)) > mc... | a3c995c589f00e3683946b684446fe46ea82e4a4 | 52,616 |
def split_date(dates):
"""
Split datetime64 dates into year, month, day components.
"""
y = dates.astype("<M8[Y]").astype(int) + 1970
m = dates.astype("<M8[M]").astype(int) % 12 + 1
d = (dates - dates.astype("<M8[M]")).astype("<m8[D]").astype(int) + 1
return y, m, d | 7152dbdd1f839ef3c401de06631fb0a249c36642 | 52,617 |
from typing import Dict
def random_random_crop(image: tf.Tensor,
size: tf.Tensor,
groundtruths: Dict[str, tf.Tensor],
seed=None) -> (tf.Tensor, tf.Tensor):
"""Will `randomly` perform a random crop of a tensor to a given size.
Slices a shape ... | 24c57847f97874b3d9ea71a625e1a90b5ee09605 | 52,618 |
def flowless(hyper_list, T, weight=None):
"""
Implementation of greedy++ algorithm proposed in [1]. It efficiently compute almost densest subgraph without max
flow.
Parameters
----------
G: undirected, graph (networkx).
T: int, number of iterations.
weight: str that specify the edge att... | ab9298e5944a8f7f3180f1cea66867cda8349e7b | 52,619 |
def getDmzProxySecurityActionValue( nodename, proxyname, action, ):
"""Gets an individual security value"""
return getDmzProxySecurityActionLevelOrValue( nodename, proxyname, action, 'values' ) | 4b8ab7b23242fc4284a396be29e68aad42539a02 | 52,620 |
def get_left_right_spans(ribo):
"""
In counting number of reads going to each region (UTR5, CDS and UTR3),
We artificially introduce two regions
UTR5_junction: A region between UTR5 and CDS containing the start site
[start_site - left_span, start_site + leftspan]
UTR3_junction: ... | 274b492c79b67403e5583d5bb7d7f2387029df3d | 52,621 |
def filters_effect(
ftype=None, cutoff_hz=None, sfreq=None, width_hz=None, ripple_db=None, window=None,
):
"""
Generate example filter input-output plots for pure sinewave data.
Parameters
----------
key=val
see :ref:`check_filter params() Parameters <filter_parameters_label>`
R... | b609796ce53d23e0dd050ba4bf419691d3d06658 | 52,622 |
def _aggregate(y, aggfunc, weights):
"""Apply aggregation function by row.
Parameters
----------
y : pd.DataFrame
Multivariate series to transform.
aggfunc : str
Aggregation function used for transformation.
weights : list of floats
Weights to apply in aggregation.
... | e4ac01ecccbbda6f99ef36af364e9784cd9b347e | 52,623 |
def create_session(engine):
""" Create a session for accessing the DB.
"""
return sqla.orm.scoped_session(
sqla.orm.sessionmaker(
autocommit=False,
autoflush=False,
bind=engine
)
) | 05bec07e03e0bcb948e0bb2e94ede7cd7209e640 | 52,624 |
from datetime import datetime
def request(caller_id):
"""
Method requests single PublicIP address for caller. If caller's quota
is exceeded, exception is raised. Otherwise caller obtains a new PublicIP
address.
@cmview_user
@response{string} newly obtained PublicIP's address
@raises{publ... | 40fc150ffd5722309d00fd77a3ffceca0236c12f | 52,626 |
def get_user_tweets(user_name):
"""Retrieve all (accessible) tweets from a given user name by stepping backward through the status paging"""
all_tweets, lowest_id = _get_user_tweets_batch(user_name)
while True:
next_batch, lowest_id = _get_user_tweets_batch(user_name, lowest_id)
all_tweets +... | e1bcbc82e8c579b2d45e201bb7ffd2a724ae2a82 | 52,627 |
def hex_to_chars(num):
""" Convert the hex representation of the number to a correctly ordered
string.
Parameters
----------
val: int
The integer representing the string. This is in reverse order.
Ie. XXYYZZ -> chr(ZZ)chr(YY)chr(XX)
Returns
-------
str
The actua... | 2f87de04dc2442a125ed355b4d6ce2043138700d | 52,628 |
def Split(l, indexes, axis=-1, merge_sublayers=False, name=""):
"""\
Split layer into a list of tensor layers.
:param l: parent layer
:param indexes: ``[20, 60] => [:20, 20:60, 60:]``
:param axis: which axis to split on (-1 = last)
:merge_sublayers: merge layers symbolically (affects plotting)... | ac3d9ce5982e1139157586d37bc45d9a23ee9c86 | 52,629 |
import pickle
def load(filename):
"""
Load a compressed pickle from disk
"""
return pickle.loads(_loads(filename)) | a7cfb856b069c1d48dcfd71de6094a1cea6c160d | 52,630 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.