content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def fine_license_ratio(license_data, fine_data, column_name1=None, column_name2=None,year=None):
"""Get ratio of fines to licenses issued in a given year
Parameters:
-----------
license_data: DataFrame
Any subset of the Professional and Occupational Licensing dataframe
fine_data: DataFrame
Any subset of... | 12,700 |
def import_obj(obj_path, hard=False):
"""
import_obj imports an object by uri, example::
>>> import_obj("module:main")
<function main at x>
:param obj_path: a string represents the object uri.
:param hard: a boolean value indicates whether to raise an exception on
impor... | 12,701 |
def Get_Histogram_key(qubitOperator):
"""
Function to obtain histogram key string for Cirq Simulator.
e.g.
PauliWord = QubitOperator('X0 Z2 Y3', 0.5j)
returning: histogram_string = '0,2,3'
Args:
qubitOperator (openfermion.ops._qubit_operator.QubitOperator): QubitOper... | 12,702 |
def get_organizations():
""" Queries API for a list of all basketball organizations registered
with Basketbal Vlaanderen.
:return: list of basketball organizations
:rtype: [Organization]
"""
organizations = []
for organization_data in get_list():
organizations.append(Organizatio... | 12,703 |
def logout():
"""Logout."""
logout_user()
flash('您已成功登出', 'info')
return redirect(url_for('public.home')) | 12,704 |
def get_column_labels():
"""
This function generates a list of column names for the extracted features
that are returned by the get_features function.
"""
# list the names of the extracted features
feature_labels = ["amplitude_envelope",
"root_mean_square_energy",
... | 12,705 |
def corr_finder(X, threshold):
""" For each variable, find the independent variables that are equal to
or more highly correlated than the threshold with the curraent variable
Parameters
----------
X : pandas Dataframe
Contains only independent variables and desired index
threshold:... | 12,706 |
def scrape_url(url):
"""
makes request to input url and passes the response to be scraped and parsed
if it is not an error code response
"""
try:
r = requests.get(url, allow_redirects=True, timeout=TIMEOUT)
except Exception as e:
print('ERROR with URL: {}'.format(url))
re... | 12,707 |
def add(a, b):
"""Compute a + b"""
pass | 12,708 |
def magic_file(filename):
""" Returns tuple of (num_of_matches, array_of_matches)
arranged highest confidence match first.
:param filename: path to file
:return: list of possible matches, highest confidence first
"""
head, foot = _file_details(filename)
if not head:
raise ValueError... | 12,709 |
def plot_sentiment(
df: pd.DataFrame, title: str = None, height: int = 300, label_col: str = "label"
) -> Figure:
"""
Plot the predicted sentiment of the sentences.
Args:
df (pd.DataFrame):
Dataframe with the outputs of a sentiment analysis model.
title (str):
Ti... | 12,710 |
def get_participant_output(conversation_id: Optional[pulumi.Input[str]] = None,
location: Optional[pulumi.Input[str]] = None,
participant_id: Optional[pulumi.Input[str]] = None,
project: Optional[pulumi.Input[Optional[str]]] = None,
... | 12,711 |
def subf(pattern, format, string, count=0, flags=0): # noqa A002
"""Apply `sub` with format style replace."""
is_replace = _is_replace(format)
is_string = isinstance(format, (_util.string_type, _util.binary_type))
if is_replace and not format.use_format:
raise ValueError("Compiled replace is n... | 12,712 |
def curve_comparison_2d(x, y, labels=None, xlabel=None, ylabel=None,
markers=None, colors=None, file_name=None, logy=False,
save=False):
"""
Takes a 1d array of x values and a 3d array of y values and produces a
plot comparing the data sets contained in y such... | 12,713 |
def page_file(
self: BaseHTTPRequestHandler, filename: str, mime: str, folder: str = ""
) -> None:
"""Sends an on-disk file to the client, with the given mime type"""
filename = folder + filename
# 404 if the file is not found.
if not os.path.exists(filename):
self.send_error(404, f"File n... | 12,714 |
def independent_connections(fn):
"""Target must support simultaneous, independent database connections."""
# This is also true of some configurations of UnixODBC and probably win32
# ODBC as well.
return _chain_decorators_on(
fn,
no_support('sqlite', 'Independent connections disabled wh... | 12,715 |
def Route(template, handler):
"""Make a Route whose placeholders accept only allowable map IDs or labels."""
return webapp2.Route(template.replace('>', r':[\w-]+>'), handler) | 12,716 |
def values_iterator(dictionary):
"""Add support for python2 or 3 dictionary iterators."""
try:
v = dictionary.itervalues() # python 2
except:
v = dictionary.values() # python 3
return v | 12,717 |
def _standardize_bicluster(bicluster):
"""Standardize a bicluster by subtracting the mean and dividing by standard
deviation.
Ref.:
Pontes, B., Girldez, R., & Aguilar-Ruiz, J. S. (2015). Quality measures
for gene expression biclusters. PloS one, 10(3), e0115497.
Note that UniBic synthetic data ... | 12,718 |
def test_nucid_to_xs_with_names():
"""Test the _nucid_to_xs function given a nuc_names dictionary."""
mat_lib = {
"mat:M1": {290630000: 0.058, 290650000: 0.026},
"mat:M2": {10010000: 0.067, 80160000: 0.033},
}
nuc_names = {}
nuc_names[290630000] = "cu63"
nuc_names[290650000] = "... | 12,719 |
def upload_video(video_file, upload_url):
"""Uploads video file to Street View via Upload URL.
Args:
video_file: The video file to upload.
upload_url: The upload URL, provided by SV Publish API in step 1.
Returns:
None.
"""
credentials = get_credentials()
http = credentials.authorize(httplib2.... | 12,720 |
def export_globals(function):
"""Add a function's globals to the current globals."""
rootmod = _inspect.getmodule(function)
globals()[rootmod.__name__] = rootmod
for k, v in _inspect.getmembers(rootmod, _inspect.ismodule):
if not k.startswith('__'):
globals()[k] = v | 12,721 |
def asymmetric(interface):
"""Show asymmetric pfc"""
cmd = 'pfc show asymmetric'
if interface is not None and clicommon.get_interface_naming_mode() == "alias":
interface = iface_alias_converter.alias_to_name(interface)
if interface is not None:
cmd += ' {0}'.format(interface)
run_c... | 12,722 |
def get_deployment_polarion_id():
"""
Determine the polarion_id of the deployment or upgrade
Returns:
str: polarion_id of the deployment or upgrade
"""
polarion_config = config.REPORTING.get('polarion')
if polarion_config:
if config.UPGRADE.get('upgrade'):
if config... | 12,723 |
def parse_command(message) -> ParsedStatusCommand:
"""Parsing command arguments to arguments list"""
LOGGER.debug('Got message: %s', message)
try:
_, target, *args = shlex.split(message)
return ParsedStatusCommand(target, *args)
except ValueError as ex:
raise CommandParsingError(... | 12,724 |
def mail_on_fail(func: callable):
"""Send an email when something fails. Use this as a decorator."""
@wraps(func)
def _wrap(*args, **kwargs):
try:
return func(*args, **kwargs)
except Exception as e:
# Handle recursive error handling.
# This way if a task w... | 12,725 |
def compare_gaussian_classifiers():
"""
Fit both Gaussian Naive Bayes and LDA classifiers on both gaussians1 and gaussians2 datasets
"""
for f in ["gaussian1.npy", "gaussian2.npy"]:
# Load dataset
X, y = load_dataset(r'C:\Users\Lenovo\Documents\GitHub\IML.HUJI\datasets//' + f)
# ... | 12,726 |
def generate_confusion_matrix(args, sort_method, dataset_cfg, output_dir, video_predictions, video_labels, tb_writer, shrink=False):
"""save confusion matrix"""
'''
for i in range(10):
print(video_predictions[i].max())
print(video_predictions[i].min())
print(video_labels[i])
... | 12,727 |
def base_conv(num, base):
"""Write a Python program to converting
an Integer to a string in any base"""
_list = []
if num//base == 0:
return str(num%base)
else:
return (base_conv(num//base, base) + str(num%base)) | 12,728 |
def handle_log(request):
""" Handle streaming logs to a client """
params = request.match_info
log_dir = py.path.local('data').join(
params['project_slug'],
params['job_slug'],
)
# Handle .log ext for DockCI legacy data
log_path_bare = log_dir.join(params['stage_slug'])
log... | 12,729 |
def get_scheme(patterns, config):
"""Returns the encoding scheme specified by the given config object
Args:
patterns (list(list)): List of input patterns
config (dict): The config object
"""
assert(type(patterns) == list and len(patterns) > 0)
assert(type(config) == dict)
min_ma... | 12,730 |
def add_sort_to_todo_items(sender, **kwargs):
"""The receiver called before a todo item is saved
to give it a unique sort"""
todo = kwargs['instance']
if not todo.pk:
latest_sort = TodoModel.objects.filter(category=todo.category).count()
todo.sort = latest_sort + 1 | 12,731 |
def date_range(start: Literal["2015-1-1"], end: Literal["2015-1-3"]):
"""
usage.alphalens: 3
"""
... | 12,732 |
def open_signatures_window(*args):
"""
open_signatures_window() -> TWidget *
Open the signatures window ( 'ui_open_builtin' ).
@return: pointer to resulting window
"""
return _ida_kernwin.open_signatures_window(*args) | 12,733 |
def get_subscription_id(_ctx=ctx):
"""
Gets the subscription ID from either the node or
the provider context
"""
return get_credentials(_ctx=_ctx).subscription_id | 12,734 |
def train_one():
"""
train an agent
"""
if not os.path.exists(config.TRAINING_DATA_FILE):
print("==============Start Fetching Data===========")
df = DataDowloader(start_date = config.START_DATE,
end_date = config.END_DATE,
ticker_l... | 12,735 |
def origin_trial_function_call(feature_name, execution_context=None):
"""Returns a function call to determine if an origin trial is enabled."""
return 'RuntimeEnabledFeatures::{feature_name}Enabled({context})'.format(
feature_name=feature_name,
context=execution_context
if execution_cont... | 12,736 |
def plotComputedSolution(n,u,uO):
"""
Plot solution at tStop timesteps.
Parameters
----------
n: Integer
Advance solution n time steps
u : Numpy array
Current solution
uO: Numpy array
Old solution
Returns
-------
None.
"""
for j in range(n):
... | 12,737 |
def get_bit(byteval, index) -> bool:
"""retrieve bit value from byte at provided index"""
return (byteval & (1 << index)) != 0 | 12,738 |
def upsert_target(data, analyst):
"""
Add/update target information.
:param data: The target information.
:type data: dict
:param analyst: The user adding the target.
:type analyst: str
:returns: dict with keys "success" (boolean) and "message" (str)
"""
if 'email_address' not in d... | 12,739 |
def test_elem_z009_elem_z009_v(mode, save_output, output_format):
"""
TEST :3.3.2 XML Representation of Element Declaration Schema
Components : Components in A may be indirectly using components from
C. Lets assume that a type declared in B derives from one in C (which
is possible because B imports ... | 12,740 |
def batch_data(data, batch_size):
"""
data is a dict := {'x': [numpy array], 'y': [numpy array]} (on one client)
returns x, y, which are both numpy array of length: batch_size
"""
data_x = data["x"]
data_y = data["y"]
# randomly shuffle data
np.random.seed(100)
rng_state = np.random... | 12,741 |
def ast_parse_node(node):
"""
:param ast.Node node: an ast node representing an expression of variable
:return ast.Node: an ast node for:
_watchpoints_obj = var
if <var is a local variable>:
# watch(a)
_watchpoints_localvar = "a"
elif <var is a subscript>:
... | 12,742 |
def simplify_board_name(board_name: str) -> str:
"""Removes the following from board names:
- `x86-`, e.g. `x86-mario`
- `_he`, e.g. `x86-alex_he`
- `&` - e.g. `falco & falco_II`
- ',' - e.g. `hoho, but substitute a dp to vga chip` (why)
Args:
board_name: the board name to simplify
... | 12,743 |
def run(config, toml_config, args, _parser, _subparser, file=None):
"""Run project list command."""
config = ProjectListConfig.create(args, config, toml_config)
logger.info("Configuration: %s", config)
logger.info("Listing projects")
result = api.project.list_(
sodar_url=config.project_confi... | 12,744 |
def parse_args():
"""
Parse CLI arguments.
Returns
-------
argparse.Namespace
Parsed arguments
"""
parser = argparse.ArgumentParser(
description="Optimize model for inference")
parser.add_argument("-m", "--model",
dest="model_type",
... | 12,745 |
def delete_news_site(user_id, news_name):
"""
Delete subscription to user list
Params:
- user_id: The user email
- news_name: The name of news provider
Return: void
"""
user_info = get_user_by_email(user_id)
user_info = user_info.to_dict()
list_news = user_info['news_sites']
... | 12,746 |
def get_time_str(dt: datetime.datetime = None, tz_default=LocalTimeZone):
"""
@param dt 为None时,返回当前时间
@param tz_default dt无时区信息时的默认时区
"""
if not dt:
dt = datetime.datetime.now()
dt = convert_zone(dt, tz_default=tz_default)
time_str = dt.isoformat().split('+')[0]
return t... | 12,747 |
def plotLikesTablePair( likesTableFNs,
plotFile, nonNormedStats = (),
includeSpecialBins = True,
getio = None ):
"""Visually plot a likes table.
"""
if getio: return dict( depends_on = likesTableFNs,
creates ... | 12,748 |
def test_with_invalid_params(flask_app):
"""Verify that the api responds correctly when invalid/wrong input params supplied."""
# str instead of int in request_id field
request_id = 'abcd'
request_type = 'registration_request'
rv = flask_app.get('{0}?request_id={1}&request_type={2}'.format(CLASSIFIC... | 12,749 |
def test_reload():
"""
Call this function from Jupyter to check that autoreload has been set up correctly!
"""
print('bar') | 12,750 |
def get_res_details(f):
""" extracts bmaj, bmin, bpa and coordinate increment"""
cmd = "prthd in=%s 2>/dev/null"%(f)
pcmd = os.popen(cmd)
output = pcmd.read()
output = output.split('\n')
#print(output)
for lin in output:
if 'Beam Size' in lin:
print(lin)
bmaj ... | 12,751 |
def copytree(src, dst):
"""Copy directory, clear the dst if it existed."""
if src != dst:
shutil.rmtree(dst, ignore_errors=True)
shutil.copytree(src, dst)
Config.log.debug('HMI: Copying directory from %s to %s', src, dst) | 12,752 |
def del_api_msg():
"""
@api {post} /v1/interfaceapimsg/del InterfaceApiImsg_删除接口信息
@apiName interfaceApiImsgDel
@apiGroup Interface
@apiDescription 删除接口信息
@apiParam {int} apiMsgId 接口信息id
@apiParamExample {json} Request-Example:
{
"apiMsgId": 1,
}
@apiSuccessExample {json}... | 12,753 |
def find_nearest(array, value):
""" Find nearest value of interest in array (used for frequencies,
no double value issues)
Parameters
----------
array: array
Give the array in which you want to find index of value nearest-by
value: int or float
The value of interest
Return
... | 12,754 |
def tube_light_generation_by_func(k, b, alpha, beta, wavelength, w = 400, h = 400):
"""Description:
This functio generates a tube light (light beam) with given paratmers, in which,
k and b represent the function y = k*x + b
# TODO:
Test k, b range
Args:
k (int): y = k*x + b
... | 12,755 |
async def test_creating_entry_sets_up_climate(hass, discovery, device, setup):
"""Test setting up Gree creates the climate components."""
result = await hass.config_entries.flow.async_init(
GREE_DOMAIN, context={"source": config_entries.SOURCE_USER}
)
# Confirmation form
assert result["type... | 12,756 |
def upsert_multi_sector_cheby_dict(conn, multi_sector_cheby_dict):
"""
insert/update multi_sector_cheby_dict for a single object
N.B ...
https://stackoverflow.com/questions/198692/can-i-pickle-a-python-dictionary-into-a-sqlite3-text-field
pdata = cPickle.dumps(data, cPickle.... | 12,757 |
def get_book(isbn):
"""
Retrieve a specific book record by it's ISBN
---------------------------------------------
Endpoints:
GET /books/isbn
GET /books/isbn?act=(borrow|handback)
@QueryParams:
act: (optional) specific action on book
Possible values: borrow, handback
... | 12,758 |
def toint16(i):
""" Convert a number to a hexadecimal string of length 2 """
return f'{i:02x}' | 12,759 |
def save_checkpoint(state, is_best, filename = 'checkpoint.pth.tar', folder = ''):
""" Save the lastest checkpoint and the best model so far.
"""
# make directory if folder doesn't exist
if not os.path.exists(folder):
os.makedirs(folder)
torch.save(state, folder + '/' + filename)
if... | 12,760 |
def call_later(function:Callable, *args, delay=0.001):
"""
Call Your Function Later Even Between Other Operations
(This function uses threading module so be careful about
how, when, and on what object you are going to operate on)
Parameters
----------
function : Callable
this shou... | 12,761 |
def is_phone(text):
"""
验证字符串是否是固定电话
:param text: 需要检查的字符串
:return: 符合返回True,不符合返回False
"""
return check_string(text, '\(?0\d{2,3}[) -]?\d{7,8}$') | 12,762 |
def get_loc(frameInfo, bbox_type):
"""Return GeoJSON bbox."""
bbox = np.array(frameInfo.getBBox()).astype(np.float)
print("get_loc bbox: %s" %bbox)
if bbox_type == "refbbox":
bbox = np.array(frameInfo.getReferenceBBox()).astype(np.float)
coords = [
[ bbox[0,1], bbox[0,0] ],
... | 12,763 |
def load_df(input_path, fname, ext):
"""Read chain as Pandas DataFrame"""
fname = os.path.join(input_path, fname + ext)
print 'loading %s' % fname
assert(os.path.isabs(fname))
X = pd.DataFrame.from_csv(fname)
return X | 12,764 |
def _load_order_component(comp_name: str, load_order: OrderedSet,
loading: Set) -> OrderedSet:
"""Recursive function to get load order of components.
Async friendly.
"""
component = get_component(comp_name)
# If None it does not exist, error already thrown by get_componen... | 12,765 |
def zheng_he(qid_file_name,path,index):
"""
调用以上的所有函数,整合到一起
Parameters
----------
qid_file_name : str
文件名.
path : str
数据的储存文件路径..
index : int
第几个问题.
Returns
-------
None.
"""
try:
qid = get_qid(qid_file_name)
... | 12,766 |
def clean_english_str_tf(input_str):
"""Clean English string with tensorflow oprations."""
# pylint: disable=anomalous-backslash-in-string
string = tf.regex_replace(input_str, r"[^A-Za-z0-9(),!?\'\`<>/]", " ")
string = tf.regex_replace(string, "\'s", " \'s")
string = tf.regex_replace(string, "\'ve", " \'ve")
... | 12,767 |
def config_clear_protocol(_) -> None:
"""Clowder config clear protocol command entry point"""
CONSOLE.stdout(' - Clear protocol config value')
config = Config()
config.protocol = None
config.save() | 12,768 |
def create():
""" Create an admin user """
print ("List of existing users :")
for user in User.all(User):
print (user.id, user.name, user.email)
print ()
print ("New user")
print ('Enter name: ')
name = input()
print ('Enter email: ')
email = input()
password =... | 12,769 |
def _square_eqt(x, y, x0, y0, angle):
"""simple equation for a square.
this returns: max(np.dstack([abs(x0 - x), abs(y0 -y)]), 2). this should then be compared to the
"radius" of the square (half the width)
the equation comes from this post:
http://polymathprogrammer.com/2010/03/01/answered-can-yo... | 12,770 |
def path_command(subparsers):
"""Adds the specific options for the path command"""
from argparse import SUPPRESS
parser = subparsers.add_parser('path', help=path.__doc__)
parser.add_argument('-d', '--directory', dest="directory", default='', help="if given, this path will be prepended to every entry returned... | 12,771 |
def multinomial(x, num_samples=1, replacement=False, name=None):
"""
This OP returns a Tensor filled with random values sampled from a Multinomical
distribution. The input ``x`` is a tensor with probabilities for generating the
random number. Each element in ``x`` should be larger or equal to 0, but not... | 12,772 |
def run_experiment(
max_epochs,
log=None,
evaluate=True,
projection=True,
save_directory=".",
save_file=None,
save_interval=1,
**configuration,
):
"""Runs the Proof of Constraint experiment with the given configuration
:param max_epochs: number of epochs to run the experiment
... | 12,773 |
def compose_decorators(decorators: List[Callable]) -> Callable:
"""Compose multiple decorators into one.
Helper function for combining multiple instrumentation decorators into one.
:param list(Callable) decorators: A list of instrumentation decorators to be
combined into a single decorator.
""... | 12,774 |
def xyz_to_polar(sphere_points):
"""
(B,3,N) -> theta, phi (B,2,N), r (B)
x = r*cos(theta)*sin(phi)
y = r*sin(theta)*sin(phi)
z = r*cos(phi)
"""
r = torch.sqrt(torch.sum(sphere_points*sphere_points, dim=1))
theta = torch.atan2(sphere_points[:,1,:], sphere_points[:,0,:])
z = sphere_po... | 12,775 |
def get_cpu_cores():
"""获取每个cpu核的信息
Returns:
统计成功返回是一个元组:
第一个元素是一个列表存放每个cpu核的信息
第二个元素是列表长度, 也就是计算机中cpu核心的总个数
若统计出来为空, 则返回None
"""
cpu_cores = []
with open('/proc/cpuinfo') as f:
for line in f:
info = line.strip()
if... | 12,776 |
def itk_resample(image: sitk.Image, spacing: Union[float, Tuple[float, float, float]], *,
interpolation: str = "nearest", pad_value: int) -> sitk.Image:
"""
resample sitk image given spacing, pad value and interpolation.
Args:
image: sitk image
spacing: new spacing, either ... | 12,777 |
def check_local_dir(local_dir_name):
"""本地文件夹是否存在,不存在则创建"""
if not os.path.exists(local_dir_name):
os.makedirs(local_dir_name) | 12,778 |
def save(object, filename, bin = 1):
"""Saves a compressed object to disk
"""
file = gzip.GzipFile(filename, 'wb')
file.write(pickle.dumps(object, bin))
file.close() | 12,779 |
def gen_anchor_targets(
anchors,
image,
bboxes,
labels,
num_classes,
negative_overlap=0.4,
positive_overlap=0.5
):
""" Generate anchor targets for bbox detection.
@author: Eli
This is a version of anchor_targets_bbox that takes tensors for images, bboxes, and labels
to play... | 12,780 |
def extend_vocab_in_file(
vocab, max_tokens=10000, vocab_path="../models/vocabulary.json"
):
"""Extends JSON-formatted vocabulary with words from vocab that are not
present in the current vocabulary. Adds up to max_tokens words.
Overwrites file in vocab_path.
# Arguments:
new_vocab:... | 12,781 |
def parameters_to_weights(parameters: Parameters) -> Weights:
"""Convert parameters object to NumPy weights."""
return [bytes_to_ndarray(tensor) for tensor in parameters.tensors] | 12,782 |
def get_iou(data_list, class_num, save_path=None):
"""
Args:
data_list: a list, its elements [gt, output]
class_num: the number of label
"""
from multiprocessing import Pool
ConfM = ConfusionMatrix(class_num)
f = ConfM.generateM
pool = Pool()
m_list = pool.map(f, data_list)... | 12,783 |
def hook_modules(module):
""" Temporarily adds the hooks to a `nn.Module` for tracing """
hooks = []
def register_submodule_tracer(module):
def _submodule_pre_tracer(module, input):
log.debug(f'pre tracer in _submodule_pre_tracer in {type(module).__name__}')
lock(True)
... | 12,784 |
def bridge_forward_delay(brname):
"""Read a bridge device's forward delay timer.
:returns ``int``:
Bridge forward delay timer.
:raises:
OSError, IOError (ENOENT) if the device doesn't exist.
"""
return int(_get_dev_attr(brname, 'bridge/forward_delay')) | 12,785 |
def test_ins_with_4_bytes_payload_and_user_reject(dongle):
"""
"""
apdu = struct.pack('>BBBBBI', 0x80, 0x3, 0x80, 0x0, 0x0, 0x0)
with dongle.screen_event_handler(ui_interaction.confirm_on_lablel, clicked_labels, "reject"):
with pytest.raises(speculos.CommException) as excinfo:
... | 12,786 |
def main(argv):
"""
Main wrapper for training sound event localization and detection network.
:param argv: expects two optional inputs.
first input: task_id - (optional) To chose the system configuration in parameters.py.
(default) 1 - uses default parameters
... | 12,787 |
def RF(X, y, X_ind, y_ind, is_reg=False):
"""Cross Validation and independent set test for Random Forest model
Arguments:
X (ndarray): Feature data of training and validation set for cross-validation.
m X n matrix, m is the No. of samples, n is the No. of fetures
y (ndarray... | 12,788 |
def test_parameter():
"""Request for dataset returns correct parameter metadata"""
meta = hapi(server,'dataset1')
pklFile = 'test_parameter.pkl'
pklFile = os.path.join(os.path.dirname(os.path.realpath(__file__)),'data',pklFile)
if not os.path.isfile(pklFile):
writepickle(pklFile,meta)
... | 12,789 |
def keystring2list(s):
"""convert a string of keys to a list of keys."""
if len(s) == 0:
return []
keys = []
i = 0
while i < len(s):
keylength = struct.unpack(data.MESSAGE_KEY_LENGTH_FORMAT, s[i:i + data.MESSAGE_KEY_LENGTH_SIZE])[0]
i += data.MESSAGE_KEY_LENGTH_SIZE
k... | 12,790 |
def test_random_state_moon():
"""Tests the initialization with a fixed random state in K Nearest Neighbours classifier with moon data."""
clf1 = KNearestNeighbours(random_state=7, data_shape='moon')
clf2 = KNearestNeighbours(random_state=7, data_shape='moon')
data1 = clf1.data_points
data2 = clf2.d... | 12,791 |
def update_dockerfiles(old_version, new_version):
"""Update dockerfiles if there was a major change."""
if major_minor_change(old_version, new_version):
old_r_major_minor = "r%s.%s" % (old_version.major, old_version.minor)
r_major_minor = "r%s.%s" % (new_version.major, new_version.minor)
print("Detecte... | 12,792 |
def binary_fmt(num, suffix='B'):
"""A binary pretty-printer."""
if num == 0.0:
return '0 %s' % suffix
for unit in ['', 'Ki', 'Mi', 'Gi', 'Ti', 'Pi', 'Ei', 'Zi']:
if abs(num) < 1024.0:
return '%.3g %s%s' % (num, unit, suffix)
num /= 1024.0
return '%.3g %s%s' % (num, 'Yi', suffix) | 12,793 |
def transformMatrices(
translation = (0,0,0),
center = (0,0,0),
rotation = (0,1,0,0),
scale = (1,1,1),
scaleOrientation = (0,1,0,0),
parentMatrix = None,
):
"""Calculate both forward and backward matrices for these parameters"""
T,T1 = transMatrix( translatio... | 12,794 |
def ulam(u=1,v=2):
"""
Ulam Sequence
Args:
u -- first term
v -- second term
OEIS A002858
"""
T = [u,v]
S = Counter({u+v:1})
yield u
yield v
while True:
new = min([v for v,c in S.items() if c == 1])
yield new
T.appen... | 12,795 |
async def get_region(country=None, id=None):
"""
`linode_region` provides details about a specific Linode region.
"""
__args__ = dict()
__args__['country'] = country
__args__['id'] = id
__ret__ = await pulumi.runtime.invoke('linode:index/getRegion:getRegion', __args__)
return GetRegion... | 12,796 |
def entry_type(entry, default):
"""Return the type of and entry"""
if entry.attribute is None:
return default
return entry.attribute.get('entry_type', default) | 12,797 |
def build_expression(backend, arrays, expr):
"""Build an expression, based on ``expr`` and initial arrays ``arrays``,
that evaluates using backend ``backend``.
"""
return CONVERT_BACKENDS[backend](arrays, expr) | 12,798 |
def test_main_with_file_debug(clipboard, resource):
"""Test that debug mode for the main entry point has no effect on output."""
sys.argv = ['pygclip', '-s', 'monokai', '-l', 'python', resource('simple.py')]
main()
normal_result = clipboard()
sys.argv = ['pygclip', '-d', '-s', 'monokai', '-l', 'pyt... | 12,799 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.