content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import pprint
def load_transform_data(human_dataset, bot_dataset, drop_features, bins, logger, **kwargs):
"""
Load and preprocess data, returning the examples and labels as numpy.
"""
# Load data for humans.
df1 = pd.read_csv(human_dataset)
df1 = df1.drop("screen_name", axis=1) # remove scree... | 666b9161f1309f3e9765a123773318f55b9f6662 | 33,000 |
def latest():
"""
Latest route returns latest performed searches.
"""
return jsonify(get_latest_searches()) | a9cc69921566ecb9f97eab008ffc8f7fea167273 | 33,001 |
from typing import List
import zipfile
import os
def extract_zip(inzip: str, path: str) -> List[str]:
"""
Extract content of a zipfile inside a given directory.
Parameters:
===========
inzip: str
Input zip file.
path: str
Output path.
Returns:
========
namelist: L... | 4c041f9e0ef2eb742608305ae9f1ecbc3238ee5c | 33,002 |
def actions(board):
"""
Returns set of all possible actions (i, j) available on the board.
"""
PossActions = []
# Find empty positions
for i in range(3):
for j in range(3):
if(board[i][j] == EMPTY):
PossActions.append((i,j))
return Po... | 51f8b37c7b50b655c33a9ea73ded5e175c21670c | 33,003 |
import re
import json
def getCity(html):
"""This function uses the ``html`` passed to it as a string to extract, parse and return a City object
Parameters
----------
html : str
the html returned when a get request to view the city is made. This request can be made with the following statement: ``s.get(urlCiudad... | 77af6a1c49f254f08ab226138b9a5ddc4abbc9b3 | 33,004 |
def server_hostname(config):
"""
Reads the ambari server name from the config or using the supplied script
"""
global cached_server_hostname
if cached_server_hostname is not None:
return cached_server_hostname
if config.has_option('server', 'hostname_script'):
scriptname = config.get('server', 'hos... | bb6f0311566d47b32be855bcd33964b28425143e | 33,005 |
from typing import Callable
import json
from pathlib import Path
import types
def cache_instance(get_instance_fn: Callable[..., data.TrainingInstance] = None, *, cache_dir, **instance_config):
"""Decorator to automatically cache training instances."""
if get_instance_fn is None:
return partial(cache_... | 50bab385439550eca541f4d18915c031c41a8107 | 33,006 |
def get_definitions_query_filter(request_args):
""" Get query_filter for alert_alarm_definition list route.
"""
query_filters = None
display_retired = False
valid_args = ['array_name', 'platform_name', 'instrument_name', 'reference_designator']
# Process request arguments
if 'retired' in req... | a087cbd9ca6ffe9b38afc2d8802c12e4dfd47e50 | 33,007 |
import io
def _read_dictionary_page(file_obj, schema_helper, page_header, column_metadata):
"""Read a page containing dictionary data.
Consumes data using the plain encoding and returns an array of values.
"""
raw_bytes = _read_page(file_obj, page_header, column_metadata)
io_obj = io.BytesIO(raw_b... | f4c0bf36b23238f79bfcc11821e47f88186524e0 | 33,008 |
def num_songs(t):
"""Return the number of songs in the pyTunes tree, t.
>>> pytunes = make_pytunes('i_love_music')
>>> num_songs(pytunes)
3
"""
"*** YOUR CODE HERE ***"
if is_leaf(t):
return 1
else:
sum_songs = 0
for subt in branches(t):
sum_songs += ... | ffba78cccbd98963daa6c1ba29650c624fdba29f | 33,009 |
def _get_parameter_value(potential: Potential, handler: str, parameter: str) -> float:
"""Returns the value of a parameter in its default units"""
return (
potential.parameters[parameter].to(_DEFAULT_UNITS[handler][parameter]).magnitude
) | 2fef58b3018737975e96deb4d58d54f55407c624 | 33,010 |
def triplets_in_range(mini, maxi):
"""
Finds all the triplets in a given range that meet the condition a ** 2 + b ** 2 = c ** 2
>>> triplets_in_range(2, 10)
{(3, 4, 5), (6, 8, 10)}
:param mini: The minimum in the range
:param maxi: Maximum in the rnage
:return: a set of tuples (with length... | 1dbe7c64d483d87b2eab1f652a77e346f0ffefec | 33,011 |
import re
def targetInCol(df, target):
"""
Return meta information (Line or Area) from information in a column of DF.
Arguments:
doc -- csv Promax geometry file
target -- meta information to get (Line or Area)
"""
c = list(df.columns)
ptarget = r''+re.escape(target)
i = [i for i, ... | 5d40cf251bd2a7593a46a5b63b5de3a56f8cec29 | 33,012 |
def default_monitor(verbose=1):
"""Returns very simple monitor object to summarize training progress.
Args:
verbose: Level of verbosity of output.
Returns:
Default monitor object.
"""
return BaseMonitor(verbose=verbose) | fbc5494d2545439daaeb12a4d3215295226b064e | 33,013 |
def pca(X, k = 30, optim = "fastest"):
"""Use PCA to project X to k dimensions."""
# Center/scale the data.
s = np.std(X, axis=0)
s = np.where(s==0, 1, s)
X = (X - np.mean(X, axis=0))/s
if optim == "none":
# Compute covariance eigenvectors with numpy.
#
# T... | 2e5e9b82ec770aa1cda80519f7d392d68c6949a6 | 33,014 |
def get_range(a_list):
"""
=================================================================================================
get_range(a_list)
This is meant to find the maximal span of a list of values.
=======================================================================================... | 36e0cc78d2f45b25af56c1af51292f00c2f2623b | 33,015 |
def create_config(solution, nodes, description_info):
"""Creates compact string representing input data file
Parameters:
solution (list) List of solutions
nodes (list) List of node specification
description_info (tuple) CSP description in form of tuple: (algorithm name, domains, constrai... | 3ccf76ca36b92ceb698aafea43414fe014258b0e | 33,016 |
def get_effective_option(metadata, settings, key):
"""
Return option with highest priority:
not-defined key < default < pelican config settings < file metadata
"""
return metadata.get(key, settings[DP_KEY].get(key)) | 4b617bd9c7fb0f0533014fae0533c0500f64c9bb | 33,017 |
def positions_sync_out_doc_view(request):
"""
Show documentation about positionsSyncOut
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = positions_sync_out_doc.positions_sync_out_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
r... | f775b6eddf1419a781e7a43d047f288c56566b3b | 33,018 |
import gettext
def __build_caj_q_html_view__(data: object) -> any:
"""
popup's table for Caju Quality Information
"""
satellite_est = gettext("Satellite Estimation")
tns_survey = gettext("TNS Survey")
nut_count_average = gettext("Nut Count Average")
defective_rate_average = gettext("Defec... | a4442f4ba486991ea3b1c75168f8ba921d9459c7 | 33,019 |
def code(email):
"""
Returns the one-time password associated with the given user for the
current time window. Returns empty string if user is not found.
"""
print("route=/code/<email> : email:", email)
u = User.get_user(email)
if u is None:
print("user not found, returning ''")
... | 4479f6af448f6c91ab6d1c563d6baa94542826a3 | 33,020 |
def blend_image_with_masks(image, masks, colors, alpha=0.5):
"""Add transparent colored mask to an image.
Args:
image: `np.ndarray`, the image of shape (width, height, channel) or (width, height).
masks: `np.ndarray`, the mask of shape (n, width, height).
colors: list, a list of RGB colors (from ... | 9a733d9a6721c2139a64e2e718c4bb5648dbb759 | 33,021 |
import functools
def get_trainee_and_group(func):
"""Decorator to insert trainee and group as arguments to the given function.
Creates new Trainee if did not exist in DB.
Creates new Group if did not exist in DB.
Adds the trainee to the group if it was not part of it.
Appends the trainee and grou... | 76fb80e90b36c0264e50510c7226587a131095f5 | 33,022 |
import subprocess
def get_bisect_info(good_commits, bad_commit):
"""Returns a dict with info about the current bisect run.
Internally runs `git rev-list --bisect-vars`. Information includes:
- bisect_rev: midpoint revision
- bisect_nr: expected number to be tested after bisect_rev
- bisect_good:... | 7e8da4c432d73ee84b79345f2d1f195f4960ba64 | 33,023 |
def generate_chromatogram(
ms_data: dict,
chromatogram: str,
ms_level: int = 1
) -> list:
"""
Generates a either a Base Peak Chromatogram (BPC) or Total Ion Chromatogram
(TIC) from ripper data.
Args:
ms_data (dict): mzml ripper data in standard ripper format.
chromatogram (s... | 901ab7c350ccb00ee277ec96c7496675274ac0f1 | 33,024 |
def get_tensor_batch_size(values):
"""Extracts batch size from tensor"""
return tf.gather(params=tf.shape(input=values), indices=tf.constant([0])) | c1a7d0cb789526310c332d1e2a24697d1357ceb5 | 33,025 |
def generate_particle_timestamp(time_2000):
"""
This function calculates and returns a timestamp in epoch 1900
based on an ASCII hex time in epoch 2000.
Parameter:
time_2000 - number of seconds since Jan 1, 2000
Returns:
number of seconds since Jan 1, 1900
"""
return int(time_200... | 9c05fc809953e371b756a389d98f3a74c1ea5975 | 33,026 |
def clip_histogram(hist, clip_limit):
"""Perform clipping of the histogram and redistribution of bins.
The histogram is clipped and the number of excess pixels is counted.
Afterwards the excess pixels are equally redistributed across the
whole histogram (providing the bin count is smaller than the clipl... | 0947568a36024dfdfd9fc37385676e924aedb603 | 33,027 |
from typing import Iterable
from typing import Callable
from typing import Tuple
def aggregate_precision_recall(
labels_pred_iterable: Iterable,
precision_recall_fn: Callable = buffered_precision_recall,
) -> Tuple[float, float]:
"""
Computes aggregate range-based precision recall metrics for the give... | d777832230ae84ff86c0ad60dced8a1c007ed90f | 33,028 |
def find_tag_for(t):
"""If transaction matches a rule, returns corresponding tuple
(tag, ruler, match).
"""
res = []
for (tag, rulers) in list(TAGS.items()):
for ruler in rulers:
m, matches = match(ruler, t)
if m:
res.append((tag, ruler, matches))
... | 1b0afd086f428606dfc993d61a0753da98ea176d | 33,029 |
from typing import Union
from typing import Dict
from typing import Any
import typing
def DOMWidget(
layout: Union[Dict[str, Any], Element[ipywidgets.widgets.widget_layout.Layout]] = {},
on_layout: typing.Callable[[Union[Dict[str, Any], Element[ipywidgets.widgets.widget_layout.Layout]]], Any] = None,
) -> Ele... | cee1f61b5eb57582fae65e28ca8823d13bcdff51 | 33,030 |
def load(path, element_spec=None, compression=None, reader_func=None):
"""Loads a previously saved dataset.
Example usage:
>>> import tempfile
>>> path = os.path.join(tempfile.gettempdir(), "saved_data")
>>> # Save a dataset
>>> dataset = tf.data.Dataset.range(2)
>>> tf.data.experimental.save(dataset, p... | d3ec8a97cab7897658758f42486e6f4f3b605e6d | 33,031 |
def test_confusion_PRFAS():
"""
Line=True class, column=Prediction
TR_B [[1585 109 4]
TR_I [ 126 1233 17]
TR_O [ 20 12 82]]
(unweighted) Accuracy score = 90.97 % trace=2900 sum=3188
precision recall f1-score support
TR_B 0.916 0.933 0.924 1698
... | 257736819e3dd6a1c4f2644a15bc74cde2f4c49b | 33,032 |
def wrap(x, m, M):
"""
:param x: a scalar
:param m: minimum possible value in range
:param M: maximum possible value in range
Wraps ``x`` so m <= x <= M; but unlike ``bound()`` which
truncates, ``wrap()`` wraps x around the coordinate system defined by m,M.\n
For example, m = -180, M = 180 (... | 274017550a39a79daacdcc96c76c09116093f47a | 33,033 |
from typing import Iterable
from typing import List
from typing import Any
import click
from typing import cast
from typing import Callable
def execute_processors(processors: Iterable[ProcessorType], state: State) -> None:
"""Execute a sequence of processors to generate a Document structure. For block handling,
... | 4af44e41c02184286c4c038143e1461d8fbe044d | 33,034 |
def date(repo, subset, x):
"""Changesets within the interval, see :hg:`help dates`.
"""
# i18n: "date" is a keyword
ds = getstring(x, _("date requires a string"))
dm = util.matchdate(ds)
return subset.filter(lambda x: dm(repo[x].date()[0]),
condrepr=('<date %r>', ds)) | 91d6cea81861791daed3220bc03e3002a47a959d | 33,035 |
def addAuthor(author):
"""
Creates an Author dictionary
:param author: Author instance
:return: Dict
"""
author_dict = dict()
# author_dict['id'] = "{}/api/{}".format(DOMAIN, author.id)
author_dict['id'] = "{}/api/author/{}".format(DOMAIN, author.id)
author_dict['host'] = "{}/api/".... | f6b35909e223987eb37178d1f6722eaffacc94cd | 33,036 |
def add_transformer_enc_hyperparams_args(parser):
"""Only applicable when args.model_name is 'transformer_enc'"""
parser.add_argument('--hid_dim', type=int, default=128)
parser.add_argument('--num_enc_layers', type=int, default=3)
parser.add_argument('--num_enc_heads', type=int, default=8)
parser.ad... | bc38c3cc1d9fc7e87cebfbf7bdc74f8e9d0a124e | 33,037 |
def make_length(value):
""" Make a kicad length measurement from an openjson measurement """
return int(round(float(value) * MULT)) | 1fe311b94eaaf123f7a028d3a06232185903179d | 33,038 |
import os
def get_data_path():
"""
Return the path to the project's data folder
:return: The path to the data folder
"""
project_folder = os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(__file__))))
return os.path.join(project_folder, "data") | 351d11a22b56567f59858e0e0f092661beedaed6 | 33,039 |
def with_metaclass(meta, *bases):
"""copied from https://github.com/Byron/bcore/blob/master/src/python/butility/future.py#L15"""
class metaclass(meta):
__call__ = type.__call__
__init__ = type.__init__
def __new__(cls, name, nbases, d):
if nbases is None:
ret... | e0d9c4d580125cc60ab8319cc9a2ca918ef40291 | 33,040 |
import math
def calc_mupen_res(N,region_w,region_h):
"""find res to fit N mupen instances in region"""
results = []
for row_length in range(1,N+1):
col_length = math.ceil(N/float(row_length))
instance_width = int(math.floor( min(640, region_w/float(row_length) )))
instance_height = int(math.floor(... | 35b5e739102097d856b7c2e154516d4e866a1567 | 33,041 |
from typing import List
def pos_tag_wordnet(text: List) -> List:
"""Create pos_tag with wordnet format
:rtype: object
:param (List) text: string to be nltk_pos_tagged for syntactic similar synonyms
:return (List[List[str, 'pos_tag']]) tagged_text: str values with according nltk_pos_tag
... | 7da0081c37064678ce70590cecc313ee6ec60673 | 33,042 |
def create_app():
"""
Create an app with config file
:return: Flask App
"""
# init a flask app
app = Flask(__name__)
# 从yaml文件中加载配置,此加载方式有效加载
# 初始化APP
_config_app(app)
# 允许跨域请求
if app.config.get('CORS_ENABLE'):
CORS(app)
# 配置蓝图
configure_blueprints(app)
... | 74d7e7beab4e86faec1fbf8dc357791ac50874dd | 33,043 |
import json
def img_to_json(img, decimals=2, swap=False, save=None):
""" Convert an image volume to web-ready JSON format suitable for import into
the Neurosynth viewer.
Args:
img: An image filename.
round: Optional integer giving number of decimals to round values to.
swap: A temporary... | 18e1d92d73493e69efaf055616ccb2f5d55fc835 | 33,044 |
import ctypes
import typing
import array
def encode_float(
encoder_state: ctypes.Structure,
pcm_data: bytes,
frame_size: int,
max_data_bytes: int
) -> typing.Union[bytes, typing.Any]:
"""Encodes an Opus frame from floating point input"""
pcm_pointer = ctypes.cast(pcm_data, opus... | fc349b4eae1c330444114b3df86f1603c931a30a | 33,045 |
from datetime import datetime
def _login(use_cookie):
"""User login helper function.
The request data should contain at least 'email' and 'password'.
The cookie expiration duration is defined in flask app config.
If user is not authenticated, it raises Unauthorized exception.
"""
data = _get_... | 084238d593b95901fcb260088f730fd7e9ac3f64 | 33,046 |
def get_days_to_complete(course_id, date_for):
"""Return a dict with a list of days to complete and errors
NOTE: This is a work in progress, as it has issues to resolve:
* It returns the delta in days, so working in ints
* This means if a learner starts at midnight and finished just before
midnig... | a00d2e934e73710914d296c251541846d19f021c | 33,047 |
import requests
from bs4 import BeautifulSoup
import re
def get_course_data(level="graduate", department_code="CS"):
# Get appropriate regex for the provided data.
"""
Retrieves the information as tuple of the form (course numbers, titles, pre-requisites, description)
for a given program and departmen... | 306b043f2edf7d9fa38f579c5b39daef1f759964 | 33,048 |
def get_highlightjs_setting(setting, default=None):
"""
Read a setting
"""
return HIGHLIGHTJS.get(setting, default) | 86b3b52fc7e95448a2ce6e860d4b261d78d68a38 | 33,049 |
import numba
import os
def make_walks(T,
walklen=10,
epochs=3,
return_weight=1.,
neighbor_weight=1.,
threads=0):
"""
Create random walks from the transition matrix of a graph
in CSR sparse format
NOTE: scales linearly wit... | ec68f7741a788e722b24fe2e3023210ea354a4db | 33,050 |
def package_dir_path(path):
"""Return package path to package install directory"""
return path + '/.pkg' | edd4b97256ccf02a3f1165b99cae746826e8aee0 | 33,051 |
def sort_cluster_data(cluster_data, cluster_accuracy):
"""
sort cluster data based on GDT_mean values of cluster_accuracy.
-> cluster 0 will have highest GDT_mean
-> cluster <max> will have lowest GDT_mean
.. Note :: if cluster_data has noise_label assigned, will move this label to the end of t... | 964e9a646da025ae6819bc902319f7f1b6c9ae9c | 33,052 |
import random
def reprintClean(pack):
"""
Helper function specifically for reprint packs.
:param pack: List, contains the 12 cards in a pack
:return: temppack, the pack with the higher rarity cards implanted in
"""
temppack = pack
rarity = random.randint(0, 12)
if rarity == 0:
... | 3b73ab930197e482699b340b4cb9c0f068e63985 | 33,053 |
def logout():
"""Logs the current user out"""
del session['user_id']
return redirect('/') | 7584ceceb2f6afa95a82d212ca4b9b537a1d4ad2 | 33,054 |
def main() -> int:
"""
Main function. Executed if script is called standalone.
"""
args = _parse_cmd_args()
try:
return _search_symantec(args.keyword, args.limit)
except KeyboardInterrupt:
_warn("Keyboard interrupt detected\n", True)
return 1 | b8f06d95ab08ca25b55a8f0256ac51902383dfe0 | 33,055 |
def _check_imgs_array(imgs):
"""Check input image if it is an array
Parameters
----------
imgs : array of str, shape=[n_subjects, n_sessions]
Element i, j of the array is a path to the data of subject i
collected during session j.
Data are loaded with numpy.load and ... | 43705a4467a27df3027d9ebed4b8f5eec2866916 | 33,056 |
def smoothline(xs, ys=None, interpol=3, window=1, verbose=3):
"""Smoothing 1D vector.
Description
-----------
Smoothing a 1d vector can be challanging if the number of data is low sampled.
This smoothing function therefore contains two steps. First interpolation of the
input line followed ... | 7e7d50e55f801a14394dc2c9fab4e8f392dee546 | 33,057 |
def prune_model(keras_model, prun_factor_dense=10, prun_factor_conv=10, metric='L1', comp=None, num_classes=None, label_one_hot=None):
"""
A given keras model get pruned. The factor for dense and conv says how many percent
of the dense and conv layers should be deleted.
Args:
keras_model: ... | 90e01b5e1de4acc4649f48f0931f8db5cdc6867c | 33,058 |
def scale_values(tbl, columns):
"""Scale values in a dataframe using MinMax scaling.
:param tbl: Table
:param columns: iterable with names of columns to be scaled
:returns: Table with scaled columns
"""
new_tbl = tbl.copy()
for col in columns:
name = new_tbl.labels[col]
x_sc... | c2b6ff0414ab7930020844005e3bdf4783609589 | 33,059 |
def setup_args(args):
""" Setup the args based on the argparser obj
Args:
args(ArgParser): Parsed arguments
Notes:
If there is no core_root, or test location passed, create a default
location using the build type and the arch.
"""
host_os = None
arch = args.arch
bu... | c454795a3ca1d7c6e93c26758618b21cee0c522d | 33,060 |
from typing import Dict
from typing import Optional
import socket
def discover_devices(timeout : int = 30, debug : bool = False) -> Dict[Optional[str], str]:
"""
Discovers Nanoleaf devices on the network using SSDP
:param timeout: The timeout on the search in seconds (default 30)
:param debug: Prints... | fa3a9d97e76c330f2f1a3852e0e0e1278a69b23d | 33,061 |
def get_params_out_of_range(
params: list, lower_params: list, upper_params: list
) -> list:
"""
Check if any parameter specified by the user is out of the range that was defined
:param params: List of parameters read from the .inp file
:param lower_params: List of lower bounds provided by the user... | 67a8ca57a29da8b431ae26f863ff8ede58f41a34 | 33,062 |
import functools
def _filter_work_values(
works: np.ndarray,
max_value: float = 1e4,
max_n_devs: float = 100,
min_sample_size: int = 10,
) -> np.ndarray:
"""Remove pairs of works when either is determined to be an outlier.
Parameters
----------
works : ndarray
Array of records... | 93002df6f7bdaf0ffd639f37021a8e6844fee4bd | 33,063 |
def pf_from_ssig(ssig, ncounts):
"""Estimate pulsed fraction for a sinusoid from a given Z or PDS power.
See `a_from_ssig` and `pf_from_a` for more details
Examples
--------
>>> round(a_from_pf(pf_from_ssig(150, 30000)), 1)
0.1
"""
a = a_from_ssig(ssig, ncounts)
return pf_from_a(a) | 235b473f60420f38dd8c0ad19c64366f85c8ac4c | 33,064 |
def get_aic(mse: float, n: int, p: int):
"""
Calcuate AIC score.
Parameters
----------
mse: float
Mean-squared error.
n: int
Number of observations.
p: int
Number of parameters
Returns
-------
float
AIC value.
"""
return n * log(mse) + 2 ... | 033cb5ea7e9d06a2f630d3eb2718630904e4209f | 33,065 |
def triangle(a, b):
""" Return triangle function:
^ .
| / \
|____/___\____
a b
"""
return partial(primitives.tri, a, b) | f28bbe0bacb260fb2fb30b9811b1d5d6e5b99750 | 33,066 |
import pickle
def get_max_trans_date() -> date:
"""Return the date of the last transaction in the database"""
return pickle.load(open(conf("etl_accts"), "rb"))[1] | 61db89cfbbdc9f7e2b86930f50db75dcc213205c | 33,067 |
def build_argparser():
"""
Parse command line arguments.
:return: command line arguments
"""
parser = ArgumentParser()
parser.add_argument("-m", "--model", required=True, type=str,
help="Path to an xml file with a trained model.")
parser.add_argument("-i", "--input",... | 65c6e45e30b67ff879dbcf1a64cd8321192adfcf | 33,068 |
from pathlib import Path
def read_file(in_file: str):
"""Read input file."""
file_path = Path(in_file)
data = []
count = 0
with open(file_path) as fp:
for line in fp:
data.append(line)
count = count + 1
return ''.join(data), count | 4fbae8f1af7800cb5f89784a0230680a1d6b139a | 33,069 |
def web_authorize():
"""OAuth 登录跳转"""
# TODO: (演示使用, 自动登录), 请删除并配置自己的认证方式, OAuth2或账密系统
set_user_login({
'job_number': 7777,
'realname': 'Fufu'
})
return redirect(url_for('web.web_index'))
# OAuth 认证
redirect_uri = url_for('web.web_authorized', _external=True)
return oau... | 469af59659032f46b862fd17f55c28e3a1853d9d | 33,070 |
def limit(value, limits):
"""
:param <float> value: value to limit
:param <list>/<tuple> limits: (min, max) limits to which restrict the value
:return <float>: value from within limits, if input value readily fits into the limits its left unchanged. If value exceeds limit on either boundary its set to t... | 55fb603edb478a26b238d7c90084e9c17c3113b8 | 33,071 |
def _cdp_no_split_worker(work_queue, counts_by_ref, seq_1, seq_2, nt):
"""
Worker process - get refseq from work queue, aligns reads from seq_1 and seq_2,
and adds as (x,y) coords to counts_by_ref if there are alignments.
:param work_queue: joinable queue with refseq header and seq tuples (JoinableQueue... | 498e9da9c9f30adc1fa2564590cc7a99cbed9b94 | 33,072 |
def createIQSatelliteChannel(satellite_id):
"""Factory
This method creates a satellite channel object that exchanges IQ data in between both ends.
"""
return SatelliteChannel(satellite_id, stellarstation_pb2.Framing.Value('IQ')) | e1fc08de59692ab308716abc8d137d0ab90336bc | 33,073 |
def scaled_herding_forward_pass(weights, scales, input_data, n_steps):
"""
Do a forward pass with scaled units.
:param weights: A length:L list of weight matrices
:param scales: A length:L+1 list of scale vectors
:param input_data: An (n_samples, n_dims) array of input data
:param n_steps: Numbe... | e5af2c099b1296bdc1f584acaa6ce8f832fb29f6 | 33,074 |
from io import StringIO
def open_remote_factory(mocker):
"""Fixture providing open_remote function for ReferenceLoader construction."""
return mocker.Mock(return_value=StringIO(REMOTE_CONTENT)) | b3df151b021cfd3a07c5737b50d8856d3dc0a599 | 33,075 |
def get_displacement_bcs(domain, macro_strain):
"""Get the shift and fixed BCs.
The shift BC has the the right top and bottom points in x, y and z
fixed or displaced.
The fixed BC has the left top and bottom points in x, y and z
fixed.
Args:
domain: an Sfepy domain
macro_strain: t... | 02090e4d64f75b671597c4b916faf086c5bfe096 | 33,076 |
def public_rest_url(path_url: str = "",
domain: str = CONSTANTS.DEFAULT_DOMAIN,
only_hostname: bool = False,
domain_api_version: str = None,
endpoint_api_version: str = None) -> str:
"""
Creates a full URL for provided public REST e... | 3c99f5a388c33d5c7aa1e018d2d38c7cbe82b112 | 33,077 |
import torch
def get_dir_cos(dist_vec):
""" Calculates directional cosines from distance vectors.
Calculate directional cosines with respect to the standard cartesian
axes and avoid division by zero
Args:
dist_vec: distance vector between particles
Returns: dir_cos, array of directional co... | f325ca5535eaf9083082b147ff90f727214031ec | 33,078 |
def lambda_handler(event, context):
"""
Entry point for the Get All Lambda function.
"""
handler_request.log_event(event)
# Get gk_user_id from requestContext
player_id = handler_request.get_player_id(event)
if player_id is None:
return handler_response.return_response(401, 'Unautho... | 2cc1aeb6a451feb41cbf7a121c67ddfbd06e686f | 33,079 |
def reverse_complement_dna(seq):
"""
Reverse complement of a DNA sequence
Parameters
----------
seq : str
Returns str
"""
return complement_dna(seq)[::-1] | 680cf032c0a96fc254928bfa58eb25bee56e44dc | 33,080 |
def Wizard():
"""
Creates a wizardcharacter
:returns: fully initialised wizard
:rtype: Character
"""
character = (CharacterBuilder()
.with_hit_points(5)
.with_max_hp(5)
.with_spirit(20)
.with_max_spirit(20)
.wi... | 23019f41ba6bf51e049ffe16831a725dd3c20aa2 | 33,081 |
def tournament_communication(comm,
comm_fn=lambda x,y: None,
comm_kw={}):
"""
This is useful for the development of parallelized O(N) duplicate check
functions. The problem with such functions is that the operation of
checking if a set of param... | 03827a02f3df099aa3eead3d8214f0f2f90e60b1 | 33,082 |
def create_permutation_feature(number, rate_pert=1., name=None):
"""Create permutation for features."""
n = np.random.randint(0, 100000)
if name is None:
name = f_stringer_pert_rate(rate_pert)
lista_permuts = []
for i in range(number):
lista_permuts.append((name, PartialPermutationP... | 8c6931e2e2b1dcd9313fda5d8be63bfb0c549f5f | 33,083 |
import random
def DiceRoll():
"""A function to simulate rolling of one or more dice."""
def Roll():
return random.randint(1,6)
print("\nRoll Dice: Simulates rolling of one or more dice.")
num = 1
try: num = int(input("\nEnter the number of dice you wish to roll: "))
except: print... | 90e9587473fb06541ec9daa2ec223759940a5ecb | 33,084 |
def rook_move(self, game, src):
""" Validates rook move """
x = src[0]
y = src[1]
result = []
loop_condition = (lambda i: i < 8) if self.color == 'white' else (lambda i: i >= 0)
reverse_loop_condition = (lambda i: i < 8) if self.color == 'black' else (lambda i: i >= 0)
counter_eval = +1 if ... | 76a782541c565d14a84c1845841338d99f23704d | 33,085 |
def figure_5a():
"""
This creates the plot for figure 5A in the Montague paper. Figure 5A is
a 'plot of ∂(t) over time for three trials during training (1, 30, and 50).'
"""
# Create Processing Components
sample_mechanism = pnl.TransferMechanism(default_variable=np.zeros(60),
... | a8764f75cd9fc7cf0e0a9ddadc452ffdf05f099e | 33,086 |
import click
import sys
import os
import yaml
import io
def init():
"""Return top level command handler."""
@click.group(cls=cli.make_commands(__name__))
@click.option('--distro', required=True,
help='Path to treadmill distro.',
envvar='TREADMILL_DISTRO')
@click.op... | c2e93bf589137c8b6821b169628d7e1f816f9e4d | 33,087 |
import json
def lambda_handler(event, context):
""" Transforms a binary payload by invoking "decode_{event.type}" function
Parameters
----------
DeviceId : str
Device Id
ApplicationId : int
LoRaWAN Application Id / Port number
PayloadData : str
... | d645454656d85589652942b944e84863cb22a425 | 33,088 |
def _get_adi_snrs(psf, angle_list, fwhm, plsc, flux_dist_theta_all,
wavelengths=None, mode='median', ncomp=2):
""" Get the mean S/N (at 3 equidistant positions) for a given flux and
distance, on a median subtracted frame.
"""
snrs = []
theta = flux_dist_theta_all[2]
flux = flux... | 3d00ccb6163962dbfdcedda7aa565dfc549e1f2b | 33,089 |
def compute_nearest_neighbors(fit_embeddings_matrix, query_embeddings_matrix,
n_neighbors, metric='cosine'):
"""Compute nearest neighbors.
Args:
fit_embeddings_matrix: NxD matrix
"""
fit_eq_query = False
if ((fit_embeddings_matrix.shape == query_embeddings_matri... | 1020827cbaab50d591b3741d301ebe88c4ac6d93 | 33,090 |
import re
def commodify_cdli_no( cdli_no ):
"""
Given a CDLI number, fetch the text of the corresponding
artifact from the database and pass it to commodify_text
"""
# Ensure that we have a valid artifact number:
if re.match(r'P[0-9]{6}', cdli_no) is not None:
art_no = int(cdli_no[1:])... | 5c194f40cbde371329671712d648019ac2e43a90 | 33,091 |
import sys
def do_verify(options, _fuse):
"""
@param options: Commandline options
@type options: object
@param _fuse: FUSE wrapper
@type _fuse: dedupsqlfs.fuse.dedupfs.DedupFS
"""
tableOption = _fuse.operations.getTable("option")
curHashFunc = tableOption.get("hash_function")
... | cba45a78cf57422bcca2b01909666fe0fdcb72a1 | 33,092 |
def zvalues(r, N=1):
"""
Generate random pairs for the CDF a normal distribution.
The z-values are from the cumulative distribution function of the
normal distribution.
Args:
r: radius of the CDF
N: number of pairs to generate
Returns:
pairs of random numbers
"""
... | 146d363d7fbb92a9152c6b05a8f38562d4cfc107 | 33,093 |
def exp(fdatagrid):
"""Perform a element wise exponential operation.
Args:
fdatagrid (FDataGrid): Object to whose elements the exponential
operation is going to be applied.
Returns:
FDataGrid: Object whose elements are the result of exponentiating
the elements of th... | aef02937bf0fac701e0ae2bac75911a5a2a8ee9e | 33,094 |
def ksvm(param, data):
""" kernelized SVM """
certif = np.linalg.eigvalsh(data['K'])[0]
if certif < 0:
data['K'] = data['K'] - 2 * certif * np.eye(data['K'].shape[0])
optimal = {}
if len(param['kappa']) > 1 or float('inf') not in param['kappa']:
optimal.update(dist_rob_ksvm(param, da... | e549411b0ac12926753e2eefa968e978414829fa | 33,095 |
def _ordered_unique(arr):
"""
Get the unique elements of an array while preserving order.
"""
arr = np.asarray(arr)
_, idx = np.unique(arr, return_index=True)
return arr[np.sort(idx)] | c4e2578a41d7481b602c4251890276dc2a92dbe9 | 33,096 |
def is_byte_array(value, count):
"""Returns whether the given value is the Python equivalent of a
byte array."""
return isinstance(value, tuple) and len(value) == count and all(map(lambda x: x >= 0 and x <= 255, value)) | 16793415885ea637aecbeeefe24162d6efe9eb39 | 33,097 |
def _FilterSubstructureMatchByAtomMapNumbers(Mol, PatternMol, AtomIndices, AtomMapIndices):
"""Filter substructure match atom indices by atom map indices corresponding to
atom map numbers.
"""
if AtomMapIndices is None:
return list(AtomIndices)
... | 3594a11452848c9ae11f770fa560fe29d68aa418 | 33,098 |
def questions_for_written_answer_tabled_in_range(start, end):
"""Returns a list of all Questions for Written Answer tabled in date range.
"""
try:
_start = start.isoformat()
except AttributeError:
return []
try:
_end = end.isoformat()
except AttributeError:
return... | 5702005be754bb7485fb81e49ff9aab6fbc1d549 | 33,099 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.