content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import argparse
def handle_args():
"""Parse out arguments"""
parser = argparse.ArgumentParser(description="Autogenerates a script to mock the output of a command",
epilog="Example: cmdmock sensors -u")
#parser.add_argument('-i', '--interactive', action='store_true',
... | a3ac358b59dc8fa80a003f1674fa231ba13dccb5 | 49,600 |
import os
import sys
def do_start_station():
"""
Retrieve initialization files and base (package) directory
"""
basedir= os.getcwd()
sys.path.append(os.path.abspath(os.path.join(basedir, 'source')))
# print(basedir)
ignorelist = []
ignorelist = ['00_dataviewer_shell.py']
i ... | c9522f1fddb63aecd6798e19ba67cd432a32870f | 49,601 |
def parse_vmin_vmax(container, field, vmin, vmax):
""" Parse and return vmin and vmax parameters. """
field_dict = container.fields[field]
if vmin is None:
if 'valid_min' in field_dict:
vmin = field_dict['valid_min']
else:
vmin = -6 # default value
if vmax is No... | a7c096e4648662a5efe59c38de016e586c718ffb | 49,602 |
import json
def to_dict(url: str) -> dict:
"""Method to convert and return as dictionary."""
return json.loads(fetch_data(url)) | d75ade236379f61d0443610f91e2d090077028fe | 49,603 |
def polygon_iou(poly1, poly2):
"""Compute the IoU of polygons."""
return polygon_geo_cpu.polygon_iou(poly1, poly2) | 8e7bec12e3e0dfd99a040e5e256fedb6526a16de | 49,604 |
def fit( X, y, batch_size = 4, validation_split = 0.05, epochs = 1250, learning_rate=0.001):
"""Fit a BNN with mean field posterior and trainable prior to a data set X,y.
Args:
X (np.array): Input data x (features)
y (np.array): Input data y (target)
batch_size (int, optional): Batch si... | 2e3e940e4e0cc2a4537cf5e3619da58f5632aad4 | 49,605 |
import math
def jacob_f(x, u):
"""
Jacobian of Motion Model
motion model
x_{t+1} = x_t+v*dt*cos(yaw)
y_{t+1} = y_t+v*dt*sin(yaw)
yaw_{t+1} = yaw_t+omega*dt
v_{t+1} = v{t}
so
dx/dyaw = -v*dt*sin(yaw)
dx/dv = dt*cos(yaw)
dy/dyaw = v*dt*cos(yaw)
dy/dv = dt*sin(yaw)
""... | 4e9c88a8187d4c8bc76a7f954a68570ffb4a08bf | 49,606 |
def manage_ebs_volume(config, instanceid, instance_infos):
""" Manage the whole EBS process
:param ebs_config dict The EBS parameters
- tags dict: The tag name and tag value to set if a new EBS
volumes is created.
- filters dict: The tag name and ta... | 9cf92e6e0b7bc0b570629649cdc6204f436dc099 | 49,607 |
from datetime import datetime
def save_by_name(admin: dict):
"""
Save a new admin with field name as index
:return:
"""
name = admin.get('name')
if not name:
raise Error(10003, 'Field name required!')
admin['updated_at'] = china_tz(datetime.now())
admin['created_at'] = china_tz... | 7fe9db58896df4ce443e8919896a7fabc4f2fcfa | 49,608 |
from typing import Any
def create(tknzr_name: str, **kwargs: Any) -> BaseTknzr:
"""Create tokenizer instance by tokenizer's name.
Tokenizer's arguments are collected in ``**kwargs`` and are passed directly to tokenizer's constructor.
Parameters
----------
tknzr_name: str
Name of the tokenizer to creat... | 5f01ec7a380f715c71174bafd1ba7c51bbaf3c22 | 49,609 |
def logitRegression(data):
"""
训练模型,并画出模型的ROC曲线
"""
data = transLabel(data)
features = ["age", "education_num", "capital_gain", "capital_loss", "hours_per_week"]
labels = "label_code"
trainSet, testSet = train_test_split(data, test_size=0.3, random_state=2310)
model = trainModel(trainSet... | ca0357cdb6aae5b847b86082a39308dce319a572 | 49,610 |
import copy
def jet_libes_get_data(exp_id=None, data_name=None, no_data=False,
options={}, coordinates=None, data_source="JET_LIBES"):
""" Data read function for the JET Li-BES diagnostic
data_name: channel data can be reached under: "BES-ADCxx", "JPF/DH/KY6D-DOWN:xxx",
... | e58e92b2e3878867eccde22b6976bbbc3fa04b23 | 49,611 |
import numbers
def is_numlike(obj):
"""return true if *obj* looks like a number"""
return isinstance(obj, (numbers.Number, np.number)) | b31365cf1e71d96b88d7a61b595fd85a7196cc81 | 49,612 |
import os
def create_win_putty(folders):
"""
create a batch file to start scite
@param folders see @see fn create_win_batches
@return operations (list of what was done)
"""
text = ['@echo off',
'set CURRENT2=%~dp0',
'call %CURRENT2%env.bat',
... | 8ae3764d86d029f5b98866668ace7307a0601a2a | 49,613 |
def float2bin(afloat: float):
"""소수점 이하의 값이 있는 실수를 이진수로 변환
Args:
afloat: 이진수로 변환할 실수
Returns:
이진수 ('0b' prefix가 없는 실수의 형태)
"""
integer_part = int(afloat) # 정수부분
decimal_part = afloat - integer_part # 소수부분
decimal_bin = "." # 소수부문에 대한 이진표현
while decimal_part != 0.0:
... | 7873450858b3753a5da1f6a70f96d82204e37f8b | 49,614 |
def get_sequential_param_pairs(params, name1, name2):
"""Returns a dict of two sets of sequentially named parameters using the
value of name1 as the key and the value of name2 of the value.
"""
one = get_sequential_params(params, name1)
two = get_sequential_params(params, name2)
if len(one) != l... | fa2e810391e60c89acd43b7931212090a2adb9db | 49,615 |
import re
import os
def _get_newest_model(path: str) -> str:
""" In folder with daluke_pu_0.pt, daluke_pu_10.pt, daluke_pu_2.pt, daluke_pu_10.pt is returned """
pattern = re.compile(MODEL_FILE.format(i=r"\d+"))
models = list()
for f in os.listdir(path):
if pattern.match(f):
models.... | cf8145871e0c92c12a99222daa39c37388a06304 | 49,616 |
import numpy
def create_grid(bbox,height):
"""Create a vector-based grid
Args:
bbox ([type]): [description]
height ([type]): [description]
Returns:
[type]: [description]
"""
# set xmin,ymin,xmax,and ymax of the grid
xmin, ymin = pygeos.total_bounds(bbox)[0],pygeo... | c112601a0c66f7baf863b365d57bc5bb89ad8f50 | 49,617 |
def divmod_vectorize(df):
"""
1. Use divmod to transfom HHMMSSCC to miliseconds integer with vectorize
2. Outside the njit function cast date as np.datetime and time to timedelta
3. Sum date and time
"""
@vectorize([int32(int32)])
def _fix_time(mtime):
aux, cent = divmo... | e99f2b76527ce1e2aafaebfda38fb9e11c3d0821 | 49,618 |
import requests
def sendWebmention(sourceURL, targetURL, webmention=None, test_urls=True, vouchDomain=None,
headers=None, timeout=None, debug=False):
"""Send to the :targetURL: a WebMention for the :sourceURL:
The WebMention will be discovered if not given in the :webmention:
parameter... | c234243ac66122cf12e5b5298d2fc964fa638dae | 49,619 |
def fib_mem(n, computed={0:0,1:1}):
"""find fibonacci number using memoization"""
if n not in computed:
computed[n] = fib_mem(n-1, computed) + fib_mem (n-2, computed)
return computed[n] | 5d25c22ccdc5ea41fbd0faf21a8b35ac535acaef | 49,620 |
import string
def modify_fare(df, n: int = 4):
"""Introduce n new intervals (based on quantiles) for the feature fare, such that it is modified from
being continuous to being discrete
Parameters
----------
df : panda dataframe
n: number of new intervals (int)
Returns
-------
... | 1f67f0b7b55e7e61a6ee4abefb256ffadbb72345 | 49,621 |
def synthesizeChebyshevNTF(order=3, OSR=64, opt=0, H_inf=1.5, f0=0.):
"""Synthesize a noise transfer function for a delta-sigma modulator.
The NTF is a type-2 highpass Chebyshev function.
:func:`synthesizeNTF` assumes that magnitude of the denominator of the NTF
is approximately constant in the passba... | ab91df555ea2834395894b0f40a0ad6e4e8a461e | 49,622 |
import json
def get_alert_by_id(id=1):
"""Get alert data from DB given id."""
results = alert_db.read(AlertModel.id == int(id))
return Response(json.dumps(results, cls=AlchemyEncoder), mimetype='application/json') | 5fd9c430cf121fbb2c356c0c549e0e319374d635 | 49,623 |
def get_name_url_pairs(request):
"""
Return a list of (group name, group calendar URL) pairs.
Make sure that the Brothers or Pledges pair is last in the list, because
the embedded calendar is set to the URL from the last pair in the list,
and we want office positions' calendars to show up with prio... | 6d68cf288a5683afbd892627bdba7f8f02a92b36 | 49,624 |
def mean(dataframe):
"""
Compute mean of column's element in a dataframe.
"""
mean = [
compute_mean(serie)
for _, serie in dataframe.iteritems()
]
return mean | afd186d765b5fe1f13c4219916e3cb84772e1d5d | 49,625 |
def search_nearest_point(points, base_point):
"""
Parameters
-----------
points : numpy.ndarray, shape is (2, N)
base_point : numpy.ndarray, shape is (2, 1)
Returns
-------
nearest_index :
nearest_point :
"""
distance_mat = np.sqrt(np.sum((points - base_point)**2, axis=0))... | 77e76b09c62c6b8f76e059cab46dc550ceea8110 | 49,626 |
def determine_electrode_name(name, **kwargs):
"""electrode names"""
electrode_patterns = [
"(Pt|pt)[-]{0,1}[\W]ring",
"(PDX_Ch1)((_|)|dis(c|k))",
"(PDX_Ch2)((_|)|ring)",
"(PDX P[1-9]{1}K)(-|)(Ch[1-3]{1})",
"(#[1-3]{1}_|)((D|d)is(c|k)|(R|r)ing)",
"(#[1-3]{1}_|)Dis(... | e6f24e33f40abff3400909797d2a6837e92bd912 | 49,627 |
def inference(Sampled_image,Binary_Point_Map, keep_prob, Num_Channels,model_dir):
# Build network and load initial weights
#image: tf tensor of the input image
#keep_prob: Probabality for dropout only applied during training
"""
:param image: input image. Should have values in range 0-255
... | 0c9141f63a2903e752de44e174c3f7935e38d6cb | 49,628 |
def towns_flooding_risk(stations, N):
""" Return list of towns and risk of flooding """
#find the flooding level of each town
towns_level = towns_average_level(stations)[:N]
towns_risk = []
#give a rating of each water level in town
for town, level in towns_level:
risk = "Low"
if... | f63417b1215f0121ca0427e5d36d9fd214eed8ba | 49,629 |
def adjust_learning_rate(optimizer, epoch):
"""decrease the learning rate"""
lr = args.lr
if epoch >= 100:
lr = args.lr * 0.1
if epoch >= 150:
lr = args.lr * 0.01
for param_group in optimizer.param_groups:
param_group['lr'] = lr
return lr | 37734ad97fb85a71e352ce340351929fbdf00e19 | 49,630 |
def get_hash_tuple(a_dict, included_keys=None):
""" Helps in hashing a dictionary by flattening it to a flat list of its keys and values, and then converting it into a tuple (which is what the hash function expects). """
if included_keys is not None:
a_dict = {included_key:a_dict[included_key] for inclu... | b35feea54e6e4446ac1097487445027a07751910 | 49,631 |
def distance_transform(im: np.ndarray) -> np.ndarray:
"""
A function that computes the distance to the closest boundary pixel.
args:
im: np.ndarray of shape (H, W) with boolean values (dtype=np.bool)
return:
(np.ndarray) of shape (H, W). dtype=np.int32
"""
##... | 93cd39a32710ce951243c9dda1e7115aaa6cd4da | 49,632 |
import sys
def _check_python_ok_for_pygame():
"""If we're on a Mac, is this a full Framework python?
There is a problem with PyGame on Macs running in a virtual env.
If the Python used is from the venv, it will not allow full window and
keyboard interaction. Instead, we need the original framework Py... | f3b8b0db2c853a38bb4ce35fdaf4737732378e4a | 49,633 |
def get_cfg_option(cfg, sec, opt, verbose=False):
"""
Retrieve value of a specific option of a configuration.
Parameters
----------
cfg : configparser.ConfigParser()
Configuration as retrieved by the function read_cfg_file().
sec : str
The section in which the option is located.... | 1f387c63d241f1364aa17caec76efe3b33f41b88 | 49,634 |
def send_text(openid, content):
"""组装文本回复数据"""
data = {
"touser": openid,
"msgtype": "text",
"text":
{
"content": content
}
}
return send_message(data) | c0b20bd7c9a54c038ab4fd21d7bd21bd9bb95abd | 49,635 |
import os
def RecognizeCAPTCHA(captcha):
"""
暴露给Login的接口,这里就不能把model作为参数了
:param captcha: 验证码图片
:return: 验证码结果
"""
os.environ["CUDA_VISIBLE_DEVICES"] = "0"
config = tf.compat.v1.ConfigProto()
config.gpu_options.allow_growth = True
session = InteractiveSession(config=config)
mod... | 0458563c4ba8085eb6e9a96441d9cabffcb81996 | 49,636 |
import random
def run_aqrm_task(epsilon, env, learned_rm_file, tester_true, tester_learned, curriculum, show_print, is_rm_learned, currentstep, previous_testing_reward, q):
"""
This code runs one training episode.
- rm_file: It is the path towards the RM machine to solve on this episode
- envi... | a9e3acd06ee59a28bb69ebb41492eac0d67587e9 | 49,637 |
def parse_modifier(modifier):
"""Parse modifier part, return list with name, function and number."""
return [func(value) for value, func in zip(
modifier, (lambda x: x, get_action_function, int))] | 3309ea056546176e9c9b41ac6a6fef5e47dcbace | 49,638 |
import os
def parse(keypoints, path, img_res, node_type, filename, cli):
"""
Given a set of pose estimated keypoints, parses those points, and
returns a list of Networkx augmented graphs containing those points,
if the cli flag is False, otherwise returns None.
:param keypoints: set of keypoints g... | 9f1655bda431aa5e230d3ee47896454ced43512f | 49,639 |
def RePackFromDataPackStrings(inputs,
allowlist,
suppress_removed_key_output=False):
"""Combines all inputs into one.
Args:
inputs: a list of (resources_by_id, encoding) tuples to be combined.
allowlist: a list of resource IDs that should be k... | 7c3730e1bcb66cac61c50d7dda167035d18ff324 | 49,640 |
def toTypes(thing, types, typeError='wrong type'):
"""Convert something to any of the given types, printing an error if impossible."""
if needsLazyEvaluation(thing):
# cannot check the type now; create proxy object to check type after evaluation
return TypeChecker(thing, types, typeError)
else:
return coerceTo... | 406f79b8affb7f234b11cdf6e71c7df197a7e37a | 49,641 |
from typing import Optional
from typing import Tuple
from typing import List
def load_data(
mgf_filename: str,
*,
range_spectrum: tuple = (0, 1600), # spectrum range
min_intensity: Optional[float] = None, # determine threshold to remove
mz_binning_width: float = 5.0,
) -> Tuple[List[float], List... | a62f5dc0cb3447e52f45287b34bc45b8ad21096d | 49,642 |
import warnings
def find_plane_corner(object_name, x, y, axis, camera=None, *args, **kwargs):
"""Find the location in camera space of a plane's corner"""
if args or kwargs:
# I've added args / kwargs as a compatibility measure with future versions
warnings.warn("Unknown Parameters Passed to \"... | 34d18b37498a72882c2900a28fc923f1d2eb6356 | 49,643 |
def _get_python_include(repository_ctx, python_bin):
"""Gets the python include path."""
result = _execute(
repository_ctx,
[
python_bin,
"-c",
"from __future__ import print_function;" +
"from distutils import sysconfig;" +
"print(sysco... | 120ae2ce4636689a46205727611edc1d9071059c | 49,644 |
def within_index(b, e, s, i):
"""Return a boolean value that indicates if i is within the given index.
Parameters
----------
b : Expr
beginning of the index
e : Expr
end of the index
s : Expr
strides of index
i : Expr
array position
Returns
-------
se... | e0f137c9b113f173cd0a7f2cfc5b81299ccee6bd | 49,645 |
def directed_triplet_motif_index(G):
"""Return the directed motif index of three-node graph G (G is a nx graph type)
The motif index is then computed as follows:
Each possible (undirected) edge on the nodes of G is sorted in lexicographic order.
For each pair of vertices, two bits encode, in order, the... | dba5b90617f79e38a1b1aed9cd0b3e6aca0798dd | 49,646 |
def twitter_auth():
"""OAuth procedure for the Twitter API"""
consumer_key = '8U4SH1S8MqMlxFASj6GlgeobL'
consumer_secret = 'iHGgrHBnGJJhnLfH7g2ZaggAwuun2QuNEspvg2ftUD4Ij6UnTp'
access_token = '928672057042391043-Niz2uWC8iXeXepr0NVn8GEzZ8yh5gDG'
access_token_secret = 'DSIXLThko0e0Dcem7OGsa1ht2zpR... | d1f23518258d0e2f5dfd3b4a72a24bc0aff58911 | 49,647 |
def index():
"""Index view."""
if current_user.is_authenticated:
if current_user.role == 2:
issues = Issue.query.order_by(Issue.id).all()
elif current_user.roles.role_label == 'assignee':
issues = Issue.query.order_by(Issue.id).filter((Issue.assignee == current_user.id)... | ebb42cfe3b9816ceb4b174dfa81a6de661f34a86 | 49,648 |
import sys
def fn_name(depth = 0):
"""Get the function name from the call stack.
Args:
depth: call stack depth to return, 0=parent, 1=grandparent, etc.
Returns:
The function name from the call stack, at the depth given.
"""
return sys._getframe(depth + 1).f_code.co_name | c743c9849bb3f33e865e588fe149d179aee16e00 | 49,649 |
def get_data_parallel_rank():
"""Return my rank for the data parallel group."""
dp_group = get_data_parallel_group()
if dp_group is not None:
return get_rank(dp_group)
else:
return get_global_rank() | fe498b6f22fe37df81b5cef8e1bc7609c6ad9eaa | 49,650 |
import math
def kelvin_to_rgb(kelvin):
"""
Convert a color temperature given in kelvin to an approximate RGB value.
:param kelvin: Color temp in K
:return: Tuple of (r, g, b), equivalent color for the temperature
"""
temp = kelvin / 100.0
# Calculate Red:
if temp <= 66:
red =... | 8855f14452b63072e38498a35952ec3ee7a9ae04 | 49,651 |
def get_priors(source, version):
"""Retrieves prior pdfs for each parameter
"""
params = get_parameter(source=source, version=version, parameter='param_keys')
pdfs = {}
for param in params:
default = source_defaults['priors'][source].get(param, flat_prior)
v_definition = version_defi... | de43665767084cef8067cee116c033d61aeab2c8 | 49,652 |
def get_package_relative(file, package_dir):
"""
Get path of file relative to package directory.
If the file is not in the package directory, an error is raised.
Args:
file (File): The file.
package_dir (string): The package directory, for instance gotten from `get_package_dirname`.
Returns:
st... | 4363f161140fc7a99a2a1f8adcff5b0476a34bd3 | 49,653 |
def prepare_study_with_trials(
no_trials: bool = False,
less_than_two: bool = False,
more_than_three: bool = False,
with_c_d: bool = True,
n_objectives: int = 1,
direction: str = "minimize",
) -> Study:
"""Prepare a study for tests.
Args:
no_trials: If :obj:`False`, create a st... | 7f57a4fbc5854062c2504bed791f3a1eb0a57edc | 49,654 |
from typing import Callable
def get_from_algorithm_wrapper_registry(algorithm_name: str) -> Callable:
"""
Gets a wrapper function from algorithm wrapper registry.
:param algorithm_name: Algorithm for which the wrapper should be returned.
:return: The previously registered wrapper function.
"""
... | 8338b5540f0e6cb054354bf79f02b8789ebc2f42 | 49,655 |
import os
def read_hdf(hdf_fname, key):
"""
Read contents of HDF file *hdf_fname* associated with *key* and
return a :class:`DataFrame`, header tuple.
"""
if not os.path.isfile(hdf_fname):
raise ValueError('file {} does not exist'.format(hdf_fname))
with PD.HDFStore(hdf_fname) as store... | 18838972a3de3614fb864297d87b7d051b102b97 | 49,656 |
import multiprocessing
def run_simulator(fitparams):
"""
runs the function simulator with the multiprocessing manager (if function is called sequentially, this stores memory, otherwise same as calling sumulator directly)
fitparams: list, for description see function simulator
retu... | 278af74d8c668d4705247bfff9f58f8368f84954 | 49,657 |
def nthRuler(n, dow):
""" Returns the n-th hour ruler since last sunrise
by day of week. Both arguments are zero based.
"""
index = (dow * 24 + n) % 7
return ROUND_LIST[index] | fbd0fbfa83009d33d7172ec699cec17b8dc79510 | 49,658 |
def load_vowel(file, sr=None, normalize=True):
"""Use librosa to to load a single vowel with a specified sample rate
"""
data, rate = librosa.load(file, sr=sr)
if normalize:
data = normalize_vowel(data)
return data | e434d35ce86834ea58aebfa0b3ccdfa9ac869206 | 49,659 |
import click
def make_pass_instance_decorator(obj, ensure=False):
"""Given an object type this creates a decorator that will work
similar to :func:`pass_obj` but instead of passing the object of the
current context, it will inject the passed object instance.
This generates a decorator that works roug... | 9319b7f450961eae2e56c3c39ed8971761828cf3 | 49,660 |
import logging
def parse_projects_for_TMS(instance, **kwargs):
"""Parse projects for the given TMS.
Creates new Django model projects objects with parsed data.
Arguments:
instance - Django TMS object instance
"""
logging.info('parse_tms started')
logging.debug('parse_projects_for_TMS... | 3944dd7e2e4b7b1a3f8707f3a637ee1a614e0ed7 | 49,661 |
def clip_channel(coord: float, bounds: Bounds) -> float:
"""Clipping channel."""
a = bounds.lower # type: Optional[float]
b = bounds.upper # type: Optional[float]
is_bound = isinstance(bounds, GamutBound)
# These parameters are unbounded
if not is_bound: # pragma: no cover
# Will no... | ccf8c309d53d4a1ae2c752d682c36e1340c32ff6 | 49,662 |
def members_to_rep(otus):
"""Provides a lookup for a cluster member to its rep"""
res = {}
for rep, members in otus.iteritems():
for member in members:
res[member] = rep
return res | fa2a1e951a40a2872572883cf814260da8093e3a | 49,663 |
from typing import Mapping
def load_content(path: str, class_indices: Mapping[str, int]):
"""
Load .content files.
.content files (like used in cora) contain node features on separate lines. Each
line is of the form
```
node_id feature_0 feature_1 ... class_label
```
where values are ... | 2a88df9f0dfe6169f643c27ce6ea1367adfd0230 | 49,664 |
def num_2_byte_list(num):
"""
convert num to byte list
:param num:
:return:
"""
byte = []
while num > 0:
b = num & 0xff # 获取最低位的一个字节的值
byte.append(b)
num = num >> 8 # 移除最低位的一个字节
return list(reversed(byte)) | bdd80bb1a42c07f0cddc9b6a27c88204df58d7a8 | 49,665 |
def fixoutaff(outpath='',newaff='1'):
""" quick way to create test data sets - set all aff to 1 or 2 for
some hapmap data and then merge
[rerla@beast galaxy]$ head tool-data/rg/library/pbed/affyHM_CEU.fam
1341 14 0 0 2 1
1341 2 13 14 2 1
1341 13 0 0 1 1
1340 9 0 0 1 1
1340 10 0 0 2 1
... | beddabec122f7927669f324062ea8251cc6823f1 | 49,666 |
def update_accel_time(driver, at):
"""
Updates the accel time of the driver
:param driver: driver
:param at: new accel time
:type driver: DriverProfile
:return: updated driver profile
"""
return driver.update_accel_time(at) | 897c4d7ed30dc82c85481064653dea679755dc68 | 49,667 |
def _simplify(shp, tol=0.05):
"""
Generate a simplified shape, within a specified tolerance.
"""
simp = None
for thresh in [0.001, 0.0005, 0.0004, 0.0003, 0.0002, 0.0001]:
simp = shp.simplify(thresh)
if shp.difference(simp).area / shp.area < tol:
break
return simp | bf4ba42ce612477aa9606d7c710a242fbcf9dd61 | 49,668 |
import os
import tqdm
def parse_voc_annotation(data_path, file_type, anno_path,
use_difficult_bbox=False, cfg=None):
"""
解析 pascal voc数据集的annotation, 表示的形式为[image_global_path xmin,ymin,xmax,ymax,cls_id]
:param data_path: 数据集的路径 , 如 D:\doc\data\VOC\VOCtrainval-2007\VOCdevkit\VOC200... | e900ba880b011c3f3d02b94c672e6e35f9d4e91b | 49,669 |
import re
def _match(pattern, value):
"""User-defined function to implement SQL MATCH/STIX MATCHES"""
return bool(re.match(pattern, value)) | e644a5bf45cf298dec3c94b0782ab6fe606b8fdf | 49,670 |
import os
def assemble_today(calendars="/c/calendars", destination="/c/outgoing", priority="/c/priority.txt", include_week=False, quotes="/c/yoga/golden_present.txt"):
"""
look through all calendar items for events coming up
today (at minumum) and
this week (optionally)
create a new log file for ... | 56c628640e4fc1a1ba392e72fe263bd4f79010b1 | 49,671 |
def get_ds_kernels(opt):
"""
Use the previously extracted realistic estimated kernels
(kernelGAN, etc) to downscale images with.
Ref:
https://openaccess.thecvf.com/content_ICCV_2019/papers/Zhou_Kernel_Modeling_Super-Resolution_on_Real_Low-Resolution_Images_ICCV_2019_paper.pdf
https... | e9cf690669c9c80cf87fbbb93bad8a617ca7bbff | 49,672 |
from datetime import datetime
def parse_date(s):
"""
Convert date string into datetime timestamp.
Parameters
----------
s : str
Date string.
Returns
-------
data : datetime
Timestamp.
"""
return datetime.datetime.strptime(s, '%Y%m%d') | 3b36230018c95193798f6af4d298ce5940f556d2 | 49,673 |
import pkg_resources
def create_app():
"""Create and configure an instance of the Flask application."""
app = Flask(__name__)
app.managers = {}
# https://stackoverflow.com/a/32965521/8903959
version = pkg_resources.get_distribution('lib_ddos_simulator').version
template = {
"swagger": "... | d0d4c23e34a799d0bf2353dea0b0a3494442bc7a | 49,674 |
import platform
import logging
def get_chromedriver(executable_path=None, cookies=None, proxy=None, user_agent=None,
headless=False, images=False, fast_load=False):
"""Returns a Chrome WebDriver using proxies and user-agent if specified.
"""
drive = None
chrome_options = webdr... | 3df29131e4590c787373ed20171e5a8c7b58553b | 49,675 |
import random
import json
import traceback
def getRecommendArticle(request):
"""输入文章id,返回一个list,包括推荐的id
可以假设arxivID=“”时,利用用户浏览记录推荐,非空时按输入推荐。
用户浏览记录可以用session/cookie储存,建议session,读教程。
Args:
request (GET): arxivID:String,article的ID
Returns:
list,[(arxiv_id,title,author,category)... | 060de0d8fdce3151507596c0d1fba41f96b11644 | 49,676 |
import os
def tz_path(name):
"""
Return the path to a timezone file.
:param name: The name of the timezone.
:type name: str
:rtype: str
"""
if not name:
raise ValueError('Invalid timezone')
name_parts = name.lstrip('/').split('/')
for part in name_parts:
if part... | ed4fc19bcd35fb8d61e7bd92969981a5ab2f844f | 49,677 |
from typing import Callable
def check_callback(callback):
"""
Check if callback is a callable or a list of callables.
"""
if callback is not None:
if isinstance(callback, Callable):
return [callback]
elif (isinstance(callback, list) and
all([isinstance(c, Cal... | 1e0be3680c934a79777dbe99a47ecc406df19d2a | 49,678 |
import re
def compress_json(json):
"""Compresses json output by removing quotes from keys. This makes the
return value invalid json (all json keys must be double-quoted), but
the result is still valid javascript."""
return re.sub(r'"(\w+)":', r'\1:', json) | 63aa497580ef4fe3d6d8d6c830652a7369f65723 | 49,679 |
def get_magmom_mae(poscar, mag_init):
"""
mae
"""
mae_magmom = []
sites_dict = poscar.as_dict()['structure']['sites']
# initialize a magnetic moment on the transition metal
# in vector form on the x-direction
for n, s in enumerate(sites_dict):
if Element(s['label']).is_transit... | ac863e57f8b6c337b401f3305bda70c5db306ad7 | 49,680 |
import builtins
def is_bytes(value):
"""Indicate if object is bytes-like.
future.utils.isbytes is deprecated, so re-implementing, as per their
recommendation.
"""
return isinstance(value, builtins.bytes) | baec6eca7b2ddf6bf95b1a93cae5821fe4cc3d19 | 49,681 |
def parse_ref_input(ref_input):
"""
The reference paths, it support multiple paths, use '|' as the separator between all paths, the format is
'tgt_input_1|tgt_input_2|tgt_input_3'. Each tgt_input is 'key1?=value1,key2?=value2,key3?=value3'.
1. 'path?=path1,name?=name1,audio?=audio_path... | 8ee8f556d82786f1b1fc05c24e077ac2c30a4085 | 49,682 |
import os
def find_languages(folders):
""" Find the languages in the translations folders.
Langauges are stored as subfolders with a two letter langauge code
Args:
folders: folders to loo through
Returns:
langauges
"""
languages = []
for folder in folders:
subfol... | d03f40fa617f8ed39c169767e6ccc6b31ebd8d37 | 49,683 |
def GlorotNormalInitializer(out_dim=0, in_dim=1, scale=onp.sqrt(2)):
"""An initializer function for random Glorot-scaled coefficients."""
def Init(shape, rng):
fan_in, fan_out = shape[in_dim], shape[out_dim]
size = onp.prod(onp.delete(shape, [in_dim, out_dim]))
std = scale / backend.numpy.sqrt((fan_in +... | 3666cc83baf55f12c8cdb13dcf4d643e8f8170ae | 49,684 |
from typing import Any
import json
def dumps(obj: Any) -> str:
"""Generate JSON from a Python object."""
return json.dumps(obj, cls=CanonicalEncoder) | c53e3965b45982b93f93f6f2cfaa3bf747fe6482 | 49,685 |
def get_postal_code_by_coords(latitude, longitude):
"""
Finds the nearest postal code to the provided coordinates.
:param latitude:
:param longitude:
:return:
"""
retn = None
result_count = 0
radius = 1
while result_count == 0:
postal_codes = postal_codes_within_radius(l... | e5279457d3cb2e2f886e44f1a7b52d928daaccd3 | 49,686 |
def GetNumResColumnName(doc:NexDoc, col) -> str:
"""Returns the name of the specified column of the Numerical Results Window."""
return NexRun("GetNumResColumnName", locals()) | 999ab27daa4fa6cc65d8065de0a9a5b9f35270ea | 49,687 |
def calc_error(center_value, mc_values, ci=0.683):
"""
Calculate the uncertainties/errors.
"""
data = np.concatenate([[center_value], mc_values])
median, q_lower, q_upper = np.percentile(data, q=(50, 50-50*ci, 50+50*ci))
mean = np.mean(data)
std = np.std(data)
return {
"mean": ... | a1512cf4e6ad15c17c45c0fc5a1eba27113f7033 | 49,688 |
def create_app():
"""
Factory to set up the application
# http://flask.pocoo.org/docs/0.10/patterns/appfactories/
:return:
"""
app = Flask(__name__)
# Load default config
app.config.update(
DEBUG=True,
SECRET_KEY='SECRET_KEY'
)
# Override config from an environmen... | 70a2c09c9aa82f9478b9c620fefbd008d4f6b488 | 49,689 |
def get_prob_distribution (df_class, save_full_path=None, label_name=None, cols=None, plot=True):
"""
This function generates and plot the probability distributions for a given dataframe containing the probabilities
for each label in the classification problem.
:param df_class (pd.dataframe or string):... | 11ddc762784d0d74fbe278b3e0a195d3fd2a522f | 49,690 |
def plot_shape(shape, params, row=0, display_values=False):
"""
Plot shape features in a bidimensional plot.
Parameters
----------
shape: 1D array, pd.Series or pd.DataFrame
Shape features computed with shape_features function.
params: pd.DataFrame
Pandas datafr... | fa9d926206f04d967785ca5c344e24bbe4c9127a | 49,691 |
import sys
def serial_for_url(url, *args, **kwargs):
"""\
Get an instance of the Serial class, depending on port/url. The port is not
opened when the keyword parameter 'do_not_open' is true, by default it
is. All other parameters are directly passed to the __init__ method when
the port is instanti... | 016a27656cb38289639341b0b3be3704c8d7c2ba | 49,692 |
def redirect_with_filter(category='', query=''):
"""Redirects to a multistre.am URL based on filter properties.
Arguments:
category: (str) category by which to filter, e.g. status, game, profile
query: (str) filter to use [OPTIONAL]
If no category argument is given the default behav... | b291a2ff5dc1e4fc8f86bfd141abe4106585c61c | 49,693 |
import logging
def getNamePip(lines):
"""
Used if inPypi == True.
Extracts the pacakgename from lines such as
"%setup -n Jinja2-%realversion", or "%define downloadn cx_Oracle".
Returns None if known patterns are not matched
"""
name = None
for line in lines:
if line.startswith(... | cdf101f61a2e39cf10cc5d78523cf25d7e41b9df | 49,694 |
def dletseq(tree, *, args, syntax, expander, **kw):
"""[syntax, decorator] Decorator version of letseq, for 'letseq over def'.
Expands to nested function definitions, each with one ``dlet`` decorator.
Example::
@dletseq[x << 1,
x << x + 1,
x << x + 2]
def... | 9579c4b2be8e6019d7c90bab5c35b7064f6be0a4 | 49,695 |
import os
def run(app=None,
interface='127.0.0.1',
port=8080,
dev=True,
config=None): # pragma: no cover
""" Run a lightweight development server via the
currently-active runtime. Suitable for use
locally, with no required parameters at all.
:param app: Canteen a... | ea9da923c83b228b55a60abe7f49799b2ae3c8e8 | 49,696 |
def read_phases(paths, index, fractions=None, beta=None):
"""Read the relevant data from a list of exapnded ensemble
simulations with the same reference point.
Args:
paths: A list of directories containing the data to read.
index: The reference subensemble index.
fractions: The refe... | b0b07a889dcacc443e54206c4ae87391e5959586 | 49,697 |
def fasta_name_seq(s):
"""
Interprets a string as a FASTA record. Does not make any
assumptions about wrapping of the sequence string.
"""
DELIMITER = ">"
try:
lines = s.splitlines()
assert len(lines) > 1
assert lines[0][0] == DELIMITE... | e450455710a945df25ad2cf4cc3c7f9ad662e7d3 | 49,698 |
def convert_pem_to_openssh(pem_key):
"""
Converts a given public key from PEM to OpenSSH format.
:param pem_key: PEM-encoded key bytes
:type pem_key: bytearray
:return: OpenSSH-encoded key bytes
:rtype: bytearray
"""
loaded_key = crypto_serialization.load_pem_public_key(pem_key, backend... | 1c7210220893c71906a3efaa7c4fcf76a0c71749 | 49,699 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.