content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def voigt_peak_err(peak, A, dA, alphaD, dalphaD):
"""
Gives the error on the peak of the Voigt profile. \
It assumes no correlation between the parameters and that they are \
normally distributed.
:param peak: Peak of the Voigt profile.
:type peak: array
:param A: Area under the Voigt p... | 5,353,900 |
def zip_recursive(destination, source_dir, rootfiles):
"""
Recursively zips source_dir into destination.
rootfiles should contain a list of files in the top level directory that
are to be included. Any top level files not in rootfiles will be omitted
from the zip file.
"""
zipped = zipfile.... | 5,353,901 |
def discord_api_call(method: str, params: typing.Dict, func, data, token: str) -> typing.Any:
""" Calls Discord API. """
# This code is from my other repo -> https://gtihub.com/kirillzhosul/python-discord-token-grabber
# Calling.
return func(
f"https://discord.com/api/{method}",
params... | 5,353,902 |
def get_startup(config: Config) -> Startup:
"""Extracts and validates startup parameters from the application config
file for the active profile
"""
db_init_schema = config.extract_config_value(
('postgres', 'startup', 'init_schema'),
lambda x: x is not None and isinstance(x, bool),
... | 5,353,903 |
def lambda_handler(event, context):
"""Call all scrapers."""
if 'country' in event:
country = event["country"]
if country == "poland-en":
poland_scraper.scrape_poland_en(event)
elif country == "poland-pl":
poland_scraper.scrape_poland_pl(event)
elif count... | 5,353,904 |
def new_request(request):
"""Implements view that allows users to create new requests"""
user = request.user
if user.user_type == 'ADM':
return redirect('/admin')
if request.method == "POST":
request_type = request.POST.get('requestType')
if request_type == 'SC' and user.user... | 5,353,905 |
def get_slice_test(eval_kwargs, test_kwargs, test_dataloader, robustness_testing_datasets):
"""
Args:
test_dataloader:
test_kwargs:
eval_kwargs (dict):
test_dataloader (Dataloader):
robustness_testing_datasets (dict):
Returns:
"""
slice_test = None
if '... | 5,353,906 |
def transform_config(cfg, split_1='search:', split_2='known_papers:'):
"""Ugly function to make cfg.yml less ugly."""
before_search, after_search = cfg.split(split_1, 1)
search_default, papers_default = after_search.split(split_2, 1)
search, paper_comment = '', ''
for line in search_default.splitli... | 5,353,907 |
def filter_coords(raw_lasso, filter_mtx):
"""Filter the raw data corresponding to the new coordinates."""
filter_mtx_use = filter_mtx.copy()
filter_mtx_use["y"] = filter_mtx_use.index
lasso_data = pd.melt(filter_mtx_use, id_vars=["y"], value_name="MIDCounts")
lasso_data = lasso_data[lasso_data["MIDC... | 5,353,908 |
def compute_threshold(predictions_list, dev_labels, f1=True):
"""
Determine the best threshold to use for classification.
Inputs:
predictions_list: prediction found by running the model
dev_labels: ground truth label to be compared with predictions_list
f1: True is using F1 score, F... | 5,353,909 |
def color2position(C, min=None, max=None):
"""
Converts the input points set into colors
Parameters
----------
C : Tensor
the input color tensor
min : float (optional)
the minimum value for the points set. If None it will be set to -1 (default is None)
max : float (optional)... | 5,353,910 |
def is_empty_parsed_graph(graph):
"""
Checks if graph parsed from web page only contains an "empty" statement, that was not embedded in page
namely (<subjectURI>, <http://www.w3.org/ns/md#item>, <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil>)
:param graph: an rdflib.Graph
:return: True if graph co... | 5,353,911 |
def fillinNaN(var,neighbors):
"""
replacing masked area using interpolation
"""
for ii in range(var.shape[0]):
a = var[ii,:,:]
count = 0
while np.any(a.mask):
a_copy = a.copy()
for hor_shift,vert_shift in neighbors:
if not np.any(a.mask): break
a_shifted=np.roll(a_copy,shift=hor_shift,axi... | 5,353,912 |
def test_cache_complex():
"""
Test caching on a complicated expression with multiple symbols appearing
multiple times.
"""
expr = x ** 2 + (y - sy.exp(x)) * sy.sin(z - x * y)
symbol_names = {s.name for s in expr.free_symbols}
expr_t = aesara_code_(expr)
# Iterate through variables in th... | 5,353,913 |
def dtw_randomize(f_data, f_score, outpath, numrand=100):
""" Computes Dynamic Time Warping value between
(1) ChIP-seq enrichment - output of absolute_change_from_cutsite()
(2) insulation scores - output of wigvals_from_cutsite()
Permutation of insulation scores to match with ChIP-seq enrich... | 5,353,914 |
def attach_driver(context):
"""
Attach a webdriver to the behave context
Uses behave configuration to select the driver
:param context: behave context
"""
context.base_url = context.config.userdata.get('server.url')
driver_name = context.config.userdata.get('browser.driver', DRIVER_CHROME)
... | 5,353,915 |
def parse_plist_from_bytes(data):
"""
Convert a binary encoded plist to a dictionary.
:param data: plist data
:return: dictionary
"""
try:
from plistlib import loads, FMT_BINARY
return loads(data, fmt=FMT_BINARY)
except ImportError:
from bplistlib import loads
... | 5,353,916 |
def istd(arrays, axis=-1, ddof=0, weights=None, ignore_nan=False):
"""
Streaming standard deviation of arrays. Weights are also supported.
This is equivalent to calling `numpy.std(axis = 2)` on a stack of images.
Parameters
----------
arrays : iterable of ndarrays
Arrays to be combined.... | 5,353,917 |
def bench_dot(lhs_row_dim, lhs_col_dim, rhs_col_dim, density,
rhs_density, dot_func, trans_lhs, lhs_stype,
rhs_stype, only_storage, distribution="uniform"):
""" Benchmarking both storage and dot
"""
lhs_nd = rand_ndarray((lhs_row_dim, lhs_col_dim), lhs_stype, density, distributio... | 5,353,918 |
def projection_standardizer(emb):
"""Returns an affine transformation to translate an embedding to the centroid
of the given set of points."""
return Affine.translation(*(-emb.mean(axis=0)[:2])) | 5,353,919 |
def raman_normalize(database_name):
"""Raman normaization - element-wise division of the eem spectra by area under the ramam peak.
See reference Murphy et al. "Measurement of Dissolved Organic Matter Fluorescence in Aquatic
Environments: An Interlaboratory Comparison" 2010 Environmental Science and Technol... | 5,353,920 |
def forward_imputation(X_features, X_time):
"""
Fill X_features missing values with values, which are the same as its last measurement.
:param X_features: time series features for all samples
:param X_time: times, when observations were measured
:return: X_features, filled with last measurements in... | 5,353,921 |
def calc_mlevel(ctxstr, cgmap, gtftree, pmtsize=1000):
"""
Compute the mean methylation level of promoter/gene/exon/intron/IGN in each gene
"""
inv_ctxs = {'X': 'CG', 'Y': 'CHG', 'Z': 'CHH'}
ign = defaultdict(list)
mtable = defaultdict(lambda: defaultdict(lambda: defaultdict(float)))
counter... | 5,353,922 |
def _get_service(plugin):
"""
Return a service (ie an instance of a plugin class).
:param plugin: any of: the name of a plugin entry point; a plugin class; an
instantiated plugin object.
:return: the service object
"""
if isinstance(plugin, basestring):
try:
(plugin... | 5,353,923 |
def taiut1(tai1, tai2, dta):
"""
Wrapper for ERFA function ``eraTaiut1``.
Parameters
----------
tai1 : double array
tai2 : double array
dta : double array
Returns
-------
ut11 : double array
ut12 : double array
Notes
-----
The ERFA documentation is below.
... | 5,353,924 |
def store():
"""
Stores the data in the db
:Note: This clears everything from local memory and cant be retrieved without retrieve()
:return: None
"""
global is_inio
global data
global lbels
global cols
while True:
if not is_inio:
break
is_inio... | 5,353,925 |
def fetch_ppn(ppn):
"""
"""
from SPARQLWrapper import SPARQLWrapper, JSON
ENDPOINT_URL = 'http://openvirtuoso.kbresearch.nl/sparql'
sparql = SPARQLWrapper(ENDPOINT_URL)
sqlquery = """
SELECT ?collatie WHERE {{
kbc:{ppn} dcterms:extent ?formaat, ?collatie .
FILTER (?for... | 5,353,926 |
def prepare_link_title(
item: feedparser.FeedParserDict) -> feedparser.FeedParserDict:
"""
Для RSS Item возвращает ссылку, заголовок и описание
:param item:
:return:
"""
result = None
if item:
assert item.title, 'Not found title in item'
assert item.link, 'Not found link ... | 5,353,927 |
def api_docs_redirect():
""" Redirect to API docs """
return redirect('/api/v1', code=302) | 5,353,928 |
def print_topics(model, vectorizer, top_n: int=10)-> List:
"""Print the top n words found by each topic model.
Args:
model: Sklearn LatentDirichletAllocation model
vectorizer: sklearn CountVectorizer
top_n (int): Number of words you wish to return
Source: https://towa... | 5,353,929 |
def simulate_eazy_sed_from_coeffs(
eazycoeffs, eazytemplatedata, z,
returnfluxunit='', returnwaveunit='A',
limitwaverange=True, savetofile='',
**outfile_kwargs):
"""
Generate a simulated SED from a given set of input eazy-py coefficients
and eazypy templates.
NB: Requi... | 5,353,930 |
def get_timezones_all():
"""Dump the list of timezones from ptyz into a format suitable
for use with the Django Forms API's ChoiceField
"""
# TODO: Find a more user-friendly way of managing 500+ timezones
output = []
for tz in all_timezones:
output.append( (tz, tz) )
return output | 5,353,931 |
def create_logistic_vector(input_vector, cutoff):
"""
Creates a vector of 0s and 1s based on an input vector of numbers with a cut-off point.
"""
output_vector = np.zeros(len(input_vector))
n = 0
for i in range(len(input_vector)):
if input_vector[i] > cutoff:
output_vector[i... | 5,353,932 |
def profile(username):
""" user profile """
user = User.query.filter_by(username=username).first_or_404()
return render_template("user/profile.jinja.html", user=user) | 5,353,933 |
def action_rescale(action):
"""Rescale Distribution actions to exp one"""
return np.array([0 if abs(a) < 0.5 else 10 ** (a-3) if a > 0 else -(10 ** (-a - 3)) for a in action * 3]) | 5,353,934 |
async def test_button_press(hass, entity_id_suffix, api_method_name) -> None:
"""Test pressing the button entities."""
client_mock = await init_integration(hass, electric_vehicle=True)
await hass.services.async_call(
BUTTON_DOMAIN,
SERVICE_PRESS,
{ATTR_ENTITY_ID: f"button.my_mazda3_... | 5,353,935 |
def check_if_cards(list_of_cards):
"""Raise an exception if not valid cards.
Every card should be a rank character followed by a suit character.
"""
for i in list_of_cards:
if i[0] not in CARD_RANKS:
message = (
"'" + str(i) + "' is not a recognised card rank.\n"... | 5,353,936 |
def multi_knee(points: np.ndarray, t1: float = 0.99, t2: int = 3) -> np.ndarray:
"""
Recursive knee point detection based on the curvature equations.
It returns the knee points on the curve.
Args:
points (np.ndarray): numpy array with the points (x, y)
t1 (float): coefficient of determ... | 5,353,937 |
def parse_dotted_path(path):
"""
Extracts attribute name from dotted path.
"""
try:
objects, attr = path.rsplit('.', 1)
except ValueError:
objects = None
attr = path
return objects, attr | 5,353,938 |
def check_get_btc(output_fields):
"""
Checks whether the price of btc is a float and
larger than zero.
"""
btc_price = output_fields[BTC_PRICE_FLD]
check_float_value(btc_price, BTC_PRICE_FLD) | 5,353,939 |
def resource_media_fields(document, resource):
""" Returns a list of media fields defined in the resource schema.
:param document: the document eventually containing the media files.
:param resource: the resource being consumed by the request.
.. versionadded:: 0.3
"""
media_fields = app.confi... | 5,353,940 |
def bump_version(target_version, upgrade, metadata_file_path):
"""Bumps target version in metadata"""
# load
raw_data: OrderedDict = ordered_safe_load(metadata_file_path.read_text())
# parse and validate
metadata = ServiceDockerData(**raw_data)
# get + bump + set
attrname = target_version.... | 5,353,941 |
def read_config_file(f):
"""Read a config file."""
if isinstance(f, basestring):
f = os.path.expanduser(f)
try:
config = ConfigObj(f, interpolation=False, encoding='utf8')
except ConfigObjError as e:
log(LOGGER, logging.ERROR, "Unable to parse line {0} of config file "
... | 5,353,942 |
def _parse_moving(message: List[str]) -> Tuple[Actions, str]:
"""Parses the incoming message list to determine if movement is found.
Args:
message: list of words in the player message
Returns: a tuple of the action and direction
"""
short_dir = ['n', 'ne', 'e', 'se', 's', 'sw', 'w', 'nw']... | 5,353,943 |
def checkheader(headerfile, name, arch):
"""check a header by opening it and comparing the results to the name and arch
we believe it to be for. if it fails raise URLGrabError(-1)"""
h = Header_Work(headerfile)
fail = 0
if h.hdr is None:
fail = 1
else:
if name != h.name() or a... | 5,353,944 |
def _Net_forward_all(self, blobs=None, **kwargs):
"""
Run net forward in batches.
Take
blobs: list of blobs to extract as in forward()
kwargs: Keys are input blob names and values are blob ndarrays.
Refer to forward().
Give
all_outs: {blob name: list of blobs} dict.
... | 5,353,945 |
def email_members_old(request, course_prefix, course_suffix):
"""
Displays the email form and handles email actions
Right now this is blocking and does not do any batching.
Will have to make it better
"""
error_msg=""
success_msg=""
form = EmailForm()
if request.metho... | 5,353,946 |
def start_folders() -> None:
"""Creates the initial folders to save the data and plots.
:return: None -- The function creates folders and does not return a value.
"""
try:
os.mkdir(f"../data/epochs_sim")
os.mkdir(f"../plot/epochs_sim")
print("Folder to save data created")
... | 5,353,947 |
def Padding_op(Image, strides, offset_x, offset_y):
"""
Takes an image, offset required to fit output image dimensions with given strides and calculates the
padding it needs for perfect fit.
:param Image:
:param strides:
:param offset_x:
:param offset_y:
:return: Padded image
... | 5,353,948 |
def area_triangle(point_a: array_like, point_b: array_like, point_c: array_like) -> np.float64:
"""
Return the area of a triangle defined by three points.
The points are the vertices of the triangle. They must be 3D or less.
Parameters
----------
point_a, point_b, point_c : array_like
... | 5,353,949 |
def file_exists(target, parse=False):
"""Checks if a file exists"""
if parse:
target = envar_parser(target)
if os.path.isfile(target):
return True
else:
return False | 5,353,950 |
def test_valid(line):
"""Test for 40 character hex strings
Print error on failure"""
base_error = '*** WARNING *** line in torrent list'
if len(line) != 40:
print(base_error, 'incorrect length:', line)
elif any(char not in HEX for char in line):
print(base_error, 'has non-hex digits... | 5,353,951 |
def copy_for_online(levels):
""" Generates a separate Puzzlescript source file for each level in the given sequence, and copies each in order to the system clipboard.
When called, this function first prints a prompt including the name of the first level in the progression to stdout. When the user
presses t... | 5,353,952 |
def readIMAGCDF(filename, headonly=False, **kwargs):
"""
Reading Intermagnet CDF format (1.0,1.1,1.2)
"""
debug = kwargs.get('debug')
cdfdat = cdf.CDF(filename)
if debug:
logger.info("readIMAGCDF: FOUND IMAGCDF file created with version {}".format(cdfdat.version()))
if debug:
... | 5,353,953 |
def custom_formatter(code, msg):
""" 自定义结果格式化函数
:param code: 响应码
:param msg: 响应消息
"""
return {
"code": code,
"msg": "hello",
"sss": "tt",
} | 5,353,954 |
def get_sampler_callback(rank, num_replicas, noniid=0, longtail=0):
"""
noniid: noniid controls the noniidness.
- noniid = 1 refers to completely noniid
- noniid = 0 refers to iid.
longtail: longtail controls the long-tailness.
- Class i takes (1-longtail) ** i percent of data.
... | 5,353,955 |
def _test_broadcast_args(in_shape_1, in_shape_2):
"""One iteration of broadcast_args"""
shape_1 = np.array(in_shape_1).astype("int32")
shape_2 = np.array(in_shape_2).astype("int32")
with tf.Graph().as_default():
shape_1 = constant_op.constant(shape_1, shape=shape_1.shape, dtype=shape_1.dtype)
... | 5,353,956 |
def alloc_bitrate(frame_nos, chunk_frames, pref_bitrate, nrow_tiles, ncol_tiles):
"""
Allocates equal bitrate to all the tiles
"""
vid_bitrate = []
for i in range(len(chunk_frames)):
chunk = chunk_frames[i]
chunk_bitrate = [[-1 for x in range(ncol_tiles)] for y in range(nrow_tiles)]
chunk_weight = ... | 5,353,957 |
def file_filter(extensions: Collection[str]) -> Any:
"""Register a page content filter for file extensions."""
def wrapper(f):
for ext in extensions:
_file_filters[ext] = f
return f
return wrapper | 5,353,958 |
def epc_calc_img_size(reg_dict):
"""
Calcalute the output image size from the EPC660 sensor
Parameters
----------
reg_dict : dict
Returns
----------
int
The number of rows
int
The number of columns in the image
"""
col_start, col_end, row_start, row_end ... | 5,353,959 |
def test():
"""
Run Find in Files widget test.
"""
# Standard library imports
from os.path import dirname
import sys
from unittest.mock import MagicMock
# Local imports
from spyder.utils.qthelpers import qapplication
app = qapplication()
plugin_mock = MagicMock()
plugin... | 5,353,960 |
def main():
"""Script entry point."""
vm_os, vm_packages = parse_cmdline()
print('OS:', vm_os)
print('Packages:', ', '.join(vm_packages))
download_vagrantfile(vm_os)
download_ansible_roles(vm_packages)
write_playbook(vm_packages)
create_workspace()
run_vagrant_up() | 5,353,961 |
def get_rki_data(read_data=dd.defaultDict['read_data'],
file_format=dd.defaultDict['file_format'],
out_folder=dd.defaultDict['out_folder'],
no_raw=dd.defaultDict['no_raw'],
impute_dates=dd.defaultDict['impute_dates'],
make_plot=dd.defa... | 5,353,962 |
def simple_url_formatter(endpoint, url):
"""
A simple URL formatter to use when no application context
is available.
:param str endpoint: the endpoint to use.
:param str url: the URL to format
"""
return u"/{}".format(url) | 5,353,963 |
def generate_service(
name: str,
image: str,
ports: List[str] = [],
volumes: List[str] = [],
dependsOn: List[str] = [],
) -> str:
"""
Creates a string with docker compose service specification.
Arguments are a list of values that need to be added to each section
named after the param... | 5,353,964 |
def read_integer(msg=None, error_msg=None):
"""
Asks the user for an integer value (int or long)
:param msg: The message, displayed to the user.
:param error_msg: The message, displayed to the user, in case he did not entered a valid int or long.
:return: An int or a long from the user.
"""
... | 5,353,965 |
def set_async_call_stack_depth(maxDepth: int) -> dict:
"""Enables or disables async call stacks tracking.
Parameters
----------
maxDepth: int
Maximum depth of async call stacks. Setting to `0` will effectively disable collecting async
call stacks (default).
"""
return {
... | 5,353,966 |
def main():
"""合計50問を生成して標準出力に出力する"""
print("No,条件式,True | False,説明")
ls = create_basic_conditions(10) + create_logical_conditions(20)
for no, i in enumerate(range(len(ls))):
print(no+1, ls[i], sep=',') | 5,353,967 |
def print_output(name, src, toStdErr):
"""
Relay the output stream to stdout line by line
:param name:
:param src: source stream
:param toStdErr: flag set if stderr is to be the dest
:return:
"""
global needPassword
debug ("starting printer for %s" % name )
line = ""
while n... | 5,353,968 |
def save_empty_abundance_file(ngrid, outputfilepath='.'):
"""Dummy abundance file with only zeros"""
Z_atomic = np.arange(1, 31)
abundancedata = {'cellid': range(1, ngrid + 1)}
for atomic_number in Z_atomic:
abundancedata[f'Z={atomic_number}'] = np.zeros(ngrid)
# abundancedata['Z=28'] = np... | 5,353,969 |
def percError(predicted, observed):
"""Percentage Error
Parameters
==========
predicted : array-like
Array-like (list, numpy array, etc.) of predictions
observed : array-like
Array-like (list, numpy array, etc.) of observed values of scalar
quantity
Returns
=======
... | 5,353,970 |
def _dict_eq(a, b):
"""
Compare dictionaries using their items iterators and loading as much
as half of each into a local temporary store. For comparisons of ordered
dicts, memory usage is nil. For comparisons of dicts whose iterators
differ in sequence maximally, memory consumption is O(N). Exec... | 5,353,971 |
def avoid_snakes(my_head: Dict[str, int], snakes: List[dict], possible_moves: List[str]) -> List[str]:
"""
my_head: Dictionary of x/y coordinates of the Battlesnake head.
e.g. {"x": 0, "y": 0}
snakes: List of dictionaries of x/y coordinates for every segment of a Battlesnake.
e.g. [ ... | 5,353,972 |
def getChipZip(request, path):
"""Download the AutoPH file, converted to zip compression"""
from django.core.servers.basehttp import FileWrapper
import zipfile
logger = logging.getLogger(__name__)
path = os.path.join("/", path)
try:
name = os.path.basename(path)
name = name.spli... | 5,353,973 |
def m_unicom_online_time2_0(seq):
"""
获取联通手机在网时长所对应的code
:param seq: 联通在网时长区间
:return: code
example:
:seq: [0-1]
:return 1
"""
if not seq:
return []
if seq[0] in ["[0-1]", "(1-2]", "[3-6]"]:
seq = ["(0_6)"]
elif seq... | 5,353,974 |
def convert_config_gui_structure(config_gui_structure, port, instance_id,
is_port_in_database, conf):
"""
Converts the internal data structure to a dictionary which follows the
"Configuration file structure", see setup.rst
:param config_gui_structure: Data structure used... | 5,353,975 |
def message_similarity_hard(m1, m2):
"""
Inputs: One dimension various length numpy array.
"""
return int(np.all(m1==m2)) | 5,353,976 |
def test_uiuc_imports():
"""
Test that UIUC files can be imported without error
"""
for airfoil_file in AIRFOIL_FILES:
airfoil_file_name = os.path.basename(airfoil_file)
print(airfoil_file_name)
if airfoil_file_name in AIRFOIL_FILES_BLACKLIST:
continue
uppe... | 5,353,977 |
def identity_block(input_tensor, kernel_size, filters, stage, block):
"""
The identity_block is the block that has no conv layer at shortcut
Arguments
input_tensor: input tensor
kernel_size: defualt 3, the kernel size of middle conv layer at main path
filters: list of integers,... | 5,353,978 |
def convert_to_squad(story_summary_content, question_content, set_type):
"""
:param story_summary_content:
:param question_content:
:param category_content:
:param set_type:
:return: formatted SQUAD data
At initial version, we are just focusing on the context and question, nothing more,
... | 5,353,979 |
def push_output(process, primary_fd, out_buffer: TextBuffer, process_state: ProcessState,
is_interactive_session: bool, on_error: callable):
"""
Receive output from running process and forward to streams, capture
:param process:
:param primary_fd:
:param out_buffer:
:param proc... | 5,353,980 |
def check_conditions(conditions, variable_dict, domain_dict, domain_list):
"""A function that checks if the generated variables pass the conditions and generates new ones until they do.
:param conditions: The conditions of the template.
:param variable_dict: List of variables.
:param domain_dict: the do... | 5,353,981 |
def set_pin_on_teaching_page(request,
section_label,
pin=True):
"""
if pin=True, pin the section on teaching page
if pin=False, unpin the section from teaching page
@except InvalidSectionID
@except NotSectionInstructorException
@except Us... | 5,353,982 |
def inject_python_resources() -> dict[str, Any]:
"""
Inject common resources to be used in Jinja templates.
"""
return dict(
isinstance=isinstance,
zip=zip,
enumerate=enumerate,
len=len,
str=str,
bool=bool,
int=int,
float=float,
) | 5,353,983 |
def get_feature_subsets_options(study, data_types):
"""Given a study and list of data types, get the relevant feature
subsets
"""
feature_subsets = ['custom']
if 'expression' in data_types:
try:
feature_subsets.extend(study.expression.feature_subsets.keys())
except Attrib... | 5,353,984 |
def _loop(params, context):
"""
Loop through some actions in the context of a L{Runner} run.
"""
for item in params['iterable']:
context.variables['item'] = item
result = yield context.runner.runActions(params['actions'], context)
defer.returnValue(result) | 5,353,985 |
def sample_batch_annotate_files(storage_uri):
# os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = r"C:\Users\user\Desktop\doc_ai\rmi-insights-3e257c9c456c.json"
"""Perform batch file annotation."""
mime_type = "application/pdf"
client = vision_v1.ImageAnnotatorClient()
gcs_source = {"uri": s... | 5,353,986 |
def possibilities(q=0, *num):
"""
:param q: Número de quadrados a considerar
:param num: Em quantos quadrados a soma do nº de bombas é 1
:return:
pos -> Possibilidade de distribuição das bombas
tot -> Número de quadrados nos quais só há uma bomba
i -> Início da contagem dos quadrados onde a ... | 5,353,987 |
def parse_page_options(text):
"""
Parses special fields in page header. The header is separated by a line
with 3 dashes. It contains lines of the "key: value" form, which define
page options.
Returns a dictionary with such options. Page text is available as option
named "text".
"""
i... | 5,353,988 |
def _read_16_bit_message(prefix, payload_base, prefix_type, is_time,
data, offset, eieio_header):
""" Return a packet containing 16 bit elements
"""
if payload_base is None:
if prefix is None:
return EIEIO16BitDataMessage(eieio_header.count, data, offset)
... | 5,353,989 |
def test_linear():
""" Tests that KernelExplainer returns the correct result when the model is linear.
(as per corollary 1 of https://arxiv.org/abs/1705.07874)
"""
np.random.seed(2)
x = np.random.normal(size=(200, 3), scale=1)
# a linear model
def f(x):
return x[:, 0] + 2.0*x[:, 1... | 5,353,990 |
def csm_shape(csm):
"""
Return the shape field of the sparse variable.
"""
return csm_properties(csm)[3] | 5,353,991 |
def hyperlist_to_labellist(hyperlist):
"""
:param hyperlist:
:return: labellist, labels to use for plotting
"""
return [hyper_to_label(hyper) for hyper in hyperlist] | 5,353,992 |
def _pretty_print_dict(dictionary):
"""Generates a pretty-print formatted version of the input JSON.
Args:
dictionary (dict): the JSON string to format.
Returns:
str: pretty-print formatted string.
"""
return json.dumps(_ascii_encode_dict(dictionary), indent=2, sort_keys=True) | 5,353,993 |
def _set_version(obj, version):
"""
Set the given version on the passed object
This function should be used with 'raw' values, any type conversion should be managed in
VersionField._set_version_value(). This is needed for future enhancement of concurrency.
"""
obj._concurrencymeta.field._set_ve... | 5,353,994 |
def _bivariate_kdeplot(x, y, filled, fill_lowest,
kernel, bw, gridsize, cut, clip,
axlabel, cbar, cbar_ax, cbar_kws, ax, **kwargs):
"""Plot a joint KDE estimate as a bivariate contour plot."""
# Determine the clipping
if clip is None:
clip = [(-np.inf, n... | 5,353,995 |
def load_file(path):
"""
Load single cell dataset from file
"""
if os.path.exists(DATA_PATH+path+'.h5ad'):
adata = sc.read_h5ad(DATA_PATH+path+'.h5ad')
elif os.path.isdir(path): # mtx format
adata = read_mtx(path)
elif os.path.isfile(path):
if path.endswith(('.csv', '.c... | 5,353,996 |
def unified_load(namespace, subclasses=None, recurse=False):
"""Provides a unified interface to both the module and class loaders,
finding modules by default or classes if given a ``subclasses`` parameter.
"""
if subclasses is not None:
return ClassLoader(recurse=recurse).load(namespace, subcla... | 5,353,997 |
def generate_free_rooms(room_times: dict) -> dict:
"""
Generates data structure for getting free rooms for each time.
"""
# create data format
free_rooms = {'M': {},
'Tu': {},
'W': {},
'Th': {},
'F': {}
}
#... | 5,353,998 |
def code_parse_line(li, pattern_type="import/import_externa"):
"""
External Packages
"""
### Import pattern
if pattern_type == "import":
if li.find("from") > -1:
l = li[li.find("from") + 4 : li.find("import")].strip().split(",")
else:
l = li.strip().split("impor... | 5,353,999 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.