content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def hill_climbing(data_frame, et0=None, u=5, metric='bic', metric_params=None, chc=False, tw_bound_type='b', tw_bound=5, optimization_type='size', k_complex=0.1, cores=multiprocessing.cpu_count(), forbidden_parent=None):
"""Gets the adjacency matrix of the Bayesian network encoded by the elimination tree et
Ar... | 531f867d74982db34802daf39f82cea81219fc49 | 61,500 |
def get_dataloader(batch_size, image_size, data_dir='processed_celeba_small/'):
"""
Batch the neural network data using DataLoader
:param batch_size: The size of each batch; the number of images in a batch
:param img_size: The square size of the image data (x, y)
:param data_dir: Directory where ima... | ff4328fe649575850c79e3d84e98ddb8310dcb0b | 61,501 |
def get_sample_list(obj, args):
""" Try to get an attribute from an object.
Example: {% if block|getattr:"editable,True" %}
Beware that the default is always a string, if you want this
to return False, pass an empty second argument:
{% if block|getattr:"editable," %}
"""
args = args.split(... | 9f218a4b3bd306a796edbe7393fc8c1baa9bd29b | 61,502 |
def get_energy(vv, tt, chemical_potential, gbar=2.0, *args, **kwargs):
# type: (np.ndarray, np.ndarray, np.ndarray, float, list, dict) -> np.ndarray
"""Get IFG energy E in atomic units.
:param vv: Matrix of specific volumes in atomic units.
:param tt: Matrix of temperatures in atomic units.
:param ... | 78cfbb098f159be4b803a7aa33c94f92eb442229 | 61,503 |
from model.backbone.cspdarknet import yolov4_tiny_cspdarknet_backbone
from model.backbone.cspdarknet import yolov4_tiny_cspdarknet_backbone
import os
def build_yolov4_eval(cfg):
"""
这是搭建评估阶段YOLO v4的函数
:param cfg: 参数配置类
:return:
"""
# 初始化anchor和classes
anchors = get_anchors(cfg.DATASET.ANCH... | 4dc8773b99e00be7def5ba75294282109c720fbc | 61,504 |
def load_idx_cmds():
"""Load the cmds.h5 file, trying up to 3 times
It seems that one can occasionally get:
File "tables/hdf5extension.pyx", line 492, in tables.hdf5extension.File._g_new
tables.exceptions.HDF5ExtError: HDF5 error back trace
...
File "H5FDsec2.c", line 941, in H5FD_sec2_lock
u... | 0f1044e699d6eaf310663e3429c023634a436576 | 61,505 |
def objective_to_coeffs(objective_func, variables,
objective_type='minimize'):
"""Extracts variable coefficients from symbolic minimization objective
funtion.
Parameters
----------
objective_func: symbolic linear expression
variables: list of symbols
objective_type: ... | 0302f4a7789f9569340f70c33113cd26f7e42a20 | 61,506 |
from typing import Any
import os
def get_test_output_dir(request: Any) -> str:
""" Compute the working directory for an individual test. """
test_name = request.node.name
test_dir = os.path.join(str(top_output_dir), test_name)
log.info(f'get_test_output_dir is {test_dir}')
return test_dir | 9a269512dc3c27a9f13a625c7a5e6190e3f11111 | 61,507 |
import os
def get_package_name(path, root_path):
"""
gets the full package name for provided path.
:param str path: full path of package.
example path = `/home/src/my_app/database`.
:param str root_path: root path in which this path is located.
example ... | d8b04654e37dfd7cf0910327d506e23b75ad3b69 | 61,508 |
def _stateless_uniform_orthogonal(shape, seed, gain=1.0,
dtype=tf.dtypes.float32):
"""Samples an orthogonal matrix from the uniform/Haar distribution."""
# The implementation of this function is essentially copied from
# tf.initializers.Orthogonal.
# Check the shape
if len(... | 31019a8c2cad11317d680898920efe2d86fe2704 | 61,509 |
def read_ssm_params(params, ssm):
"""Build dictionary from SSM keys in the form `ssm://{key}` to value in the
paramater store.
"""
result = ssm.get_parameters(Names=[s[len('ssm://'):] for s in params],
WithDecryption=True)
if result['InvalidParameters']:
raise... | dc4aa3272b8b371621074230bc2ce2b3cad1dd72 | 61,510 |
from typing import Tuple
def _split_resource(context: Context) -> Tuple[str, str, str]:
"""Splits a background event's resource into a CloudEvent service, resource, and subject."""
service = ""
resource = ""
if isinstance(context.resource, dict):
service = context.resource.get("service", "")
... | 5196f07516df20f1303745b70be77232e06d5c9a | 61,511 |
def packages_by_price(inf, sup, packages):
""" Retrieves all avaiable packages that are within a specified price threshold
:param: lowest value of price
:param: highest value of price
:param: list of packages
"""
lista = []
if inf: inf = str_to_float(inf)
else: inf = float(0)
if s... | d26ddd4f3a513b0cf9fc69cfbbc620195b95f13e | 61,512 |
def convert_example(example, tokenizer, is_test=False):
"""
Builds model inputs from a sequence for sequence classification tasks.
It use `jieba.cut` to tokenize text.
Args:
example(obj:`list[str]`): List of input data, containing text and label if it have label.
tokenizer(obj: paddlen... | e9c84c3a28bd6c03d4fb5deb82f012ecef5aae0e | 61,513 |
def aten_type_as(mapper, graph, node):
""" 构造转换Tensor类型的PaddleLayer。
TorchScript示例:
%57 : Tensor = aten::type_as(%56, %mask.1)
参数含义:
%57 (Tensor): 输出,改变类型后的Tensor。
%56 (Tensor): 需要改变类型的Tensor。
%mask.1 (Tensor): 转换成与该Tensor相一致的类型。
"""
scope_name = mapper.normalize... | 92c42927438d982f27aae1ec2173aa41d3912aff | 61,514 |
import re
def is_stable_version(version):
"""
A stable version has no letters in the final component, but only numbers.
Stable version example: 1.2, 1.3.4, 1.0.5
Not stable version: 1.2alpha, 1.3.4beta, 0.1.0rc1, 3.0.0dev
"""
if not isinstance(version, tuple):
version = version.split(... | 995dff30ff81908e0d5a00d88816d874e9bfd626 | 61,515 |
def generate_color_array(colors, opacities):
"""Generate RGB arrays each with opacity values that corresponds
to the frequency of the mutation present in each sample"""
co = np.zeros((len(colors), 4))
for i, (c, o) in enumerate(zip(colors, opacities)):
co[i, :3] = matplotlib.colors.to_rgb(c)
... | f5d13f148cf63f1599328c018d81d4be496bcc54 | 61,516 |
import click
def runner() -> click.testing.CliRunner:
"""Return a CLI console for testing"""
return click.testing.CliRunner() | 098c0fdf232eb57913459d446b5b36d582ce5737 | 61,517 |
import json
def login():
"""
Log in the user
"""
errors = None
try:
request_data = json.loads(request.data)
validate_dict_with_schema(request_data, "user/register/request")
user = User.check_user(
email=request_data["email"],
password=request_data["p... | df97c182c13faca2e48d4af0faa0fb3e164ed76c | 61,518 |
def mnx():
"""Path to xref reduced xref file."""
return join(dirname(__file__), "data", "chem_xref_seedset.tsv") | 46e49ce7df6cf285cc1f13336a72e3c78f9b733e | 61,519 |
def get_preferred_ca_repository():
"""Returns a singleton Secret repository instance."""
global _PREFERRED_CA_REPOSITORY
return _get_repository(_PREFERRED_CA_REPOSITORY,
PreferredCertificateAuthorityRepo) | c3bc5d5c1637b17bf859d3ba326f8aa35c9aac14 | 61,520 |
from datetime import datetime
def chart_grouping_as_date(value):
"""Transforms a string YYYYMM or YYYY in a date object"""
value = str(value)
for format in ('%Y', '%Y%m'):
try:
return datetime.strptime(str(value), format).date()
except ValueError:
pass | 92f80be0baea30944ebd90e1377dfa953f5fb7fa | 61,521 |
import logging
import subprocess
import re
def RunPESQ(audio_file_ref, audio_file_test, sample_rate=16000):
"""Runs PESQ to compare audio test file to a reference audio file.
Args:
audio_file_ref: The reference audio file used by PESQ.
audio_file_test: The audio test file to compare.
sample_rate: Sam... | 5b6b60c0e24aa2674ab3182052112d2ad7994415 | 61,522 |
def _ncvar_to_dict(ncvar, lazydict=False):
""" Convert a NetCDF Dataset variable to a dictionary. """
# copy all attribute except for scaling parameters
d = dict((k, getattr(ncvar, k)) for k in ncvar.ncattrs()
if k not in ['scale_factor', 'add_offset'])
data_extractor = _NetCDFVariableDataE... | 2db5ac12bf06bf2f95cda89b2f6206f8b1813b06 | 61,523 |
def get_stream_credentials(username, password):
"""
Uses the `/user/uuid` endpoint.
takes a valid username and password as parameter.
It will return all the necessary credentials to use the API
and the upload endpoints.
e.g. username="bej48snvvthy", password=""
"""
endpoint = KICKFLIP_... | 17a98632f71fdeb502e14db3cc37c68069ae7621 | 61,524 |
import re
def desc(
operation: str = 'None'
):
"""
函数描述装饰器
自动添加请求属性配对
:return:
"""
def inner_method(f):
# 获取方法的参数名集合
# FullArgSpec(args=['test_arg1'], varargs=None, varkw=None, defaults=None, kwonlyargs=[], kwonlydefaults=None, annotations={})
full_arg_spec = g... | 644ab2db06c9d9028be54cab2b03054db56aa919 | 61,525 |
import requests
def run_ticket_validation(user_id, access_token, nonce):
"""
Validates Oculus session ticket.
Returns a unique ID for this player.
"""
token_check_url = 'https://graph.oculus.com/user_nonce_validate?access_token={access_token}&nonce={nonce}&user_id={user_id}'
url = token_check... | d8f5ca9d92681fe1f7ccd91fde08cada3a788f4d | 61,526 |
import sys
def loadprior(system, paramnames):
"""Load best parameters from random searches (Computed previously).
Parameters not included are set to a default value found in the parameters files.
Parameters:
system (string): name of the system type being used
paramnames (list of strings): ... | 1c08b828a8adbc20dda4558746c971d89a7ea680 | 61,527 |
def impartial(f, *args, **kwargs):
"""
Acts just like Python's functools.partial, except that any arguments
to the returned function are ignored (making it 'impartial', get it?)
"""
def func(*_a, **_k):
return f(*args, **kwargs)
return func | ef512146057ae09546b6e7fac64c2496ac8f7d53 | 61,528 |
def convert_15_to_18(the15Id):
""" Convert Salesforce 15 Id to 18 Id
Arguments:
* the15Id - to be converted 15 Id
Return:
* 18 Id - converted 18 Id
"""
if not the15Id or len(the15Id) != 15: return the15Id
cmap = {
"00000": "A", "00001": "B", "00010": "C", "00011": "D", ... | 7a9ae31da7a5a84977ca1f4a1d02307d4be1e5fa | 61,529 |
def obs_seq(truth, obs_dim, obs_un, obs_op, seed):
"""This function takes the true state trajectory, and parameters, and returns an associated sequence of observations
"""
np.random.seed(seed)
[sys_dim, nanl] = np.shape(truth)
obs = np.zeros([obs_dim, nanl])
zero = np.zeros(obs_dim)
R = np.... | fc64bd73b2bfb519eadb1601271d8c76497b4bb0 | 61,530 |
import torch
import asyncio
async def webenv_slice(lock, state, indices, obs, act_len):
"""
Turns two PyTorch state tensors (pre-step and pre-output) (and what WebEnv received: observations and action lengths) into post-step state and lists of predictions and actions, asynchronously.
"""
# `obs` and `act_len`... | ffded703fbed40bf43713d62a798cbb6f5518c1e | 61,531 |
def bpow_const(a, f):
"""Broken power law with constant. This model assumes that there is a
break in the power spectrum at some given frequency. At high
frequencies the power spectrum is dominated by the constant background.
Parameters
----------
a : ndarray(5)
* a[0] : the natura... | a57c36c7965d1fe8ebfe8db937741ad6557ba911 | 61,532 |
def basic_encoding(x: pd.DataFrame, is_classification: bool):
""" Perform 'basic' encoding of categorical features.
Specifically, perform:
- Ordinal encoding for features with 2 or fewer unique values.
- One hot encoding for features with at most 10 unique values.
- Ordinal encoding for feat... | 1567d8a0170a32d4353cc777c90cdd1ccef69d86 | 61,533 |
import argparse
def get_args() -> argparse.Namespace:
"""
Parse command line arguments.
Returns:
argparse.Namespace: parsed arguments
"""
parser = argparse.ArgumentParser()
parser.add_argument("--path", help="full path to top level show folder", required=True)
parser.add_argument(... | 18deeb1debefbe9bde5e793728b111382fdb72bd | 61,534 |
def liked_products_view(request, **kwargs):
"""Return all the products liked by a given user"""
user_list = get_object_or_404(Like, user=request.user)
serializer = LikeSerializer(instance=user_list)
return Response(data=serializer.data) | 7024a91bf66980148a26976f1696a10bbe4a0726 | 61,535 |
def generate_header(build_type):
"""Return a C/C++ header for the given build type.
Args:
build_type: The build type definition to use.
Returns:
A string containing the C/C++ header file.
"""
return BUILD_TYPE_TEMPLATE.format(build_type=build_type) | 02fe6427fcfd23536c09d908593d0148e1a843cc | 61,536 |
def grid_dist(self,bmu_ind):
"""
som and bmu_ind
depending on the lattice "hexa" or "rect" we have different grid distance
functions.
bmu_ind is a number between 0 and number of nodes-1. depending on the map size
bmu_coord will be calculated and then distance matrix in the map will be returned
... | 60d3a1865bd750fe6c44aa16eedb4ecde504e855 | 61,537 |
def split_with_ratio(dataset: Dataset, valid_ratio: float = 0.1):
"""split dataset into train and validation dataset with specified ratio"""
n_total = len(dataset) # type: ignore
n_validate = int(valid_ratio * n_total)
ds_train, ds_validate = random_split(dataset, [n_total - n_validate, n_validate])
... | 113a76ed579dfb0109c65647f002fccfa65a1768 | 61,538 |
def try_enum(cls, val):
"""A function that tries to turn the value into enum ``cls``.
If it fails it returns the value instead.
"""
try:
return cls._enum_value_map_[val]
except (KeyError, TypeError, AttributeError):
return val | 14b61156d9129d51272b28227b440b7c5b5774c1 | 61,539 |
def get_existing_symptoms(journal):
"""Given a journal w/ proper format, aggregates all the symptoms
args:
journal (dict)
returns:
[str]: array of symptom names
"""
symptoms = []
for log in journal['journal']:
symptoms.extend([
symptom['name'] for symptom i... | e8f90ff3344318b53ae91e79d29f572110103959 | 61,540 |
def addresses_from_address_families(address_families, spec):
"""Given a list of AddressFamilies and a Spec, return matching Addresses."""
if type(spec) in (DescendantAddresses, SiblingAddresses, AscendantAddresses):
addresses = tuple(a for af in address_families for a in af.addressables.keys())
elif type(spec... | fcb2f39724ca0b3eb8bda7af6123bd876e61fbd1 | 61,541 |
import itertools
def process_vlen(data_header, array):
"""Process vlen coming back from NCStream v2.
This takes the array of values and slices into an object array, with entries containing
the appropriate pieces of the original array. Sizes are controlled by the passed in
`data_header`.
Paramete... | 9504d65ff669e7dea6c7a813619a6253b6a4a3eb | 61,542 |
def analyze():
""" 聚类分析
:return:
"""
analyze_form = AnalyzeForm()
if analyze_form.validate_on_submit():
k = analyze_form.k_cluster.data
run_old_all_process(start_time=analyze_form.start_time.data,
end_time=analyze_form.end_time.data,
... | 82521404b6f9774858150ba887c4acd1e5a7920f | 61,543 |
from typing import Union
from pathlib import Path
def is_subpath(path: Union[Path, str], base: Union[Path, str]) -> bool:
"""Return True if path is within base."""
return get_relative_path(path, base) is not None | 35a10874d9af23d0d0d3bef64309652c1195f4a9 | 61,544 |
def cal_fps(raw_trajs_frequent_pattern: dict, sd_trajs_frequent_pattern: dict) -> float:
"""
calculate FPS
Args:
raw_trajs_frequent_pattern: frequent patterns of the original trajectory
sd_trajs_frequent_pattern : frequent patterns that generate trajectories
Returns:
FPS
... | 0b877ba77d928d0550f3fb695c0805f9447b4f61 | 61,545 |
def smart_page_crop_header_footer( # pylint: disable=too-many-branches, too-many-locals # noqa: C901 # too-complex
pdf,
elements_list,
):
"""
Remove header and footer elements smartly.
Check element that inside given parameter of header and footer margin, by default is SMART_PAGE_CROP_REL_MARGIN... | 7e187547f825b63e06f0d8e179e6ee75ece081ae | 61,546 |
def k_means(X, k, max_iter=300):
"""
X.shape = (データ数, 次元数)
k = クラスタ数
"""
n_data, n_features = X.shape
# 重心の初期値
centroids = init_centroid(X, k, n_data)
# 新しいクラスタを格納するための配列
new_cluster = np.zeros(n_data)
# 各データの所属クラスタを保存する配列
cluster = np.zeros(n_data)
fo... | 56414c07de1f6bfb17488bd8d02ec4527c47ec2e | 61,547 |
import requests
import pandas as pd
import logging
from requests.exceptions import SSLError
import pandas as pd
from pytz import timezone
import pandas as pd
import numpy as np
import pandas as pd
def download_ims_single_station(stationid, savepath=None,
channel_name='TD', update=None)... | 08c3e116bec0eadae2711c9dca9006ef991591da | 61,548 |
import requests
def select(host,user,pswd,cert=None,format=None,ID=None,template=None,title=None):
"""Get all data that fits a certain simple query
Inputs:
host - string, URL of MDCS instance
user - string, username of desired account on MDCS server
pswd - string, password of desi... | d684a87b97a626000673ada9bb49a972bbc80471 | 61,549 |
from datetime import datetime
def cal2iso(cal):
"""Calendar date to ISO format.
Parameters
----------
cal : string or array
Calendar date. Format: YYYY-MM-DD HH:MM:SS.SSS. May be
shortened, for example, to YYYY or YYYY-MM. DD == 0 is not
allowed and is forced to 1. MM may be a t... | dd0f6fc8c054a33ca4ac1cfd21916f6538364e42 | 61,550 |
def sample_recipe(user, **params):
"""Create and return a sample recipe"""
defaults = {
'title': 'Sample Recipe',
'time_minutes': 10,
'price': 5.00
}
defaults.update(params)
return Recipe.objects.create(user=user, **defaults) | f85925570225b7bdaab87f8f9d0f5f687a12d36c | 61,551 |
def argmax_index(values):
"""
given an iterable of values return the index of the greatest value
"""
return argmax(izip(count(), values)) | d5ba4642d0d8f2baaef16d8ee9bbd05230c56f3c | 61,552 |
import os
import glob
def prepare_holdem():
"""
Prepare the hold'em dataset.
:return: Dictionary of tables.
"""
hf = os.path.join('data', 'IRCdata', 'nolimit', '*', 'hdb')
pf = os.path.join('data', 'IRCdata', 'nolimit', '*', 'pdb', 'pdb.*')
rf = os.path.join('data', 'IRCdata', 'nolimit', '... | 73ad9c32f3684fbfcfdbb662409854ac426ad0f0 | 61,553 |
def list_rides(athlete, start_date=None, end_date=None, exclude_keywords=None):
"""
List all of the rides for individual athlete.
:param athlete: The Athlete model object.
:type athlete: bafs.orm.Athlete
:param start_date: The date to start listing rides.
:type start_date: datetime.date
:... | 24919dda775ad1c954cb2fd5df5cedf48853ffe0 | 61,554 |
import torch
def calculate_true_values(states,
goal,
distance,
gamma,
final_value,
nonterminal,
distance_scale,
reward_scale=10.,
... | 8f5e0dad55ec46f883ade9f5e615ef21b54128bc | 61,555 |
import logging
def kullback_leibler_divergence(x,y, delta = 0.001):
"""Calculates the jeffrey divergence between the vectors x and y
Keyword arguments:
x,y -- the vectors between which the distance is to be calculated
delta -- a very small value meant to replace 0, to p... | 0ea0852d58ca64a16d86cfcd1023b2e01aa145a0 | 61,556 |
from functools import reduce
def rightchainop(As, Op=None, Bs=None, X=None):
"""
2---A1---A2---...-AN--|
| | | |
|____|__ ... _|_ |
| Op ... | X
|________ ... __| |
| | | |
1---B1---B2---...-BN--|
(n... | 20724a4c05cf6de660cb636e0e91fc072028db3b | 61,557 |
def equals_decimal_and_corrupted(value, corrupted_value):
"""
Ex. value is Decimal('0.1'),
tender.feature.enum values can be like
'0.050000000000000002776', '0.10000000000000000555', '0.14999999999999999445'
how do I check this ?
:param value:
:param corrupted_value:
:return:
"""
... | 7374fb00caf6c2be158d505117518061d3e8cd33 | 61,558 |
import os
import click
def generate_dockerfile_extension(base_image, template_name, config_path):
"""
Extends the base_image with a named template.
:param base_image:
:param template_name:
:return: name of created docker image (type=string)
"""
template_path = get_template_path(temp... | 6cb811802629d9a2d01200ebd486a4bbcaf9ab9e | 61,559 |
def compara_assinatura(ass_main, matriz_ass_input):
"""
Essa funcao recebe duas assinaturas de texto e deve devolver o grau de
similaridade nas assinaturas.
"""
lista_Sab = []
soma_mod = 0
if type(matriz_ass_input[0]) is list:
for lin in range(len(matriz_ass_input)):
for ... | b9dae58c37f06cbcbab577e54e3bbbcf793d7977 | 61,560 |
import time
def decode_beam_search_for_topk(sess,
model,
data_set,
knapsack_matrix,
output_file_handle):
"""TODO(nh2tran): docstring."""
print("decode_beam_search_for_topk()")
spectrum_time = time.time()
scans = [x[... | 46a4a0b1ce783babb2a7052837a9a3d43cb0b6c3 | 61,561 |
def pad_to_2_cells(s: str) -> str:
"""Right-pads s with spaces so that it occupies at least 2 cells.
Raises ValueError if s does not occupy at least 1 cell.
"""
width: int = wcswidth(s)
if width <= 0:
raise ValueError('Argument must have a width >= 1')
if wcswidth(s) >= 2:
retu... | ee565f4bd186d7c9126f27841b1564c1508ade34 | 61,562 |
from typing import Sequence
def deploy_dask(nodes: Sequence[Node]) -> DaskDeployment:
"""Deploys Dask on cluster nodes.
Dask scheduler will be deployed on the first node.
Dask workers will be deployed on each node.
:param nodes: Nodes for Dask to be deployed on.
"""
if not nodes... | 19ee10341fa4d7f0c01cce0e03074fb306f9807e | 61,563 |
import re
def Connect(host='localhost', port=443, user='root', pwd='',
service="hostd", adapter="SOAP", namespace=None, path="/sdk",
connectionPoolTimeout=CONNECTION_POOL_IDLE_TIMEOUT_SEC,
version=None, keyFile=None, certFile=None, thumbprint=None,
sslContext=None, b64t... | 93a71f0f227f105c40e73d5897055950f6d7a52e | 61,564 |
import array
def guess(s1):
""" Guess initial postshock conditions using ideal gas behaviour """
k = s1.k; R = s1.R; M1 = s1.M
p2 = s1.p*(2*k*M1**2-(k-1))/(k+1)
T2 = s1.T*(2*k*M1**2-(k-1))*((k-1)*M1**2+2.)/((k+1)**2*M1**2)
M2= ((M1**2*(k-1)+2)/(2*k*M1**2-(k-1)))**0.5
v2 = M2*(k*R*T2)**0.5
... | 2073bf04cf4a4a921fd9abc16aa3a83a2d997fc2 | 61,565 |
def qr_cam():
"""Realiza a leitura do qr-code pela camera."""
capture = cv2.VideoCapture(0)
while True:
# To quit this program press q.
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# Breaks down the video into frames
ret, frame = capture.read()
# Display... | 9d76ce255a0355f151846687fe1d7e09326ebe17 | 61,566 |
import os
import torch
import json
def load_boxes_and_labels(cfg, mode):
"""
Loading boxes and labels from csv files.
Args:
cfg (CfgNode): config.
mode (str): 'train', 'val', or 'test' mode.
Returns:
all_boxes (dict): a dict which maps from `video_name` and
`frame_... | 78f995cfada0e3c6fce9c880226cf48d8c1a7313 | 61,567 |
def efficientnet_b8(pretrained=False, **kwargs):
""" EfficientNet-B8 """
# NOTE for train, drop_rate should be 0.5, drop_path_rate should be 0.2
model = _gen_efficientnet(
'efficientnet_b8', channel_multiplier=2.2, depth_multiplier=3.6, pretrained=pretrained, **kwargs)
return model | 38f0e21c830e1ae98c192ed912bd931dde8f81a1 | 61,568 |
import sys
import os
import ctypes
def get_tesseract(search_path='.'):
""" Get tesseract handle
"""
if sys.platform == 'win32':
lib_name = 'libtesseract303'
_path = os.environ['PATH']
for _dir in ['', 'win32', '..' , '..\win32']:
temp_path = os.path.join(search_path, _d... | a832c882cb1f64609db37bf0e9699d93c9423856 | 61,569 |
import os
import pickle
def load_options(run_folder, options_file_name = 'options-and-config.pickle'):
""" Loads the training, model, and noise configurations from the given folder """
with open(os.path.join(run_folder, options_file_name), 'rb') as f:
train_options = pickle.load(f)
noise_confi... | 23af1f8082fbfa509a4c7675bc6dd8d666cbbc87 | 61,570 |
import re
def prune_lines(infile):
""" Discard all lines which don't have the data we're after
Adapted from http://stackoverflow.com/questions/17131353/problems-targeting-carriage-return-and-newlines-with-regex-in-python
"""
result = []
with open(infile, 'r') as text:
lines = text.read... | 0d3bccf996b2afeab3e56cd29e5559235cb34d12 | 61,571 |
import os
def is_pynsist():
"""Return True if this is a pynsist installation of Spyder."""
base_path = osp.abspath(osp.dirname(__file__))
pkgs_path = osp.abspath(
osp.join(base_path, '..', '..', '..', 'pkgs'))
if os.environ.get('PYTHONPATH') is not None:
return pkgs_path in os.environ.... | b0d4aeee0f729e8e2485e3643b301d1ea7e20383 | 61,572 |
def delete_comment(request, pk):
""" Handles deleting a comment, also checks the correct user doing the deleting """
comment = Comment.objects.get(pk=pk, feed_item__feed__user=request.user)
feed_item_id = comment.feed_item_id
comment.delete()
messages.add_message(request, messages.WARNING, 'Your com... | 59b6e39a0b4de73f9649bd4d33a63e4e975c8122 | 61,573 |
def generate_inputs(generate_calc_job_node, fixture_localhost, generate_structure, generate_kpoints_mesh):
"""Create the required inputs for the ``ProjwfcCalculation``."""
def _generate_inputs(output_parameters=None):
entry_point_name = 'quantumespresso.pw'
parent_inputs = {
'struc... | 191bc148760a8ed217caffea1ae235db3de5a231 | 61,574 |
import json
import time
def predict(event, context):
"""
AWS lambda function, to handle incoming GET requests asking our model for predictions.
:param event: standard AWS lambda event param - it contains the query parameters for the GET call
:param context: standard AWS lambda context param - not use... | 3b87338724bb4c708222d43d793543e247ca6aa0 | 61,575 |
def get_times_for_patients(
lambda_2,
lambda_1,
mu,
num_of_servers,
threshold,
seed_num,
measurement_type,
runtime,
):
"""Determines the appropriate times to be used set by the user
Parameters
----------
lambda_2 : [float]
lambda_1 : [float]
mu : [float]
num_... | 725ae599d2f5af2e0589171c477a7a73f9489db3 | 61,576 |
import subprocess
import sys
def get_real_interface(interface):
"""Translate virtual interface to a physical interface if it wasn't already
a physical interface.
interface - Name of the interface.
"""
query = 'source {}/interfaces/{} 1>/dev/null 2>&1; echo $Interface'.format(
netctl_root,... | df7c88894808e62a5481a2fdb39b7a3337ea0cd5 | 61,577 |
def _GetDefiningLayerAndPrim(stage, schemaName):
""" Searches the stage LayerStack for a prim whose name is equal to
schemaName.
"""
# SchemaBase is not actually defined in the core schema file, but this
# behavior causes the code generator to produce correct C++ inheritance.
if schemaName =... | c898b1f1fdd3430b044b556a269b0cdf84a552c1 | 61,578 |
def allowed_image_filesize(filesize):
"""Function to check if image file uploaded is within filesize."""
if int(filesize) <= app.config["MAX_IMAGE_FILESIZE"]:
return True
else:
return False | 52e24c8bd8159aa2135664a16c5aa96fac919155 | 61,579 |
def twoSum(nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: bool
"""
# Time Complexity - O(n)
# Space Complexity - O(n)
res = set()
for i in nums:
if i in res:
return True
res.add(k - i)
return False | 93e6d3f4d2d80f28a125b85b3eab5f4601d119d6 | 61,580 |
import csv
def getCPTcodes():
"""
get CPT codes, put in dictionary
:return: the dictionary of codes
"""
with open('../codes/CPT.csv', 'rU') as csvfile:
reader = csv.reader(csvfile)
codeDict = {rows[0]:rows[1] for rows in reader}
return codeDict | b08f1b270c6faf4218b6391e0a84bb752bfcf37d | 61,581 |
import scipy
def homogenized_cheby(n: int, kind: str = "t") -> np.ndarray:
"""Compute the coefficients for the homogenized version of T_n or U'_n.
Args:
n: degree of the polynomial. May be negative, in that case the degree will
be abs(n) but the sign may differ (see notes for exact definit... | e9f890972830e7067a8cc6f02db53665669dc37d | 61,582 |
def unique_by(func, objects):
"""
Sorts by applying func to each item
:param func: Applied to each object to get the sortable result
:param objects: iterable
:return: The sorted objects
"""
seen = set()
def hash(obj):
value = func(obj)
return value not in seen and no... | e3f72626543b0b0234530f936e02a100f00e6cba | 61,583 |
def filtered_products(request, filter_group, filter_name):
""" The view rendering a page for all products (Artwork)
filtered by a user selected criteria """
# Call my helper function in utils.py to run the filter if there is filter
if filter_group and filter_name:
filtered_products = special_fi... | 862bc0c3cbca417bccc05016db6dcaa5ddce64f3 | 61,584 |
def get_actual_start_time(task):
"""Returns the start time of the earliest time logs of the given task if it
has any time logs, or it will return the task start_time.
:param task: The stalker task instance that the time log will be
investigated.
:type task: :class:`stalker.models.task.Task`
:... | 963a6f3b88dcedd12e96396382d144e099111038 | 61,585 |
import os
def read_file(fname):
"""Read the given file.
:param fname: Filename to be read
:return: File content
"""
with open(os.path.join(os.path.dirname(__file__), fname)) as f:
return f.read() | 8681f8a3e267c5a3e22658a6d7e0fbd9242d3e51 | 61,586 |
import os
def split_file_on_disk(file_path, num_splits, output_paths=None, delete=False):
"""
"""
all_output_paths = []
all_output_files = []
for part_idx in range(num_splits):
if output_paths is None:
output_path = get_part_path(file_path, part_idx)
else:
... | 0c28050d7dc7520467253e64cceb92e6c7da3aa0 | 61,587 |
import torch
def cls_mse_loss(input_logits, target_logits):
"""Takes softmax on both sides and returns MSE loss
Note:
- Returns the sum over all examples. Divide by the batch size afterwards
if you want the mean.
- Sends gradients to inputs but not the targets.
"""
assert input_logits.si... | 42922316c11243bdf57b2eb3451642a4047bba5c | 61,588 |
import os
def load_gridded_forecast(fname, loader=None, **kwargs):
""" Loads grid based forecast from hard-disk.
The function loads the forecast provided with at the filepath defined by fname. The function attempts to understand
the file format based on the extension of the filepath. Optionally, if loade... | 9908be52f15b50d171176e97aa79ad85e959d973 | 61,589 |
def sorted_by_popularity(tokens):
"""Sort tokens according to popularity (see NAME_CHAR_POPULARITY_MAP) so
that tokens that are LESS popular in Japanese names come first, and return
the sorted tokens.
Args:
tokens: tokens to sort.
Returns:
Sorted tokens.
"""
return sorted(to... | 408e6a236e394bf864e5e867576bf0602abc6c1e | 61,590 |
def property_info(info, delimiter=' | '):
"""Returns property info from tupple.
Input tuple must containts flags if property is writable, readable
and deletable.
#!jinja
{# return someone like this: WRITE | READ | DELETE #}
{{ property_info(info) }}
"""
rv = []
if info[... | 0b39c7ba69a05365f0051eab9941fd2ddce02642 | 61,591 |
def treeToList(node):
"""
Converts XML tree to list of entries. Useful to start recursive search.
@ In, node, ET.Element, the xml tree root node to convert
@ Out, treeToList, list(list(ET.Element)), of full paths to entries in xml tree
"""
flattened = findBranches(node,[node],[])
return list(tuple(... | ad9608e162f36c41d3b81729d14d61c741b8bdd5 | 61,592 |
def extract_title(path):
"""
Given document file path
Extract the title
>>> extract_title("/group/home/puls/Shared/capitalization-recovery/12/www.ameinfo.com.rssfeeds.10660/DE01D30EA383DFD9FA1427CB9CC935F2")
u'Polaroid launches new range of products at opening day of GITEX Technology Week 2014'
... | d0fb37405e1779d16abaf217e5de52a7a8a2634d | 61,593 |
def new_assignment():
"""Provides an interface for adding new assignments."""
return flask.render_template('new_assignment.html',
offices = office_utils.get_all_offices()) | 0e169b800daacad6ab15fc620038eb38d790b7ad | 61,594 |
import os
def get_image_filepath(df_row, source_dir=''):
"""Return the filepath of the image that is described in the row of the data table."""
# Current format for the image filepath is:
# <PTID>/<Visit (spaces removed)>/<PTID>_<Scan.Date (/ replaced by -)>_<Visit (spaces removed)>_<Image.ID>_<DX>_Warped... | 88af64b14f48f5e80dc47a9f0ce1d9b57a24ca4b | 61,595 |
def list_schemes():
"""Returns the tuple (schemes, encodings).
`schemes` is an iterator for all supported password schemes (depends on
the used Dovecot version and features of the libc).
`encodings` is a tuple with all usable encoding suffixes.
"""
dcv = cfg_dget("misc.dovecot_version")
sch... | 3355f6bcdbeed2b8599b3246d7f663c118819b5e | 61,596 |
import re
def clean(s):
"""Strip leading & trailing space, remove newlines, compress space.
Also expand '{NL}' to a literal newline.
:param str s:
:rtype: str
"""
s = s.strip()
s = re.sub(' +', ' ', s)
s = s.replace('\n', '')
s = s.replace('\r', '')
s = s.replace('{NL}', '\n')
... | f2c07984de1766b7a1d0258b29ad8030e87896e8 | 61,597 |
def dict_label(text, dictionary={}, regulation=[['U', [10]]]):
"""
根据词库做实体标注
text = '企业提供部门经理的身份证和身份证明'
dictionary = {
'主体': ['企业'],
'客体': ['部门经理'],
'材料': ['身份证', '身份证明']
}
regulation = [
['主体', [1, 2, 3]],
['客体', [4, 5, 6]],
['材料', [7, 8, 9]],
['U', [1... | 7ee2de94c5a71dae0b6c2c2ffcb908b98692da71 | 61,598 |
import time
import math
def timeSince(since):
"""
compute the training/evaluate time
"""
now = time.time()
s = now - since
m = math.floor(s / 60)
s -= m * 60
h = math.floor(m / 60)
m -= h * 60
return '%d h %d m %d s'%(h, m, s) | 4fefbf6198bc89ca53eae341c116b0f6e693e8d1 | 61,599 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.