content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def get_transform_dest_array(output_size):
"""
Returns a destination array of the desired size. This is also used to define the
order of points necessary for cv2.getPerspectiveTransform: the order can change, but
it must remain consistent between these two arrays.
:param output_size: The size to mak... | 84f092b5f263f3dd65ea9dfb18890454666e982d | 3,648,931 |
def fetch(url):
"""
引数urlで与えられたURLのWebページを取得する。
WebページのエンコーディングはContent-Typeヘッダーから取得する。
戻り値:str型のHTML
"""
f = urlopen(url)
# HTTPヘッダーからエンコーディングを取得する(明示されていない場合はutf-8とする)。
encoding = f.info().get_content_charset(failobj="utf-8")
html = f.read().decode(encoding) # 得られたエンコーディングを指定して文字... | 31b69019f35e983a7a6c9d60b4367502b6540c56 | 3,648,932 |
def get_rounded_coordinates(point):
"""Helper to round coordinates for use in permalinks"""
return str(round(point.x, COORDINATE_ROUND)) + '%2C' + str(round(point.y, COORDINATE_ROUND)) | a707864e4b62a91e609b3674bdfe0de7fdddf154 | 3,648,934 |
def rgb_to_hls(image: np.ndarray, eps: float = 1e-8) -> np.ndarray:
"""Convert a RGB image to HLS. Image data is assumed to be in the range
of [0.0, 1.0].
Args:
image (np.ndarray[B, 3, H, W]):
RGB image to be converted to HLS.
eps (float):
Epsilon value to avoid div ... | 841379110bd273a7a6239e3598656c46acbde583 | 3,648,935 |
def array_max_dynamic_range(arr):
"""
Returns an array scaled to a minimum value of 0 and a maximum value of 1.
"""
finite_arr = arr[np.isfinite(arr)]
low = np.nanmin(finite_arr)
high = np.nanmax(finite_arr)
return (arr - low)/(high - low) | b2182c43dea2981b3759119cf1381a82a9e168b1 | 3,648,936 |
def production(*args):
"""Creates a production rule or list of rules from the input.
Supports two kinds of input:
A parsed string of form "S->ABC" where S is a single character, and
ABC is a string of characters. S is the input symbol, ABC is the output
symbols.
Neither... | bcb3e415a283f654ab65e0656a3c7e3912eeb53b | 3,648,937 |
def _unpack_compute(input_place, num, axis):
"""Unpack a tensor into `num` tensors along axis dimension."""
input_shape = get_shape(input_place)
for index, _ in enumerate(input_shape):
input_shape[index] = input_shape[index] if index != axis else 1
output_shape_list = [input_shape for i in ran... | 89972e932d3c0bf3b5cbc548633dd2b2a6173c85 | 3,648,938 |
def flatten(items):
"""Convert a sequence of sequences to a single flat sequence.
Works on dictionaries, tuples, lists.
"""
result = []
for item in items:
if isinstance(item, list):
result += flatten(item)
else:
result.append(item)
return result | d44e3391f791dfd2ec9b323c37c510a415bb23bf | 3,648,939 |
from typing import Dict
def _datum_to_cap(datum: Dict) -> float:
"""Cap value of a datum."""
return _cap_str_to_mln_float(datum["cap"]) | 4554cb021f077e3b69495a6266a2596a968ee79d | 3,648,940 |
def add_eval_to_game(game: chess.pgn.Game, engine: chess.engine.SimpleEngine, analysis_time: float,
should_re_add_analysis: bool = False) -> chess.pgn.Game:
"""
MODIFIES "game" IN PLACE
"""
current_move = game
while len(current_move.variations):
if "eval" in current_move... | 72c677fc9f71cafca6af5b86cca69d896547835d | 3,648,941 |
def MC_no(a,b,N,pi,mp):
""" Monte Carlo simulation drawn from beta distribution for the uninsured agents
Args:
N (integer): number of draws
a (integer): parameter
b (integer): parameter
Returns:
(numpy float): Monte Carlo integration that computes expe... | 7910a1894839eaac89af9df61a3f64fbb1eaf933 | 3,648,942 |
def get_conflicting_types(type, tyepdef_dict):
"""Finds typedefs defined in the same class that conflict. General algo
is: Find a type definition that is identical to type but for a
different key. If the type definitions is coming from a different
class, neglect it. This is a pretty slow function for... | 5270ddfbf8a1f887de7ea9fcf2dcd32511ce6a32 | 3,648,943 |
from typing import Tuple
def extract_entity_type_and_name_from_uri(uri: str) -> Tuple[str, str]:
"""
从entity uri中提取出其type和name
:param uri: 如 http://www.kg.com/kg/ontoligies/ifa#Firm/百度
:return: ('Firm', '百度')
"""
name_separator = uri.rfind('/')
type_separator = uri.rfind('#')
return ur... | a70b1fdb5490f029cc6a88bee53eee048731a709 | 3,648,944 |
def ret_dict() -> dict:
"""
Returns
-------
"""
# blahs
return {} | 79a29f69f5d0389d266f917500d25d696415c25a | 3,648,946 |
def load_rokdoc_well_markers(infile):
"""
Function to load well markers exported from RokDoc in ASCII format.
"""
with open(infile, 'r') as fd:
buf = fd.readlines()
marker = []
well = []
md = []
tvdkb = []
twt = []
tvdss = []
x = []
y = []
... | f3a781accdd84ff2f5aff12e59aeff05aa428d6a | 3,648,947 |
def get_fees():
"""
Returns all information related to fees configured for the institution.
:returns: String containing xml or an lxml element.
"""
return get_anonymous('getFees') | 17d16c65d8aefa5989f0c371ed2db2527691ccf9 | 3,648,948 |
import torch
from typing import Tuple
def resample_uv_to_bbox(
predictor_output: DensePoseChartPredictorOutput,
labels: torch.Tensor,
box_xywh_abs: Tuple[int, int, int, int],
) -> torch.Tensor:
"""
Resamples U and V coordinate estimates for the given bounding box
Args:
predictor_outpu... | 655fa330a0fb68d0a6f94084b1a4fde2e1368792 | 3,648,949 |
from typing import List
def get_error_code(output: int,
program: List[int]
) -> int:
"""
Determine what pair of inputs, "noun" and "verb", produces the output.
The inputs should be provided to the program by replacing the values
at addresses 1 and 2. The value pl... | a3ff93557217197c3988b1f2ffde0a114ec6de81 | 3,648,951 |
def page(page_id):
"""Gets one page from the database."""
page = Page.objects.get(id=page_id)
return render_template('page.html', page=page) | 011d0d96564e328674c9e919eed3647c41ebb0a4 | 3,648,952 |
def compute_Csigma_from_alphaandC(TT,minT,alphaT,CT,ibrav=4):
"""
This function calculate the difference between the constant stress heat capacity
:math:`C_{\sigma}` and the constant strain heat capacity :math:`C_{\epsilon}`
from the *V* (obtained from the input lattice parameters *minT*, the thermal
... | 66159810aeeadd4614f66b6c7bc43a11a5ebf28d | 3,648,953 |
def services(request):
"""
"""
context = {}
services = Service.objects.filter(active=True, hidden=False)
context["services"] = services
context["services_nav"] = True
return render(request, "services.html", context) | 45792f2032236a74f8edd2141bf10a2dd7b6c075 | 3,648,954 |
def _create_presigned_url(method, object_name, duration_in_seconds=600):
"""
Create presigned S3 URL
"""
s3_client = boto3.client('s3',
endpoint_url=CONFIG.get('s3', 'url'),
aws_access_key_id=CONFIG.get('s3', 'access_key_id'),
... | f285d90058d3f6d450e82917d883f97100b78889 | 3,648,955 |
def read_data(model_parameters, ARGS):
"""Read the data from provided paths and assign it into lists"""
data = pd.read_pickle(ARGS.path_data)
y = pd.read_pickle(ARGS.path_target)['target'].values
data_output = [data['codes'].values]
if model_parameters.numeric_size:
data_output.append(data[... | 66f89d87b22579f3d06a1d8f0faf0db4bc0fd13d | 3,648,956 |
def _is_src(file):
""" Returns true if the file is a source file
Bazel allows for headers in the srcs attributes, we need to filter them out.
Args:
file (File): The file to check.
"""
if file.extension in ["c", "cc", "cpp", "cxx", "C", "c++", "C++"] and \
file.is_source:
return ... | b0466073d4d1b05c5cab37946fb6ca8432dc752d | 3,648,957 |
def constructResponseObject(responsePassed):
"""
constructs an Error response object, even if the
"""
if (not (responsePassed is None)):
temp_resp = Response()
temp_resp.status_code = responsePassed.status_code or 404
if((temp_resp.status_code >= 200) and (temp_resp.status_code ... | e5f5aa0f87db30598e85fe66e8bf3062eac4388c | 3,648,958 |
def calculate_signal_strength(rssi):
# type: (int) -> int
"""Calculate the signal strength of access point."""
signal_strength = 0
if rssi >= -50:
signal_strength = 100
else:
signal_strength = 2 * (rssi + 100)
return signal_strength | d5a0955446e0fe0548639ddd1a849f7e7901c36b | 3,648,959 |
from datetime import datetime
async def verify_email(token: str, auth: AuthJWT = Depends()):
"""Verify the user's email with the supplied token"""
# Manually assign the token value
auth._token = token # pylint: disable=protected-access
user = await User.by_email(auth.get_jwt_subject())
if user.em... | 4e6eebd22b6206fa20f9c03230c09b470c414740 | 3,648,960 |
def lookAtThisMethod(
first_parameter,
second_paramter=None,
third_parameter=32,
fourth_parameter="a short string as default argument",
**kwargs
):
"""The point of this is see how it reformats parameters
It might be fun to see what goes on
Here I guess it should respect this spacing, since we are in... | 8dab028b40184bb7cf686c524d5abd452cee2bc3 | 3,648,962 |
from typing import Sequence
from typing import Callable
from typing import List
from typing import Set
def data_incremental_benchmark(
benchmark_instance: GenericCLScenario,
experience_size: int,
shuffle: bool = False,
drop_last: bool = False,
split_streams: Sequence[str] = ("train",),
custom_... | e24756245b3d6b5126d32fb66541e4cd23a993c2 | 3,648,963 |
import typing
def generate_doc_from_endpoints(
routes: typing.List[tornado.web.URLSpec],
*,
api_base_url,
description,
api_version,
title,
contact,
schemes,
security_definitions,
security
):
"""Generate doc based on routes"""
from tornado_swagger.model import export_swa... | 943a3c7a8bdd71bce92089c9dd89a7c262124dc0 | 3,648,964 |
def _filter_builds(build: Build) -> bool:
"""
Determine if build should be filtered.
:param build: Build to check.
:return: True if build should not be filtered.
"""
if build.display_name.startswith("!"):
return True
return False | c3bbc91595752b92b77034afcdd35d4a0b70f737 | 3,648,965 |
def load_transformers(model_name, skip_model=False):
"""Loads transformers config, tokenizer, and model."""
config = AutoConfig.from_pretrained(model_name)
tokenizer = AutoTokenizer.from_pretrained(
model_name,
add_prefix_space=True,
additional_special_tokens=('[T]', '[P]'),
)
... | 49b8809745ba70b2a2a8ccd6063bbe2ea3acbae0 | 3,648,966 |
def build_test_data(data):
"""
Generates various features needed to predict
the class of the news.
Input: DataFrame
Returns Array of generated features.
"""
data = process(data)
generators = [
CountFeatureGenerator,
TfidfFeatureGenerator,
... | a4bd3af16deff190471ffbd6028cb47b314d498f | 3,648,967 |
def set_password_for_sub_account(account_id, password):
"""
Create a message to set the password for a given sub-account.
:param account_id: Integer representing the ID of the account
:param password: String representing the password for the sub-account
:return: Message (dict)
"""
data = san... | 02887e73bd11c551f472c033e256882206e9042a | 3,648,968 |
def generate_batch(n, batch_size):
""" Generates a set of batch indices
Args:
n: total number of samples in set
batch_size: size of batch
Returns:
batch_index: a list of length batch_size containing randomly sampled indices
"""
batch_index = a.sample(range... | a8fe7d9356b30824210c89e2defa4b6bae697ffd | 3,648,970 |
def solve(si, y, infile):
"""Conducts the solution step, based on the dopri5 integrator in scipy
:param si: the simulation info object
:type si: SimInfo
:param y: the solution vector
:type y: np.ndarray
:param infile: the imported infile module
:type infile: imported module
"""
n = ... | 079e97394befb39d6c65dc0c8a7eb2d57cf37920 | 3,648,971 |
def base(request, format=None):
"""Informational version endpoint."""
message = f"Welcome to {VERSION} of the Cannlytics API. Available endpoints:\n\n"
for endpoint in ENDPOINTS:
message += f"{endpoint}\n"
return Response({ "message": message}, content_type="application/json") | 51d8deaa6b5fda2b69fc8674e0d9d927d910c0ba | 3,648,972 |
def discover(discover_system: bool = True) -> Discovery:
"""
Discover Reliably capabilities from this extension.
"""
logger.info("Discovering capabilities from chaostoolkit-reliably")
discovery = initialize_discovery_result(
"chaostoolkit-reliably", __version__, "reliably"
)
discove... | 78bb7bcb086d08099f5585c3e27452647ecb8d64 | 3,648,973 |
from collections import Counter
def frequent_word(message: str) -> str:
"""get frequent word."""
words = Counter(message.split())
result = max(words, key=words.get)
print(result)
return result | 86af88287a8874d824b96e1a96e430555db64f2e | 3,648,974 |
def parse_bjobs_nodes(output):
"""Parse and return the bjobs command run with
options to obtain node list, i.e. with `-w`.
This function parses and returns the nodes of
a job in a list with the duplicates removed.
:param output: output of the `bjobs -w` command
:type output: str
:return: c... | a582307d0d869d2dbde454928571246320cb6e31 | 3,648,975 |
def find_nearest_array(array, array_comparison, tol = 1e-4):
"""
Find nearest array
@ In, array, array-like, the array to compare from
@ In, array_comparison, array-like, the array to compare to
@ In, tol, float, the tolerance
"""
array_comparison = np.asarray(array_comparison)
indeces = np.zero... | 5c15cb58d50eef03ae7bcffed18bc60587fec0fc | 3,648,976 |
from datetime import datetime
def create_block_statistics_on_addition(
block_hash: str,
block_hash_parent: str,
chain_name: str,
deploy_cost_total: int,
deploy_count: int,
deploy_gas_price_avg: int,
era_id: int,
height: int,
is_switch_block: bool,
network: str,
size_bytes: ... | 921e7045ff0df080a3769d0e62753e0e5a13e4af | 3,648,978 |
def text(title='Text Request', label='', parent=None, **kwargs):
"""
Quick and easy access for getting text input. You do not have to have a
QApplication instance, as this will look for one.
:return: str, or None
"""
# -- Ensure we have a QApplication instance
q_app = qApp()
# -- Get t... | c3d0c4fab15f6882fea614f5eec252738abc3e1c | 3,648,980 |
def get_key_score(chroma_vector, keys, key_index):
"""Returns the score of an approximated key, given the index of the key weights to try out"""
chroma_vector = np.rot90(chroma_vector,3)
chroma_vector = chroma_vector[0,:]
key_vector = keys[key_index,:]
score = np.dot(key_vector,chroma_vector)
return score | b41d4f3af4d621ba46b8786a5c906c470454fcc1 | 3,648,981 |
def app():
"""Create the test application."""
return flask_app | 01fbd44671a342be38560bc4c5b089a55214caf3 | 3,648,982 |
def coord_for(n, a=0, b=1):
"""Function that takes 3 parameters or arguments, listed above, and returns a list of the interval division coordinates."""
a=float(a)
b=float(b)
coords = []
inc = (b-a)/ n
for x in range(n+1):
coords.append(a+inc*x)
return coords | 57e12200dcc113786c9deeb4865d7906d74c763f | 3,648,983 |
def find_indeces_vector(transect_lons, transect_lats, model_lons, model_lats,
tols={
'NEMO': {'tol_lon': 0.104, 'tol_lat': 0.0388},
'GEM2.5': {'tol_lon': 0.016, 'tol_lat': 0.012},
}):
"""Find all indeces for the ... | 93ad7a8cd16e154069618e606293e64ee3266501 | 3,648,984 |
def _make_prediction_ops(features, hparams, mode, num_output_classes):
"""Returns (predictions, predictions_for_loss)."""
del hparams, mode
logits = tf.layers.dense(
features, num_output_classes, name='logits')
confidences = tf.nn.softmax(logits)
confidence_of_max_prediction = tf.reduce_max(confidences... | 0a58ab8753a39b3e9da67dfc7988383585e6562e | 3,648,985 |
def manhattan_loadings(
iteration,
gtf,
loadings,
title=None,
size=4,
hover_fields=None,
collect_all=False,
n_divisions=500,
):
"""modify hail manhattan plot"""
palette = [
'#1f77b4',
'#ff7f0e',
'#2ca02c',
'#d62728',
'#9467bd',
'#8... | 5f99c1f5a16ee35c056ef019870d2d89a31ba988 | 3,648,986 |
def preprocess_point(p, C):
"""Preprocess a single point (a clip).
WARN: NAN-preserving
Arguments:
p {ndarray} -- shape = (variable, C.joint_n, C.joint_d)
C {DDNetConfig} -- A Config object
Returns:
ndarray, ndarray -- X0, X1 to input to the net
"""
assert p.shape[1... | a1f2c1eda877562439c0b194490a6ac50df6bd81 | 3,648,987 |
def link_to_existing_user_by_email_if_backend_is_trusted(backend, details, user=None, *args, **kwargs):
"""Return user entry with same email address as one returned on details."""
if user or not _is_trusted_email_backend(backend):
return
email = details.get('email')
if email:
# try to ... | 58f2363030ae0b8f8d3533dedbae6c7af304136c | 3,648,988 |
def get_global_threshold(image_gray, threshold_value=130):
""" 이미지에 Global Threshold 를 적용해서 흑백(Binary) 이미지객체를 반환합니다.
하나의 값(threshold_value)을 기준으로 이미지 전체에 적용하여 Threshold 를 적용합니다.
픽셀의 밝기 값이 기준 값 이상이면 흰색, 기준 값 이하이면 검정색을 적용합니다.
이 때 인자로 입력되는 이미지는 Gray-scale 이 적용된 2차원 이미지여야 합니다.
:param image_gray:
... | 03c344a40c5a84027d790ddf404106efe29716e9 | 3,648,990 |
import torch
def get_batch(src_gen, trgt_gen, batch_size=10):
"""
Return a batch of batch_size of results as in get_rotated_src_target_spirals
Args:
batch_size (int): number of samples in the batch
factor (float): scaling factor for the spiral
Return:
[torch.tensor,torch.tensor]: s... | 6e0e4549c12fb252c54496f7947e5787970b64eb | 3,648,991 |
def compute_crop_parameters(image_size, bbox, image_center=None):
"""
Computes the principal point and scaling factor for focal length given a square
bounding box crop of an image.
These intrinsic parameters are used to preserve the original principal point even
after cropping the image.
Args:... | 18ca5822bf86fb01ff8652fc9239ce6ae4d2801f | 3,648,992 |
def input_fn_builder(input_file, seq_length, num_labels, is_training,
drop_remainder):
"""Creates an `input_fn` closure to be passed to TPUEstimator."""
name_to_features = {
"input_ids": tf.FixedLenFeature([seq_length], tf.int64),
"input_mask": tf.FixedLenFeature([seq_lengt... | ad82ded8691561eb8f60b645497200cd36d94a21 | 3,648,993 |
def get_user_by_username(username):
"""Return User by username"""
try:
return User.objects.get(username=username)
except User.DoesNotExist:
return None | b6c676d22c7ef586392b20a072d2239c2dfce7e6 | 3,648,994 |
def get_xyz_to_rgb_matrix(name):
"""
XYZ to RGB の Matrix を求める。
DCI-P3 で D65 の係数を返せるように内部関数化した。
"""
if name != "DCI-P3":
xyz_to_rgb_matrix = RGB_COLOURSPACES[name].XYZ_to_RGB_matrix
else:
rgb_to_xyz_matrix\
= calc_rgb_to_xyz_matrix(RGB_COLOURSPACES[DCI_P3].primaries,
... | 007b71f52af4e23ada073c712a840e05c0ac33a5 | 3,648,995 |
def find_bordering_snapnums(
snap_times_gyr,
dGyr=.005,
tmin=None,
tmax=None):
""" """
## handle default maximum time
tmax = snap_times_gyr[-1] if tmax is None else tmax
## handle default minimum time
if tmin is None:
tmin = snap_times_gyr[0]
## remove dGyr so that... | 23a58ecce4036d9b7a6a91991de237dd30b87129 | 3,648,996 |
def maxIterationComb(N,k,l):
"""
title::
maxIterationComb
description::
Compute N!/k!l!(N-k-l)! (max iterations).
attributes::
N
Number of targets (graph size)
k
Number of human patrollers
l
Number of drones
returns::... | d0019a1498a50f3733474fb0212627d1b061484d | 3,648,997 |
def create_project_details_list (project):
"""makes a projects details section for the html
Parameters
----------
project: HeatRecovery
A HeatRecovery object thats run function has been called
Returns
-------
dict
with values used by summary
"""
try:
costs =... | 74c68b0592939cc819091ac2d30bee44b455f27b | 3,648,998 |
def compute_cluster_top_objects_by_distance(precomputed_distances,
max_top_number=10,
object_clusters=None):
"""
Compute the most representative objects for each cluster
using the precomputed_distances.
Parameters
... | 2ff29d6b59d2db3d9e169a44c0addf42d9abea9b | 3,648,999 |
def validate_ints(*args):
""" validates that inputs are ints only """
for value in args:
if not isinstance(value, int):
return False
return True | e56ebf78e072731188b2c8282289d307fcfaabdf | 3,649,001 |
def smooth_l1_loss(y_true, y_pred):
"""
Computes the smooth-L1 loss.
Parameters
----------
y_true : tensor
Ground-truth targets of any shape.
y_pred : tensor
Estimates of same shape as y_true.
Returns
-------
loss : tensor
The loss, sumed over all elements f... | dcf18b7d14feecdbc8b6637ccc3d35ff1880f9d2 | 3,649,002 |
def get_class_occurrences(layer_types):
"""
Takes in a numpy.ndarray of size (nb_points, 10) describing for each point of the track the types of clouds identified at each of the 10 heights
times counting the number of times 8 type of clouds was spotted vertically.
and returns occrrences (binary) as th... | 20c611089a50751e6a6b1d0ebaedc02474b04443 | 3,649,003 |
def parse_duration(datestring):
"""
Parses an ISO 8601 durations into a float value containing seconds.
The following duration formats are supported:
-PnnW duration in weeks
-PnnYnnMnnDTnnHnnMnnS complete duration specification
Years and month are not supported, values must... | 4fce243684fd2305198ae49693327a110f781a1d | 3,649,004 |
import math
from functools import reduce
import operator
from typing import Counter
def knn(position, data_set, labels, k):
"""
k-近邻算法
:param position: 待分类点
:param data_set: 数据样本
:param labels: 标签集合
:param k: 取值
:return: 所属标签
"""
distance_list = []
for index, item in enumerate(... | 137f87c6a63fbafd3140694386dfd418108ad5b9 | 3,649,005 |
def _cals(raw):
"""Helper to deal with the .cals->._cals attribute change."""
try:
return raw._cals
except AttributeError:
return raw.cals | a08273a559b780022c04fe5d5d60a71c600fd481 | 3,649,006 |
def irnn_data_iterator(X, y, batch_size, math_engine):
"""Slices numpy arrays into batches and wraps them in blobs"""
def make_blob(data, math_engine):
"""Wraps numpy data into neoml blob"""
shape = data.shape
if len(shape) == 2: # data
# Wrap 2-D array into blob of (BatchWi... | 5a6b6726d3d0f78929b2551b8720bfbbb39471eb | 3,649,007 |
def naive_forecast(series, steps_ahead=3, freq='D', series_name='naive'):
"""
Function fits data into the last available observation value.
INPUT:
:param series: pandas Series of data,
:param steps_ahead: number of steps into the future to predict, default is 3,
:param freq: (str) representati... | 1b64edb39ab986d2e850ec5329fb2ed8ae5cd136 | 3,649,008 |
def show_current_task():
"""
显示当前任务正在运行的任务
:return:
"""
try:
current_user_name = session["user_name"]
current_user = RedisService.get_user(current_user_name)
current_task = TaskService.get_working_tasks(user_id=current_user.id)[0]
if current_task:
hook_ru... | 09e0077232343e46db606b9a3642bfb5d6b17a69 | 3,649,011 |
from rsc.service.ImageService import ImageService
def access_image(access_code:str):
"""
下载图像
post header : {
Content-Type: application/json,
access_token: access_token from vans-token-manager
client_id: client_id from vans-token-manager conf. create by developers.
}
:r... | d1ac9efd9e4ba7c7fb9f63d2f0d188e09367fee9 | 3,649,012 |
def workaround_issue_20(handler):
"""
Workaround for
https://github.com/pytest-dev/pytest-services/issues/20,
disabling installation of a broken handler.
"""
return hasattr(handler, 'socket') | 20d688aedad9e771362d97ad9cac391e7dbfac32 | 3,649,013 |
def item_count(sequences, sequence_column_name):
"""
input:Dataframe sequences
"""
item_max_id = sequences[sequence_column_name].map(max).max()
return int(item_max_id) | 9bcb64ff3389ef34ed297bca4f55b4de66ac5966 | 3,649,014 |
def bare_stft(x: Tensor, padded_window: Tensor, hop_size: int) -> Tensor:
"""Compute STFT of real 1D signal.
This function does not handle padding of x, and the window tensor.
This function assumes fft_size = window_size.
Args:
x: [..., n_sample]
padded_window: [fft_size], a window padde... | ccefbdc55478de91640a322735dd02f87a185578 | 3,649,015 |
def IsDragResultOk(*args, **kwargs):
"""IsDragResultOk(int res) -> bool"""
return _misc_.IsDragResultOk(*args, **kwargs) | 87e4c1968b3e5d7adbdc4cfb393481fca647beba | 3,649,016 |
def element_wise(counter_method):
"""This is a decorator function allowing multi-process/thread input.
Note that this decorator should always follow the decorator 'tag_maker'.
"""
def _make_iterator(*args):
"""Make a compound iterator from a process iterator and
a thread one.
N... | 44c00b9a40b7dba53dcfaac52bc866341a924d01 | 3,649,020 |
import requests
def get_datacite_dates(prefix):
"""Get sumbitted date for DataCite DOIs with specific prefix"""
doi_dates = {}
doi_urls = {}
url = (
"https://api.datacite.org/dois?query=prefix:"
+ prefix
+ "&page[cursor]=1&page[size]=500"
)
next_link = url
meta = re... | 2b75cdfbb7c5f7085ab95f22ec601fbccdac07ea | 3,649,021 |
def rate_answer():
"""
**Rates an already given answer**
**Args:**
* json:
* {"insight" : String with the name of the Insight
* "paper_id" : String with the paper_id which is in our case the completet link to the paper
* "upvote" : Boolean if the answe... | 5efc00e015d2127f91462348050f2d445530690d | 3,649,022 |
def get_ip():
"""
Query the ipify service (https://www.ipify.org) to retrieve this machine's
public IP address.
:rtype: string
:returns: The public IP address of this machine as a string.
:raises: ConnectionError if the request couldn't reach the ipify service,
or ServiceError if there ... | d560c90986cc99be3ad07c0099743821104e514a | 3,649,023 |
import ast
def update_plot(p1, p2, arrow, txt, ax, fig, reset_points, line):
"""
Given a line with an agent's move and the current plot, update
the plot based on the agent's move.
"""
l = line.strip()
if 'Agent score' in l:
txt.remove()
txt = plt.text(2, 33, 'Agent Score: {0:.... | 579b4f218fc17eae9b8595e916571e24eba27cb5 | 3,649,024 |
import csv
def upload_file_view(request):
"""Upload file page and retrieve headers"""
data = {}
global ROW_COUNT
if request.method == "GET":
return render(request, "pages/upload-file.html", data)
try:
if request.FILES:
csv_file = request.FILES['csv_file']
r... | 62d76c398aee02a61a3dd8dd7ac1251367786c9c | 3,649,025 |
from typing import Optional
def get_user_by_login_identifier(user_login_identifier) -> Optional[UserSchema]:
"""Get a user by their login identifier.
:param str user_login_identifier: The user's login identifier, either their \
``email`` or ``display_name`` are valid inputs
:return: The discover... | 821ba79ed56ec9b918dbec60af91e9b472cdb689 | 3,649,026 |
def decode_fixed64(buf, pos):
"""Decode a single 64 bit fixed-size value"""
return decode_struct(_fixed64_fmt, buf, pos) | 298df6d28f77132bac6d9924b9628af5efa940b5 | 3,649,027 |
def from_xfr(xfr, zone_factory=Zone, relativize=True):
"""Convert the output of a zone transfer generator into a zone object.
@param xfr: The xfr generator
@type xfr: generator of dns.message.Message objects
@param relativize: should names be relativized? The default is True.
It is essential that ... | cc3aa11a8ff3dff6cf0609c3527daa193602b522 | 3,649,028 |
from datetime import datetime
def compare_sql_datetime_with_string(filter_on, date_string):
"""Filter an SQL query by a date or range of dates
Returns an SQLAlchemy `BinaryExpression` that can be used in a call to
`filter`.
`filter_on` should be an SQLAlchemy column expression that has a date or
... | 2938872ffdd3e30c2d364ae30e3a93fa560e55ef | 3,649,029 |
def get_users():
"""get_users() -> Fetch all users in the database"""
connect() # Connect
cursor.execute("SELECT * FROM users") # Select all users
item = cursor.fetchall()
users = []
for user in item:
users.append(format_user(user)) # Format the users
disconnect()
return users | e294406af8abbd0fa813beeadcd8b01552e4d206 | 3,649,030 |
def get_decoder_self_attention_bias(length):
"""Calculate bias for decoder that maintains model's autoregressive property.
Creates a tensor that masks out locations that correspond to illegal
connections, so prediction at position i cannot draw information from future
positions.
Args:
length: int length o... | a5de0984715cbc07c16c0ab5a5dc24edb7ca7602 | 3,649,031 |
from typing import Union
from typing import Tuple
import torch
import math
from re import X
def rollout_discrete(
x_grid: Tensor,
idx: Union[int, Tensor],
model: Model,
best_f: Union[float, Tensor],
bounds: Tensor,
quadrature: Union[str, Tuple] = "qmc",
horizon: int = 4,
num_y_samples:... | c400e0042a4ec236030d7e5d19615441b4cc0456 | 3,649,032 |
import itertools
import torch
def get_accumulative_accuracies(test_loaders, taskcla, result_file, network_cls='resnet32'):
""" Confusion matrix with progressively more classes considered """
iter_model = iter_task_models(network_cls, taskcla, result_file)
accuracies = np.zeros((len(taskcla), len(taskcla))... | 3b10f89b80318c3bb2776af3d336c2b87d2a623e | 3,649,033 |
import copy
def readout_oper(config):
"""get the layer to process the feature asnd the cls token
"""
class Drop(object):
"""drop class
just drop the cls token
"""
def __init__(self, config):
if 'ViT' in config.MODEL.ENCODER.TYPE:
self.token_num =... | 36d682851e24535b7b000ae1b343bb90ca2077d6 | 3,649,034 |
import json
def stream_n_messages(request, n):
"""Stream n JSON messages"""
n = int(n)
response = get_dict(request, 'url', 'args', 'headers', 'origin')
n = min(n, 100)
def generate_stream():
for i in range(n):
response['id'] = i
yield json.dumps(response, default=j... | ea8ec1dd939cc43baa3367696f44956b2aafa780 | 3,649,035 |
def read_covid():
"""Read parsed covid table"""
return pd.read_csv(_COVID_FILE, parse_dates=["date"]) | fd99256808be1772106260b1da47850de0584adb | 3,649,036 |
def define_network(*addr):
"""gives all network related data or host addresses if requested
addr = tuple of arguments netaddr/mask[nb of requested hosts]
"""
if len(addr) == 2:
# provides list of host-addresses for this subnet
# we do this by calling the generator host_g
host_g... | 905cf702fda005645c608b9dadb84f3659d991c1 | 3,649,038 |
from typing import List
def init_anim() -> List:
"""Initialize the animation."""
return [] | 121fff8b4102c2961449d970307e762bd983bdbe | 3,649,039 |
def keep_digits(txt: str) -> str:
"""Discard from ``txt`` all non-numeric characters."""
return "".join(filter(str.isdigit, txt)) | 34387003ea03651dd2582b3c49f1095c5589167b | 3,649,040 |
import re
def camel_case_split(identifier):
"""Split camelCase function names to tokens.
Args:
identifier (str): Identifier to split
Returns:
(list): lower case split tokens. ex: ['camel', 'case']
"""
matches = re.finditer('.+?(?:(?<=[a-z])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])|$)', ... | f212bbe5cc33cb31bea023f726abf60a1491b7df | 3,649,041 |
from typing import Any
def _ensure_meadowrun_sqs_access_policy(iam_client: Any) -> str:
"""
Creates a policy that gives permission to read/write SQS queues for use with
grid_task_queue.py
"""
# https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/iam.html#IAM.Client.create_po... | 6bafad83dcf0ed82eac626ad36b9d73416757f37 | 3,649,042 |
def get_subset(dframe, strata, subsetno):
"""This function extracts a subset of the data"""
df_subset = pd.DataFrame(columns=list(dframe)) #initialize
df_real = dframe.dropna() #get rid of nans
edges = np.linspace(0, 1, strata+1) #edges of data strata
for i in range(0, strata):
df_temp = df_... | c1657cbce23bb222f68bc5b7efe3fe54dfcc26bd | 3,649,043 |
import logging
def create_logger(name: str) -> logging.Logger:
"""Create logger, adding the common handler."""
if name is None:
raise TypeError("name is None")
logger = logging.getLogger(name)
# Should be unique
logger.addHandler(_LOGGING_HANDLER)
return logger | c4c888345586718f8b476368ef118656d9650469 | 3,649,044 |
def say_hello():
""" Say hello """
return utils.jsonify_success({
'message': 'Hello {}! You are logged in.'.format(current_user.email)
}) | 52c0f572c0bd521a3ab12f1781d39c37130a78d3 | 3,649,045 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.