content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import scipy
import numpy as np
import os.path as op
from lisa import organ_localizator
import organ_localizator
def near_blur_intensity_localization_fv(data3dr, voxelsize_mm, seeds=None, unique_cls=None): # scale
"""
Use organ_localizator features plus intensity features
:param data3dr:
:para... | 536655ffbd45839e46dc1fe2e3c102afe84b8434 | 49,100 |
from typing import Any
def tsa_factory(y: Y_TYPE, s: dict, k: int, a: A_TYPE = None,
t: T_TYPE = None, e: E_TYPE = None,
p:int=TSA_P_DEFAULT, d:int=TSA_D_DEFAULT, q:int=TSA_D_DEFAULT) -> ([float], Any, Any):
""" Extremely simple univariate, fixed p,d,q ARI... | 63565ad1633ceda65d0bd1645e34a2bc44dde44e | 49,101 |
import random
import hashlib
import logging
def signature_generation(msg, private_key):
"""
Generates signature for a given message. Note that it will most likely
return different signature even for the same message, since it uses a random
integer as a parameter for generating the sign. This can be av... | 704021825430ab7cc7d25d3453e4065e41df2a79 | 49,102 |
def wrap_numbers(input_dict, name):
"""Given an `input_dict` and a function `name`, adjust the numbers
which "wrap" (restart from zero) across different calls by adding
"old value" to "new value" and return an updated dict.
"""
with _wn.lock:
return _wn.run(input_dict, name) | fd7c26d5c756f5d2ecad3d56d3235ade1801847d | 49,103 |
from typing import OrderedDict
import os
def headers_to_table(headers, filenames=None, keywords=None, empty_value=None,
lower_keywords=False, logger=logger):
"""Read a bunch of headers and return a table with the values."""
# TODO: Refactor to better performance
hlist = []
actual ... | 8da1ea3f46b8013093ad9c13a72484e4f17a2719 | 49,104 |
def dict_remove_empty(d):
"""remove keys that have [] or {} or as values"""
new = {}
for k, v in d.iteritems():
if not (v == [] or v == {}):
new[k] = v
return new | 40d6b4f2e3e20cee3885efb9fe3d60fafe9a4169 | 49,105 |
def destroy(parameters):
"""
Destroys a vm forcefully
"""
logger.debug("Inside destroy() function")
vm_id = parameters['vm_id']
vm_details = current.db.vm_data[vm_id]
logger.debug(str(vm_details))
try:
domain = getVirshDomain(vm_details)
if domain.info()[0] == VIR_DOMAIN_... | a3473e8306a457b4a7e0b4ed8a4f407806b638b8 | 49,106 |
def subscribe(body: SubscriptionInput = None):
"""Subscription for receiving a notification about discovery and KB updates.
# noqa: E501
:param subscription_input: Subscription information.
:type subscription_input: dict | bytes
:rtype: SubscriptionOutput
"""
logger.debug("Entry: subscri... | 001682641d41f6316fdfab554e7a9d7e248c30ae | 49,107 |
def sigmoid_activation(x):
"""Commpute the sigmoid activation value for a given input.
Args:
x (array): input data point
Returns:
float: sigmoid activation value
"""
return 1.0 / (1 + np.exp(-x)) | 66d268ee430a0c9aadce05ca4d61735c681d01ac | 49,108 |
def read(f, normalized=True):
"""MP3 to numpy array"""
a = pydub.AudioSegment.from_mp3(f)
y = np.array(a.get_array_of_samples())
if a.channels == 2:
y = y.reshape((-1, 2))
if normalized:
return a.frame_rate, np.float32(y) / 2**15
else:
return a.frame_rate, y | 30b3ee110e8bbc582f6f85b3c81294f1e904cb7d | 49,109 |
def maintenance(jobname):
"""Performs server maintenance, e.g. executed regularly by the server itself (localhost)
Returns:
200 OK: text/plain (on success)
403 Forbidden (if not localhost)
500 Internal Server Error (on error)
"""
global logger
report = []
try:
us... | 826372e61d81f011e917ec8ce6fd9eb8f1625f04 | 49,110 |
def find(id=None, _cleaner=None, populate_rooms=False, populate_cleaner=False, populate_feedbacks=True):
""" TODO: populate_rooms has no test coverage
Populates feedbacks list as default (acts as if feedbacks in embedded documents)
"""
query = {}
if id:
query['_id'] = sanitize_id(id)
if _cleaner:
query['_cle... | d409464144f0802b6f56523b44a1d9ad760f9588 | 49,111 |
def GeneticModel03(x,y, popSize, iters, mutsPerKid, dbkids=False, natCouples=1 ,clonekids=0):
"""
This is an hybrid model from Model01 and Model02.
Params:
x(np.array): x coordinate array.
y(np.array): y coordinate array.
popSize(int): Size of the population.
... | ccb2ed0d613137eaec95800d8f97a68dc4a04095 | 49,112 |
def show_img(img,
ax=None,
vmin=None,
vmax=None,
interpolation=None,
title_=None,
cbar_orientation='horizontal',
plot_colormap='jet',
plot_size=(12,7),
sig_digits=2,
plot_aspect=None,
... | 60ff9aeaea2d497edfa4615fafe22b49418a89bb | 49,113 |
def downscale_mean(arr, red):
"""
Downscale an image by the local mean
Parameters
----------
arr: 2D numpy.array
Array to reduce
red: int, or couple
Factor by how much the array is reduced.
If couple, the first factor reduces in x, and the second in y.
... | 6b521a2b2266352dca1684c200d9884c8cb18f40 | 49,114 |
def H(qbit: QbitVal) -> Gate:
"""
Hadamard gate.
:param qbit: parameter.
:return: Gate.
"""
root2 = 1 / Sqrt(Real(2))
return Gate('H',
[qbit],
H_matrix,
mapping=lambda q: QbitVal((q.alpha + q.beta) * root2,
... | 0a8c577ad9a390915c34448b12c9eb17aeaf126f | 49,115 |
def run_svm_one_vs_rest_on_MNIST():
"""
Trains svm, classifies test data, computes test error on test set
Returns:
Test error for the binary svm
"""
train_x, train_y, test_x, test_y = get_MNIST_data()
train_y[train_y != 0] = 1
test_y[test_y != 0] = 1
pred_test_y = one_vs_rest_sv... | 77ec0ff16e0ecdaceb4c28ca576e9e98c480480c | 49,116 |
from typing import AnyStr
import os
def read_toml(tomlpath: AnyStr) -> XgmContainer:
"""read an XgmContainer from a toml file and its content files
:param tomlpath: path to the toml file
:return: XgmContainer instance read from tomlpath
"""
tomldir = os.path.dirname(tomlpath)
with open(tomlpa... | 806d68e584ae32f6d6477dc07baf7c86a303ba4e | 49,117 |
def check_expEstimates(theta, deltaT, binSize, T, numTrials, data_mean, data_var,\
maxTimeLag, numTimescales, numIter = 500, plot_it = 1):
"""Preprocessing function to check if timescales from exponential fits are reliable for the given data.
Parameters
-----------
the... | da36783ee989ae4ee1936d77e4f4beb2db99ec83 | 49,118 |
import logging
def fit_galaxy_sky_multi(galaxy0, datas, weights, ctrs, psfs, regpenalty,
factor):
"""Fit the galaxy model to multiple data cubes.
Parameters
----------
galaxy0 : ndarray (3-d)
Initial galaxy model.
datas : list of ndarray
Sky-subtracted dat... | 858d220e8151131df5f839f939a6aadccb07d46e | 49,119 |
def image_upload(request):
"""
This method return the wangEditor image upload data
You should implement this method by your self
{
// errno 即错误代码,0 表示没有错误。
// 如果有错误,errno != 0,可通过下文中的监听函数 fail 拿到该错误码进行自定义处理
errno: 0,
// data 是一个数组,返回若干图片的线上地址
data: [
'图片1地址',
'... | e2fed0b41a261752a42528d934a1c74d51ac9915 | 49,120 |
from typing import Union
from typing import cast
def scale_unscaled_ramp(rmin: Union[int, float, str], rmax: Union[int, float, str], unscaled: RAMP_SPEC) -> RAMP_SPEC:
"""
Take a unscaled (normalised) ramp that covers values from 0.0 to 1.0 and scale it linearly to cover the
provided range.
:param rm... | e80f437f6c8085f75ebf98293cbe838e44886af4 | 49,121 |
def get_class_name(obj):
"""
Returns the name of the class of the given object
:param obj: the object whose class is to be determined
:return: the name of the class as a string
"""
return obj.__class__.__name__ | 93be3acf545376dc1df43684da75a59e967d2b2f | 49,122 |
def encode_bytes(bytes):
"""Encodes bytes as Base64 unicode string."""
return b64encode(bytes).decode('utf-8') | 149ca9b94512f2bc830c20943c495ee711b3cd51 | 49,123 |
def get_starcheck_catalog_at_date(date, starcheck_db=None, timelines_db=None):
"""
For a given date, return a dictionary describing the starcheck catalog that should apply.
The content of that dictionary is from the database tables that parsed the starcheck report.
A catalog is defined as applying, in t... | d9aa25b9d55ce8510ab1b8004766efba26535f07 | 49,124 |
def result_aggregator(aggregator_fn: ResultAggregatorFn):
"""Transform previous aggregate and list of results into an aggregated
single result. Called by load model function
Args:
aggregator_fn (ResultAggregatorFn): Aggregator function
"""
def wrapper(fn):
set_scenario_attribute(fn... | 6b8dd6a8b277b862d4ed4dd5082891a610e47b94 | 49,125 |
def convert_to_ipa(phrase, specialized=True):
"""Takes a piece of text and transibes it to the
International Phonetic Alphabet (IPA).
Note: some changes to transcription were made depending on the
system, to not have these changed, set <specialized> to false.
"""
conversions = {
"oʊ":... | ee823df010f55db7967116061c4fe75222d8c137 | 49,126 |
def lower_walls_plumed(*args, **kwargs):
"""A restraint that is zero if the argument is below a certain threshold.
The restraint potential energy is given by
kappa * ((arg - at + offset) / eps)**exp
if arg - at + offset is less than 0, and 0 otherwise.
Parameters
----------
arg : tor... | 051ac9282dae1b163f745818db9c5c3b7d3728d6 | 49,127 |
import json
import pprint
def query_record( rec_id: str ) -> dict:
""" Handles api call for GET reference-data and associated referent-data.
Called by views.data_records() """
log.debug( 'starting query_record()' )
assert type(rec_id) == str
data = { 'rec': {}, 'entrants': [] }
if rec_id =... | bc89e02f10a359d3fdd96fc94d2b548fef79fb79 | 49,128 |
import json
def export_nearby_wells(
req: WellsExport
):
"""
finds wells near to a point
fetches distance data using the Wally database,
combines it with screen data from GWELLS and
filters based on well list in request
"""
point_parsed = json.loads(req.point)
export_wells = r... | c406e0a995a4b2d639b7bd47989d613fec0fd802 | 49,129 |
def is_pod_not_running(pod_name, deployment_target=None, pod_number=0, verbose=True):
"""Returns True if the given pod is in "Running" state, and False otherwise."""
json_path = "{.items[%(pod_number)s].status.phase}" % locals()
status = get_pod_status(pod_name, json_path, deployment_target=deployment_tar... | ec6d0bfe6687daab6c4fe9d4ac75855362ef6c50 | 49,130 |
def _bciPercentileBias(replicates,allData,alpha):
"""Simple percentile CI with bias correction"""
#The jackknife, the bootstrap and other resampling plans
#(See page 118)
#https://statistics.stanford.edu/sites/default/files/BIO%2063.pdf
alpha = alpha/2
#get z for the bias and the desired alpha... | 159838547e2af1f48302258a34b2bd41625074dd | 49,131 |
from typing import Dict
from typing import List
from typing import Callable
from typing import Iterator
def create_orth_variants_augmenter(
level: float, lower: float, orth_variants: Dict[str, List[Dict]]
) -> Callable[["Language", Example], Iterator[Example]]:
"""Create a data augmentation callback that uses... | 2a97c42d1e7a84d4afcdcdc5e62993bca7192d3f | 49,132 |
def create_magnitude_spectrum(image):
"""Creates a magnitude spectrum from image
params:
image: A numpy ndarray, which has 2 or 3 dimensions (BGR)
return: A numpy ndarray, which has 2 dimensions
"""
image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
dft = cv2.dft(np.float32(image), flags=cv... | 0664a5236bb08bbd5604e885aec158ad29b5c8fd | 49,133 |
def traj_loader(parm, crd, step=1000):
"""
Load and return a trajectory from mda universe.
Input parmater file, coordinate file, and loading step interval (default=1000).
"""
traj = mda.Universe(parm, crd, in_memory=True, in_memory_step=step, verbose=True)
return traj | e5347664507ceb4eb83fa80bd5b7f5f3232ae90d | 49,134 |
def index(request: HttpRequest) -> HttpResponse:
"""Render the index page."""
# Build a list of race options (year/type/state/district/csv)
null = None
options = [['2004', 'pres', 'National', 'atlarge', '2004_pres_us.csv'],\
['2006', 'senate', 'Virginia', 'atlarge', '2006_senate_va.csv']... | e4ef4e976a5e68b116245ed9c26b5ef9fe948ea8 | 49,135 |
def len_and_chsum(msg, group=False):
"""Calculate length and checksum. Note that the checksum is not moduloed with 256 or formatted,
it's just the sum part of the checksum."""
count = 0
chsum_count = 0
for tag, value in list(msg.items()):
if not isinstance(tag, bytes):
tag = str(... | b07a2d633a11328fe632008318485c00143251d8 | 49,136 |
from torch.nn.parallel.scatter_gather import scatter_kwargs, gather
from torch.nn.parallel.replicate import replicate
from torch.nn.parallel.parallel_apply import parallel_apply
import os
import torch
def data_parallel_decorator(ModuleClass):
"""
A decorator for forward function to use multiGPU training
w... | 283802699af0d8850008bcfa9a3ec010862ce739 | 49,137 |
from functools import reduce
import operator
def mapping_dicts(lucid_tokens_df, corpus_df, lucid2pascal):
"""return id2word, mapping LUCID id's to words, and id2pic, mapping LUCID id's to
sets of picture names and pic2id, mapping picture names to tokens"""
id2word = dict(zip(lucid_tokens_df['id'], lucid_t... | 9e9ba806eb0a99610aac33c246a76b4394388dfd | 49,138 |
def test_log_append_true(tmp_path, container_runtime_or_fail):
"""run 5 times, append to log each time"""
def side_effect(*_args, **_kwargs):
return None
repeat = 5
new_session_msg = "New ansible-navigator instance"
log_file = tmp_path / "ansible-navigator.log"
cli_args = [
"an... | d3380aeb7bfadbc68ee12000328ac317386cfd28 | 49,139 |
def load_config(path):
"""
"""
def scan(l):
if l == "":
return (NL, l)
elif l[0] == '#':
return (COMM, l)
b = l.find('=')
if b < 0:
return (COMM, l)
key = l[:b].strip()
if key == "":
return (COMM, l)
ret... | 9f53fea839bb8425102d11f15eec76fb3ec56f1a | 49,140 |
def dataset(client):
"""Create a dataset."""
with client.with_dataset(name='dataset') as dataset:
dataset.authors = {
'name': 'me',
'email': 'me@example.com',
}
return dataset | 4f77cd30c58ad74e48280be193f4dd30b0fb5584 | 49,141 |
from .detection import default_conv, default_nnw
def update_SE_kwargs(kwargs={},
kwargs_update={'DETECT_THRESH':3,
'ANALYSIS_THRESH':3}):
""" Update SExtractor keywords in kwargs """
SE_key = kwargs.keys()
for key in kwargs_update.keys():
... | 97742337731568ec2114a2008e2b2fb5a24dd6ae | 49,142 |
from datetime import datetime
def actual_time(ts) -> str:
""" Takes in a UNIX timestamp and spits out actual time as a string without microseconds. """
dt = datetime.datetime.fromtimestamp(float(ts)/1000.0)
dt = dt.replace(microsecond=0)
return str(dt) | c554df608f7933ec08aaee9589582015d0f4612d | 49,143 |
def classify_vector(in_x, weights):
"""
最终的分类函数,根据回归系数和特征向量来计算 Sigmoid 的值,大于0.5函数返回1,否则返回0
:param in_x: 特征向量,features
:param weights: 根据梯度下降/随机梯度下降 计算得到的回归系数
:return:
"""
# print(np.sum(in_x * weights))
prob = sigmoid(np.sum(in_x * weights))
if prob > 0.5:
return 1.0
ret... | 30834f3730116666780753da9aeda25092139954 | 49,144 |
def pd_resample(pd_object, rule, *args, **kwargs):
"""
对pandas中的resample操作,根据pandas version版本自动选择调用方式
:param pd_object: 可迭代的序列,pd.Series, pd.DataFrame或者只是Iterable
:param rule: 具体的resample函数中需要的参数 eg. 21D, 即重采样周期值
:return:
"""
if g_pandas_has_resampler:
"""pandas版本高,使用如pd_object.resam... | df9fe26589144d4aeb92d34b8b45cc54262305c9 | 49,145 |
def clone(pc):
"""
Return a copy of a pointcloud, including registration metadata
Arguments:
pc: pcl.PointCloud()
Returns:
cp: pcl.PointCloud()
"""
cp = pcl.PointCloud(np.asarray(pc))
if is_registered(pc):
force_srs(cp, same_as=pc)
return cp | ecb0c3fb99942c406df06963b4638d407191af08 | 49,146 |
def strategy_best(cookies, cps, history, time_left, build_info):
"""
The best strategy that you are able to implement.
"""
build_items_list = build_info.build_items()
max_cps_div_cost_item = None
for idx in range(len(build_items_list)):
if build_info.get_cost(build_items_list[idx]) <= co... | 77999615f6cde7b7c18c2234e62553db759633be | 49,147 |
import random
def run_link_removal(path, net_name):
"""
Sets up framework and runs the edge removal simulation.
Parameters
----------
path: string
path to the network to be analyzed
net_name: string
name of the network (for labeling)
Returns
-------
No direct outp... | bef1a73069accd7d8c2c8bde4a11fbff4922ad07 | 49,148 |
import re
def autofocus_field(field, *args, **kwargs):
"""
Add the 'autofocus' attribute to an input tag.
Usage::
{% autofocus_field field field_class='col-md-12' %}
Extra args and kwargs are passed to ``bootstrap_field``.
"""
return mark_safe(re.sub(
'<input', '<input autof... | 03da61b7f1409d9b19d4512c50e245195efb31c1 | 49,149 |
def get_buildrequire_pkgs_from_build(build, session, config):
"""
Function which queries koji for pkgs whom belong to a given build tag
of a koji build and paires rpms with their respective package.
:param dict build: build information returned by koji.
:param koji.ClientSession session: koji conne... | c580ca1c2144b8d04dde5e9d3938bfd5e66c6e72 | 49,150 |
def SceneShadowManagerPrepareAddShadowManager(builder, shadowManager):
"""This method is deprecated. Please switch to AddShadowManager."""
return AddShadowManager(builder, shadowManager) | 368c5f7381e7b0cab5cf7339db057ae512959731 | 49,151 |
import joblib
def load_scaler(scaler_filepath):
"""Load MinMaxScaler save object.
Parameters
----------
scaler_filepath : pathlib.PosixPath
Path to MinMaxScaler save object
Returns
-------
sklearn.preprocessing._data.MinMaxScaler
"""
return joblib.load(scaler_filepath) | cf65787614f2bcfce6df3f32da81e551e8376805 | 49,152 |
import scipy
def get_sender_sparse_date_info(email_ids_per_sender,
senders_idx_to_mid_dic,
df_info):
"""
gets time info as one-hot encoding in sparse matrix
idx matching mids as in idx_to_mids in rows and days in columns
idx_to_mids for e... | 1f6a648d09bd8963195fb861ff71aaa7c01adaf9 | 49,153 |
import grp
def is_existing_group(group_name):
"""Asserts the group exists on the host.
Returns:
bool, True if group exists on the box, False otherwise
"""
try:
grp.getgrnam(group_name)
return True
except KeyError:
return False | 8831281684107d9f4c4511cb4cf3493494269650 | 49,154 |
from typing import Dict
from typing import Any
def unpack_struct(struct: Tag, keydict: Dict[str, Any]) -> Dict[str, Any]:
"""Parse a tag with children, if tag is not arrayof....
Parameters
----------
struct: bs4.Tag
Section of returned tree to be parsed as a complex type
Returns
----... | 246a4057f3a46df7cbab321c2a2e75d0f7721a0c | 49,155 |
def server_error_error():
"""
500错误处理
"""
return server_error('Server error') | d61b9f7fee80a0efa7636eb6c83bb94642a7973f | 49,156 |
def get_c2d_topic_for_subscribe(device_id):
"""
:return: The topic for cloud to device messages.It is of the format
"devices/<deviceid>/messages/devicebound/#"
"""
return _get_topic_base(device_id) + "/messages/devicebound/#" | cd62f848d09df4026bce8a716c9dda486c1cb403 | 49,157 |
import os
def loadfolded(fname):
"""Load the folded power spectrum file"""
if fname in folded_filedata and os.path.getmtime(fname) <= folded_filedata[fname][0]:
return folded_filedata[fname][1]
f_in= np.fromfile(fname, sep=' ',count=-1)
#Load header
scale=1000
time=f_in[0]
bins_a=i... | 58b3a979ba5549452c8878dc5ca95316c6b58d28 | 49,158 |
def stakeholder_tweets(users, keywords, credentials=None, limit=None):
"""
Get tweets from users by keywords
@users = list of annotated entities
(see find_stakeholder_twitter_users)
@keywords = list of keyword objects
(see content.content_keywords)
"""
# Throw ... | dd95f13f04940be0dbcc45e269448e48ce764a68 | 49,159 |
import re
def re_search(text: str, expression: str) -> bool:
"""
Test regex match. This method is comparatively
very slow and should be avoided where possible.
"""
return re.search(expression, text) is not None | e86daa552a3f769f46bca794b9d2a4587cbed11c | 49,160 |
import os
import json
def get_conf_json(path, file):
"""
通用: 获取 JSON 配置文件
:param path: 相对于 conf, e.g. bgp
:param file: 文件名, 不带扩展名, e.g. as-name
:return: dict,e.g. {'123': '成都'}
"""
ret = {}
file = os.path.join(current_app.root_path, 'conf', path, file + '.json')
try:
with... | 8941ddbec7f0c79edf2db7ffc53abfbb1058ffff | 49,161 |
def GenerateStochasticBlockModelWithFeatures(
num_vertices,
num_edges,
pi,
prop_mat = None,
out_degs = None,
feature_center_distance = 0.0,
feature_dim = 0,
num_feature_groups = None,
feature_group_match_type = MatchType.RANDOM,
feature_cluster_variance = 1.0,
edge_feature_di... | 6f8ce55f920d1f46a77b895b5d580fb0ef5dd5c8 | 49,162 |
import os
import uuid
def make_unique_filename(initial_filename):
"""Add a random part to a filename so it's unique. File extension is preserved."""
before_ext, ext = os.path.splitext(initial_filename)
ext = ext.replace('.', '') # Remove the dot, if already there.
random_part = uuid.uuid4()
retur... | 6456af3ede2404aba5889d5d876437055026c7c1 | 49,163 |
def median(lst):
"""
Get the median value of a list
Arguments:
lst (list) -- list of ints or floats
Returns:
(int or float) -- median value in the list
"""
n = len(lst)
if n < 1:
return None
if n % 2 == 1:
return sorted(lst)[n//2]
else:
... | b6b7eefdf63490e35e74063995cabd38f4c12089 | 49,164 |
def fit_taus(zi, Kti, iter_max=42, eps_max=1e-6, plot=False, quiet=False):
"""
Fit the ASHRAE pseudo-spectral coefficients tau_b & tau_d given a
set of elevation z and clear sky index Kt values.
"""
# Need at least two points
if len(Kti) < 2:
if not quiet:
print("Warning: In... | 855947ba033e4656c74603f59cdf54cab423bf27 | 49,165 |
from datetime import datetime
import typing
import os
import requests
import copy
import sys
def api_get_flights(airline: str,
flight_date: datetime,
api_url=api_url,
api_token=api_token,
tries=0,
timeout=api_timeout) ... | 301ce8cafd70a37236192052c394957f17eae531 | 49,166 |
def e_log() -> str:
"""Check next update content."""
with open(file=TMERGE_LOGFILE, encoding='utf-8') as log_file:
content = log_file.read()
return content | a3b2338c8b1cc12d9d35d42aea02d1188944910b | 49,167 |
def read_ferre_headers(path):
"""
Read a full FERRE library header with multi-extensions.
:param path:
The path of a FERRE header file.
Returns:
libstr0, libstr : first header, then list of extension headers; headers returned as dictionaries
"""
try:
with open(path, "r")... | 454881c30cf372039d539b511bd2df51acd79cef | 49,168 |
import glob
def load_images(folder_path, img_size=32, num_channels=3, dtype=np.float32, normalize=True):
"""Loads images from a folder.
Args:
folder_path: Path to a folder with png images.
img_size: Size of the image.
num_channels: Number of channels in the output image.
dtype... | 1b0c624230e93d7b995cc7876237ff7801e68ca3 | 49,169 |
def orop(funeval, *aa):
""" Lazy version of `or' """
for a in aa:
if funeval(a): return True
return False | f8ed7f88bbbd894cddf5d56a015ba7fe554342e4 | 49,170 |
def get_value(kind, index):
""" Retrieve a previously stored value """
data = retrieve(kind, index)
if data is not None:
data = data["value"]
return data | 6378ad989cd7751b8579f0aec19aac0d689fe424 | 49,171 |
def load_labels():
"""Load the image label file and transform it to the desired format"""
y_labels = pd.read_csv("../data/y_labels/train_v2.csv")
y_labels["tags"] = y_labels["tags"].apply(lambda x:x.split(" "))
y_labels["image_name"] = y_labels["image_name"].apply(lambda x: x + ".jpg")
UNIQUE_LABELS... | 346ee8a1625d7f5d766b3850850403b6a9aebd4e | 49,172 |
import tqdm
def get_QBias(mobile, bc, sss=[None, None, None], d_cutoff=8.0,
prec=3, norm=True, plot=True, warn=True, verbose=True, **kwargs):
"""
Get QValue for formed bias contacts.
.. Note :: selection of get_QBias() is hardcoded to sel='protein and name CA'.
Reason: bias contacts ... | 1242a9a13cc8be663f61bc089d8bc85cba51e4e8 | 49,173 |
import weakref
def weakref_props(*properties):
"""A class decorator to assign properties that hold weakrefs to objects.
This decorator will not overwrite existing attributes and methods.
Parameters
----------
properties : list of str
A list of property attributes to assign to weakrefs.
... | 4ae42fc4e2dccbb7193a377e122f96c4f7d5112d | 49,174 |
def edge_total_communicability(G, u, v, t=1, tol=1e-7, maxit=50):
"""
Computes the edge total communicabilities of edge :math:`(u, v)`.
If nodes :math:`u` and :math:`v` are the :math:`i^{th}` and :math:`j^{th}` nodes of the graph, the edge total communicability of :math:`(u, v)` is given by the product of ... | 97d36e5110040407b318d0e1b5446a546e1ecbc2 | 49,175 |
def kernel_eligible_pair(X, Y):
"""
Validate X and Y if those are eligible to compute karnel
Parameters
----------
X: np.ndarray (n, d) of real (-inf, inf)
n: number of samples in X
d: number of features
if a 1d array (d,) is given, it's automatically
converted ... | 81fb5dd493231c35ae0b99366ee5ee3aa7a60352 | 49,176 |
import requests
def getBadges( steamId ):
"""
:param steamId: int
:return:
{
"player_xp": int,
"player_level": 13,
"player_xp_needed_to_level_up": int,
"player_xp_needed_current_level": int,
"badges":
[
... | 6bc8d0df5d27e4c53aa4235ddc25d4a99fe5f0c3 | 49,177 |
def detect_objects(interpreter, image, threshold):
"""Returns a list of detection results, each a dictionary of object info."""
set_input_tensor(interpreter, image)
interpreter.invoke()
# Get all output details
boxes = get_output_tensor(interpreter, 0)
classes = get_output_tensor(interpreter, 1... | 04f216efaf1b60c27aaae824bf1d6c18e9f309c9 | 49,178 |
def convert_dict_float_to_dec(dict):
"""
Given a dict, take any values that is a float number and convert it to decimal so it can be written to DDB.
:param dict:
:return: a new dict object with all floating number values replaced with Decimal representation.
"""
new_dict = {}
for key in dict... | 504d03a0bbbf873e7b7122788ab933e1f8fab00e | 49,179 |
from pathlib import Path
def lglob(self: Path, pattern="*"):
"""Like Path.glob, but returns a list rather than a generator"""
return list(self.glob(pattern)) | eba1b9d6300a1e1aca5c47bedd6ac456430e4d89 | 49,180 |
def simulationStep(step=0):
"""
Make a simulation step and simulate up to the given second in sim time.
If the given value is 0 or absent, exactly one step is performed.
Values smaller than or equal to the current sim time result in no action.
"""
if "" not in _connections:
raise FatalTr... | 8ab8cb739d4cc7901525c9230211ee98c56d0cb2 | 49,181 |
def transformer_low_resource(configs):
""" Configuration for training transformer on low-resource datasets.
This is equivalent to configuration of IWSLT'14 De2en in fairseq.
"""
configs = transformer_base_v2(configs)
# model configurations
model_configs = configs['model_configs']
model_co... | d8d840dad1b1153dc617ce99e51d8900cc0a0fd8 | 49,182 |
import platform
def handle_credential_command(command, credentials, target_location='.'):
"""Function that executes a git command that requires credentials.
Parameters
----------
command : str
String command to run
credentials : list of str
The user's entered git remote credential... | 0a70507ce9d465452dde862a205a75d044af9a9c | 49,183 |
def _get_setting(name, default=None):
"""Get the Sublime setting."""
return sublime.load_settings('Preferences.sublime-settings').get(name, default) | 72b6e8d4cc878f056d4e9910a9e40a82bc1354ed | 49,184 |
import os
def status():
"""Endpoint to get the current status of the service.
This endpoints returns information about the activated functionality and the models used.
Returns:
A JSON Response containing information about the functionalities (classification
and detection) and their curre... | 68228fbfa41e1e18698b22b40c1ebea4acfd122a | 49,185 |
def vuln_delete_multiid_route():
"""delete multiple vulns route"""
form = MultiidForm()
if form.validate_on_submit():
Vuln.query.filter(Vuln.id.in_([tmp.data for tmp in form.ids.entries])).delete(synchronize_session=False)
db.session.commit()
db.session.expire_all()
return '... | 102e73625bcbf281766a54f2385c189d85128267 | 49,186 |
def operator_enum_converter(operator: OperatorEnum):
"""
Function for internal use. Used to translate an OperatorEnum into a string representation of that operator
"""
if operator == OperatorEnum.Equals:
return "=="
elif operator == OperatorEnum.GreaterThan:
return ">"
elif operator == OperatorEnum.GreaterTh... | 8e8a6e23b32784d69d772bd28aa2d2a9f08317ff | 49,187 |
def put_using_index_tuple(a, index_tuple, v):
"""Replaces specified elements of an array with given values.
This function is very similar to put(), but takes a tuple of index arrays rather than a single index array.
The indexing works like fancy indexing:
a[index_tuple] = v
Parameters
----... | 14386dcf7238df544b78d3b5a8bcb960fd852d71 | 49,188 |
def ins_to_dict(ins, option=None):
"""
Convert instance object to dictionary
ex)
ins_to_dict(A, {
'cascade': 3, # 如果子项没有cascade,则使用父项-1,如果cascade不大于0,则不对象属性
'recursion_value': '{...}'
# 'include': ['a1'], # 只有include中的字段才会返回,不区分值是否是对象,include的优先级>exclude
# 'exclude': ['... | f4454e182410cd599b51072b252a8cb58a283508 | 49,189 |
def expandFile(filename, no_stdin_warning=False, **kwargs):
"""Get a filename, expand the text in it and print it.
args: (see `processToList`)
no_stdin_warning (bool) : If True, print short message on stderr
when the program is waiting on input from
... | cfc2cc4b1acfbc7e76dd26b044c0104e9ad8fb3c | 49,190 |
def unflatten(flattened: dict) -> dict:
"""
Unflattens a dictionary
:param flattened: Flattened dictionary
:return: Unflattened dictionary
"""
unflattened = {}
for key, value in flattened.items():
parts = key.split(".")
d = unflattened
for part in parts[:-1]:
... | 1a54f4289cb77e5d6355f91e6a26477bce420c6c | 49,191 |
def col2asset(col, assetPath, scale=30, region=None, create=True, **kwargs):
""" Upload all images from one collection to a Earth Engine Asset. You can
use the same arguments as the original function ee.batch.export.image.toDrive
:param col: Collection to upload
:type col: ee.ImageCollection
:param... | 6e2586232d5811ef0babd655e5b9bb022eea69c0 | 49,192 |
import array
import os
def wod_load_index(wod_dir,data_dirs):
""" Parse index of WOD cast data in netCDF format.
Args:
data_dirs: list of strings specifying data directory locations to examine
Returns:
wod_index: dict with following keys to NumPy arrays of equal length
... | 44525a0d4888ec5580a120318c84602cb76cbea7 | 49,193 |
def train(args, trainer, task, epoch_itr):
"""Trains the model for one epoch and return validation losses.
It is modified to optimize the posterior (selector) and summarizer
separately.
"""
# Initialize data iterator
itr = epoch_itr.next_epoch_itr(
fix_batches_to_gpus=args.fix_batches_t... | b3ec43e29f3dc32a4794482f2e1bb75ca51148c6 | 49,194 |
from pathlib import Path
import requests
def upload_notebook(notebook: Path, enable_annotations: bool, enable_discovery: bool, nbss_url: str):
"""
Upload a notebook file to an nbss instance with
"""
upload_url = f"{nbss_url.rstrip('/')}/api/v1/notebook"
with open(notebook, 'rb') as f:
retu... | 5247fe18a1a95076e7c6e35879fa438486a1ce65 | 49,195 |
def compat_assert_outcomes():
"""
Use RunResult.assert_outcomes() in a way that's consistent across pytest
versions.
For more info, on how/why this is inconsistent between pytest versions:
https://github.com/pytest-dev/pytest/issues/6505
"""
def _compat_assert_outcomes(run_result, **kwargs... | 63fe48f7fc3c8b56f296df19ce9c297169e4163a | 49,196 |
from typing import Sequence
def parse_attrs(attrs):
"""Parse an attrs sequence/dict to have tuples as keys/items."""
if isinstance(attrs, Sequence):
ret = [item.split(".") for item in attrs]
else:
ret = dict()
for key, value in attrs.items():
ret[tuple(key.split("."))] = value
return ret | 15779e14fbdb9783d91732aa3420ccb18ee6c620 | 49,197 |
from typing import List
import random
def continuous_setting(agents: List[Agent]) -> Allocation:
"""
Algorithm 3.
Approximation algorithm of the optimal auction for a continuous cake.
Complexity and approximation:
- Requires at most 2n2 values from each agent.
- Runs in time polynomial in n.
... | 0e6cc75e82557f39c5ad5d5e2fd225c0329cdf33 | 49,198 |
def plot_on_sphere(xyz_data, normalize=False):
"""
plots each row of an nx3 numpy array on the surface of a sphere
to do this we first normalize each row
"""
#make 3d figure
fig = plt.figure()
ax = plt.axes(projection='3d')
#build up a sphere
u, v = np.mgrid[0:2*np.pi:200j, 0:np... | 0b803cecb3a625a2746c4db08de8141dcf51f32b | 49,199 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.